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 25.3 KB
Newer Older
1
// Copyright (c) 2017, 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 kPropBundleURI = "chrome://torlauncher/locale/torlauncher.properties";
16 17
const kPropNamePrefix = "torlauncher.";

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

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

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

34 35 36 37 38 39 40 41 42
  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);
  },

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

      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);
    }
  },

69 70 71
  // 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.
72 73
  showConfirm: function(aParentWindow, aMsg, aDefaultButtonLabel,
                        aCancelButtonLabel)
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
  {
    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
93
                     + (ps.BUTTON_POS_1 * ps.BUTTON_TITLE_IS_STRING);
94 95 96

      var notUsed = { value: false };
      var btnIndex =  ps.confirmEx(aParentWindow, title, aMsg, btnFlags,
97 98
                                   aDefaultButtonLabel, aCancelButtonLabel,
                                   null, null, notUsed);
99 100 101 102 103 104 105 106 107 108
      return (0 == btnIndex);
    }
    catch (e)
    {
      return confirm(aMsg);
    }

    return false;
  },

109 110 111 112 113 114 115 116 117 118
  showSaveSettingsAlert: function(aParentWindow, aDetails)
  {
    if (!aDetails)
      aDetails = TorLauncherUtil.getLocalizedString("ensure_tor_is_running");

    var s = TorLauncherUtil.getFormattedLocalizedString(
                                  "failed_to_save_settings", [aDetails], 1);
    this.showAlert(aParentWindow, s);
  },

119
  // Localized Strings
120 121 122 123
  flushLocalizedStringCache: function()
  {
    TLUtilInternal.mStringBundle = undefined;
  },
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

  // "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;
  },

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
  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")
      {
        if ("onehop_create" == val)
          val = "handshake_dir";
        else if ("circuit_create" == val)
          val = "handshake_or";

        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;

194 195 196
    if ((aKeyword == "REASON") && aStatusObj.HOSTADDR)
      result += " - " + aStatusObj.HOSTADDR;

197 198 199
    return (result) ? result : "";
  },

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
  // Preferences
  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;
  },

234 235 236 237 238 239 240 241 242
  setIntPref: function(aPrefName, aVal)
  {
    var val = (undefined != aVal) ? aVal : 0;
    try
    {
      TLUtilInternal.mPrefsSvc.setIntPref(aPrefName, val);
    } catch (e) {}
  },

243 244 245 246 247 248 249 250 251 252 253
  getCharPref: function(aPrefName, aDefaultVal)
  {
    var rv = aDefaultVal ? aDefaultVal : "";

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

    return rv;
  },
254

255 256 257 258 259 260 261 262
  setCharPref: function(aPrefName, aVal)
  {
    try
    {
      TLUtilInternal.mPrefsSvc.setCharPref(aPrefName, aVal ? aVal : "");
    } catch (e) {}
  },

263 264 265 266 267 268 269 270
  clearUserPref: function(aPrefName)
  {
    try
    {
      TLUtilInternal.mPrefsSvc.clearUserPref(aPrefName);
    } catch (e) {}
  },

271 272 273 274 275 276 277 278 279 280 281 282 283
  // 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;
  },

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
  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);
  },
299

300 301
  get shouldPromptForLocale()
  {
302 303 304 305
    // 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";
306 307 308 309 310 311 312 313 314 315
    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) {}

316
    return this.getBoolPref(kPrefPromptForLocale, true); */
317 318
  },

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
  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);
  },

335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
  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);
  },
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401

  // Returns an array of strings or undefined if none are available.
  get defaultBridgeTypes()
  {
    try
    {
      var prefBranch = Cc["@mozilla.org/preferences-service;1"]
                           .getService(Ci.nsIPrefService)
                           .getBranch("extensions.torlauncher.default_bridge.");
      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
    {
      var prefBranch = Cc["@mozilla.org/preferences-service;1"]
                           .getService(Ci.nsIPrefService)
                           .getBranch("extensions.torlauncher.default_bridge.");
      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);
        }
      }
402
      this.rearrangeBridges(bridgeArray);
403 404 405 406 407 408

      return bridgeArray;
    } catch(e) {};

    return undefined;
  },
409 410

  // Returns an nsIFile.
411 412
  // If aTorFileType is "control_ipc" or "socks_ipc", aCreate is ignored
  // and there is no requirement that the IPC object exists.
413 414 415 416 417 418 419
  // 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;

420 421 422 423
    let torFile;  // an nsIFile to be returned
    let path;     // a relative or absolute path that will determine torFile

    let isRelativePath = false;
424 425
    let isUserData = (aTorFileType != "tor") &&
                     (aTorFileType != "torrc-defaults");
