end 254491    [proxies BOTP] mis-handling of non-existent welcome-file's    WAS.webcontainer
431310
public boolean isAvailableInDocumentRoot(String resource,boolean searchEDR) {
		boolean available = false;
		try { 
	    	if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable (Level.FINE))
	    		logger.logp(Level.FINE, CLASS_NAME,"isAvailable()","File not found in WAR directorr so check DocumetRoots");
            DocumentRootUtils docRoot = new DocumentRootUtils( this._webapp, extendedDocumentRoot,preFragmentExtendedDocumentRoot);
            docRoot.handleDocumentRoots(resource,preFragmentExtendedDocumentRoot!=null,!WCCustomProperties.SKIP_META_INF_RESOURCES_PROCESSING,searchEDR);
            
            //Check first to see if we found an Entry match inside of a DocumentRoot
            EntryResource entryr = docRoot.getMatchedEntryResource();
            if(entryr != null){
                if(entryr.getEntry() != null){
                    return true;
                }
            }
            
            String filePath = docRoot.getFilePath();
            if (filePath!=null) {
		    	if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable (Level.FINE))
		    		logger.logp(Level.FINE, CLASS_NAME,"isAvailable()","Match found in DocumetRootd");
            	File caseFile = new Java2SecurityFile(filePath);
                available = caseFile.exists();
            }  
		} catch (FileNotFoundException fne) {
	    	if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable (Level.FINE))
	    		logger.logp(Level.FINE, CLASS_NAME,"isAvailable()","FileNotFoundException caught");
        	/* ignore */
        } catch (IOException ioe) {
        	if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable (Level.FINE))
        		logger.logp(Level.FINE, CLASS_NAME,"isAvailable()","IOException caught");
        	/* ignore */
        }                
        return available;
	}
797732
function errors() {
        // handling 404 errors from config.express['404_redirect'] property
        if (config['404_redirect']) {
            server.use(function (req, res, next) {
                res.status(302)
                res.writeHead(302, { 'Location': config['404_redirect'] })
                res.end()
            })
        } else {
            server.use(function (req, res, next) {
                res.status(404).send({ message: 'not found' })
            })
        }

        if (errorHandlers.length) {
            for (let eh of errorHandlers) {
                server.use(wrapper(eh))
            }
        }

        //Default error handler
        server.use((err, req, res, next) => {
            if (!config.silent && !errorHandlers.length)
                app.drivers.logger.error('Unhandled server error', err)
            res.status(500)
               .json({
                   message: err.message,
                   stack: process.env.NODE_ENV === 'production' ? undefined : err.stack
               })
        })
    }
59316
def __enableProxy(self):
        
        os.environ[
            "HTTP_PROXY"] = self.httpProxy()
        os.environ[
            "HTTPS_PROXY"] = self.httpsProxy()

        os.environ["REQUESTS_CA_BUNDLE"] = os.path.join(
            os.path.dirname(
                os.path.abspath(__file__)),
            "cert.pem")
