GitLab is used only for code review, issue tracking and project management. Canonical locations for source code are still https://gitweb.torproject.org/ https://git.torproject.org/ and git-rw.torproject.org.

tl-util.jsm 31.3 KB
Newer Older
1
// Copyright (c) 2019, The Tor Project, Inc.
2 3 4 5 6 7 8 9 10 11 12 13
// See LICENSE for licensing information.
//
// vim: set sw=2 sts=2 ts=8 et syntax=javascript:

/*************************************************************************
 * Tor Launcher Util JS Module
 *************************************************************************/

let EXPORTED_SYMBOLS = [ "TorLauncherUtil" ];

const Cc = Components.classes;
const Ci = Components.interfaces;
14
const Cu = Components.utils;
15
const Cr = Components.results;
16
const kPropBundleURI = "chrome://torlauncher/locale/torlauncher.properties";
17
const kPropNamePrefix = "torlauncher.";
18
const kPrefBranchDefaultBridge = "extensions.torlauncher.default_bridge.";
19

20 21 22 23
Cu.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyModuleGetter(this, "TorLauncherLogger",
                          "resource://torlauncher/modules/tl-logger.jsm");

24 25 26 27
let TorLauncherUtil =  // Public
{
  get isMac()
  {
28
    return TLUtilInternal._isMac;
29 30 31 32 33 34 35
  },

  get isWindows()
  {
    return ("WINNT" == TLUtilInternal._OS);
  },

36 37 38 39 40 41 42 43 44
  isAppVersionAtLeast: function(aVersion)
  {
    var appInfo = Cc["@mozilla.org/xre/app-info;1"]
                    .getService(Ci.nsIXULAppInfo);
    var vc = Cc["@mozilla.org/xpcom/version-comparator;1"]
               .getService(Ci.nsIVersionComparator);
    return (vc.compare(appInfo.version, aVersion) >= 0);
  },

45 46 47
  // Error Reporting / Prompting
  showAlert: function(aParentWindow, aMsg)
  {
48
    // TODO: alert() does not always resize correctly to fit the message.
49 50 51 52 53 54
    try
    {
      if (!aParentWindow)
      {
        var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Ci.nsIWindowMediator);
55 56 57 58 59 60 61 62 63 64 65 66
        let settingsWindow =
                          wm.getMostRecentWindow("TorLauncher:NetworkSettings");
        if (TLUtilInternal._isWindowVisible(settingsWindow))
        {
          aParentWindow = settingsWindow;
        }
        else
        {
          let browserWindow = wm.getMostRecentWindow("navigator:browser");
          if (TLUtilInternal._isWindowVisible(browserWindow))
            aParentWindow = browserWindow;
        }
67 68 69 70 71 72 73 74 75 76 77 78 79
      }

      var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"]
                 .getService(Ci.nsIPromptService);
      var title = this.getLocalizedString("error_title");
      ps.alert(aParentWindow, title, aMsg);
    }
    catch (e)
    {
      alert(aMsg);
    }
  },

80 81 82
  // Returns true if user confirms; false if not.
  // Note that no prompt is shown (and false is returned) if the Network Settings
  // window is open.
83 84
  showConfirm: function(aParentWindow, aMsg, aDefaultButtonLabel,
                        aCancelButtonLabel)
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
  {
    try
    {
      if (!aParentWindow)
      {
        var wm = Cc["@mozilla.org/appshell/window-mediator;1"]
                   .getService(Ci.nsIWindowMediator);
        aParentWindow = wm.getMostRecentWindow("TorLauncher:NetworkSettings");
        if (aParentWindow)
          return false; // Don't show prompt if Network Settings window is open.

        aParentWindow = wm.getMostRecentWindow("navigator:browser");
      }

      var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"]
                 .getService(Ci.nsIPromptService);
      var title = this.getLocalizedString("error_title");
      var btnFlags = (ps.BUTTON_POS_0 * ps.BUTTON_TITLE_IS_STRING)
                     + ps.BUTTON_POS_0_DEFAULT
104
                     + (ps.BUTTON_POS_1 * ps.BUTTON_TITLE_IS_STRING);
105 106 107

      var notUsed = { value: false };
      var btnIndex =  ps.confirmEx(aParentWindow, title, aMsg, btnFlags,
108 109
                                   aDefaultButtonLabel, aCancelButtonLabel,
                                   null, null, notUsed);
110 111 112 113 114 115 116 117 118 119
      return (0 == btnIndex);
    }
    catch (e)
    {
      return confirm(aMsg);
    }

    return false;
  },

