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 26.8 KB
Newer Older
1
// Copyright (c) 2018, 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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
  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;

222 223 224
    if ((aKeyword == "REASON") && aStatusObj.HOSTADDR)
      result += " - " + aStatusObj.HOSTADDR;

225 226 227
    return (result) ? result : "";
  },

228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  // 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;
  },

262 263 264 265 266 267 268 269 270
  setIntPref: function(aPrefName, aVal)
  {
    var val = (undefined != aVal) ? aVal : 0;
    try
    {
      TLUtilInternal.mPrefsSvc.setIntPref(aPrefName, val);
    } catch (e) {}
  },

271 272 273 274 275 276 277 278 279 280 281
  getCharPref: function(aPrefName, aDefaultVal)
  {
    var rv = aDefaultVal ? aDefaultVal : "";

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

    return rv;
  },
282

283 284 285 286 287 288 289 290
  setCharPref: function(aPrefName, aVal)
  {
    try
    {
      TLUtilInternal.mPrefsSvc.setCharPref(aPrefName, aVal ? aVal : "");
    } catch (e) {}
  },

291 292 293 294 295 296 297 298
  clearUserPref: function(aPrefName)
  {
    try
    {
      TLUtilInternal.mPrefsSvc.clearUserPref(aPrefName);
    } catch (e) {}
  },

299 300 301 302 303 304 305
  getPrefBranch: function(aBranchName)
  {
    return Cc["@mozilla.org/preferences-service;1"]
             .getService(Ci.nsIPrefService)
             .getBranch(aBranchName);
  },

306 307 308 309 310 311 312 313 314 315 316 317 318
  // 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;
  },

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

335 336
  get shouldPromptForLocale()
  {
337 338 339 340
    // 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";
341 342 343 344 345 346 347 348 349 350
    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) {}

351
    return this.getBoolPref(kPrefPromptForLocale, true); */
352 353
  },

354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
  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);
  },

370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
  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);
  },
385 386 387 388 389 390

  // Returns an array of strings or undefined if none are available.
  get defaultBridgeTypes()
  {
    try
    {
391
      var prefBranch = this.getPrefBranch(kPrefBranchDefaultBridge);
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
      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
    {
418
      var prefBranch = this.getPrefBranch(kPrefBranchDefaultBridge);
419 420 421 422 423 424 425 426 427 428 429 430 431 432
      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);
        }
      }
433
      this.rearrangeBridges(bridgeArray);
434 435 436 437 438 439

      return bridgeArray;
    } catch(e) {};

    return undefined;
  },
440 441

  // Returns an nsIFile.
442 443
  // If aTorFileType is "control_ipc" or "socks_ipc", aCreate is ignored
  // and there is no requirement that the IPC object exists.
444 445 446 447 448 449 450
  // 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;

451 452 453 454
    let torFile;  // an nsIFile to be returned
    let path;     // a relative or absolute path that will determine torFile

    let isRelativePath = false;
455
    let isUserData = (aTorFileType != "tor") &&
456
                     (aTorFileType != "pt-startup-dir") &&
457
                     (aTorFileType != "torrc-defaults");
458 459 460
    let isControlIPC = ("control_ipc" == aTorFileType);
    let isSOCKSIPC = ("socks_ipc" == aTorFileType);
    let isIPC = isControlIPC || isSOCKSIPC;
461
    let checkIPCPathLen = true;
462
    let useAppDir = false;
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

    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.
489
    let prefName = "extensions.torlauncher." + aTorFileType + "_path";
490
    path = this.getCharPref(prefName);
491 492 493 494
    if (path)
    {
      let re = (this.isWindows) ?  /^[A-Za-z]:\\/ : /^\//;
      isRelativePath = !re.test(path);
495
      checkIPCPathLen = false; // always try to use path if provided in pref
496
    }
497 498 499 500 501 502 503 504 505 506 507 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
    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)
