home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 35 Internet / 35-Internet.zip / phoenx05.zip / phoenix / components / nsProxyAutoConfig.js < prev    next >
Text File  |  2002-12-10  |  17KB  |  465 lines

  1. /* -*- Mode: Java; tab-width: 4; c-basic-offset: 4; -*- */
  2. /* ***** BEGIN LICENSE BLOCK *****
  3.  * Version: NPL 1.1/GPL 2.0/LGPL 2.1
  4.  *
  5.  * The contents of this file are subject to the Netscape Public License
  6.  * Version 1.1 (the "License"); you may not use this file except in
  7.  * compliance with the License. You may obtain a copy of the License at
  8.  * http://www.mozilla.org/NPL/
  9.  *
  10.  * Software distributed under the License is distributed on an "AS IS" basis,
  11.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12.  * for the specific language governing rights and limitations under the
  13.  * License.
  14.  *
  15.  * The Original Code is mozilla.org code.
  16.  *
  17.  * The Initial Developer of the Original Code is 
  18.  * Netscape Communications Corporation.
  19.  * Portions created by the Initial Developer are Copyright (C) 1998
  20.  * the Initial Developer. All Rights Reserved.
  21.  *
  22.  * Contributor(s):
  23.  *   Akhil Arora <akhil.arora@sun.com>
  24.  *   Tomi Leppikangas <Tomi.Leppikangas@oulu.fi>
  25.  *
  26.  * Alternatively, the contents of this file may be used under the terms of
  27.  * either the GNU General Public License Version 2 or later (the "GPL"), or 
  28.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  29.  * in which case the provisions of the GPL or the LGPL are applicable instead
  30.  * of those above. If you wish to allow use of your version of this file only
  31.  * under the terms of either the GPL or the LGPL, and not to allow others to
  32.  * use your version of this file under the terms of the NPL, indicate your
  33.  * decision by deleting the provisions above and replace them with the notice
  34.  * and other provisions required by the GPL or the LGPL. If you do not delete
  35.  * the provisions above, a recipient may use your version of this file under
  36.  * the terms of any one of the NPL, the GPL or the LGPL.
  37.  *
  38.  * ***** END LICENSE BLOCK ***** */
  39.  
  40. /*
  41.    Script for Proxy Auto Config in the new world order.
  42.        - Gagan Saksena 04/24/00 
  43. */
  44.  
  45. const kPAC_CONTRACTID = "@mozilla.org/network/proxy_autoconfig;1";
  46. const kIOSERVICE_CONTRACTID = "@mozilla.org/network/io-service;1";
  47. const kDNS_CONTRACTID = "@mozilla.org/network/dns-service;1";
  48. const kPAC_CID = Components.ID("{63ac8c66-1dd2-11b2-b070-84d00d3eaece}");
  49. const nsIProxyAutoConfig = Components.interfaces.nsIProxyAutoConfig;
  50. const nsIIOService = Components.interfaces['nsIIOService'];
  51. const nsIDNSService = Components.interfaces.nsIDNSService;
  52. const nsIRequest = Components.interfaces.nsIRequest;
  53.  
  54. // implementor of nsIProxyAutoConfig
  55. function nsProxyAutoConfig() {};
  56.  
  57. // global variable that will hold the downloaded js 
  58. var pac = null;
  59. //hold PAC's URL, used in evalAsCodebase()
  60. var pacURL;
  61. // ptr to eval'ed FindProxyForURL function
  62. var LocalFindProxyForURL=null;
  63. // sendbox in which we eval loaded autoconfig js file
  64. var ProxySandBox = null;
  65.  
  66. nsProxyAutoConfig.prototype = {
  67.     sis: null,
  68.     done: false,
  69.  
  70.     ProxyForURL: function(url, host, port, type) {
  71.         /* If we're not done loading the pac yet, wait (ideally). For
  72.            now, just return DIRECT to avoid loops. A simple mutex
  73.            between ProxyForURL and LoadPACFromURL locks-up the
  74.            browser. */
  75.         if (!this.done) {
  76.             host.value = null;
  77.             type.value = "direct";
  78.             return;
  79.         }
  80.  
  81.         var uri = url.QueryInterface(Components.interfaces.nsIURI);
  82.         // Call the original function-
  83.         var proxy = LocalFindProxyForURL(uri.spec, uri.host);
  84.         if(proxy == null) {
  85.             return;
  86.         }
  87.  
  88.         /* we ignore everything else past the first proxy.
  89.            we could theoretically check isResolvable now and continue
  90.            parsing (see bug 84798). but for now... */
  91.         proxy = proxy.split(";")[0];
  92.  
  93.         // direct connection (no proxy)
  94.         if ( proxy.search(/^\s*DIRECT\s*$/i) != -1 ) {
  95.             host.value = null;
  96.             type.value = "direct";
  97.         }
  98.         else {
  99.             // split proxy string to find proxy type, proxy host and port number
  100.             var typehostport = /^\s*(\w+)\s+([^:]+)(:\d+)?/(proxy);
  101.             if(typehostport != null) {
  102.                 host.value = typehostport[2];
  103.                 typehostport[1] = typehostport[1].toUpperCase();
  104.  
  105.                 switch(typehostport[1]) {
  106.                     case "PROXY": // http PROXY              
  107.                         // assume port 80 if port number not specified (see bug 91630)
  108.                         port.value = (typehostport[3] != null)? typehostport[3].substr(1): 80;
  109.                         type.value = "http";
  110.                         break;
  111.                     case "SOCKS": // SOCKS v4
  112.                         // assume port 1080 like NN4 if port number not specified
  113.                         port.value = (typehostport[3] != null)? typehostport[3].substr(1): 1080;
  114.                         type.value = "socks4";
  115.                         break;
  116.                     // Currently only SOCKS v4 is supported (see bug 78176)                      
  117.                 }
  118.             }
  119.         }
  120.     },
  121.  
  122.     LoadPACFromURL: function(uri, ioService) {
  123.         this.done = false;
  124.         var channel = ioService.newChannelFromURI(uri);
  125.         // don't cache the PAC content
  126.         channel.loadFlags |= nsIRequest.LOAD_BYPASS_CACHE;
  127.         pacURL = uri.spec;
  128.         channel.asyncOpen(this, null);
  129.     },
  130.  
  131.     // nsIStreamListener interface
  132.     onStartRequest: function(request, ctxt) { 
  133.         pac = '';
  134.         LocalFindProxyForURL=null;
  135.         this.sis = 
  136.         Components.Constructor('@mozilla.org/scriptableinputstream;1',
  137.                                'nsIScriptableInputStream', 
  138.                                'init');
  139.     },
  140.  
  141.     onStopRequest: function(request, ctxt, status, errorMsg) {
  142.         if(!ProxySandBox) {
  143.            ProxySandBox = new Sandbox();
  144.         }
  145.         // add predefined functions to pac
  146.         var mypac = pacUtils + pac;
  147.         // evaluate loded js file
  148.         evalInSandbox(mypac, ProxySandBox, pacURL);
  149.         try {
  150.             ProxySandBox.myIP = dns.myIPAddress;
  151.         } catch (e) {
  152.             // Well, theres nothing better.
  153.             // see bugs 80363 and 92516.
  154.             ProxySandBox.myIP = "127.0.0.1";
  155.         }
  156.         ProxySandBox.dnsResolve = dnsResolve;
  157.         LocalFindProxyForURL=ProxySandBox.FindProxyForURL;
  158.         this.done = true;
  159.     },
  160.  
  161.     onDataAvailable: function(request, ctxt, inStream, sourceOffset, count) {
  162.         var ins = new this.sis(inStream);
  163.         pac += ins.read(count);
  164.     }
  165. }
  166.  
  167. // Synchronous calls to nsDNSService::Resolve ignore the cache! (bug 97097)
  168. // Keep a simple one of our own.
  169. var dnsResolveCachedHost = null;
  170. var dnsResolveCachedIp = null;
  171.  
  172. // wrapper for dns.resolve to catch exception on failure
  173. function dnsResolve(host) {
  174.     if (host == dnsResolveCachedHost) {
  175.         return dnsResolveCachedIp;
  176.     }
  177.     dnsResolveCachedHost = host;
  178.     try {
  179.         dnsResolveCachedIp = dns.resolve(host);
  180.     }
  181.     catch (e) {
  182.         dnsResolveCachedIp = null;
  183.     }
  184.     return dnsResolveCachedIp;
  185. }
  186.  
  187. var pacModule = new Object();
  188.  
  189. pacModule.registerSelf =
  190.     function (compMgr, fileSpec, location, type) {
  191.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  192.         compMgr.registerFactoryLocation(kPAC_CID,
  193.                                         "Proxy Auto Config",
  194.                                         kPAC_CONTRACTID,
  195.                                         fileSpec, 
  196.                                         location, 
  197.                                         type);
  198.     }
  199.  
  200. pacModule.getClassObject =
  201. function (compMgr, cid, iid) {
  202.         if (!cid.equals(kPAC_CID))
  203.             throw Components.results.NS_ERROR_NO_INTERFACE;
  204.  
  205.         if (!iid.equals(Components.interfaces.nsIFactory))
  206.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  207.  
  208.         return pacFactory;
  209.     }
  210.  
  211. pacModule.canUnload =
  212.     function (compMgr) {
  213.         return true;
  214.     }
  215.  
  216. var pacFactory = new Object();
  217. pacFactory.createInstance =
  218.     function (outer, iid) {
  219.         if (outer != null)
  220.             throw Components.results.NS_ERROR_NO_AGGREGATION;
  221.  
  222.         if (!iid.equals(nsIProxyAutoConfig) &&
  223.             !!iid.equals(Components.interfaces.nsIStreamListener) &&
  224.             !iid.equals(Components.interfaces.nsISupports)) {
  225.             // shouldn't this be NO_INTERFACE?
  226.             throw Components.results.NS_ERROR_INVALID_ARG;
  227.         }
  228.         return PacMan;
  229.     }
  230.  
  231. function NSGetModule(compMgr, fileSpec) {
  232.     return pacModule;
  233. }
  234.  
  235. var PacMan = new nsProxyAutoConfig() ;
  236.  
  237. var ios = Components.classes[kIOSERVICE_CONTRACTID].getService(nsIIOService);
  238. var dns = Components.classes[kDNS_CONTRACTID].getService(nsIDNSService);
  239.  
  240. var pacUtils = 
  241. "function dnsDomainIs(host, domain) {\n" +
  242. "    return (host.length >= domain.length &&\n" +
  243. "            host.substring(host.length - domain.length) == domain);\n" +
  244. "}\n" +
  245.  
  246. "function dnsDomainLevels(host) {\n" +
  247. "    return host.split('.').length-1;\n" +
  248. "}\n" +
  249.  
  250. "function convert_addr(ipchars) {\n"+
  251. "    var bytes = ipchars.split('.');\n"+
  252. "    var result = ((bytes[0] & 0xff) << 24) |\n"+
  253. "                 ((bytes[1] & 0xff) << 16) |\n"+
  254. "                 ((bytes[2] & 0xff) <<  8) |\n"+
  255. "                  (bytes[3] & 0xff);\n"+
  256. "    return result;\n"+
  257. "}\n"+
  258.  
  259. "function isInNet(ipaddr, pattern, maskstr) {\n"+
  260. "    var test = /^(\\d{1,4})\\.(\\d{1,4})\\.(\\d{1,4})\\.(\\d{1,4})$/(ipaddr);\n"+
  261. "    if (test == null) {\n"+
  262. "        ipaddr = dnsResolve(ipaddr);\n"+
  263. "        if (ipaddr == null)\n"+
  264. "            return false;\n"+
  265. "    } else if (test[1] > 255 || test[2] > 255 || \n"+
  266. "               test[3] > 255 || test[4] > 255) {\n"+
  267. "        return false;    // not an IP address\n"+
  268. "    }\n"+
  269. "    var host = convert_addr(ipaddr);\n"+
  270. "    var pat  = convert_addr(pattern);\n"+
  271. "    var mask = convert_addr(maskstr);\n"+
  272. "    return ((host & mask) == (pat & mask));\n"+
  273. "    \n"+
  274. "}\n"+
  275.  
  276. "function isPlainHostName(host) {\n" +
  277. "    return (host.search('\\\\.') == -1);\n" +
  278. "}\n" +
  279.  
  280. "function isResolvable(host) {\n" +
  281. "    var ip = dnsResolve(host);\n" +
  282. "    return (ip != null);\n" +
  283. "}\n" +
  284.  
  285. "function localHostOrDomainIs(host, hostdom) {\n" +
  286. "    if (isPlainHostName(host)) {\n" +
  287. "        return (hostdom.search('/^' + host + '/') != -1);\n" +
  288. "    }\n" +
  289. "    else {\n" +
  290. "        return (host == hostdom); //TODO check \n" +
  291. "    }\n" +
  292. "}\n" +
  293.  
  294. " var myIP;\n" +
  295. "function myIpAddress() {\n" +
  296. "    return (myIP) ? myIP : '127.0.0.1';\n" +
  297. "}\n" +
  298.  
  299. "function shExpMatch(url, pattern) {\n" +
  300. "   pattern = pattern.replace(/\\./g, '\\\\.');\n" +
  301. "   pattern = pattern.replace(/\\*/g, '.*');\n" +
  302. "   pattern = pattern.replace(/\\?/g, '.');\n" +
  303. "   var newRe = new RegExp('^'+pattern+'$');\n" +
  304. "   return newRe.test(url);\n" +
  305. "}\n" +
  306.  
  307. "var wdays = new Array('SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT');\n" +
  308.  
  309. "var monthes = new Array('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC');\n"+
  310.  
  311. "function weekdayRange() {\n" +
  312. "    function getDay(weekday) {\n" +
  313. "        for (var i = 0; i < 6; i++) {\n" +
  314. "            if (weekday == wdays[i]) \n" +
  315. "                return i;\n" +
  316. "        }\n" +
  317. "        return -1;\n" +
  318. "    }\n" +
  319. "    var date = new Date();\n" +
  320. "    var argc = arguments.length;\n" +
  321. "    var wday;\n" +
  322. "    if (argc < 1)\n" +
  323. "        return false;\n" +
  324. "    if (arguments[argc - 1] == 'GMT') {\n" +
  325. "        argc--;\n" +
  326. "        wday = date.getUTCDay();\n" +
  327. "    } else {\n" +
  328. "        wday = date.getDay();\n" +
  329. "    }\n" +
  330. "    var wd1 = getDay(arguments[0]);\n" +
  331. "    var wd2 = (argc == 2) ? getDay(arguments[1]) : wd1;\n" +
  332. "    return (wd1 == -1 || wd2 == -1) ? false\n" +
  333. "                                    : (wd1 <= wday && wday <= wd2);\n" +
  334. "}\n" +
  335.  
  336. "function dateRange() {\n" +
  337. "    function getMonth(name) {\n" +
  338. "        for (var i = 0; i < 6; i++) {\n" +
  339. "            if (name == monthes[i])\n" +
  340. "                return i;\n" +
  341. "        }\n" +
  342. "        return -1;\n" +
  343. "    }\n" +
  344. "    var date = new Date();\n" +
  345. "    var argc = arguments.length;\n" +
  346. "    if (argc < 1) {\n" +
  347. "        return false;\n" +
  348. "    }\n" +
  349. "    var isGMT = (arguments[argc - 1] == 'GMT');\n" +
  350. "\n" +
  351. "    if (isGMT) {\n" +
  352. "        argc--;\n" +
  353. "    }\n" +
  354. "    // function will work even without explict handling of this case\n" +
  355. "    if (argc == 1) {\n" +
  356. "        var tmp = parseInt(arguments[0]);\n" +
  357. "        if (isNaN(tmp)) {\n" +
  358. "            return ((isGMT ? date.getUTCMonth() : date.getMonth()) ==\n" +
  359. "getMonth(arguments[0]));\n" +
  360. "        } else if (tmp < 32) {\n" +
  361. "            return ((isGMT ? date.getUTCDate() : date.getDate()) == tmp);\n" +
  362. "        } else { \n" +
  363. "            return ((isGMT ? date.getUTCFullYear() : date.getFullYear()) ==\n" +
  364. "tmp);\n" +
  365. "        }\n" +
  366. "    }\n" +
  367. "    var year = date.getFullYear();\n" +
  368. "    var date1, date2;\n" +
  369. "    date1 = new Date(year,  0,  1,  0,  0,  0);\n" +
  370. "    date2 = new Date(year, 11, 31, 23, 59, 59);\n" +
  371. "    var adjustMonth = false;\n" +
  372. "    for (var i = 0; i < (argc >> 1); i++) {\n" +
  373. "        var tmp = parseInt(arguments[i]);\n" +
  374. "        if (isNaN(tmp)) {\n" +
  375. "            var mon = getMonth(arguments[i]);\n" +
  376. "            date1.setMonth(mon);\n" +
  377. "        } else if (tmp < 32) {\n" +
  378. "            adjustMonth = (argc <= 2);\n" +
  379. "            date1.setDate(tmp);\n" +
  380. "        } else {\n" +
  381. "            date1.setFullYear(tmp);\n" +
  382. "        }\n" +
  383. "    }\n" +
  384. "    for (var i = (argc >> 1); i < argc; i++) {\n" +
  385. "        var tmp = parseInt(arguments[i]);\n" +
  386. "        if (isNaN(tmp)) {\n" +
  387. "            var mon = getMonth(arguments[i]);\n" +
  388. "            date2.setMonth(mon);\n" +
  389. "        } else if (tmp < 32) {\n" +
  390. "            date2.setDate(tmp);\n" +
  391. "        } else {\n" +
  392. "            date2.setFullYear(tmp);\n" +
  393. "        }\n" +
  394. "    }\n" +
  395. "    if (adjustMonth) {\n" +
  396. "        date1.setMonth(date.getMonth());\n" +
  397. "        date2.setMonth(date.getMonth());\n" +
  398. "    }\n" +
  399. "    if (isGMT) {\n" +
  400. "    var tmp = date;\n" +
  401. "        tmp.setFullYear(date.getUTCFullYear());\n" +
  402. "        tmp.setMonth(date.getUTCMonth());\n" +
  403. "        tmp.setDate(date.getUTCDate());\n" +
  404. "        tmp.setHours(date.getUTCHours());\n" +
  405. "        tmp.setMinutes(date.getUTCMinutes());\n" +
  406. "        tmp.setSeconds(date.getUTCSeconds());\n" +
  407. "        date = tmp;\n" +
  408. "    }\n" +
  409. "    return ((date1 <= date) && (date <= date2));\n" +
  410. "}\n" +
  411.  
  412. "function timeRange() {\n" +
  413. "    var argc = arguments.length;\n" +
  414. "    var date = new Date();\n" +
  415. "    var isGMT= false;\n"+
  416. "\n" +
  417. "    if (argc < 1) {\n" +
  418. "        return false;\n" +
  419. "    }\n" +
  420. "    if (arguments[argc - 1] == 'GMT') {\n" +
  421. "        isGMT = true;\n" +
  422. "        argc--;\n" +
  423. "    }\n" +
  424. "\n" +
  425. "    var hour = isGMT ? date.getUTCHours() : date.getHours();\n" +
  426. "    var date1, date2;\n" +
  427. "    date1 = new Date();\n" +
  428. "    date2 = new Date();\n" +
  429. "\n" +
  430. "    if (argc == 1) {\n" +
  431. "        return (hour == arguments[0]);\n" +
  432. "    } else if (argc == 2) {\n" +
  433. "        return ((arguments[0] <= hour) && (hour <= arguments[1]));\n" +
  434. "    } else {\n" +
  435. "        switch (argc) {\n" +
  436. "        case 6:\n" +
  437. "            date1.setSeconds(arguments[2]);\n" +
  438. "            date2.setSeconds(arguments[5]);\n" +
  439. "        case 4:\n" +
  440. "            var middle = argc >> 1;\n" +
  441. "            date1.setHours(arguments[0]);\n" +
  442. "            date1.setMinutes(arguments[1]);\n" +
  443. "            date2.setHours(arguments[middle]);\n" +
  444. "            date2.setMinutes(arguments[middle + 1]);\n" +
  445. "            if (middle == 2) {\n" +
  446. "                date2.setSeconds(59);\n" +
  447. "            }\n" +
  448. "            break;\n" +
  449. "        default:\n" +
  450. "          throw 'timeRange: bad number of arguments'\n" +
  451. "        }\n" +
  452. "    }\n" +
  453. "\n" +
  454. "    if (isGMT) {\n" +
  455. "        date.setFullYear(date.getUTCFullYear());\n" +
  456. "        date.setMonth(date.getUTCMonth());\n" +
  457. "        date.setDate(date.getUTCDate());\n" +
  458. "        date.setHours(date.getUTCHours());\n" +
  459. "        date.setMinutes(date.getUTCMinutes());\n" +
  460. "        date.setSeconds(date.getUTCSeconds());\n" +
  461. "    }\n" +
  462. "    return ((date1 <= date) && (date <= date2));\n" +
  463. "}\n"
  464.  
  465.