120
  getSaveSettingsErrorMessage: function(aDetails)
121 122 123 124
  {
    if (!aDetails)
      aDetails = TorLauncherUtil.getLocalizedString("ensure_tor_is_running");

125
    return TorLauncherUtil.getFormattedLocalizedString(
126 127 128
                                  "failed_to_save_settings", [aDetails], 1);
  },

129
  // Localized Strings
130 131 132 133
  flushLocalizedStringCache: function()
  {
    TLUtilInternal.mStringBundle = undefined;
  },
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

  // "torlauncher." is prepended to aStringName.
  getLocalizedString: function(aStringName)
  {
    if (!aStringName)
      return aStringName;

    try
    {
      var key = kPropNamePrefix + aStringName;
      return TLUtilInternal._stringBundle.GetStringFromName(key);
    } catch(e) {}

    return aStringName;
  },

  // "torlauncher." is prepended to aStringName.
  getFormattedLocalizedString: function(aStringName, aArray, aLen)
  {
    if (!aStringName || !aArray)
      return aStringName;

    try
    {
      var key = kPropNamePrefix + aStringName;
      return TLUtilInternal._stringBundle.formatStringFromName(key,
                                                               aArray, aLen);
    } catch(e) {}

    return aStringName;
  },

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
  getLocalizedStringForError: function(aNSResult)
  {
    for (let prop in Cr)
    {
      if (Cr[prop] == aNSResult)
      {
        let key = "nsresult." + prop;
        let rv = this.getLocalizedString(key);
        if (rv !== key)
          return rv;

        return prop;  // As a fallback, return the NS_ERROR... name.
      }
    }

    return undefined;
  },

184 185 186 187 188 189 190 191 192 193 194 195 196
  getLocalizedBootstrapStatus: function(aStatusObj, aKeyword)
  {
    if (!aStatusObj || !aKeyword)
      return "";

    var result;
    var fallbackStr;
    if (aStatusObj[aKeyword])
    {
      var val = aStatusObj[aKeyword].toLowerCase();
      var key;
      if (aKeyword == "TAG")
      {
197 198 199 200 201 202 203 204 205 206 207
        // The bootstrap status tags in tagMap below are used by Tor
        // versions prior to 0.4.0.x. We map each one to the tag that will
        // produce the localized string that is the best fit.
        let tagMap =
        {
          "conn_dir":       "conn",
          "handshake_dir":  "onehop_create",
          "conn_or":        "enough_dirinfo",
          "handshake_or":   "ap_conn"
        };
        if (val in tagMap) val = tagMap[val];
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228

        key = "bootstrapStatus." + val;
        fallbackStr = aStatusObj.SUMMARY;
      }
      else if (aKeyword == "REASON")
      {
        if ("connectreset" == val)
          val = "connectrefused";

        key = "bootstrapWarning." + val;
        fallbackStr = aStatusObj.WARNING;
      }

      result = TorLauncherUtil.getLocalizedString(key);
      if (result == key)
        result = undefined;
    }

    if (!result)
      result = fallbackStr;

229 230 231
    if ((aKeyword == "REASON") && aStatusObj.HOSTADDR)
      result += " - " + aStatusObj.HOSTADDR;

232 233 234
    return (result) ? result : "";
  },

235
  // Preferences
236 237 238 239 240
  loadDefaultPreferences: function()
  {
    return TLUtilInternal._loadPreferences();
  },

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
  getBoolPref: function(aPrefName, aDefaultVal)
  {
    var rv = (undefined != aDefaultVal) ? aDefaultVal : false;

    try
    {
      rv = TLUtilInternal.mPrefsSvc.getBoolPref(aPrefName);
    } catch (e) {}

    return rv;
  },

  setBoolPref: function(aPrefName, aVal)
  {
    var val = (undefined != aVal) ? aVal : false;
    try
    {
      TLUtilInternal.mPrefsSvc.setBoolPref(aPrefName, val);
    } catch (e) {}
  },

  getIntPref: function(aPrefName, aDefaultVal)
  {
    var rv = aDefaultVal ? aDefaultVal : 0;

    try
    {
      rv = TLUtilInternal.mPrefsSvc.getIntPref(aPrefName);
    } catch (e) {}

    return rv;
  },

274 275 276 277 278 279 280 281 282
  setIntPref: function(aPrefName, aVal)
  {
    var val = (undefined != aVal) ? aVal : 0;
    try
    {
      TLUtilInternal.mPrefsSvc.setIntPref(aPrefName, val);
    } catch (e) {}
  },