1682
def main(overwrite):
    
    logger.debug("Checking existence of '%s'.", CONF_PATH)
    if not os.path.exists(CONF_PATH):
        logger.debug("Directory %s not found! Panicking..", CONF_PATH)
        raise UserWarning(
            "Can't find '%s' - it looks like ProFTPD is not installed!" % (
                CONF_PATH,
            )
        )

    # check existence of proftpd.conf
    logger.debug("Checking existence of configuration file '%s'.", CONF_FILE)
    if not os.path.exists(CONF_FILE):
        logger.debug("Configuration file not found, creating..")
        _write_conf_file()
    else:
        logger.debug("Found.")

        if not os.path.exists(CONF_FILE + "_"):
            logger.debug(
                "Backing up the configuration file '%s' -> '%s'.",
                CONF_FILE,
                CONF_FILE + "_"
            )
            shutil.copyfile(CONF_FILE, CONF_FILE + "_")
        else:
            logger.debug(
                "Backup already exists. '%s' will be overwritten.",
                CONF_FILE
            )
    if overwrite:
        logger.debug("--update switch not found, overwriting conf file")
        _write_conf_file()

    logger.debug("Checking existence of the '%s' file.", MODULES_FILE)
    if not os.path.exists(MODULES_FILE) and _is_deb_system():
        with open(MODULES_FILE, "w") as f:
            f.write(DEFAULT_MODULES_CONF)
            logger.debug("Modules file not found. Created '%s'.", MODULES_FILE)

    # create data directory, where the user informations will be stored
    logger.debug("Checking existence of user's directory '%s'.", DATA_PATH)
    if not os.path.exists(DATA_PATH):
        logger.debug("Directory '%s' not found, creating..", DATA_PATH)

        os.makedirs(DATA_PATH, 0777)

        logger.debug("Done. '%s' created.", DATA_PATH)

    # create user files if they doesn't exists
    logger.debug("Checking existence of passwd file '%s'.", LOGIN_FILE)
    if not os.path.exists(LOGIN_FILE):
        logger.debug("passwd file not found, creating..")

        open(LOGIN_FILE, "a").close()

        logger.debug("Done. '%s' created.")

    logger.debug("Setting permissions..")
    os.chown(LOGIN_FILE, get_ftp_uid(), -1)
    os.chmod(LOGIN_FILE, 0400)

    # load values from protpd conf file
    logger.debug("Switching and adding options..")
    data = ""
    with open(CONF_FILE) as f:
        data = f.read()

    # set path to passwd file
    logger.debug("\tAuthUserFile")
    data = add_or_update(
        data,
        "AuthUserFile",
        LOGIN_FILE
    )
    logger.debug("\tRequireValidShell")
    data = add_or_update(data, "RequireValidShell", "off")
    logger.debug("\tDefaultRoot")
    data = add_or_update(data, "DefaultRoot", "~")

    # http://www.proftpd.org/docs/modules/mod_log.html
    logger.debug("\tLogFormat")
    data = add_or_update(data, "LogFormat", 'paths "%f, %u, %m, %{%s}t"')
    logger.debug("\tExtendedLog")
    data = add_or_update(
        data,
        "ExtendedLog",
        LOG_FILE + " WRITE paths"
    )

    if not _is_deb_system():
        logger.debug("Detected non debian based linux. Aplying SUSE changes.")
        data = comment(data, "IdentLookups off")
        data = comment(data, "Include /etc/proftpd/modules.conf")
        data = add_or_update(data, "User", "ftp")

    # save changed file
    logger.debug("Saving into config file..")
    with open(CONF_FILE, "w") as f:
        f.write(data)
        logger.debug("Done.")

    logger.debug("Sending proftpd signal to reload configuration..")
    reload_configuration()
    logger.debug("Done.")
    logger.info("All set.")
