home *** CD-ROM | disk | FTP | other *** search
/ PC Welt 2005 December / PCWELT_12_2005.ISO / bin / components / nsProxyAutoConfig.js < prev    next >
Encoding:
Text File  |  2004-09-01  |  14.7 KB  |  438 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-auto-config;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.     getProxyForURI: function(uri) {
  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 getProxyForURI and loadPACFromURI locks-up the
  74.         // browser.
  75.         if (!this.done)
  76.             return null;
  77.  
  78.         // Call the original function-
  79.         return LocalFindProxyForURL(uri.spec, uri.host);
  80.     },
  81.  
  82.     loadPACFromURI: function(uri, ioService) {
  83.         this.done = false;
  84.         var channel = ioService.newChannelFromURI(uri);
  85.         // don't cache the PAC content
  86.         channel.loadFlags |= nsIRequest.LOAD_BYPASS_CACHE;
  87.         pacURL = uri.spec;
  88.         channel.notificationCallbacks = this;
  89.         channel.asyncOpen(this, null);
  90.         Components.returnCode = Components.results.NS_OK;
  91.     },
  92.  
  93.     // nsIInterfaceRequestor interface
  94.     getInterface: function(iid, instance) {
  95.         if (iid.equals(Components.interfaces.nsIAuthPrompt)) {
  96.             // use the window watcher service to get a nsIAuthPrompt impl
  97.             var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  98.                                .getService(Components.interfaces.nsIWindowWatcher);
  99.             return ww.getNewAuthPrompter(null);
  100.         }
  101.         Components.returnCode = Components.results.NS_ERROR_NO_INTERFACE;
  102.         return null;
  103.     },
  104.  
  105.     // nsIStreamListener interface
  106.     onStartRequest: function(request, ctxt) { 
  107.         pac = '';
  108.         LocalFindProxyForURL=null;
  109.         this.sis = 
  110.         Components.Constructor('@mozilla.org/scriptableinputstream;1',
  111.                                'nsIScriptableInputStream', 
  112.                                'init');
  113.     },
  114.  
  115.     onStopRequest: function(request, ctxt, status) {
  116.         if(!ProxySandBox) {
  117.            ProxySandBox = new Sandbox();
  118.         }
  119.         // add predefined functions to pac
  120.         var mypac = pacUtils + pac;
  121.         ProxySandBox.myIpAddress = myIpAddress;
  122.         ProxySandBox.dnsResolve = dnsResolve;
  123.         ProxySandBox.alert = proxyAlert;
  124.         // evaluate loaded js file
  125.         evalInSandbox(mypac, ProxySandBox, pacURL);
  126.         LocalFindProxyForURL=ProxySandBox.FindProxyForURL;
  127.         this.done = true;
  128.     },
  129.  
  130.     onDataAvailable: function(request, ctxt, inStream, sourceOffset, count) {
  131.         var ins = new this.sis(inStream);
  132.         pac += ins.read(count);
  133.     }
  134. }
  135.  
  136. function proxyAlert(msg) {
  137.     try {
  138.         var cns = Components.classes["@mozilla.org/consoleservice;1"]
  139.                             .getService(Components.interfaces.nsIConsoleService);
  140.         cns.logStringMessage("PAC-alert: "+msg);
  141.     } catch (e) {
  142.         dump("PAC: proxyAlert ERROR: "+e+"\n");
  143.     }
  144. }
  145.  
  146. // wrapper for getting local IP address called by PAC file
  147. function myIpAddress() {
  148.     try {
  149.         return dns.resolve(dns.myHostName, 0).getNextAddrAsString();
  150.     } catch (e) {
  151.         return '127.0.0.1';
  152.     }
  153. }
  154.  
  155. // wrapper for resolving hostnames called by PAC file
  156. function dnsResolve(host) {
  157.     try {
  158.         return dns.resolve(host, 0).getNextAddrAsString();
  159.     } catch (e) {
  160.         return null;
  161.     }
  162. }
  163.  
  164. var pacModule = new Object();
  165.  
  166. pacModule.registerSelf =
  167.     function (compMgr, fileSpec, location, type) {
  168.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  169.         compMgr.registerFactoryLocation(kPAC_CID,
  170.                                         "nsProxyAutoConfig",
  171.                                         kPAC_CONTRACTID,
  172.                                         fileSpec, 
  173.                                         location, 
  174.                                         type);
  175.     }
  176.  
  177. pacModule.getClassObject =
  178. function (compMgr, cid, iid) {
  179.         if (!cid.equals(kPAC_CID))
  180.             throw Components.results.NS_ERROR_NO_INTERFACE;
  181.  
  182.         if (!iid.equals(Components.interfaces.nsIFactory))
  183.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  184.  
  185.         return pacFactory;
  186.     }
  187.  
  188. pacModule.canUnload =
  189.     function (compMgr) {
  190.         return true;
  191.     }
  192.  
  193. var pacFactory = new Object();
  194. pacFactory.createInstance =
  195.     function (outer, iid) {
  196.         if (outer != null)
  197.             throw Components.results.NS_ERROR_NO_AGGREGATION;
  198.  
  199.         if (!iid.equals(nsIProxyAutoConfig) &&
  200.             !iid.equals(Components.interfaces.nsIStreamListener) &&
  201.             !iid.equals(Components.interfaces.nsIRequestObserver) &&
  202.             !iid.equals(Components.interfaces.nsISupports)) {
  203.             // shouldn't this be NO_INTERFACE?
  204.             throw Components.results.NS_ERROR_INVALID_ARG;
  205.         }
  206.         return PacMan;
  207.     }
  208.  
  209. function NSGetModule(compMgr, fileSpec) {
  210.     return pacModule;
  211. }
  212.  
  213. var PacMan = new nsProxyAutoConfig() ;
  214.  
  215. var ios = Components.classes[kIOSERVICE_CONTRACTID].getService(nsIIOService);
  216. var dns = Components.classes[kDNS_CONTRACTID].getService(nsIDNSService);
  217.  
  218. var pacUtils = 
  219. "function dnsDomainIs(host, domain) {\n" +
  220. "    return (host.length >= domain.length &&\n" +
  221. "            host.substring(host.length - domain.length) == domain);\n" +
  222. "}\n" +
  223.  
  224. "function dnsDomainLevels(host) {\n" +
  225. "    return host.split('.').length-1;\n" +
  226. "}\n" +
  227.  
  228. "function convert_addr(ipchars) {\n"+
  229. "    var bytes = ipchars.split('.');\n"+
  230. "    var result = ((bytes[0] & 0xff) << 24) |\n"+
  231. "                 ((bytes[1] & 0xff) << 16) |\n"+
  232. "                 ((bytes[2] & 0xff) <<  8) |\n"+
  233. "                  (bytes[3] & 0xff);\n"+
  234. "    return result;\n"+
  235. "}\n"+
  236.  
  237. "function isInNet(ipaddr, pattern, maskstr) {\n"+
  238. "    var test = /^(\\d{1,4})\\.(\\d{1,4})\\.(\\d{1,4})\\.(\\d{1,4})$/(ipaddr);\n"+
  239. "    if (test == null) {\n"+
  240. "        ipaddr = dnsResolve(ipaddr);\n"+
  241. "        if (ipaddr == null)\n"+
  242. "            return false;\n"+
  243. "    } else if (test[1] > 255 || test[2] > 255 || \n"+
  244. "               test[3] > 255 || test[4] > 255) {\n"+
  245. "        return false;    // not an IP address\n"+
  246. "    }\n"+
  247. "    var host = convert_addr(ipaddr);\n"+
  248. "    var pat  = convert_addr(pattern);\n"+
  249. "    var mask = convert_addr(maskstr);\n"+
  250. "    return ((host & mask) == (pat & mask));\n"+
  251. "    \n"+
  252. "}\n"+
  253.  
  254. "function isPlainHostName(host) {\n" +
  255. "    return (host.search('\\\\.') == -1);\n" +
  256. "}\n" +
  257.  
  258. "function isResolvable(host) {\n" +
  259. "    var ip = dnsResolve(host);\n" +
  260. "    return (ip != null);\n" +
  261. "}\n" +
  262.  
  263. "function localHostOrDomainIs(host, hostdom) {\n" +
  264. "    if (isPlainHostName(host)) {\n" +
  265. "        return (hostdom.search('/^' + host + '/') != -1);\n" +
  266. "    }\n" +
  267. "    else {\n" +
  268. "        return (host == hostdom); //TODO check \n" +
  269. "    }\n" +
  270. "}\n" +
  271.  
  272. "function shExpMatch(url, pattern) {\n" +
  273. "   pattern = pattern.replace(/\\./g, '\\\\.');\n" +
  274. "   pattern = pattern.replace(/\\*/g, '.*');\n" +
  275. "   pattern = pattern.replace(/\\?/g, '.');\n" +
  276. "   var newRe = new RegExp('^'+pattern+'$');\n" +
  277. "   return newRe.test(url);\n" +
  278. "}\n" +
  279.  
  280. "var wdays = new Array('SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT');\n" +
  281.  
  282. "var monthes = new Array('JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC');\n"+
  283.  
  284. "function weekdayRange() {\n" +
  285. "    function getDay(weekday) {\n" +
  286. "        for (var i = 0; i < 6; i++) {\n" +
  287. "            if (weekday == wdays[i]) \n" +
  288. "                return i;\n" +
  289. "        }\n" +
  290. "        return -1;\n" +
  291. "    }\n" +
  292. "    var date = new Date();\n" +
  293. "    var argc = arguments.length;\n" +
  294. "    var wday;\n" +
  295. "    if (argc < 1)\n" +
  296. "        return false;\n" +
  297. "    if (arguments[argc - 1] == 'GMT') {\n" +
  298. "        argc--;\n" +
  299. "        wday = date.getUTCDay();\n" +
  300. "    } else {\n" +
  301. "        wday = date.getDay();\n" +
  302. "    }\n" +
  303. "    var wd1 = getDay(arguments[0]);\n" +
  304. "    var wd2 = (argc == 2) ? getDay(arguments[1]) : wd1;\n" +
  305. "    return (wd1 == -1 || wd2 == -1) ? false\n" +
  306. "                                    : (wd1 <= wday && wday <= wd2);\n" +
  307. "}\n" +
  308.  
  309. "function dateRange() {\n" +
  310. "    function getMonth(name) {\n" +
  311. "        for (var i = 0; i < 6; i++) {\n" +
  312. "            if (name == monthes[i])\n" +
  313. "                return i;\n" +
  314. "        }\n" +
  315. "        return -1;\n" +
  316. "    }\n" +
  317. "    var date = new Date();\n" +
  318. "    var argc = arguments.length;\n" +
  319. "    if (argc < 1) {\n" +
  320. "        return false;\n" +
  321. "    }\n" +
  322. "    var isGMT = (arguments[argc - 1] == 'GMT');\n" +
  323. "\n" +
  324. "    if (isGMT) {\n" +
  325. "        argc--;\n" +
  326. "    }\n" +
  327. "    // function will work even without explict handling of this case\n" +
  328. "    if (argc == 1) {\n" +
  329. "        var tmp = parseInt(arguments[0]);\n" +
  330. "        if (isNaN(tmp)) {\n" +
  331. "            return ((isGMT ? date.getUTCMonth() : date.getMonth()) ==\n" +
  332. "getMonth(arguments[0]));\n" +
  333. "        } else if (tmp < 32) {\n" +
  334. "            return ((isGMT ? date.getUTCDate() : date.getDate()) == tmp);\n" +
  335. "        } else { \n" +
  336. "            return ((isGMT ? date.getUTCFullYear() : date.getFullYear()) ==\n" +
  337. "tmp);\n" +
  338. "        }\n" +
  339. "    }\n" +
  340. "    var year = date.getFullYear();\n" +
  341. "    var date1, date2;\n" +
  342. "    date1 = new Date(year,  0,  1,  0,  0,  0);\n" +
  343. "    date2 = new Date(year, 11, 31, 23, 59, 59);\n" +
  344. "    var adjustMonth = false;\n" +
  345. "    for (var i = 0; i < (argc >> 1); i++) {\n" +
  346. "        var tmp = parseInt(arguments[i]);\n" +
  347. "        if (isNaN(tmp)) {\n" +
  348. "            var mon = getMonth(arguments[i]);\n" +
  349. "            date1.setMonth(mon);\n" +
  350. "        } else if (tmp < 32) {\n" +
  351. "            adjustMonth = (argc <= 2);\n" +
  352. "            date1.setDate(tmp);\n" +
  353. "        } else {\n" +
  354. "            date1.setFullYear(tmp);\n" +
  355. "        }\n" +
  356. "    }\n" +
  357. "    for (var i = (argc >> 1); i < argc; i++) {\n" +
  358. "        var tmp = parseInt(arguments[i]);\n" +
  359. "        if (isNaN(tmp)) {\n" +
  360. "            var mon = getMonth(arguments[i]);\n" +
  361. "            date2.setMonth(mon);\n" +
  362. "        } else if (tmp < 32) {\n" +
  363. "            date2.setDate(tmp);\n" +
  364. "        } else {\n" +
  365. "            date2.setFullYear(tmp);\n" +
  366. "        }\n" +
  367. "    }\n" +
  368. "    if (adjustMonth) {\n" +
  369. "        date1.setMonth(date.getMonth());\n" +
  370. "        date2.setMonth(date.getMonth());\n" +
  371. "    }\n" +
  372. "    if (isGMT) {\n" +
  373. "    var tmp = date;\n" +
  374. "        tmp.setFullYear(date.getUTCFullYear());\n" +
  375. "        tmp.setMonth(date.getUTCMonth());\n" +
  376. "        tmp.setDate(date.getUTCDate());\n" +
  377. "        tmp.setHours(date.getUTCHours());\n" +
  378. "        tmp.setMinutes(date.getUTCMinutes());\n" +
  379. "        tmp.setSeconds(date.getUTCSeconds());\n" +
  380. "        date = tmp;\n" +
  381. "    }\n" +
  382. "    return ((date1 <= date) && (date <= date2));\n" +
  383. "}\n" +
  384.  
  385. "function timeRange() {\n" +
  386. "    var argc = arguments.length;\n" +
  387. "    var date = new Date();\n" +
  388. "    var isGMT= false;\n"+
  389. "\n" +
  390. "    if (argc < 1) {\n" +
  391. "        return false;\n" +
  392. "    }\n" +
  393. "    if (arguments[argc - 1] == 'GMT') {\n" +
  394. "        isGMT = true;\n" +
  395. "        argc--;\n" +
  396. "    }\n" +
  397. "\n" +
  398. "    var hour = isGMT ? date.getUTCHours() : date.getHours();\n" +
  399. "    var date1, date2;\n" +
  400. "    date1 = new Date();\n" +
  401. "    date2 = new Date();\n" +
  402. "\n" +
  403. "    if (argc == 1) {\n" +
  404. "        return (hour == arguments[0]);\n" +
  405. "    } else if (argc == 2) {\n" +
  406. "        return ((arguments[0] <= hour) && (hour <= arguments[1]));\n" +
  407. "    } else {\n" +
  408. "        switch (argc) {\n" +
  409. "        case 6:\n" +
  410. "            date1.setSeconds(arguments[2]);\n" +
  411. "            date2.setSeconds(arguments[5]);\n" +
  412. "        case 4:\n" +
  413. "            var middle = argc >> 1;\n" +
  414. "            date1.setHours(arguments[0]);\n" +
  415. "            date1.setMinutes(arguments[1]);\n" +
  416. "            date2.setHours(arguments[middle]);\n" +
  417. "            date2.setMinutes(arguments[middle + 1]);\n" +
  418. "            if (middle == 2) {\n" +
  419. "                date2.setSeconds(59);\n" +
  420. "            }\n" +
  421. "            break;\n" +
  422. "        default:\n" +
  423. "          throw 'timeRange: bad number of arguments'\n" +
  424. "        }\n" +
  425. "    }\n" +
  426. "\n" +
  427. "    if (isGMT) {\n" +
  428. "        date.setFullYear(date.getUTCFullYear());\n" +
  429. "        date.setMonth(date.getUTCMonth());\n" +
  430. "        date.setDate(date.getUTCDate());\n" +
  431. "        date.setHours(date.getUTCHours());\n" +
  432. "        date.setMinutes(date.getUTCMinutes());\n" +
  433. "        date.setSeconds(date.getUTCSeconds());\n" +
  434. "    }\n" +
  435. "    return ((date1 <= date) && (date <= date2));\n" +
  436. "}\n"
  437.  
  438.