283 284 285 286 287 288 289 290 291 292 293
  getCharPref: function(aPrefName, aDefaultVal)
  {
    var rv = aDefaultVal ? aDefaultVal : "";

    try
    {
      rv = TLUtilInternal.mPrefsSvc.getCharPref(aPrefName);
    } catch (e) {}

    return rv;
  },
294

295 296 297 298 299 300 301 302
  setCharPref: function(aPrefName, aVal)
  {
    try
    {
      TLUtilInternal.mPrefsSvc.setCharPref(aPrefName, aVal ? aVal : "");
    } catch (e) {}
  },

303 304 305 306 307 308 309 310
  clearUserPref: function(aPrefName)
  {
    try
    {
      TLUtilInternal.mPrefsSvc.clearUserPref(aPrefName);
    } catch (e) {}
  },

311 312 313 314 315 316 317
  getPrefBranch: function(aBranchName)
  {
    return Cc["@mozilla.org/preferences-service;1"]
             .getService(Ci.nsIPrefService)
             .getBranch(aBranchName);
  },

318 319 320 321 322 323 324 325 326 327 328 329 330
  // Currently, this returns a random permutation of an array, bridgeArray.
  // Later, we might want to change this function to weight based on the
  // bridges' bandwidths.
  rearrangeBridges: function(bridgeArray)
  {
    for (var j, x, i = bridgeArray.length; i;
           j = parseInt(Math.random() * i),
           x = bridgeArray[--i],
           bridgeArray[i] = bridgeArray[j],
           bridgeArray[j] = x);
    return bridgeArray;
  },

331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
  get shouldStartAndOwnTor()
  {
    const kPrefStartTor = "extensions.torlauncher.start_tor";
    try
    {
      const kEnvSkipLaunch = "TOR_SKIP_LAUNCH";

      var env = Cc["@mozilla.org/process/environment;1"]
                  .getService(Ci.nsIEnvironment);
      if (env.exists(kEnvSkipLaunch))
        return ("1" != env.get(kEnvSkipLaunch));
    } catch(e) {}

    return this.getBoolPref(kPrefStartTor, true);
  },
346

347 348
  get shouldPromptForLocale()
  {
349 350 351 352
    // We are not supporting locale selection on the alpha/stable channel
    // right now. Thus, no prompt for the user.
    return false;
    /* const kPrefPromptForLocale = "extensions.torlauncher.prompt_for_locale";
353 354 355 356 357 358 359 360 361 362
    try
    {
      const kEnvSkipLocalePrompt = "TOR_SKIP_LOCALE_PROMPT";

      var env = Cc["@mozilla.org/process/environment;1"]
                  .getService(Ci.nsIEnvironment);
      if (env.exists(kEnvSkipLocalePrompt))
        return ("1" != env.get(kEnvSkipLocalePrompt));
    } catch(e) {}

363
    return this.getBoolPref(kPrefPromptForLocale, true); */
364 365
  },

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
  get shouldShowNetworkSettings()
  {
    const kPrefPromptAtStartup = "extensions.torlauncher.prompt_at_startup";
    try
    {
      const kEnvForceShowNetConfig = "TOR_FORCE_NET_CONFIG";

      var env = Cc["@mozilla.org/process/environment;1"]
                  .getService(Ci.nsIEnvironment);
      if (env.exists(kEnvForceShowNetConfig))
        return ("1" == env.get(kEnvForceShowNetConfig));
    } catch(e) {}

    return this.getBoolPref(kPrefPromptAtStartup, true);
  },

382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
  get shouldOnlyConfigureTor()
  {
    const kPrefOnlyConfigureTor = "extensions.torlauncher.only_configure_tor";
    try
    {
      const kEnvOnlyConfigureTor = "TOR_CONFIGURE_ONLY";

      var env = Cc["@mozilla.org/process/environment;1"]
                  .getService(Ci.nsIEnvironment);
      if (env.exists(kEnvOnlyConfigureTor))
        return ("1" == env.get(kEnvOnlyConfigureTor));
    } catch(e) {}

    return this.getBoolPref(kPrefOnlyConfigureTor, false);
  },