145519
function exitHandler(options, err) {
  if (err) {
    if (err.stack) {
      console.error(err.stack);
    } else {
      console.error(err.toString());
    }
  }
	if (whitelistedVulnerabilities.length > 0) {
        logger.info(colors.bold.yellow("Filtering the following vulnerabilities"));
        logger.info(colors.bold.yellow('=================================================='));
        for (var i = 0; i < whitelistedVulnerabilities.length; i++) {
        	var detail = whitelistedVulnerabilities[i];
          logger.info(`${colors.bold.blue(detail['title'])} affected versions: ${colors.red(detail['package'])} ${colors.red(detail['versions'])}`);
          logger.info(`${detail['description']}`);
          logger.info(colors.bold("ID") + ": " + detail.id);
          if (detail.whitelistedPaths) {
            detail.whitelistedPaths.forEach(function(path) {
              logger.info(colors.bold("Ignored Path") + ": " + path);
            })
          }
          logger.info(colors.bold.yellow('=================================================='));
        };
	}

  logger.info('');
  logger.info('Audited dependencies: ' + actualAudits +
            ', Vulnerable: ' + colors.bold.red(vulnerabilityCount) +
            ', Ignored: ' + whitelistedVulnerabilities.length);

    if(config.get('report')) {
        var filtered = whitelistedVulnerabilities.length;
        mkdirp('reports');
        if (JUnit[0] != '<') { // This is a hack in case this gets called twice
        	// Convert to XML
            JUnit = jsontoxml(JUnit);
        }
        var dom = new DOMParser().parseFromString(JUnit);
        dom.documentElement.setAttribute('name', `auditjs.security.${programPackage.split('.')[0]}`);
        dom.documentElement.setAttribute('errors', 0);
        dom.documentElement.setAttribute('tests', expectedAudits);
        dom.documentElement.setAttribute('package', 'test');
        dom.documentElement.setAttribute('id', '');
        dom.documentElement.setAttribute('skipped', filtered);
        dom.documentElement.setAttribute('failures', vulnerabilityCount);
        JUnit = new XMLSerializer().serializeToString(dom);
        logger.info( `Wrote JUnit report to reports/${output}`);
        fs.writeFileSync('reports/' + output, `<?xml version="1.0" encoding="UTF-8"?>\n${JUnit}`);
    }

    if (config.get('suppressExitError')) {
      process.exit(0);
    } else {
      process.exit(vulnerabilityCount);
    }
}
918089
function download(url, dest, cb) {
  var reportError = function(err) {
    cb(['Cannot download "', url, '": ',
      typeof err.message === 'string' ? err.message : err].join(''));
  };
  var successful = function(response) {
    return response.statusCode >= 200 && response.statusCode < 300;
  };

  applyProxy({ rejectUnauthorized: false }, function(options) {
    options.headers = {
      'User-Agent': [
        'node/', process.version, ' ',
        'node-sass-installer/', pkg.version
      ].join('')
    };
    try {
      request(url, options, function(err, response) {
        if (err) {
          reportError(err);
        } else if (!successful(response)) {
            reportError(['HTTP error', response.statusCode, response.statusMessage].join(' '));
        } else {
            cb();
        }
      }).on('response', function(response) {
          if (successful(response)) {
            response.pipe(fs.createWriteStream(dest));
          }
      });
    } catch (err) {
      cb(err);
    }
  });
}
190089
function attemptPing (db, job, webhookOptions) {
  if (!(typeof webhookOptions === 'object')) {
    throw new Error('No webhook is configured.')
  }

  return webhook.ping(job, webhookOptions)
    .then(response => {
      return _logPing(db, job.id, response)
        .then(function () {
          return response
        })
    })
}
919282
function(err, r, b) {
      if (err) throw err;
      try {
        fs.unlink(keyname, this.parallel());
        fs.unlink(keyname + ".pub", this.parallel());
      } catch(e) {
        // do nothing
      };
      console.log("Heroku SSH keypair deleted from local FS");
      callback(err, this.privkey, this.pubkey, this.user_host_field);
    }
