home *** CD-ROM | disk | FTP | other *** search
/ Chip 2003 September / Chip_2003-09_cd1.bin / zkuste / macos / Files / wamcom.sit / wamcom-131-macos9-20030721 / Components / nsProxyAutoConfig.js < prev    next >
Text File  |  2003-06-30  |  17KB  |  480 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.notificationCallbacks = this;
  129.         channel.asyncOpen(this, null);
  130.         Components.returnCode = Components.results.NS_OK;
  131.     },
  132.  
  133.     // nsIInterfaceRequestor interface
  134.     getInterface: function(iid, instance) {
  135.         if (iid.equals(Components.interfaces.nsIAuthPrompt)) {
  136.             // use the window watcher service to get a nsIAuthPrompt impl
  137.             var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  138.                                .getService(Components.interfaces.nsIWindowWatcher);
  139.             return ww.getNewAuthPrompter(null);
  140.         }
  141.         Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  142.         return null;
  143.     },
  144.  
  145.     // nsIStreamListener interface
  146.     onStartRequest: function(request, ctxt) { 
  147.         pac = '';
  148.         LocalFindProxyForURL=null;
  149.         this.sis = 
  150.         Components.Constructor('@mozilla.org/scriptableinputstream;1',
  151.                                'nsIScriptableInputStream', 
  152.                                'init');
  153.     },
  154.  
  155.     onStopRequest: function(request, ctxt, status, errorMsg) {
  156.         if(!ProxySandBox) {
  157.            ProxySandBox = new Sandbox();
  158.         }
  159.         // add predefined functions to pac
  160.         var mypac = pacUtils + pac;
  161.         // evaluate loded js file
  162.         evalInSandbox(mypac, ProxySandBox, pacURL);
  163.         try {
  164.             ProxySandBox.myIP = dns.myIPAddress;
  165.         } catch (e) {
  166.             // Well, theres nothing better.
  167.             // see bugs 80363 and 92516.
  168.             ProxySandBox.myIP = "127.0.0.1";
  169.         }
  170.         ProxySandBox.dnsResolve = dnsResolve;
  171.         LocalFindProxyForURL=ProxySandBox.FindProxyForURL;
  172.         this.done = true;
  173.     },
  174.  
  175.     onDataAvailable: function(request, ctxt, inStream, sourceOffset, count) {
  176.         var ins = new this.sis(inStream);
  177.         pac += ins.read(count);
  178.     }
  179. }
  180.  
  181. // Synchronous calls to nsDNSService::Resolve ignore the cache! (bug 97097)
  182. // Keep a simple one of our own.
  183. var dnsResolveCachedHost = null;
  184. var dnsResolveCachedIp = null;
  185.  
  186. // wrapper for dns.resolve to catch exception on failure
  187. function dnsResolve(host) {
  188.     if (host == dnsResolveCachedHost) {
  189.         return dnsResolveCachedIp;
  190.     }
  191.     try {
  192.         dnsResolveCachedIp = dns.resolve(host);
  193.         dnsResolveCachedHost = host;
  194.     }
  195.     catch (e) {
  196.         dnsResolveCachedIp = null;
  197.         dnsResolveCachedHost = null;
  198.     }
  199.     return dnsResolveCachedIp;
  200. }
  201.  
  202. var pacModule = new Object();
  203.  
  204. pacModule.registerSelf =
  205.     function (compMgr, fileSpec, location, type) {
  206.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  207.         compMgr.registerFactoryLocation(kPAC_CID,
  208.                                         "Proxy Auto Config",
  209.                                         kPAC_CONTRACTID,
  210.                                         fileSpec, 
  211.                                         location, 
  212.                                         type);
  213.     }
  214.  
  215. pacModule.getClassObject =
  216. function (compMgr, cid, iid) {
  217.         if (!cid.equals(kPAC_CID))
  218.             throw Components.results.NS_ERROR_NO_INTERFACE;
  219.  
  220.         if (!iid.equals(Components.interfaces.nsIFactory))
  221.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  222.  
  223.         return pacFactory;
  224.     }
  225.  
  226. pacModule.canUnload =
  227.     function (compMgr) {
  228.         return true;
  229.     }
  230.  
  231. var pacFactory = new Object();
  232. pacFactory.createInstance =
  233.     function (outer, iid) {
  234.         if (outer != null)
  235.             throw Components.results.NS_ERROR_NO_AGGREGATION;
  236.  
  237.         if (!iid.equals(nsIProxyAutoConfig) &&
  238.             !!iid.equals(Components.interfaces.nsIStreamListener) &&
  239.             !iid.equals(Components.interfaces.nsISupports)) {
  240.             // shouldn't this be NO_INTERFACE?
  241.             throw Components.results.NS_ERROR_INVALID_ARG;
  242.         }
  243.         return PacMan;
  244.     }
  245.  
  246. function NSGetModule(compMgr, fileSpec) {
  247.     return pacModule;
  248. }
  249.  
  250. var PacMan = new nsProxyAutoConfig() ;
  251.  
  252. var ios = Components.classes[kIOSERVICE_CONTRACTID].getService(nsIIOService);
  253. var dns = Components.classes[kDNS_CONTRACTID].getService(nsIDNSService);
  254.  
  255. var pacUtils = 
  256. "function dnsDomainIs(host, domain) {\n" +
  257. "    return (host.length >= domain.length &&\n" +
  258. "            host.substring(host.length - domain.length) == domain);\n" +
  259. "}\n" +
  260.  
  261. "function dnsDomainLevels(host) {\n" +
  262. "    return host.split('.').length-1;\n" +
  263. "}\n" +
  264.  
  265. "function convert_addr(ipchars) {\n"+
  266. "    var bytes = ipchars.split('.');\n"+
  267. "    var result = ((bytes[0] & 0xff) << 24) |\n"+
  268. "                 ((bytes[1] & 0xff) << 16) |\n"+
  269. "                 ((bytes[2] & 0xff) <<  8) |\n"+
  270. "                  (bytes[3] & 0xff);\n"+
  271. "    return result;\n"+
  272. "}\n"+
  273.  
  274. "function isInNet(ipaddr, pattern, maskstr) {\n"+
  275. "    var test = /^(\\d{1,4})\\.(\\d{1,4})\\.(\\d{1,4})\\.(\\d{1,4})$/(ipaddr);\n"+
  276. "    if (test == null) {\n"+
  277. "        ipaddr = dnsResolve(ipaddr);\n"+
  278. "        if (ipaddr == null)\n"+
  279. "            return false;\n"+
  280. "    } else if (test[1] > 255 || test[2] > 255 || \n"+
  281. "               test[3] > 255 || test[4] > 255) {\n"+
  282. "        return false;    // not an IP address\n"+
  283. "    }\n"+
  284. "    var host = convert_addr(ipaddr);\n"+
  285. "    var pat  = convert_addr(pattern);\n"+
  286. "    var mask = convert_addr(maskstr);\n"+
  287. "    return ((host & mask) == (pat & mask));\n"+
  288. "    \n"+
  289. "}\n"+
  290.  
  291. "function isPlainHostName(host) {\n" +
  292. "    return (host.search('\\\\.') == -1);\n" +
  293. "}\n" +
  294.  
  295. "function isResolvable(host) {\n" +
  296. "    var ip = dnsResolve(host);\n" +
  297. "    return (ip != null);\n" +
  298. "}\n" +
  299.  
  300. "function localHostOrDomainIs(host, hostdom) {\n" +
  301. "    if (isPlainHostName(host)) {\n" +
  302. "        return (hostdom.search('/^' + host + '/') != -1);\n" +
  303. "    }\n" +
  304. "    else {\n" +
  305. "        return (host == hostdom); //TODO check \n" +
  306. "    }\n" +
  307. "}\n" +
  308.  
  309. " var myIP;\n" +
  310. "function myIpAddress() {\n" +
  311. "    return (myIP) ? myIP : '127.0.0.1';\n" +
  312. "}\n" +
  313.  
  314. "function shExpMatch(url, pattern) {\n" +
  315. "   pattern = pattern.replace(/\\./g, '\\\\.');\n" +
  316. "   pattern = pattern.replace(/\\*/g, '.*');\n" +
  317. "   pattern = pattern.replace(/\\?/g, '.');\n" +
  318. "   var newRe = new RegExp('^'+pattern+'$');\n" +
  319. "   return newRe.test(url);\n" +
  320. "}\n" +
  321.  
  322. "var wdays = new Array('SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT');\n" +
  323.  
  324. "var monthes = new Array('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC');\n"+
  325.  
  326. "function weekdayRange() {\n" +
  327. "    function getDay(weekday) {\n" +
  328. "        for (var i = 0; i < 6; i++) {\n" +
  329. "            if (weekday == wdays[i]) \n" +
  330. "                return i;\n" +
  331. "        }\n" +
  332. "        return -1;\n" +
  333. "    }\n" +
  334. "    var date = new Date();\n" +
  335. "    var argc = arguments.length;\n" +
  336. "    var wday;\n" +
  337. "    if (argc < 1)\n" +
  338. "        return false;\n" +
  339. "    if (arguments[argc - 1] == 'GMT') {\n" +
  340. "        argc--;\n" +
  341. "        wday = date.getUTCDay();\n" +
  342. "    } else {\n" +
  343. "        wday = date.getDay();\n" +
  344. "    }\n" +
  345. "    var wd1 = getDay(arguments[0]);\n" +
  346. "    var wd2 = (argc == 2) ? getDay(arguments[1]) : wd1;\n" +
  347. "    return (wd1 == -1 || wd2 == -1) ? false\n" +
  348. "                                    : (wd1 <= wday && wday <= wd2);\n" +
  349. "}\n" +
  350.  
  351. "function dateRange() {\n" +
  352. "    function getMonth(name) {\n" +
  353. "        for (var i = 0; i < 6; i++) {\n" +
  354. "            if (name == monthes[i])\n" +
  355. "                return i;\n" +
  356. "        }\n" +
  357. "        return -1;\n" +
  358. "    }\n" +
  359. "    var date = new Date();\n" +
  360. "    var argc = arguments.length;\n" +
  361. "    if (argc < 1) {\n" +
  362. "        return false;\n" +
  363. "    }\n" +
  364. "    var isGMT = (arguments[argc - 1] == 'GMT');\n" +
  365. "\n" +
  366. "    if (isGMT) {\n" +
  367. "        argc--;\n" +
  368. "    }\n" +
  369. "    // function will work even without explict handling of this case\n" +
  370. "    if (argc == 1) {\n" +
  371. "        var tmp = parseInt(arguments[0]);\n" +
  372. "        if (isNaN(tmp)) {\n" +
  373. "            return ((isGMT ? date.getUTCMonth() : date.getMonth()) ==\n" +
  374. "getMonth(arguments[0]));\n" +
  375. "        } else if (tmp < 32) {\n" +
  376. "            return ((isGMT ? date.getUTCDate() : date.getDate()) == tmp);\n" +
  377. "        } else { \n" +
  378. "            return ((isGMT ? date.getUTCFullYear() : date.getFullYear()) ==\n" +
  379. "tmp);\n" +
  380. "        }\n" +
  381. "    }\n" +
  382. "    var year = date.getFullYear();\n" +
  383. "    var date1, date2;\n" +
  384. "    date1 = new Date(year,  0,  1,  0,  0,  0);\n" +
  385. "    date2 = new Date(year, 11, 31, 23, 59, 59);\n" +
  386. "    var adjustMonth = false;\n" +
  387. "    for (var i = 0; i < (argc >> 1); i++) {\n" +
  388. "        var tmp = parseInt(arguments[i]);\n" +
  389. "        if (isNaN(tmp)) {\n" +
  390. "            var mon = getMonth(arguments[i]);\n" +
  391. "            date1.setMonth(mon);\n" +
  392. "        } else if (tmp < 32) {\n" +
  393. "            adjustMonth = (argc <= 2);\n" +
  394. "            date1.setDate(tmp);\n" +
  395. "        } else {\n" +
  396. "            date1.setFullYear(tmp);\n" +
  397. "        }\n" +
  398. "    }\n" +
  399. "    for (var i = (argc >> 1); i < argc; i++) {\n" +
  400. "        var tmp = parseInt(arguments[i]);\n" +
  401. "        if (isNaN(tmp)) {\n" +
  402. "            var mon = getMonth(arguments[i]);\n" +
  403. "            date2.setMonth(mon);\n" +
  404. "        } else if (tmp < 32) {\n" +
  405. "            date2.setDate(tmp);\n" +
  406. "        } else {\n" +
  407. "            date2.setFullYear(tmp);\n" +
  408. "        }\n" +
  409. "    }\n" +
  410. "    if (adjustMonth) {\n" +
  411. "        date1.setMonth(date.getMonth());\n" +
  412. "        date2.setMonth(date.getMonth());\n" +
  413. "    }\n" +
  414. "    if (isGMT) {\n" +
  415. "    var tmp = date;\n" +
  416. "        tmp.setFullYear(date.getUTCFullYear());\n" +
  417. "        tmp.setMonth(date.getUTCMonth());\n" +
  418. "        tmp.setDate(date.getUTCDate());\n" +
  419. "        tmp.setHours(date.getUTCHours());\n" +
  420. "        tmp.setMinutes(date.getUTCMinutes());\n" +
  421. "        tmp.setSeconds(date.getUTCSeconds());\n" +
  422. "        date = tmp;\n" +
  423. "    }\n" +
  424. "    return ((date1 <= date) && (date <= date2));\n" +
  425. "}\n" +
  426.  
  427. "function timeRange() {\n" +
  428. "    var argc = arguments.length;\n" +
  429. "    var date = new Date();\n" +
  430. "    var isGMT= false;\n"+
  431. "\n" +
  432. "    if (argc < 1) {\n" +
  433. "        return false;\n" +
  434. "    }\n" +
  435. "    if (arguments[argc - 1] == 'GMT') {\n" +
  436. "        isGMT = true;\n" +
  437. "        argc--;\n" +
  438. "    }\n" +
  439. "\n" +
  440. "    var hour = isGMT ? date.getUTCHours() : date.getHours();\n" +
  441. "    var date1, date2;\n" +
  442. "    date1 = new Date();\n" +
  443. "    date2 = new Date();\n" +
  444. "\n" +
  445. "    if (argc == 1) {\n" +
  446. "        return (hour == arguments[0]);\n" +
  447. "    } else if (argc == 2) {\n" +
  448. "        return ((arguments[0] <= hour) && (hour <= arguments[1]));\n" +
  449. "    } else {\n" +
  450. "        switch (argc) {\n" +
  451. "        case 6:\n" +
  452. "            date1.setSeconds(arguments[2]);\n" +
  453. "            date2.setSeconds(arguments[5]);\n" +
  454. "        case 4:\n" +
  455. "            var middle = argc >> 1;\n" +
  456. "            date1.setHours(arguments[0]);\n" +
  457. "            date1.setMinutes(arguments[1]);\n" +
  458. "            date2.setHours(arguments[middle]);\n" +
  459. "            date2.setMinutes(arguments[middle + 1]);\n" +
  460. "            if (middle == 2) {\n" +
  461. "                date2.setSeconds(59);\n" +
  462. "            }\n" +
  463. "            break;\n" +
  464. "        default:\n" +
  465. "          throw 'timeRange: bad number of arguments'\n" +
  466. "        }\n" +
  467. "    }\n" +
  468. "\n" +
  469. "    if (isGMT) {\n" +
  470. "        date.setFullYear(date.getUTCFullYear());\n" +
  471. "        date.setMonth(date.getUTCMonth());\n" +
  472. "        date.setDate(date.getUTCDate());\n" +
  473. "        date.setHours(date.getUTCHours());\n" +
  474. "        date.setMinutes(date.getUTCMinutes());\n" +
  475. "        date.setSeconds(date.getUTCSeconds());\n" +
  476. "    }\n" +
  477. "    return ((date1 <= date) && (date <= date2));\n" +
  478. "}\n"
  479.  
  480.