541
    {
542 543
      // No preference and no pre-determined IPC path: use a default path.
      isRelativePath = true;
544 545 546 547 548 549 550
      if (TLUtilInternal._isUserDataOutsideOfAppDir)
      {
        // This block is used for the TorBrowser-Data/ case.
        if (this.isWindows)
        {
          if ("tor" == aTorFileType)
            path = "TorBrowser\\Tor\\tor.exe";
551 552
          else if ("pt-startup-dir" == aTorFileType)
            useAppDir = true;
553 554 555 556 557 558 559 560 561 562 563
          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";
564 565
          else if ("pt-startup-dir" == aTorFileType)
            path = "Contents/MacOS/Tor";
566 567 568 569 570 571
          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";
572 573
          else if (isIPC)
            path = "Tor/" + ipcFileName;
574 575 576 577 578
        }
        else // Linux and others.
        {
          if ("tor" == aTorFileType)
            path = "TorBrowser/Tor/tor";
579 580
          else if ("pt-startup-dir" == aTorFileType)
            useAppDir = true;
581 582 583 584 585 586
          else if ("torrc-defaults" == aTorFileType)
            path = "TorBrowser/Tor/torrc-defaults";
          else if ("torrc" == aTorFileType)
            path = "Tor/torrc";
          else if ("tordatadir" == aTorFileType)
            path = "Tor";
587 588
          else if (isIPC)
            path = "Tor/" + ipcFileName;
589 590 591 592 593 594 595
        }
      }
      else if (this.isWindows)
      {
        // This block is used for the non-TorBrowser-Data/ case.
        if ("tor" == aTorFileType)
          path = "Tor\\tor.exe";
596 597
        else if ("pt-startup-dir" == aTorFileType)
          useAppDir = true;
598 599 600 601 602 603 604 605 606 607 608 609
        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";
610 611
        else if ("pt-startup-dir" == aTorFileType)
          useAppDir = true;
612 613 614 615 616 617
        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";
618 619
        else if (isIPC)
          path = "Data/Tor/" + ipcFileName;
620 621
      }

622
      if (!path && !useAppDir)
623 624
        return null;
    }
625 626 627

    try
    {
628 629 630 631 632
      if (useAppDir)
      {
        torFile = TLUtilInternal._appDir.clone();
      }
      else if (path)
633
      {
634
        if (isRelativePath)
635
        {
636 637 638 639 640 641 642 643 644 645 646 647 648
          // 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);
649 650 651
        }
        else
        {
652 653
          torFile = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
          torFile.initWithPath(path);
654 655
        }

656
        if (!torFile.exists() && !isIPC && aCreate)
657
        {
658 659 660
          try
          {
            if ("tordatadir" == aTorFileType)
Matthew Finkel's avatar
Matthew Finkel committed
661
              torFile.create(torFile.DIRECTORY_TYPE, 0o700);
662
            else
Matthew Finkel's avatar
Matthew Finkel committed
663
              torFile.create(torFile.NORMAL_FILE_TYPE, 0o600);
664 665 666 667 668 669 670
          }
          catch (e)
          {
            TorLauncherLogger.safelog(4,
                                "unable to create " + torFile.path + ": ", e);
            return null;
          }
671 672 673
        }
      }

674 675
      // 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
676
      // created by tor.
677
      if (torFile.exists() || isIPC)
678
      {
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
        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;
702 703
      }

704 705
      TorLauncherLogger.log(4, aTorFileType + " file not found: "
                               + torFile.path);
706 707 708 709
    }
    catch(e)
    {
      TorLauncherLogger.safelog(4, "getTorFile " + aTorFileType +
710
                                   " failed for " + path + ": ", e);
711 712 713 714
    }

    return null;  // File not found or error (logged above).
  }, // getTorFile()
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730

  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) {}
  },
731 732 733 734 735 736 737 738
};


Object.freeze(TorLauncherUtil);


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

743 744 745
  mPrefsSvc : null,
  mStringBundle : null,
  mOS : "",
746 747 748 749 750
  // 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)
751
  mIsFirstIPCPathRequest : true,
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

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

  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

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
  // 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
886
      d.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0o700);
887 888 889 890 891 892 893 894 895
      return d;
    }
    catch (e)
    {
      TorLauncherLogger.safelog(4, "_createUniqueIPCDir failed for "
                                   + aBasePath + ": ", e);
      return null;
    }
  },
896 897 898 899 900 901 902 903 904 905 906 907 908 909

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

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

    return false;
  },
910 911 912 913
};


TLUtilInternal._init();