proxy for http server
@param {Object}                 [options]
@param {String}                 [options.server] url to the server
@param {AuthenticationAbstract} [options.auth] authentication object
178885
function ProxyHttp(options) {
    ProxyAbstract.call(this, options);
    this._server = options.server || 'https://api.smsapi.pl/';
    this._auth = options.auth || null;
}
548310
function HttpsConfig(options) {
    var httpsOptions = options && options.httpsOptions

    underscore.extend(this, HttpsConfig._DEFAULT)
    CommonConfig.call(this, options)
    this.httpsOptions = applyHttpsOptions.call(this, httpsOptions)
    this.type = serverTypes.HTTPS
}
1316159
function Server(options) {
  options = util._extend({}, options);

  this._log = (options.log || defaultLogger).child({ component: 'http' });
  this._settings = options.settings;

  var start = this._start.bind(this);
  var fallback = this._fallback.bind(this);

  // HTTP2 over TLS (using NPN or ALPN)
  if ((options.key && options.cert) || options.pfx) {
    this._log.info('Creating HTTP/2 server over TLS');
    this._mode = 'tls';
    options.ALPNProtocols = supportedProtocols;
    options.NPNProtocols = supportedProtocols;
    options.ciphers = options.ciphers || cipherSuites;
    options.honorCipherOrder = (options.honorCipherOrder != false);
    this._server = https.createServer(options);
    this._originalSocketListeners = this._server.listeners('secureConnection');
    this._server.removeAllListeners('secureConnection');
    this._server.on('secureConnection', function(socket) {
      var negotiatedProtocol = socket.alpnProtocol || socket.npnProtocol;
      // It's true that the client MUST use SNI, but if it doesn't, we don't care, don't fall back to HTTP/1,
      // since if the ALPN negotiation is otherwise successful, the client thinks we speak HTTP/2 but we don't.
      if (negotiatedProtocol === protocol.VERSION) {
        start(socket);
      } else {
        fallback(socket);
      }
    });
    this._server.on('request', this.emit.bind(this, 'request'));

    forwardEvent('error', this._server, this);
    forwardEvent('listening', this._server, this);
  }

  // HTTP2 over plain TCP
  else if (options.plain) {
    this._log.info('Creating HTTP/2 server over plain TCP');
    this._mode = 'plain';
    this._server = net.createServer(start);
  }

  // HTTP/2 with HTTP/1.1 upgrade
  else {
    this._log.error('Trying to create HTTP/2 server with Upgrade from HTTP/1.1');
    throw new Error('HTTP1.1 -> HTTP2 upgrade is not yet supported. Please provide TLS keys.');
  }

  this._server.on('close', this.emit.bind(this, 'close'));
}
576480
def use_proxy(uri, port, user=nil, pass=nil)
      @http_class = Net::HTTP::Proxy(uri, port, user, pass)
    end
897819
function Server(options) {
  var self = this;
  options = options || {};

  self.serverVersion = '2.0.2';
  self.authKey = "";
  self.protocolVersion = protodef.VersionDummy.Version.V1_0;
  self.minProtocolVersion = 0;
  self.maxProtocolVersion = 0;
  self.port = options['driver-port'] || 28015;

  self._connections = {};
  self.nextConnectionId = 0;

  if (options.debug === true) {
    util._debug = true;
  }
  self.silent = options.silent || constants.SILENT || false;

  self.databases = {};
  self.init();
  self.id = util.uuid();
  self.name = options.name || os.hostname()+util.s4().slice(1);

  self._server = self._createServer();
}
1292025
function(provider, options) {
      var authType;
      if (_.isString(provider)) {
        authType = provider;
        provider = Parse.User._authProviders[provider];
      } else {
        authType = provider.getAuthType();
      }
      if (_.has(options, 'authData')) {
        var authData = this.get('authData') || {};
        authData[authType] = options.authData;
        this.set('authData', authData);

        // Overridden so that the user can be made the current user.
        var newOptions = _.clone(options) || {};
        newOptions.success = function(model) {
          model._handleSaveResult(true);
          if (options.success) {
            options.success.apply(this, arguments);
          }
        };
        return this.save({'authData': authData}, newOptions);
      } else {
        var self = this;
        var promise = new Parse.Promise();
        provider.authenticate({
          success: function(provider, result) {
            self._linkWith(provider, {
              authData: result,
              success: options.success,
              error: options.error
            }).then(function() {
              promise.resolve(self);
            });
          },
          error: function(provider, error) {
            if (options.error) {
              options.error(self, error);
            }
            promise.reject(error);
          }
        });
        return promise;
      }
    }
