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 30.3 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
  // Preferences
229 230 231 232 233
  loadDefaultPreferences: function()
  {
    return TLUtilInternal._loadPreferences();
  },

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 262 263 264 265 266
  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;
  },

267 268 269 270 271 272 273 274 275
  setIntPref: function(aPrefName, aVal)
  {
    var val = (undefined != aVal) ? aVal : 0;
    try
    {
      TLUtilInternal.mPrefsSvc.setIntPref(aPrefName, val);
    } catch (e) {}
  },

276 277 278 279 280 281 282 283 284 285 286
  getCharPref: function(aPrefName, aDefaultVal)
  {
    var rv = aDefaultVal ? aDefaultVal : "";

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

    return rv;
  },
287

288 289 290 291 292 293 294 295
  setCharPref: function(aPrefName, aVal)
  {
    try
    {
      TLUtilInternal.mPrefsSvc.setCharPref(aPrefName, aVal ? aVal : "");
    } catch (e) {}
  },

296 297 298 299 300 301 302 303
  clearUserPref: function(aPrefName)
  {
    try
    {
      TLUtilInternal.mPrefsSvc.clearUserPref(aPrefName);
    } catch (e) {}
  },

304 305 306 307 308 309 310
  getPrefBranch: function(aBranchName)
  {
    return Cc["@mozilla.org/preferences-service;1"]
             .getService(Ci.nsIPrefService)
             .getBranch(aBranchName);
  },

311 312 313 314 315 316 317 318 319 320 321 322 323
  // 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;
  },

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
  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);
  },
339

340 341
  get shouldPromptForLocale()
  {
342 343 344 345
    // 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";
346 347 348 349 350 351 352 353 354 355
    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) {}

356
    return this.getBoolPref(kPrefPromptForLocale, true); */
357 358
  },

359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
  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);
  },

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
  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);
  },
390 391 392 393 394 395

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

      return bridgeArray;
    } catch(e) {};

    return undefined;
  },
445 446

  // Returns an nsIFile.
447 448
  // If aTorFileType is "control_ipc" or "socks_ipc", aCreate is ignored
  // and there is no requirement that the IPC object exists.
449 450 451 452 453 454 455
  // 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;

456 457 458 459
    let torFile;  // an nsIFile to be returned
    let path;     // a relative or absolute path that will determine torFile

    let isRelativePath = false;
460
    let isUserData = (aTorFileType != "tor") &&
461
                     (aTorFileType != "pt-startup-dir") &&
462
                     (aTorFileType != "torrc-defaults");
463 464 465
    let isControlIPC = ("control_ipc" == aTorFileType);
    let isSOCKSIPC = ("socks_ipc" == aTorFileType);
    let isIPC = isControlIPC || isSOCKSIPC;
466
    let checkIPCPathLen = true;
467
    let useAppDir = false;
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

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

637
      if (!path && !useAppDir)
638 639
        return null;
    }
640 641 642

    try
    {
643 644 645 646 647
      if (useAppDir)
      {
        torFile = TLUtilInternal._appDir.clone();
      }
      else if (path)
648
      {
649
        if (isRelativePath)
650
        {
651 652 653 654 655 656 657 658 659 660 661 662 663
          // 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);
664 665 666
        }
        else
        {
667 668
          torFile = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
          torFile.initWithPath(path);
669 670
        }

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

694 695
      // 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
696
      // created by tor.
697
      if (torFile.exists() || isIPC)
698
      {
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
        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;
722 723
      }

724 725
      TorLauncherLogger.log(4, aTorFileType + " file not found: "
                               + torFile.path);
726 727 728 729
    }
    catch(e)
    {
      TorLauncherLogger.safelog(4, "getTorFile " + aTorFileType +
730
                                   " failed for " + path + ": ", e);
731 732 733 734
    }

    return null;  // File not found or error (logged above).
  }, // getTorFile()
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750

  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) {}
  },
751 752 753 754 755 756 757 758
};


Object.freeze(TorLauncherUtil);


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

763 764 765
  mPrefsSvc : null,
  mStringBundle : null,
  mOS : "",
766 767 768 769 770
  // 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)
771
  mIsFirstIPCPathRequest : true,
772 773 774
  mNumDefaultPrefsDefined: 0,
  mNumDefaultPrefsLoaded: 0,
  mDefaultPreferencesLoaded: false,
775 776 777 778 779 780 781

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

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 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
  _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;
    }

    var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"]
                       .getService(Ci.mozIJSSubScriptLoader);
    loader.loadSubScript(
            "resource://torlauncher/defaults/preferences/prefs.js", this);

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

882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
  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;
  },
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 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

  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

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
  // 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
1009
      d.createUnique(Ci.nsIFile.DIRECTORY_TYPE, 0o700);
1010 1011 1012 1013 1014 1015 1016 1017 1018
      return d;
    }
    catch (e)
    {
      TorLauncherLogger.safelog(4, "_createUniqueIPCDir failed for "
                                   + aBasePath + ": ", e);
      return null;
    }
  },
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032

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

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

    return false;
  },
1033 1034 1035 1036
};


TLUtilInternal._init();