426 427 428
    let isControlIPC = ("control_ipc" == aTorFileType);
    let isSOCKSIPC = ("socks_ipc" == aTorFileType);
    let isIPC = isControlIPC || isSOCKSIPC;
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    let checkIPCPathLen = true;

    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.
456
    let prefName = "extensions.torlauncher." + aTorFileType + "_path";
457
    path = this.getCharPref(prefName);
458 459 460 461
    if (path)
    {
      let re = (this.isWindows) ?  /^[A-Za-z]:\\/ : /^\//;
      isRelativePath = !re.test(path);
462
      checkIPCPathLen = false; // always try to use path if provided in pref
463
    }
464 465 466 467 468 469 470 471 472 473 474 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 501 502 503 504 505 506 507
    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)
508
    {
509 510
      // No preference and no pre-determined IPC path: use a default path.
      isRelativePath = true;
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
      if (TLUtilInternal._isUserDataOutsideOfAppDir)
      {
        // This block is used for the TorBrowser-Data/ case.
        if (this.isWindows)
        {
          if ("tor" == aTorFileType)
            path = "TorBrowser\\Tor\\tor.exe";
          else if ("torrc-defaults" == aTorFileType)
            path = "TorBrowser\\Tor\\torrc-defaults";
          else if ("torrc" == aTorFileType)
            path = "Tor\\torrc";
          else if ("tordatadir" == aTorFileType)
            path = "Tor";
        }
        else if (this.isMac)
        {
          if ("tor" == aTorFileType)
            path = "Contents/Resources/TorBrowser/Tor/tor";
          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";
535 536
          else if (isIPC)
            path = "Tor/" + ipcFileName;
537 538 539 540 541 542 543 544 545 546 547
        }
        else // Linux and others.
        {
          if ("tor" == aTorFileType)
            path = "TorBrowser/Tor/tor";
          else if ("torrc-defaults" == aTorFileType)
            path = "TorBrowser/Tor/torrc-defaults";
          else if ("torrc" == aTorFileType)
            path = "Tor/torrc";
          else if ("tordatadir" == aTorFileType)
            path = "Tor";
548 549
          else if (isIPC)
            path = "Tor/" + ipcFileName;
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
        }
      }
      else if (this.isWindows)
      {
        // This block is used for the non-TorBrowser-Data/ case.
        if ("tor" == aTorFileType)
          path = "Tor\\tor.exe";
        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";
      }
      else // Linux, Mac OS and others.
      {
        // This block is also used for the non-TorBrowser-Data/ case.
        if ("tor" == aTorFileType)
          path = "Tor/tor";
        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";
575 576
        else if (isIPC)
          path = "Data/Tor/" + ipcFileName;
577 578
      }

579 580 581
      if (!path)
        return null;
    }
582 583 584

    try
    {
585
      if (path)
586
      {
587
        if (isRelativePath)
588
        {
589 590 591 592 593 594 595 596 597 598 599 600 601
          // 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);
602 603 604
        }
        else
        {
605 606
          torFile = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
          torFile.initWithPath(path);
607 608
        }

609
        if (!torFile.exists() && !isIPC && aCreate)
610
        {
611 612 613 614 615 616 617 618 619 620 621 622 623
          try
          {
            if ("tordatadir" == aTorFileType)
              torFile.create(torFile.DIRECTORY_TYPE, 0700);
            else
              torFile.create(torFile.NORMAL_FILE_TYPE, 0600);
          }
          catch (e)
          {
            TorLauncherLogger.safelog(4,
                                "unable to create " + torFile.path + ": ", e);
            return null;
          }
624 625 626
        }
      }

627 628
      // 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
629
      // created by tor.
630
      if (torFile.exists() || isIPC)
631
      {
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
        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;
655 656
      }

657 658
      TorLauncherLogger.log(4, aTorFileType + " file not found: "
                               + torFile.path);
659 660 661 662
    }
    catch(e)
    {
      TorLauncherLogger.safelog(4, "getTorFile " + aTorFileType +
663
                                   " failed for " + path + ": ", e);
664 665 666 667
    }

    return null;  // File not found or error (logged above).
  }, // getTorFile()
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683

  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) {}
  },
684 685 686 687 688 689 690 691
};


Object.freeze(TorLauncherUtil);


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

696 697 698
  mPrefsSvc : null,
  mStringBundle : null,
  mOS : "",
699 700 701 702 703
  // 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)
704
  mIsFirstIPCPathRequest : true,
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733

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

  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;
  },
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 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

  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

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
  // 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");
      d.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0700);
      return d;
    }
    catch (e)
    {
      TorLauncherLogger.safelog(4, "_createUniqueIPCDir failed for "
                                   + aBasePath + ": ", e);
      return null;
    }
  },
849 850 851 852
};


TLUtilInternal._init();