1311016
function proxy() {
  const defaultProxy = {
    changeOrigin: true,
    ws: true,
    logLevel: 'info',
    xfwd: true,
    logProvider() {
      return {
        log(...args) {
          Logger.log(proxyLogRewrite(args));
        },
        debug(...args) {
          Logger.debug(proxyLogRewrite(args));
        },
        info(...args) {
          Logger.info(proxyLogRewrite(args));
        },
        warn(...args) {
          Logger.warn(proxyLogRewrite(args));
        },
        error(...args) {
          Logger.error(proxyLogRewrite(args));
        }
      };
    }
  };

  const { proxies } = settings.configuration;

  if (!proxies) {
    return null;
  }

  const config = [];

  // Iterate through each proxy configuration
  proxies.forEach(proxyConfiguration => {
    // Merge in defaults including custom Logger and custom request/response function
    const proxyConfig = merge({}, defaultProxy, proxyConfiguration, {
      onProxyReq: (proxyReq, req) => {
        onRequest(proxyConfiguration, proxyReq, req);
        if (typeof proxyConfiguration.onProxyReq === 'function') {
          proxyConfiguration.onProxyReq(proxyReq, req);
        }
      },

      onProxyRes: (proxyRes, req, res) => {
        onResponse(proxyConfiguration, proxyRes, req, res);
        if (typeof proxyConfiguration.onProxyRes === 'function') {
          proxyConfiguration.onProxyRes(proxyRes, req, res);
        }
      },

      onError: (err, req, res) => {
        onProxyError(proxyConfiguration, err, req, res);
        if (typeof proxyConfiguration.onError === 'function') {
          proxyConfiguration.onError(err, req, res);
        }
      }
    });

    const proxyContext = Array.isArray(proxyConfig.context) ? proxyConfig.context[0] : proxyConfig.context;

    // Only create proxy if enabled
    if (proxyConfig.enabled) {
      config.push(proxyConfig);
    } else {
      Logger.info(
        `Proxy with context: ${chalk.dim(proxyContext)} and target: ${chalk.dim(proxyConfig.target)} is ${chalk.magenta(
          'DISABLED'
        )}`
      );
    }
  });

  // return null if the array is 0 to make the checks easier upstream
  return config.length === 0 ? null : config;
}
315554
def main():
    
    log = logging.getLogger(mod_logger + '.main')
    log.debug('This is DEBUG!')
    log.info('This is INFO!')
    log.warning('This is WARNING!')
    log.error('This is ERROR!')
    log.info('Running s3util.main...')
    my_bucket = 'cons3rt-deploying-cons3rt'
    my_regex = 'sourcebuilder.*apache-maven-.*3.3.3.*'
    try:
        s3util = S3Util(my_bucket)
    except S3UtilError as e:
        log.error('There was a problem creating S3Util:\n%s', e)
    else:
        log.info('Created S3Util successfully')
        key = s3util.find_key(my_regex)
        test = None
        if key is not None:
            test = s3util.download_file(key, '/Users/yennaco/Downloads')
        if test is not None:
            upload = s3util.upload_file(test, 'media-files-offline-assets/test')
            log.info('Upload result: %s', upload)
    log.info('End of main!')
455562
function(p) {

				// The proxy supports allow-cross-origin-resource
				// Alas that's the only thing we're using.
				if (p.data && p.data.file) {
					var file = p.data.file;
					if (file) {
						if (file.files) {
							p.data = file.files[0];
						}
						else {
							p.data = file;
						}
					}
				}

				if (p.method === 'delete') {
					p.method = 'post';
				}

				return true;
			}