397 398 399 400 401 402

  // Returns an array of strings or undefined if none are available.
  get defaultBridgeTypes()
  {
    try
    {
403
      var prefBranch = this.getPrefBranch(kPrefBranchDefaultBridge);
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
      var childPrefs = prefBranch.getChildList("", []);
      var typeArray = [];
      for (var i = 0; i < childPrefs.length; ++i)
      {
        var s = childPrefs[i].replace(/\..*$/, "");
        if (-1 == typeArray.lastIndexOf(s))
          typeArray.push(s);
      }

      return typeArray.sort();
    } catch(e) {};

    return undefined;
  },

  // Returns an array of strings or undefined if none are available.
  // The list is filtered by the default_bridge_type pref value.
  get defaultBridges()
  {
    const kPrefName = "extensions.torlauncher.default_bridge_type";
    var filterType = this.getCharPref(kPrefName);
    if (!filterType)
      return undefined;

    try
    {
430
      var prefBranch = this.getPrefBranch(kPrefBranchDefaultBridge);
431 432 433 434 435 436 437 438 439 440 441 442 443 444
      var childPrefs = prefBranch.getChildList("", []);
      var bridgeArray = [];
      // The pref service seems to return the values in reverse order, so
      // we compensate by traversing in reverse order.
      for (var i = childPrefs.length - 1; i >= 0; --i)
      {
        var bridgeType = childPrefs[i].replace(/\..*$/, "");
        if (bridgeType == filterType)
        {
          var s = prefBranch.getCharPref(childPrefs[i]);
          if (s)
            bridgeArray.push(s);
        }
      }
445
      this.rearrangeBridges(bridgeArray);
446 447 448 449 450 451

      return bridgeArray;
    } catch(e) {};

    return undefined;
  },
452 453

  // Returns an nsIFile.
454 455
  // If aTorFileType is "control_ipc" or "socks_ipc", aCreate is ignored
  // and there is no requirement that the IPC object exists.
