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 19.3 KB
Newer Older
1
// Copyright (c) 2016, 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 234 235 236 237 238 239 240 241 242 243 244
  // 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;
  },

  getCharPref: function(aPrefName, aDefaultVal)
  {
    var rv = aDefaultVal ? aDefaultVal : "";

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

    return rv;
  },
245

246 247 248 249 250 251 252 253
  setCharPref: function(aPrefName, aVal)
  {
    try
    {
      TLUtilInternal.mPrefsSvc.setCharPref(aPrefName, aVal ? aVal : "");
    } catch (e) {}
  },

254 255 256 257 258 259 260 261 262 263 264 265 266
  // 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;
  },

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
  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);
  },
282

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
  get shouldPromptForLocale()
  {
    const kPrefPromptForLocale = "extensions.torlauncher.prompt_for_locale";
    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) {}

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

299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
  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);
  },

315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
  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);
  },
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 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

  // 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);
        }
      }
382
      this.rearrangeBridges(bridgeArray);
383 384 385 386 387 388

      return bridgeArray;
    } catch(e) {};

    return undefined;
  },
389 390 391 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 418 419 420 421 422 423 424 425 426 427 428 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 456 457 458 459 460 461 462 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 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

  // Returns an nsIFile.
  // If aTorFileType is "control_socket", aCreate is ignored and there is
  // no requirement that the socket exist.
  // 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;

    let isRelativePath = true;
    let isUserData = (aTorFileType != "tor") &&
                     (aTorFileType != "torrc-defaults");
    let isControlSocket = ("control_socket" == aTorFileType);
    let prefName = "extensions.torlauncher." + aTorFileType + "_path";
    let path = this.getCharPref(prefName);
    if (path)
    {
      let re = (this.isWindows) ?  /^[A-Za-z]:\\/ : /^\//;
      isRelativePath = !re.test(path);
    }
    else
    {
      // Get default path.
      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";
          else if (isControlSocket)
            path = "Tor/control.socket";
        }
        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";
          else if (isControlSocket)
            path = "Tor/control.socket";
        }
      }
      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";
        else if (isControlSocket)
          path = "Data/Tor/control.socket";
      }
    }

    if (!path)
      return null;

    try
    {
      let f;
      if (isRelativePath)
      {
        // Turn 'path' into an absolute path.
        if (TLUtilInternal._isUserDataOutsideOfAppDir)
        {
          let baseDir = isUserData ? TLUtilInternal._dataDir
                                   : TLUtilInternal._appDir;
          f = baseDir.clone();
        }
        else
        {
          f = TLUtilInternal._appDir.clone();
          f.append("TorBrowser");
        }
        f.appendRelativePath(path);
      }
      else
      {
        f = Cc['@mozilla.org/file/local;1'].createInstance(Ci.nsIFile);
        f.initWithPath(path);
      }

      if (!f.exists() && !isControlSocket && aCreate)
      {
        try
        {
          if ("tordatadir" == aTorFileType)
            f.create(f.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
          else
            f.create(f.NORMAL_FILE_TYPE, FileUtils.PERMS_FILE);
        }
        catch (e)
        {
          TorLauncherLogger.safelog(4, "unable to create " + f.path + ": ", e);
          return null;
        }
      }

      // If the file exists or the control socket was requested, normalize
      // the path and return a file object. The control socket will be
      // created by tor.
      if (f.exists() || isControlSocket)
      {
        try { f.normalize(); } catch(e) {}
        return f;
      }

      TorLauncherLogger.log(4, aTorFileType + " file not found: " + f.path);
    }
    catch(e)
    {
      TorLauncherLogger.safelog(4, "getTorFile " + aTorFileType +
                                     " failed for " + path + ": ", e);
    }

    return null;  // File not found or error (logged above).
  }, // getTorFile()
546 547 548 549 550 551 552 553
};


Object.freeze(TorLauncherUtil);


let TLUtilInternal =  // Private
{
554 555 556
  kThunderbirdID: "{3550f703-e582-4d05-9a08-453d09bdfdc6}",
  kInstantbirdID: "{33cb9019-c295-46dd-be21-8c4936574bee}",

557 558 559
  mPrefsSvc : null,
  mStringBundle : null,
  mOS : "",
560 561 562 563 564
  // 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)
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593

  _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;
  },
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676

  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

677 678 679 680
};


TLUtilInternal._init();