542016
function createServer(bs) {
    var proxy = bs.options.get("proxy");
    var server = bs.options.get("server");

    if (!proxy && !server) {
        return require("./snippet-server")(bs);
    }

    if (proxy) {
        return require("./proxy-server")(bs);
    }

    if (server) {
        return require("./static-server")(bs);
    }
}
380828
public static void init(String[] args) throws UnknownHostException {
        boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false, hidden = false;
        boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
        boolean mlst = false, mlsd = false;
        boolean lenient = false;
        long keepAliveTimeout = -1;
        int controlKeepAliveReplyTimeout = -1;
        int minParams = 5; // listings require 3 params
        String protocol = null; // SSL protocol
        String doCommand = null;
        String trustmgr = null;
        String proxyHost = null;
        int proxyPort = 80;
        String proxyUser = null;
        String proxyPassword = null;
        String username = null;
        String password = null;

        int base = 0;
        for (base = 0; base < args.length; base++) {
            if (args[base].equals("-s")) {
                storeFile = true;
            } else if (args[base].equals("-a")) {
                localActive = true;
            } else if (args[base].equals("-A")) {
                username = "anonymous";
                password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
            } else if (args[base].equals("-b")) {
                binaryTransfer = true;
            } else if (args[base].equals("-c")) {
                doCommand = args[++base];
                minParams = 3;
            } else if (args[base].equals("-d")) {
                mlsd = true;
                minParams = 3;
            } else if (args[base].equals("-e")) {
                useEpsvWithIPv4 = true;
            } else if (args[base].equals("-f")) {
                feat = true;
                minParams = 3;
            } else if (args[base].equals("-h")) {
                hidden = true;
            } else if (args[base].equals("-k")) {
                keepAliveTimeout = Long.parseLong(args[++base]);
            } else if (args[base].equals("-l")) {
                listFiles = true;
                minParams = 3;
            } else if (args[base].equals("-L")) {
                lenient = true;
            } else if (args[base].equals("-n")) {
                listNames = true;
                minParams = 3;
            } else if (args[base].equals("-p")) {
                protocol = args[++base];
            } else if (args[base].equals("-t")) {
                mlst = true;
                minParams = 3;
            } else if (args[base].equals("-w")) {
                controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
            } else if (args[base].equals("-T")) {
                trustmgr = args[++base];
            } else if (args[base].equals("-PrH")) {
                proxyHost = args[++base];
                String[] parts = proxyHost.split(":");
                if (parts.length == 2) {
                    proxyHost = parts[0];
                    proxyPort = Integer.parseInt(parts[1]);
                }
            } else if (args[base].equals("-PrU")) {
                proxyUser = args[++base];
            } else if (args[base].equals("-PrP")) {
                proxyPassword = args[++base];
            } else if (args[base].equals("-#")) {
                printHash = true;
            } else {
                break;
            }
        }

        int remain = args.length - base;
        if (username != null) {
            minParams -= 2;
        }
        if (remain < minParams) // server, user, pass, remote, local [protocol]
        {
            System.err.println(USAGE);
            System.exit(1);
        }

        String server = args[base++];
        int port = 0;
        String[] parts = server.split(":");
        if (parts.length == 2) {
            server = parts[0];
            port = Integer.parseInt(parts[1]);
        }
        if (username == null) {
            username = args[base++];
            password = args[base++];
        }

        String remote = null;
        if (args.length - base > 0) {
            remote = args[base++];
        }

        String local = null;
        if (args.length - base > 0) {
            local = args[base++];
        }

        final FTPClient ftp;
        if (protocol == null) {
            if (proxyHost != null) {
                System.out.println("Using HTTP proxy server: " + proxyHost);
                ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
            } else {
                ftp = new FTPClient();
            }
        } else {
            FTPSClient ftps;
            if (protocol.equals("true")) {
                ftps = new FTPSClient(true);
            } else if (protocol.equals("false")) {
                ftps = new FTPSClient(false);
            } else {
                String[] prot = protocol.split(",");
                if (prot.length == 1) { // Just protocol
                    ftps = new FTPSClient(protocol);
                } else { // protocol,true|false
                    ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
                }
            }
            ftp = ftps;
            if ("all".equals(trustmgr)) {
                ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
            } else if ("valid".equals(trustmgr)) {
                ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
            } else if ("none".equals(trustmgr)) {
                ftps.setTrustManager(null);
            }
        }

        if (printHash) {
            ftp.setCopyStreamListener(createListener());
        }
        if (keepAliveTimeout >= 0) {
            ftp.setControlKeepAliveTimeout(keepAliveTimeout);
        }
        if (controlKeepAliveReplyTimeout >= 0) {
            ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
        }
        ftp.setListHiddenFiles(hidden);

        // suppress login details
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

        try {
            int reply;
            if (port > 0) {
                ftp.connect(server, port);
            } else {
                ftp.connect(server);
            }
            System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

            // After connection attempt, you should check the reply code to
            // verify
            // success.
            reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                System.err.println("FTP server refused connection.");
                System.exit(1);
            }
        } catch (IOException e) {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    // do nothing
                }
            }
            System.err.println("Could not connect to server.");
            e.printStackTrace();
            System.exit(1);
        }

        __main: try {
            if (!ftp.login(username, password)) {
                ftp.logout();
                error = true;
                break __main;
            }

            System.out.println("Remote system is " + ftp.getSystemType());

            if (binaryTransfer) {
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
            } else {
                // in theory this should not be necessary as servers should
                // default to ASCII
                // but they don't all do so - see NET-500
                ftp.setFileType(FTP.ASCII_FILE_TYPE);
            }

            // Use passive mode as default because most of us are
            // behind firewalls these days.
            if (localActive) {
                ftp.enterLocalActiveMode();
            } else {
                ftp.enterLocalPassiveMode();
            }

            ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

            if (storeFile) {
                InputStream input;

                input = new FileInputStream(local);

                ftp.storeFile(remote, input);

                input.close();
            } else if (listFiles) {
                if (lenient) {
                    FTPClientConfig config = new FTPClientConfig();
                    config.setLenientFutureDates(true);
                    ftp.configure(config);
                }

                for (FTPFile f : ftp.listFiles(remote)) {
                    System.out.println(f.getRawListing());
                    System.out.println(f.toFormattedString());
                }
            } else if (mlsd) {
                for (FTPFile f : ftp.mlistDir(remote)) {
                    System.out.println(f.getRawListing());
                    System.out.println(f.toFormattedString());
                }
            } else if (mlst) {
                FTPFile f = ftp.mlistFile(remote);
                if (f != null) {
                    System.out.println(f.toFormattedString());
                }
            } else if (listNames) {
                for (String s : ftp.listNames(remote)) {
                    System.out.println(s);
                }
            } else if (feat) {
                // boolean feature check
                if (remote != null) { // See if the command is present
                    if (ftp.hasFeature(remote)) {
                        System.out.println("Has feature: " + remote);
                    } else {
                        if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                            System.out.println("FEAT " + remote + " was not detected");
                        } else {
                            System.out.println("Command failed: " + ftp.getReplyString());
                        }
                    }

                    // Strings feature check
                    String[] features = ftp.featureValues(remote);
                    if (features != null) {
                        for (String f : features) {
                            System.out.println("FEAT " + remote + "=" + f + ".");
                        }
                    } else {
                        if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                            System.out.println("FEAT " + remote + " is not present");
                        } else {
                            System.out.println("Command failed: " + ftp.getReplyString());
                        }
                    }
                } else {
                    if (ftp.features()) {
                        // Command listener has already printed the output
                    } else {
                        System.out.println("Failed: " + ftp.getReplyString());
                    }
                }
            } else if (doCommand != null) {
                if (ftp.doCommand(doCommand, remote)) {
                    // Command listener has already printed the output
                    // for(String s : ftp.getReplyStrings()) {
                    // System.out.println(s);
                    // }
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            } else {
                OutputStream output;

                output = new FileOutputStream(local);

                ftp.retrieveFile(remote, output);

                output.close();
            }

            ftp.noop(); // check that control connection is working OK

            ftp.logout();
        } catch (FTPConnectionClosedException e) {
            error = true;
            System.err.println("Server closed connection.");
            e.printStackTrace();
        } catch (IOException e) {
            error = true;
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException f) {
                    // do nothing
                }
            }
        }

        System.exit(error ? 1 : 0);
    }