456 457 458 459 460 461 462
  // For all other file types, null is returned if the file does not exist
  // and it cannot be created (it will be created if aCreate is true).
  getTorFile: function(aTorFileType, aCreate)
  {
    if (!aTorFileType)
      return null;

463 464 465 466
    let torFile;  // an nsIFile to be returned
    let path;     // a relative or absolute path that will determine torFile

    let isRelativePath = false;
467
    let isUserData = (aTorFileType != "tor") &&
468
                     (aTorFileType != "pt-startup-dir") &&
469
                     (aTorFileType != "torrc-defaults");
470 471 472
    let isControlIPC = ("control_ipc" == aTorFileType);
    let isSOCKSIPC = ("socks_ipc" == aTorFileType);
    let isIPC = isControlIPC || isSOCKSIPC;
473
    let checkIPCPathLen = true;
474
    let useAppDir = false;
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500

    const kControlIPCFileName = "control.socket";
    const kSOCKSIPCFileName = "socks.socket";
    let extraIPCPathLen = (isSOCKSIPC) ? 2 : 0;
    let ipcFileName;
    if (isControlIPC)
      ipcFileName = kControlIPCFileName;
    else if (isSOCKSIPC)
      ipcFileName = kSOCKSIPCFileName;

    // If this is the first request for an IPC path during this browser
    // session, remove the old temporary directory. This helps to keep /tmp
    // clean if the browser crashes or is killed.
    let ipcDirPath;
    if (isIPC && TLUtilInternal.mIsFirstIPCPathRequest)
    {
      this.cleanupTempDirectories();
      TLUtilInternal.mIsFirstIPCPathRequest = false;
    }
    else
    {
      // Retrieve path for IPC objects (it may have already been determined).
      ipcDirPath = this.getCharPref(TLUtilInternal.kIPCDirPrefName);
    }

    // First, check the _path preference for this file type.
501
    let prefName = "extensions.torlauncher." + aTorFileType + "_path";
502
    path = this.getCharPref(prefName);
503 504 505 506
    if (path)
    {
      let re = (this.isWindows) ?  /^[A-Za-z]:\\/ : /^\//;
      isRelativePath = !re.test(path);
507
      checkIPCPathLen = false; // always try to use path if provided in pref
508
    }
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
    else if (isIPC)
    {
      if (ipcDirPath)
      {
        // We have already determined where IPC objects will be placed.
        torFile = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
        torFile.initWithPath(ipcDirPath);
        torFile.append(ipcFileName);
        checkIPCPathLen = false; // already checked.
      }
      else
      {
        // If XDG_RUNTIME_DIR is set, use it as the base directory for IPC
        // objects (e.g., Unix domain sockets) -- assuming it is not too long.
        let env = Cc["@mozilla.org/process/environment;1"]
                    .getService(Ci.nsIEnvironment);
        if (env.exists("XDG_RUNTIME_DIR"))
        {
          let ipcDir = TLUtilInternal._createUniqueIPCDir(
                                               env.get("XDG_RUNTIME_DIR"));
          if (ipcDir)
          {
            let f = ipcDir.clone();
            f.append(ipcFileName);
            if (TLUtilInternal._isIPCPathLengthOK(f.path, extraIPCPathLen))
            {
              torFile = f;
              checkIPCPathLen = false; // no need to check again.

              // Store directory path so it can be reused for other IPC objects
              // and so it can be removed during exit.
              this.setCharPref(TLUtilInternal.kIPCDirPrefName, ipcDir.path);
            }
            else
            {
              // too long; remove the directory that we just created.
              ipcDir.remove(false);
            }
          }
        }
      }
    }

    if (!path && !torFile)
553
    {
554 555
      // No preference and no pre-determined IPC path: use a default path.
      isRelativePath = true;
556 557 558 559 560 561 562
      if (TLUtilInternal._isUserDataOutsideOfAppDir)
      {
        // This block is used for the TorBrowser-Data/ case.
        if (this.isWindows)
        {
          if ("tor" == aTorFileType)
            path = "TorBrowser\\Tor\\tor.exe";
563 564
          else if ("pt-startup-dir" == aTorFileType)
            useAppDir = true;
565 566 567 568 569 570
          else if ("torrc-defaults" == aTorFileType)
            path = "TorBrowser\\Tor\\torrc-defaults";
          else if ("torrc" == aTorFileType)
            path = "Tor\\torrc";
          else if ("tordatadir" == aTorFileType)
            path = "Tor";
571 572
          else if ("pt-profiles-dir" == aTorFileType)
            path = "Tor\\PluggableTransports";
573 574 575 576 577
        }
        else if (this.isMac)
        {
          if ("tor" == aTorFileType)
            path = "Contents/Resources/TorBrowser/Tor/tor";
578 579
          else if ("pt-startup-dir" == aTorFileType)
            path = "Contents/MacOS/Tor";
580 581 582 583 584 585
          else if ("torrc-defaults" == aTorFileType)
            path = "Contents/Resources/TorBrowser/Tor/torrc-defaults";
          else if ("torrc" == aTorFileType)
            path = "Tor/torrc";
          else if ("tordatadir" == aTorFileType)
            path = "Tor";
586 587
          else if ("pt-profiles-dir" == aTorFileType)
            path = "Tor/PluggableTransports";
588 589
          else if (isIPC)
            path = "Tor/" + ipcFileName;
590 591 592 593 594
        }
        else // Linux and others.
        {
          if ("tor" == aTorFileType)
            path = "TorBrowser/Tor/tor";
595 596
          else if ("pt-startup-dir" == aTorFileType)
            useAppDir = true;
597 598 599 600 601 602
          else if ("torrc-defaults" == aTorFileType)
            path = "TorBrowser/Tor/torrc-defaults";
          else if ("torrc" == aTorFileType)
            path = "Tor/torrc";
          else if ("tordatadir" == aTorFileType)
            path = "Tor";
603 604
          else if ("pt-profiles-dir" == aTorFileType)
            path = "Tor/PluggableTransports";
605 606
          else if (isIPC)
            path = "Tor/" + ipcFileName;
607 608 609 610 611 612 613
        }
      }
      else if (this.isWindows)
      {
        // This block is used for the non-TorBrowser-Data/ case.
        if ("tor" == aTorFileType)
          path = "Tor\\tor.exe";
614 615
        else if ("pt-startup-dir" == aTorFileType)
          useAppDir = true;
616 617 618 619 620 621
        else if ("torrc-defaults" == aTorFileType)
          path = "Data\\Tor\\torrc-defaults";
        else if ("torrc" == aTorFileType)
          path = "Data\\Tor\\torrc";
        else if ("tordatadir" == aTorFileType)
          path = "Data\\Tor";
622 623 624
        else if ("pt-profiles-dir" == aTorFileType)
          path = "Data\\Browser";
        }
625 626 627 628 629
      else // Linux, Mac OS and others.
      {
        // This block is also used for the non-TorBrowser-Data/ case.
        if ("tor" == aTorFileType)
          path = "Tor/tor";
630 631
        else if ("pt-startup-dir" == aTorFileType)
          useAppDir = true;
632 633 634 635 636 637
        else if ("torrc-defaults" == aTorFileType)
          path = "Data/Tor/torrc-defaults";
        else if ("torrc" == aTorFileType)
          path = "Data/Tor/torrc";
        else if ("tordatadir" == aTorFileType)
          path = "Data/Tor";
638 639
        else if ("pt-profiles-dir" == aTorFileType)
          path = "Data/Browser";
640 641
        else if (isIPC)
          path = "Data/Tor/" + ipcFileName;
642 643
      }

644
      if (!path && !useAppDir)
645 646
        return null;
    }
647 648 649

    try
    {
650 651 652 653 654
      if (useAppDir)
      {
        torFile = TLUtilInternal._appDir.clone();
      }
      else if (path)
655
      {
656
        if (isRelativePath)
657
        {
658 659 660 661 662 663 664 665 666 667 668 669 670
          // Turn 'path' into an absolute path.
          if (TLUtilInternal._isUserDataOutsideOfAppDir)
          {
            let baseDir = isUserData ? TLUtilInternal._dataDir
                                     : TLUtilInternal._appDir;
            torFile = baseDir.clone();
          }
          else
          {
            torFile = TLUtilInternal._appDir.clone();
            torFile.append("TorBrowser");
          }
          torFile.appendRelativePath(path);
671 672 673
        }
        else
        {
674 675
          torFile = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
          torFile.initWithPath(path);
676 677
        }

678
        if (!torFile.exists() && !isIPC && aCreate)
679
        {
680 681
          try
          {
682 683 684
            if (("tordatadir" == aTorFileType) ||
                ("pt-profiles-dir" == aTorFileType))
            {
Matthew Finkel's avatar
Matthew Finkel committed
685
              torFile.create(torFile.DIRECTORY_TYPE, 0o700);
686
            }
687
            else
688
            {
Matthew Finkel's avatar
Matthew Finkel committed
689
              torFile.create(torFile.NORMAL_FILE_TYPE, 0o600);
690
            }
691 692 693 694 695 696 697
          }
          catch (e)
          {
            TorLauncherLogger.safelog(4,
                                "unable to create " + torFile.path + ": ", e);
            return null;
          }
698 699 700
        }
      }

701 702
      // If the file exists or an IPC object was requested, normalize the path
      // and return a file object. The control and SOCKS IPC objects will be
703
      // created by tor.
704
      if (torFile.exists() || isIPC)
705
      {
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
        try { torFile.normalize(); } catch(e) {}

        // Ensure that the IPC path length is short enough for use by the
        // operating system. If not, create and use a unique directory under
        // /tmp for all IPC objects. The created directory path is stored in
        // a preference so it can be reused for other IPC objects and so it
        // can be removed during exit.
        if (isIPC && checkIPCPathLen &&
            !TLUtilInternal._isIPCPathLengthOK(torFile.path, extraIPCPathLen))
        {
          torFile = TLUtilInternal._createUniqueIPCDir("/tmp");
          if (!torFile)
          {
            TorLauncherLogger.log(4,
                              "failed to create unique directory under /tmp");
            return null;
          }

          this.setCharPref(TLUtilInternal.kIPCDirPrefName, torFile.path);
          torFile.append(ipcFileName);
        }

        return torFile;
729 730
      }

731 732
      TorLauncherLogger.log(4, aTorFileType + " file not found: "
                               + torFile.path);
733 734 735 736
    }
    catch(e)
    {
      TorLauncherLogger.safelog(4, "getTorFile " + aTorFileType +
737
                                   " failed for " + path + ": ", e);
738 739 740 741
    }

    return null;  // File not found or error (logged above).
  }, // getTorFile()
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757

  cleanupTempDirectories: function()
  {
    try
    {
      let dirPath = this.getCharPref(TLUtilInternal.kIPCDirPrefName);
      this.clearUserPref(TLUtilInternal.kIPCDirPrefName);
      if (dirPath)
      {
        let f = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
        f.initWithPath(dirPath);
        if (f.exists())
          f.remove(false); // Remove directory if it is empty
      }
    } catch(e) {}
  },