299828
function PrivacyListProxy(options) {
    this.service = options.service;
    this.helpers = options.helpers;
    this.connection = options.stropheClient;
    this.Client = options.xmppClient;
    this.nodeStanzasCallbacks = options.nodeStanzasCallbacks;
}
389932
function proxyOptsFromStr(str) {
    if (!str) {
        return (false);
    }

    var s = str;

    // Normalize: host:port -> http://host:port
    // FWIW `curl` supports using "http_proxy=host:port".
    if (!/^[a-z0-9]+:\/\//.test(s)) {
        s = 'http://' + s;
    }
    var parsed = url.parse(s);

    var proxyOpts = {
        protocol: parsed.protocol,
        host: parsed.hostname
    };

    if (parsed.port) {
        proxyOpts.port = Number(parsed.port);
    }

    if (parsed.auth) {
        proxyOpts.proxyAuth = parsed.auth;
    }

    return (proxyOpts);
}
1303726
function(url, protocols, options) {
    var that = this;
    that._options = {devel: false, debug: false, chunking: undefined};
    if (options) {
        utils.objectExtend(that._options, options);
    }
    that._base_url = utils.amendUrl(url);
    that._server = that._options.server || utils.random_number_string(1000);
    that._connid = utils.random_string(8);
    that._trans_url = that._base_url + '/' + that._server + '/' + that._connid;
    that._protocols = ['websocket',
                       'xhr-streaming',
                       'iframe-eventsource',
                       'iframe-htmlfile',
                       'xhr-polling',
                       'iframe-xhr-polling',
                       'jsonp-polling'];
    switch(typeof protocols) {
    case 'undefined': break;
    case 'string': that._protocols = [protocols]; break;
    default: that._protocols = protocols; break;
    }
    that.protocol = null;
    that.readyState = SockJS.CONNECTING;
    that._didClose();
}
675117
function XHRProxy(options) { // @arg Object = {} - { verbose }
                             // @options.verbose Boolean = false
//{@dev
    $valid($type(options, "Object|omit"), XHRProxy, "options");
//}@dev

    options = options || {};
    this._verbose = options["verbose"] || false;

//{@dev
    $valid($type(options.verbose, "Boolean|omit"), XHRProxy, "options.verbose");
//}@dev

    this._event = new WMEvent()["register"](ALLOW_XHR_EVENTS);
    this._xhr = null;
    this._lv = FUNCTION_LEVEL_0;

    if (global["XMLHttpRequest"]) { // _runOnBrowser
        this._lv = FUNCTION_LEVEL_1;
        this._xhr = new XMLHttpRequest();

        if ("onload"          in this._xhr &&
            "responseType"    in this._xhr &&
            "withCredentials" in this._xhr) {
            this._lv = FUNCTION_LEVEL_2;
        }
    } else { // _runOnNode -> simulate XMLHttpRequest Object
        this._xhr = {
            "readyState":       READY_STATE_UNSENT,
            // --- request ---
            "method":           "",     // "GET" or "POST"
            "url":              "",
            "async":            true,
            "auth":             "",     // "" or "user:password"
            "requestHeader":    {},     // { header: value, ... }
            // --- response ---
            "response":         null,
            "responseText":     "",
            "responseXML":      null,
            "responseHeaders":  {},     // { header: value, ... }
            "status":           0,
            "statusText":       "",
            "upload":           null,
            "withCredentials":  false
        };
    }

//{@dev
    if (this._verbose) {
        console.log("XMLHttpRequest Level is " + this._lv);
    }
//}@dev

    this._lastRequestURL = "";
    this._lastReadyState = READY_STATE_UNSENT;

    // setup property getter and setter.
    Object.defineProperties(this, {
        "readyState":     { "get": getReadyState                                },
        "response":       { "get": getResponse                                  },
        "responseText":   { "get": getResponseText                              },
        "responseType":   { "get": getResponseType,   "set": setResponseType    },
        "responseXML":    { "get": getResponseXML                               },
        "status":         { "get": getStatus                                    },
        "statusText":     { "get": getStatusText                                },
        "upload":         { "get": getUpload,         "set": setUpload          },
        "withCredentials":{ "get": getWithCredentials,"set": setWithCredentials }
    });
}
543319
function(value, options) {
      if (!v.isDefined(value)) {
        return;
      }

      options = v.extend({}, this.options, options);

      var message = options.message || this.message || "is not a valid url"
        , schemes = options.schemes || this.schemes || ['http', 'https']
        , allowLocal = options.allowLocal || this.allowLocal || false
        , allowDataUrl = options.allowDataUrl || this.allowDataUrl || false;
      if (!v.isString(value)) {
        return message;
      }

      // https://gist.github.com/dperini/729294
      var regex =
        "^" +
        // protocol identifier
        "(?:(?:" + schemes.join("|") + ")://)" +
        // user:pass authentication
        "(?:\\S+(?::\\S*)?@)?" +
        "(?:";

      var tld = "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))";

      if (allowLocal) {
        tld += "?";
      } else {
        regex +=
          // IP address exclusion
          // private & local networks
          "(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
          "(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
          "(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})";
      }

      regex +=
          // IP address dotted notation octets
          // excludes loopback network 0.0.0.0
          // excludes reserved space >= 224.0.0.0
          // excludes network & broacast addresses
          // (first & last IP address of each class)
          "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
          "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
          "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
        "|" +
          // host name
          "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
          // domain name
          "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
          tld +
        ")" +
        // port number
        "(?::\\d{2,5})?" +
        // resource path
        "(?:[/?#]\\S*)?" +
      "$";

      if (allowDataUrl) {
        // RFC 2397
        var mediaType = "\\w+\\/[-+.\\w]+(?:;[\\w=]+)*";
        var urlchar = "[A-Za-z0-9-_.!~\\*'();\\/?:@&=+$,%]*";
        var dataurl = "data:(?:"+mediaType+")?(?:;base64)?,"+urlchar;
        regex = "(?:"+regex+")|(?:^"+dataurl+"$)";
      }

      var PATTERN = new RegExp(regex, 'i');
      if (!PATTERN.exec(value)) {
        return message;
      }
    }