820457
public function adjustHttpStatus() {
        $httpStatus = array ( 
            100 => 'HTTP/1.1 100 Continue', 
            101 => 'HTTP/1.1 101 Switching Protocols', 
            200 => 'HTTP/1.1 200 OK', 
            201 => 'HTTP/1.1 201 Created', 
            202 => 'HTTP/1.1 202 Accepted', 
            203 => 'HTTP/1.1 203 Non-Authoritative Information', 
            204 => 'HTTP/1.1 204 No Content', 
            205 => 'HTTP/1.1 205 Reset Content', 
            206 => 'HTTP/1.1 206 Partial Content', 
            300 => 'HTTP/1.1 300 Multiple Choices', 
            301 => 'HTTP/1.1 301 Moved Permanently', 
            302 => 'HTTP/1.1 302 Found', 
            303 => 'HTTP/1.1 303 See Other', 
            304 => 'HTTP/1.1 304 Not Modified', 
            305 => 'HTTP/1.1 305 Use Proxy', 
            307 => 'HTTP/1.1 307 Temporary Redirect', 
            400 => 'HTTP/1.1 400 Bad Request', 
            401 => 'HTTP/1.1 401 Unauthorized', 
            402 => 'HTTP/1.1 402 Payment Required', 
            403 => 'HTTP/1.1 403 Forbidden', 
            404 => 'HTTP/1.1 404 Not Found', 
            405 => 'HTTP/1.1 405 Method Not Allowed', 
            406 => 'HTTP/1.1 406 Not Acceptable', 
            407 => 'HTTP/1.1 407 Proxy Authentication Required', 
            408 => 'HTTP/1.1 408 Request Time-out', 
            409 => 'HTTP/1.1 409 Conflict', 
            410 => 'HTTP/1.1 410 Gone', 
            411 => 'HTTP/1.1 411 Length Required', 
            412 => 'HTTP/1.1 412 Precondition Failed', 
            413 => 'HTTP/1.1 413 Request Entity Too Large', 
            414 => 'HTTP/1.1 414 Request-URI Too Large', 
            415 => 'HTTP/1.1 415 Unsupported Media Type', 
            416 => 'HTTP/1.1 416 Requested range not satisfiable', 
            417 => 'HTTP/1.1 417 Expectation Failed', 
            500 => 'HTTP/1.1 500 Internal Server Error', 
            501 => 'HTTP/1.1 501 Not Implemented', 
            502 => 'HTTP/1.1 502 Bad Gateway', 
            503 => 'HTTP/1.1 503 Service Unavailable', 
            504 => 'HTTP/1.1 504 Gateway Time-out',
            505 => 'HTTP/1.1 505 HTTP Version not supported',  
        );

        $str = isset($httpStatus[$this->ret]) ? $httpStatus[$this->ret] : "HTTP/1.1 {$this->ret} PhalApi Unknown Status";
        @header($str);

        return $this;
    }