758 759 760 761 762 763 764 765
};


Object.freeze(TorLauncherUtil);


let TLUtilInternal =  // Private
{
766 767
  kThunderbirdID: "{3550f703-e582-4d05-9a08-453d09bdfdc6}",
  kInstantbirdID: "{33cb9019-c295-46dd-be21-8c4936574bee}",
768
  kIPCDirPrefName: "extensions.torlauncher.tmp_ipc_dir",
769

770 771 772
  mPrefsSvc : null,
  mStringBundle : null,
  mOS : "",
773 774 775 776 777
  // mIsUserDataOutsideOfAppDir is true when TorBrowser-Data is used.
  mIsUserDataOutsideOfAppDir: undefined, // Boolean (cached; access via
                                         //   this._isUserDataOutsideOfAppDir)
  mAppDir: null,        // nsIFile (cached; access via this._appDir)
  mDataDir: null,       // nsIFile (cached; access via this._dataDir)
778
  mIsFirstIPCPathRequest : true,
779 780 781
  mNumDefaultPrefsDefined: 0,
  mNumDefaultPrefsLoaded: 0,
  mDefaultPreferencesLoaded: false,
782 783 784 785 786 787 788

  _init: function()
  {
    this.mPrefsSvc = Cc["@mozilla.org/preferences-service;1"]
                       .getService(Ci.nsIPrefBranch);
  },

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
  _getPrefDefaultBranch: function(aBranchName)
  {
    return Cc["@mozilla.org/preferences-service;1"]
             .getService(Ci.nsIPrefService)
             .getDefaultBranch(aBranchName);
  },

  _setPref: function(aSetPrefFunc, aPrefName, aValue)
  {
    try
    {
      aSetPrefFunc(aPrefName, aValue);
    }
    catch(e)
    {
      TorLauncherLogger.log(5, "Setting default pref '" + aPrefName +
           "' threw exception: " + e);
      return false;
    }

    return true;
  },

  pref: function (aPrefName, aValue)
  {
    // Increment this counter for each pref() call.
    this.mNumDefaultPrefsDefined += 1;

    let lastPeriod = aPrefName.lastIndexOf(".");
    // This pref doesn't contain a period (".")
    // or the period is the first character.
    if (lastPeriod == 0 || lastPeriod == -1)
    {
      TorLauncherLogger.log(5, "Ignoring invalid pref '" + aPrefName + "'");
      return;
    }
    // This pref has a period at the last character, we can't set
    // a default value on a pref root.
    if (aPrefName.length == (lastPeriod + 1))
    {
      TorLauncherLogger.log(5,
            "Ignoring invalid pref ending with a period: '" + aPrefName + "'");
      return;
    }

    let prefRoot = aPrefName.substring(0, lastPeriod + 1);
    let defaultBranch = this._getPrefDefaultBranch(prefRoot);
    let prefName = aPrefName.substring(lastPeriod + 1);
    let setPrefFunc;
    switch (typeof aValue)
    {
      case "boolean":
        setPrefFunc = defaultBranch.setBoolPref;
        if (!this._setPref(setPrefFunc, prefName, aValue))
        {
          return;
        }
        break;
      case "number":
        setPrefFunc = defaultBranch.setIntPref;
        if (!this._setPref(setPrefFunc, prefName, aValue))
        {
          return;
        }
        break;
      case "string":
        setPrefFunc = defaultBranch.setCharPref;
        if (!this._setPref(setPrefFunc, prefName, aValue))
        {
          return;
        }
        break;
      default:
        TorLauncherLogger.log(5, "Cowardly not setting pref '" +
             aPrefName + "' of type '" + (typeof aValue) + "'");
        return;
    }

    // Increment this counter for each pref() call where the default preference
    // was successfully set.
    this.mNumDefaultPrefsLoaded += 1;
  },

  _loadPreferences: function()
  {
    if (this.mDefaultPreferencesLoaded)
    {
      return this.mDefaultPreferencesLoaded;
    }

879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
    // Check whether default preferences have already been loaded, e.g.,
    // because Tor Launcher is integrated into the browser rather than
    // running as an extension. This code assumes that a default value is
    // defined for extensions.torlauncher.loglevel.
    let prefName = "extensions.torlauncher.loglevel";
    let val;
    try
    {
      let defaultBranch = this._getPrefDefaultBranch(prefName);
      val = defaultBranch.getIntPref("");
    } catch (e) {}
    if (val !== undefined)
    {
      this.mDefaultPreferencesLoaded = true;
      return true;
    }

    // Use the JS subscript loaded in conjunction with our pref() function
    // to load the default preferences.
    const kPrefsURL =
          "resource://torlauncher/defaults/preferences/torlauncher-prefs.js";
900 901
    var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"]
                       .getService(Ci.mozIJSSubScriptLoader);
902
    loader.loadSubScript(kPrefsURL, this);
903 904 905 906 907 908

    this.mDefaultPreferencesLoaded =
          (this.mNumDefaultPrefsDefined == this.mNumDefaultPrefsLoaded);
    return this.mDefaultPreferencesLoaded;
  },

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
  get _stringBundle()
  {
    if (!this.mStringBundle)
    {
      this.mStringBundle = Cc["@mozilla.org/intl/stringbundle;1"]
                             .getService(Ci.nsIStringBundleService)
                             .createBundle(kPropBundleURI);
    }

    return this.mStringBundle;
  },

  get _OS()
  {
    if (!this.mOS) try
    {
      var xr = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
      this.mOS = xr.OS;
    } catch (e) {}

    return this.mOS;
  },
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013

  get _isMac()
  {
    return ("Darwin" == this._OS);
  },

  get _isUserDataOutsideOfAppDir()
  {
    if (this.mIsUserDataOutsideOfAppDir == undefined)
    {
      // Determine if we are using a "side-by-side" data model by checking
      // whether the user profile is outside of the app directory.
      try
      {
        let ds = Cc["@mozilla.org/file/directory_service;1"]
                        .getService(Ci.nsIProperties);
        let profDir = ds.get("ProfD", Ci.nsIFile);
        this.mIsUserDataOutsideOfAppDir = !this._appDir.contains(profDir);
      }
      catch (e)
      {
        this.mIsUserDataOutsideOfAppDir = false;
      }
    }

    return this.mIsUserDataOutsideOfAppDir;
  }, // get _isUserDataOutsideOfAppDir

  // Returns an nsIFile that points to the application directory.
  // May throw.
  get _appDir()
  {
    if (!this.mAppDir)
    {
      let topDir = Cc["@mozilla.org/file/directory_service;1"]
                    .getService(Ci.nsIProperties).get("CurProcD", Ci.nsIFile);
      let appInfo = Cc["@mozilla.org/xre/app-info;1"]
                      .getService(Ci.nsIXULAppInfo);
      // On Linux and Windows, we want to return the Browser/ directory.
      // Because topDir ("CurProcD") points to Browser/browser on those
      // platforms, we need to go up one level.
      // On Mac OS, we want to return the TorBrowser.app/ directory.
      // Because topDir points to Contents/Resources/browser on Mac OS,
      // we need to go up 3 levels.
      let tbbBrowserDepth = (this._isMac) ? 3 : 1;
      if ((appInfo.ID == this.kThunderbirdID) ||
          (appInfo.ID == this.kInstantbirdID))
      {
        // On Thunderbird/Instantbird, the topDir is the root dir and not
        // browser/, so we need to iterate one level less than Firefox.
        --tbbBrowserDepth;
      }

      while (tbbBrowserDepth > 0)
      {
        let didRemove = (topDir.leafName != ".");
        topDir = topDir.parent;
        if (didRemove)
          tbbBrowserDepth--;
      }

      this.mAppDir = topDir;
    }

    return this.mAppDir;
  }, // get _appDir

  // Returns an nsIFile that points to the TorBrowser-Data/ directory.
  // This function is only used when this._isUserDataOutsideOfAppDir == true.
  // May throw.
  get _dataDir()
  {
    if (!this.mDataDir)
    {
      let ds = Cc["@mozilla.org/file/directory_service;1"]
                      .getService(Ci.nsIProperties);
      let profDir = ds.get("ProfD", Ci.nsIFile);
      this.mDataDir = profDir.parent.parent;
    }

    return this.mDataDir;
  }, // get _dataDir

1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
  // Return true if aPath is short enough to be used as an IPC object path,
  // e.g., for a Unix domain socket path. aExtraLen is the "delta" necessary
  // to accommodate other IPC objects that have longer names; it is used to
  // account for "control.socket" vs. "socks.socket" (we want to ensure that
  // all IPC objects are placed in the same parent directory unless the user
  // has set prefs or env vars to explicitly specify the path for an object).
  // We enforce a maximum length of 100 because all operating systems allow
  // at least 100 characters for Unix domain socket paths.
  _isIPCPathLengthOK: function(aPath, aExtraLen)
  {
    const kMaxIPCPathLen = 100;
    return aPath && ((aPath.length + aExtraLen) <= kMaxIPCPathLen);
  },

  // Returns an nsIFile or null if a unique directory could not be created.
  _createUniqueIPCDir: function(aBasePath)
  {
    try
    {
      let d = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
      d.initWithPath(aBasePath);
      d.append("Tor");
Matthew Finkel's avatar
Matthew Finkel committed
1036
      d.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0o700);
1037 1038 1039 1040 1041 1042 1043 1044 1045
      return d;
    }
    catch (e)
    {
      TorLauncherLogger.safelog(4, "_createUniqueIPCDir failed for "
                                   + aBasePath + ": ", e);
      return null;
    }
  },
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059

  _isWindowVisible: function(aWindow)
  {
    if (!aWindow)
      return false;

    try {
      let winUtils = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
                            .getInterface(Ci.nsIDOMWindowUtils);
      return winUtils.isParentWindowMainWidgetVisible;
    } catch(e) {}

    return false;
  },
1060 1061 1062 1063
};


TLUtilInternal._init();