708955
function(options) {
  if (typeof options !== 'object') {
    options = {};
  }
  this._options = options = _.defaults(options, {
    trustedProxies: ['127.0.0.1'],
    clickjacking: 'deny',
    noMimeSniffing: true,
    log: console.log,
    maxInputSize: 1024 * 1024
  });

  this._app = connect();

  this._app.use(function(req, res, next) {
    // Set body to stream if posting data not yet processed by the bodyparser.
    if (['GET', 'HEAD'].indexOf(req.method) < 0 && typeof req.headers['content-type'] === 'string') {
      req.body = new Readable();
      req.body.wrap(req);
      // Parse the boundary for multipart data.
      var boundary = req.headers['content-type'].match(/^multipart\/.+?(?:; boundary=(?:(?:"(.+)")|(?:([^\s]+))))$/i);
      req.multipartBoundary = boundary ? boundary[1] || boundary[2] : null;
    }
    next();
  });
  this._app.use(bodyParser.urlencoded({extended: false}));
  this._app.use(bodyParser.json({limit: options.maxInputSize}));
  this._app.use(bodyParser.text({type: 'text/*', limit: this._options.maxInputSize}));
  this._app.use(cookieParser());
  this._app.use(compression());

  this.phases = [
    {name: 'initialize', concurrent: true, error: false, errorStatus: 500},
    {name: 'authentication', concurrent: false, error: false, errorStatus: 401},
    {name: 'authorisation', concurrent: false, error: false, errorStatus: 403},
    {name: 'prevalidation', concurrent: true, error: false, errorStatus: 400},
    {name: 'preprocess', concurrent: false, error: false, errorStatus: 500},
    {name: 'postvalidation', concurrent: true, error: false, errorStatus: 400},
    {name: 'process', concurrent: false, error: false, errorStatus: 500},
    {name: 'postprocess', concurrent: false, error: false, errorStatus: 500},
    {name: '_send', concurrent: false, error: false},
    {name: 'after', concurrent: true, error: false},
    {name: 'error', concurrent: false, error: true, errorStatus: 500},
    {name: '_senderror', concurrent: false, error: true},
    {name: 'aftererror', concurrent: true, error: true}
  ];
  this.addRegisterFunctions(this);

  this._types = {
    'alpha': '[a-z]+',
    'alphanum': '[a-z0-9]+',
    'bool': '(?:1|0|true|false)',
    'float': '\\-?[0-9\\.]+',
    'int': '[1-9][0-9]*',
    'path': '.+?',
    'signed': '\\-?[0-9]+',
    'string': '[^\\/]+',
    'unsigned': '[0-9]+',
    'uuid': '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
  };

  this._send(sendHandler);
  this.error(errorHandler);
  this._senderror(sendHandler);

  var log = this._options.log;
  if (typeof log === 'function') {
    this.after(function() { logHandler.apply(this, [log]); });
    this.aftererror(function() { logHandler.apply(this, [log]); });
  }
}
115643
function(connect, options) {
	              return [
	                connect.compress({
	                  level: 9
	                }),
	                function(req, res, next) {
	                  if (req.headers.origin === undefined) {
	                    res.setHeader('Access-Control-Allow-Origin', "*");
	                  } else {
	                    res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
	                  }
	                  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
	                  console.log(req.method + " on " + req.originalUrl);
	                  if (req.originalUrl.indexOf("/data/")===0) {
	                    res.setHeader('Access-Control-Allow-Headers', 'content-type');
	                    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
	                    res.setHeader('Content-Length', '0');
	                    res.setHeader('Content-Type', 'application/json; charset=utf-8');
	                    datahandler(req,res,"./app/stubs/Unidesk/WebSocket");
	                    res.end();
	                  } else if(req.originalUrl.indexOf("/app/")===0) {
	                      var body = grunt.file.read(options.base+"src/index.html");
	                      res.write(body);
	                      res.end();
	                  } else {
	                    next();
	                  }
	                },
	                connect.static(options.base),
	                function(req, res, next){
	                	if(!(/\/(src|dist)\//).test(req.originalUrl)){
	                      var body = grunt.file.read("src/index.html");
	                      res.write(body);
	                      res.end();
	                	} else {
	                		 next();
	                	}
	                },
	                connect.directory(options.base)
	              ];
	            }
229418
function access(options) {
  options = options || {};

  // The allowed origins of the request.
  options.origins = 'origins' in options
    ? options.origins
    : '*';

  // The allowed methods for the request.
  options.methods = 'methods' in options
    ? options.methods
    : ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'OPTIONS'];

  // Allow sending of authorization and cookie information.
  options.credentials = 'credentials' in options
    ? options.credentials
    : true;

  // Cache duration of the preflight/OPTIONS request.
  options.maxAge = 'maxAge' in options
    ? options.maxAge
    : '30 days';

  // The allowed request headers.
  options.headers = 'headers' in options
    ? options.headers
    : '';

  // Server headers exposed to the user agent.
  options.exposed = 'exposed' in options
    ? options.exposed
    : '';

  //
  // Be a bit flexible in the way the arguments are supplied, transform Array's
  // in to strings and human readable numbers strings in to numbers.
  //
  ['methods', 'headers', 'exposed', 'origins'].forEach(function cleanup(key) {
    if (Array.isArray(options[key])) options[key] = options[key].join(', ');
  });

  //
  // The maxAge header value must be expressed in seconds so we need to convert
  // the milliseconds returned by the `millisecond` module in seconds.
  //
  if ('string' === typeof options.maxAge) {
    options.maxAge = ms(options.maxAge) / 1000;
  }

  var separator = /[, ]+/
    , methods = options.methods.toUpperCase().split(separator).filter(Boolean)
    , headers = options.headers.toLowerCase().split(separator).filter(Boolean)
    , origins = options.origins.toLowerCase().split(separator).filter(Boolean);

  /**
   * The actual function that handles the setting of the requests and answering
   * of the OPTIONS method.
   *
   * @param {Request} req The incoming HTTP request.
   * @param {Response} res The outgoing HTTP response.
   * @param {Function} next Optional callback for middleware support.
   * @returns {Boolean}
   * @api public
   */
  return function control(req, res, next) {
    var origin = (req.headers.origin || '').toLowerCase().trim()
      , credentials = options.credentials;

    //
    // The `origin` header WILL always be send for browsers that support CORS.
    // If it's in the request headers, we should not be sending the headers as
    // it would only be pointless overhead.
    //
    // @see https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS#Origin
    //
    if (!('origin' in req.headers)) {
      if ('function' === typeof next) next();
      return false;
    }

    //
    // Validate the current request to ensure that proper headers are being sent
    // and that we don't answer with bullshit.
    //
    if (
         ~origin.indexOf('%')
      || (origin !== 'null' && !parse(origin).protocol)
      || options.origins !== '*' && !~origins.indexOf(origin)
      || (methods.length && !~methods.indexOf(req.method))
      // @TODO header validation
    ) {
      res.statusCode = 403;
      res.setHeader('Content-Type', 'text/plain');
      res.end([
        'Invalid HTTP Access Control (CORS) request:',
        '  Origin: '+ req.headers.origin,
        '  Method: '+ req.method
      ].join('\n'));

      return true;
    }

    //
    // GET requests are not preflighted for CORS but the browser WILL reject the
    // response if the request is made with the `withCredentials` flag enabled
    // and the `Access-Control-Allow-Origin` header is set to `*`. In addition to
    // this, if the server specifies an origin host rather than `*`, the it must
    // be either a SINGLE origin or the string `null`.
    //
    if (options.origins !== '*' || credentials) {
      setHeader(res, 'Access-Control-Allow-Origin', req.headers.origin);
      vary(res, 'Origin');
    } else {
      setHeader(res, 'Access-Control-Allow-Origin', '*');
    }

    if (credentials) {
      setHeader(res, 'Access-Control-Allow-Credentials', 'true');
    }

    //
    // The HTTP Access Control (CORS) uses the OPTIONS method for preflight
    // requests so it can get approval before doing the actual request. So it's
    // vital that these requests are handled first and as soon as possible. But
    // as OPTIONS requests can also be made for other types of requests, we need
    // to explicitly check if the `Access-Control-Request-Method` header has been
    // sent to ensure that this is a preflight request.
    //
    if (
         'OPTIONS' === req.method
      && req.headers['access-control-request-method']
    ) {
      if (options.maxAge) {
        setHeader(res, 'Access-Control-Max-Age', options.maxAge);
      }

      if (options.methods) {
        setHeader(res, 'Access-Control-Allow-Methods', methods.join(', '));
      }

      if (options.headers) {
        setHeader(res, 'Access-Control-Allow-Headers', options.headers);
      } else if (req.headers['access-control-request-headers']) {
        setHeader(res, 'Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
      }

      //
      // OPTION methods SHOULD be answered with a 200 status code so we're
      // correctly following the RFC 2616
      //
      // @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
      //
      res.statusCode = 200;
      res.setHeader('Content-Length', 0);
      res.end('');

      return true;
    }

    if (options.exposed) {
      setHeader(res, 'Access-Control-Expose-Headers', options.exposed);
    }

    if ('function' === typeof next) next();
    return false;
  };
}
183651
function WPOAuth(options){
  if (!(this instanceof WPOAuth)) return new WPOAuth(options);

  // Options
  this.opts = globals = options || {};
  for (var attr in def){
    this.opts[attr] = this.opts[attr] || def[attr];
  }

  this._code = this.opts.code;

  // Error exceptions
  if (!this.opts.client_id) {
    throw new Error('`client_id` is required');
  }

  if (!this.opts.client_secret) {
    throw new Error('`client_secret` is required');
  }
}
1263354
function HttpsProxyAgent (opts) {
  if (!(this instanceof HttpsProxyAgent)) return new HttpsProxyAgent(opts);
  if ('string' == typeof opts) opts = url.parse(opts);
  if (!opts) throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!');
  debug('creating new HttpsProxyAgent instance: %o', opts);
  Agent.call(this, connect);

  var proxy = extend({}, opts);

  // if `true`, then connect to the proxy server over TLS. defaults to `false`.
  this.secureProxy = proxy.protocol ? /^https:?$/i.test(proxy.protocol) : false;

  // prefer `hostname` over `host`, and set the `port` if needed
  proxy.host = proxy.hostname || proxy.host;
  proxy.port = +proxy.port || (this.secureProxy ? 443 : 80);

  if (proxy.host && proxy.path) {
    // if both a `host` and `path` are specified then it's most likely the
    // result of a `url.parse()` call... we need to remove the `path` portion so
    // that `net.connect()` doesn't attempt to open that as a unix socket file.
    delete proxy.path;
    delete proxy.pathname;
  }

  this.proxy = proxy;
}
400157
function proxyHttps(){
  httpServer.on('connect', function(req, socket, upgradeHead){
    var hostname = req.url.split(':')[0];
    log.debug('Create internal https server for ' + hostname);
    createInternalHttpsServer(hostname, function (err, httpsServerPort) {
      if (err) {
        log.error('Failed to create internal https proxy');
        log.error(err);
        return;
      }
      // get proxy https server
      var netClient = net.createConnection(httpsServerPort);

      netClient.on('connect', function(){
        log.info('connect to https server successfully!');
        socket.write( "HTTP/1.1 200 Connection established\r\nProxy-agent: Netscape-Proxy/1.1\r\n\r\n");
      });

      socket.on('data', function(chunk){
        netClient.write(chunk);
      });
      socket.on('end', function(){
        netClient.end();
      });
      socket.on('close', function(){
        netClient.end();
      });
      socket.on('error', function(err){
        log.error('socket error ' + err.message);
        netClient.end();
      });

      netClient.on('data', function(chunk){
        socket.write(chunk);
      });
      netClient.on('end', function(){
        socket.end();
      });
      netClient.on('close', function(){
        socket.end();
      });
      netClient.on('error', function(err){
        log.error('netClient error ' + err.message);
        socket.end();
      });
    });
  });
}