802465
function proxyMiddleware(req, res, next) {
  /*
   * This test is the switch of each request to determine if the request is
   * for a static file to be handled by BrowserSync or a backend request to proxy.
   *
   * The existing test is a standard check on the files extensions but it may fail
   * for your needs. If you can, you could also check on a context in the url which
   * may be more reliable but can't be generic.
   */
  //if (/\.(html|css|js|png|jpg|jpeg|gif|ico|xml|rss|txt|eot|svg|ttf|woff|woff2|cur)(\?((r|v|rel|rev)=[\-\.\w]*)?)?$/.test(req.url)) {
  if (req.url.indexOf('/api/') == -1) {
    next();
  } else {
    proxy.web(req, res);
  }
}
1123774
def get_botcust2():
    
    logger.debug("Getting new botcust2")

    # Set up http request packages
    params = {
        'botid': 'f6a012073e345a08',
        'amp;skin': 'chat'
    }
    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, sdch, br',
        'Accept-Language': 'en-US,en;q=0.8',
        'Connection': 'keep-alive',
        'DNT': '1',
        'Host': 'kakko.pandorabots.com',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/58.0.3029.110 Safari/537.36'
    }

    # Get response from http POST request to url
    logger.debug("Sending POST request")
    response = requests.post(
        url,
        params=params,
        headers=headers
    )
    logger.debug("POST response {}".format(response))

    # Try to extract Mitsuku response from POST response
    try:
        result = response.headers['set-cookie'][9:25]
        logger.debug("Getting botcust2 successful")
    except IndexError:
        result = False
        logger.critical("Getting botcust2 from html failed")

    return result
1373800
def download_file_proxy(p_url, p_op_file, p_username, p_password, proxies):
    
    chunk_size=4096
    import requests
    r = requests.get(p_url, auth=(p_username, p_password), proxies=proxies)
    #print(r.status_code)
    with open(p_op_file, 'wb') as fd:
        for chunk in r.iter_content(chunk_size):
            fd.write(chunk)  
    return r.status_code