Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
Replaced ProxyChainManager with ProxyChain
Jan Curn7b91390f30f1
diff --git a/package.json b/package.jsonindex a0c0eb7b2..546a3604e 100644--- a/package.json+++ b/package.json@@ -44,7 +44,8 @@"underscore": "^1.8.3","portastic": "^1.0.1","tmp": "^0.0.31",- "bluebird": "^3.5.0"+ "bluebird": "^3.5.0",+ "rimraf": "^2.6.1"},"devDependencies": {"babel-cli": "^6.6.5",diff --git a/src/browser.js b/src/browser.jsindex d94b67953..690f7cfe3 100644--- a/src/browser.js+++ b/src/browser.js@@ -1,7 +1,7 @@// import { ChromeLauncher } from 'lighthouse/lighthouse-cli/chrome-launcher';import { APIFY_ENV_VARS } from './constants';import { newPromise, nodeifyPromise, parseUrl } from './utils';-import { ProxyChainManager } from './proxy_chain_manager';+import { ProxyChain } from './proxy_chain';/* global process, require */@@ -29,8 +29,6 @@ export const getDefaultBrowseOptions = () => {};};-const proxyChainManager = new ProxyChainManager();-/*** Represents a single web browser process.@@ -76,7 +74,8 @@ export class Browser {// Instance of Selenium's WebDriverthis.webDriver = null;- this.parsedChildProxyUrl = null;+ // Instance of ProxyChain or null if not used+ this.proxyChain = null;}/**@@ -126,11 +125,8 @@ export class Browser {// Otherwise we need to setup an open child proxy// that will forward to the original proxy with authentication- return proxyChainManager.addProxyChain(this.parsedProxyUrl)- .then((parsedChildProxyUrl) => {- this.parsedChildProxyUrl = parsedChildProxyUrl;- return parsedChildProxyUrl;- });+ this.proxyChain = new ProxyChain(this.parsedProxyUrl);+ return this.proxyChain.start();}).then((effectiveParsedProxyUrl) => {if (/^chrome$/i.test(this.options.browserName)) {@@ -156,12 +152,12 @@ export class Browser {}close() {+ if (this.proxyChain) {+ this.proxyChain.shutdown();+ this.proxyChain = null;+ }+return newPromise()- .then(() => {- if (this.parsedChildProxyUrl) {- return proxyChainManager.removeProxyChain(this.parsedChildProxyUrl);- }- }).then(() => {if (this.webDriver) {return this.webDriver.quit();diff --git a/src/proxy_chain.js b/src/proxy_chain.jsnew file mode 100644index 000000000..5c415b039--- /dev/null+++ b/src/proxy_chain.js@@ -0,0 +1,275 @@+import childProcess from 'child_process';+import fs from 'fs';+import path from 'path';+import _ from 'underscore';+import tmp from 'tmp';+import portastic from 'portastic';+import Promise from 'bluebird';+import rimraf from 'rimraf';+import { parseUrl } from './utils';++/* globals process */++// Constants, exported to simplify unit-testing.+export const PROXY_CHAIN = {+ PORT_FROM: 55000,+ PORT_TO: 60000,+ HOST: '127.0.0.1',+ PROTOCOL: 'http:',+ SQUID_CMD: 'squid',+ SQUID_CHECK_ARGS: ['-v'],+ SQUID_BATCH_TIMEOUT: 10000,+ TMP_DIR_TEMPLATE: '/tmp/apify-squid-XXXXXX',+ CONF_FILE_NAME: 'squid.conf',+ PID_FILE_NAME: 'squid.pid',+ LOG_PREFIX: 'ProxyChain: ',+};++const tmpDirPromised = Promise.promisify(tmp.dir);+const fsWriteFilePromised = Promise.promisify(fs.writeFile);+const execFilePromised = Promise.promisify(childProcess.execFile, { multiArgs: true });+++/**+ * Run Squid process to get its version and wait for the finish+ * @return Promise+ */+const printSquidVersion = () => { // eslint-disable-line no-unused-vars+ // TODO: check that the version is at least 3.3 and throw error otherwise!+ console.log(`${PROXY_CHAIN.LOG_PREFIX}Checking Squid installation with '${PROXY_CHAIN.SQUID_CMD} ${PROXY_CHAIN.SQUID_CHECK_ARGS.join(' ')}'`); // eslint-disable-line max-len+ const options = {+ timeout: PROXY_CHAIN.SQUID_BATCH_TIMEOUT,+ };+ return execFilePromised(PROXY_CHAIN.SQUID_CMD, PROXY_CHAIN.SQUID_CHECK_ARGS, options)+ .then((array) => {+ const stdout = array[0];+ console.log(`${PROXY_CHAIN.LOG_PREFIX}${(stdout || '').split('\n')[0]}`);+ this.isInitialized = true;+ })+ .catch((err) => {+ // Give a user-friendly message for this common error+ if (err.code === 'ENOENT') {+ err = new Error(`'${PROXY_CHAIN.SQUID_CMD}' command not found in the PATH`);+ }+ throw err;+ });+};+++/**+ * The class is used to manage a local Squid proxy instance+ * that forwards HTTP requests to a user-provided parent proxy.+ * The point of this is that there's no easy way to programmatically pass proxy+ * authentication credentials to web browsers such as Chrome, so we need to setup+ * a local open proxy that can forward to parent proxy with authentication.+ */+export class ProxyChain {+ /**+ * Creates a new instance of ProxyChain class.+ * @param parsedProxyUrl Proxy URL parsed by calling parseUrl()+ */+ constructor(parsedProxyUrl) {+ if (!parsedProxyUrl.hostname || !parsedProxyUrl.port) throw new Error('Proxy URL must contain both hostname and port');+ if (parsedProxyUrl.scheme !== 'http') throw new Error('Only "http" proxy protocol is currently supported');++ this.parsedProxyUrl = parsedProxyUrl;++ // PID of the Squid proxy process+ this.squidPid = null;++ // TCP port where Squid is listening+ this.squidPort = null;++ // Path to temporary directory with config files+ this.tmpDir = null;+ }++ _getChildProxyUrl() {+ return `${PROXY_CHAIN.PROTOCOL}//${PROXY_CHAIN.HOST}:${this.squidPort}`;+ }++ _getParentProxyUrl() {+ const p = this.parsedProxyUrl;+ return `${p.protocol}//${p.username || ''}:${p.password ? '<redacted>' : ''}@${p.host}`;+ }++ /**+ * Creates the temporary directory, writes a config to it and starts Squid process.+ * @return Promise+ * @private+ */+ start() {+ // Create temporary directory, if not created yet+ return tmpDirPromised({ template: PROXY_CHAIN.TMP_DIR_TEMPLATE })+ .then((tmpDir) => {+ this.tmpDir = tmpDir;++ return ProxyChain._findFreePort();+ })+ .then((port) => {+ this.squidPort = port;++ // Write config file+ return this._writeSquidConf();+ })+ .then((squidConfPath) => {+ // Start Squid process+ const cmd = PROXY_CHAIN.SQUID_CMD;+ const args = ['-f', squidConfPath, '-N'];+ const options = { cwd: this.tmpDir };+ console.log(`${PROXY_CHAIN.LOG_PREFIX}Starting local proxy using: ${cmd} ${args.join(' ')}`);+ const proc = childProcess.spawn(cmd, args, options);++ this.squidPid = proc.pid;++ // Wait for Squid process to be running or fail+ return new Promise((resolve, reject) => {+ let isFinished = false;+ const intervalId = setInterval(() => {+ if (this._isSquidRunning()) {+ clearInterval(intervalId);+ isFinished = true;+ resolve();+ }+ // console.log("NOT RUNNING");+ }, 50);++ proc.on('exit', (code, signal) => {+ if (isFinished) {+ console.log(`${PROXY_CHAIN.LOG_PREFIX}Squid process ${this.squidPid} exited (code: ${code}, signal: ${signal})`);+ return;+ }++ clearInterval(intervalId);+ isFinished = true;+ const msg = `Squid process ${this.squidPid} exited unexpectedly (code: ${code}, signal: ${signal})`;+ reject(new Error(msg));+ });++ proc.on('error', (err) => {+ if (isFinished) {+ console.log(`${PROXY_CHAIN.LOG_PREFIX}Squid process ${this.squidPid} failed: ${err}`);+ return;+ }++ // Give a user-friendly message for this common error+ if (err.code === 'ENOENT') {+ err = new Error(`'${PROXY_CHAIN.SQUID_CMD}' command not found in the PATH`);+ }++ clearInterval(intervalId);+ isFinished = true;+ reject(err);+ });++ // Print stdout/stderr to simplify debugging+ const printLog = (data) => {+ console.log(`${PROXY_CHAIN.LOG_PREFIX}: Squid says: ${data}`);+ };+ proc.stdout.on('data', printLog);+ proc.stderr.on('data', printLog);+ });+ })+ .then(() => {+ const childProxyUrl = this._getChildProxyUrl();+ console.log(`${PROXY_CHAIN.LOG_PREFIX}Started proxy chain ${childProxyUrl} => ${this._getParentProxyUrl()} (pid ${this.squidPid})`); // eslint-disable-line max-len++ return parseUrl(childProxyUrl);+ });+ }++ static _findFreePort() {+ // TODO: pick random port to minimize collision chance+ return portastic.find({+ min: PROXY_CHAIN.PORT_FROM,+ max: PROXY_CHAIN.PORT_TO,+ retrieve: 1,+ })+ .then((ports) => {+ if (ports.length < 1) throw new Error(`There are no more free ports in range from ${PROXY_CHAIN.PORT_FROM} to ${PROXY_CHAIN.PORT_TO}`); // eslint-disable-line max-len+ return ports[0];+ });+ }++ /**+ * Determines whether the Squid process is still running.+ * @return Boolean+ * @private+ */+ _isSquidRunning() {+ // Inspired by https://github.com/nisaacson/is-running/blob/master/index.js+ if (!this.squidPid) return false;+ try {+ return !!process.kill(this.squidPid, 0);+ } catch (e) {+ return e.code === 'EPERM';+ }+ }++ /**+ * Generates Squid proxy configuration file and writes it to the temporary directory.+ * @return Promise Promise resolving to the path to the configuration file.+ * @private+ */+ _writeSquidConf() {+ if (!this.tmpDir) throw new Error('Temporary directory not created yet');++ const proxy = this.parsedProxyUrl;++ // NOTE: need to set pid_filename to isolate our squid instance from others possibly running in the system+ const conf = `+# debug_options 44,9 28,9+http_access allow all+never_direct allow all+# this probably requires --enable-http-violations compile option+via off+forwarded_for transparent+access_log none+#access_log daemon:${path.join(this.tmpDir, 'access.log')} squid+cache_store_log none+cache_log /dev/null+#cache_log ${path.join(this.tmpDir, 'cache.log')}+logfile_rotate 0+pid_filename ${path.join(this.tmpDir, PROXY_CHAIN.PID_FILE_NAME)}++http_port ${this.squidPort}+cache_peer ${proxy.hostname} parent ${proxy.port} 0 no-query login=${proxy.auth} connect-fail-limit=99999999 proxy-only name=my_peer+cache_peer_access my_peer allow all+`;+ const filePath = path.join(this.tmpDir, PROXY_CHAIN.CONF_FILE_NAME);++ // console.log('CONFIG');+ // console.log(conf);++ return fsWriteFilePromised(filePath, conf)+ .then(() => {+ return filePath;+ });+ }++ /**+ * Removes all proxy chains and terminates the squid process.+ * @return {*}+ */+ shutdown() {+ console.log(`${PROXY_CHAIN.LOG_PREFIX}Shutting down proxy chain ${this._getChildProxyUrl()} => ${this._getParentProxyUrl()} (pid ${this.squidPid})`); // eslint-disable-line max-len++ if (this._isSquidRunning()) {+ try {+ process.kill(this.squidPid, 'SIGKILL');+ } catch (err) {+ console.log(`${PROXY_CHAIN.LOG_PREFIX}WARNING: Failed to kill Squid process ${this.squidPid}: ${err}`);+ }+ }++ if (this.tmpDir) {+ const tmpDir = this.tmpDir;+ rimraf(tmpDir, { glob: false }, (err) => {+ if (err) {+ console.log(`${PROXY_CHAIN.LOG_PREFIX}WARNING: Failed to delete temporary directory at ${tmpDir}: ${err}`);+ }+ });+ this.tmpDir = null;+ }+ }+}diff --git a/src/proxy_chain_manager.js b/src/proxy_chain_manager.jsdeleted file mode 100644index 6e4e62add..000000000--- a/src/proxy_chain_manager.js+++ /dev/null@@ -1,338 +0,0 @@-import childProcess from 'child_process';-import fs from 'fs';-import path from 'path';-import _ from 'underscore';-import tmp from 'tmp';-import portastic from 'portastic';-import Promise from 'bluebird';-import { parseUrl } from './utils';--/* globals process */--// Constants, exported to simplify unit-testing.-export const PROXY_CHAIN = {- PORT_FROM: 55000,- PORT_TO: 60000,- HOST: '127.0.0.1',- PROTOCOL: 'http:',- SQUID_CMD: 'squid',- SQUID_CHECK_ARGS: ['-v'],- SQUID_BATCH_TIMEOUT: 10000,- TMP_DIR_TEMPLATE: '/tmp/apify-squid-XXXXXX',- CONF_FILE_NAME: 'squid.conf',- PID_FILE_NAME: 'squid.pid',- LOG_PREFIX: 'ProxyChainManager: ',-};--const tmpDirPromised = Promise.promisify(tmp.dir);-const fsWriteFilePromised = Promise.promisify(fs.writeFile);-const execFilePromised = Promise.promisify(childProcess.execFile, { multiArgs: true });--/**- * The class is used to manage a local Squid proxy instance- * that forwards HTTP requests to user-provided parent proxies.- * The point of this is that there's no easy way to programmatically pass proxy- * authentication credentials to web browsers such as Chrome, so we need to setup- * a local open proxy that can forward to parent proxy with authentication.- */-export class ProxyChainManager {- constructor() {- // Indicates whether _initialize() succeeded- this.isInitialized = false;-- // Dictionary of all proxy chains, key is Squid proxy port, value is an object such as:- // { parsed- // URL of the original parent proxy.- this.portToParsedProxyUrl = {};-- // PID of the Squid proxy process- this.squidPid = null;-- // Path to temporary directory with config files- this.tmpDir = null;- }-- /**- * Creates the temporary directory and checks the installed Squid, unless it has already been done.- * @return Promise- * @private- */- _initialize() {- if (this.isInitialized) return Promise.resolve();-- // Create temporary directory, if not created yet- return tmpDirPromised({ template: PROXY_CHAIN.TMP_DIR_TEMPLATE })- .then((tmpDir) => {- this.tmpDir = tmpDir;-- // Run Squid process to get its version and wait for the finish- const options = {- cwd: this.tmpDir,- timeout: PROXY_CHAIN.SQUID_BATCH_TIMEOUT,- };- console.log(`${PROXY_CHAIN.LOG_PREFIX}Checking Squid installation with '${PROXY_CHAIN.SQUID_CMD} ${PROXY_CHAIN.SQUID_CHECK_ARGS.join(' ')}'`); // eslint-disable-line max-len- return execFilePromised(PROXY_CHAIN.SQUID_CMD, PROXY_CHAIN.SQUID_CHECK_ARGS, options)- .then((array) => {- const stdout = array[0];- // TODO: check that the version is at least 3.3 and throw error otherwise!- console.log(`${PROXY_CHAIN.LOG_PREFIX}${(stdout || '').split('\n')[0]}`);- this.isInitialized = true;- })- .catch((err) => {- // Give a user-friendly message for this common error- if (err.code === 'ENOENT') {- err = new Error(`'${PROXY_CHAIN.SQUID_CMD}' command not found in the PATH`);- }- throw err;- });- });- }-- /**- * Sets up an open child proxy which forwards to a specified parent proxy.- * @param parsedChildProxyUrl Parsed URL of the parent proxy.- * @return Promise Promise resolving to the parsed URL of the child proxy.- */- addProxyChain(parsedProxyUrl) {- if (!parsedProxyUrl.hostname || !parsedProxyUrl.port) throw new Error('Proxy URL must contain both hostname and port');- if (parsedProxyUrl.scheme !== 'http') throw new Error('Only "http" proxy protocol is currently supported');-- let parsedChildProxyUrl;- return ProxyChainManager._findFreePort()- .then((port) => {- this.portToParsedProxyUrl[port] = _.clone(parsedProxyUrl);- const parentProxyUrl = `${parsedProxyUrl.protocol}//${parsedProxyUrl.username || ''}:${parsedProxyUrl.password ? '<redacted>' : ''}@${parsedProxyUrl.host}`; // eslint-disable-line max-len- const childProxyUrl = `${PROXY_CHAIN.PROTOCOL}//${PROXY_CHAIN.HOST}:${port}`;- parsedChildProxyUrl = parseUrl(childProxyUrl);-- console.log(`${PROXY_CHAIN.LOG_PREFIX}Adding proxy chain ${childProxyUrl} => ${parentProxyUrl}`);- return this._manageSquidProcess();- })- .then(() => {- return parsedChildProxyUrl;- });- }-- /**- * Removes a child proxy.- * @param parsedChildProxyUrl The result of the earlier call to the addProxyChain() method.- * @return Promise Returns a promise that resolves when the proxy chain is reconfigured.- */- removeProxyChain(parsedChildProxyUrl) {- if (parsedChildProxyUrl.protocol === PROXY_CHAIN.PROTOCOL- && parsedChildProxyUrl.host === PROXY_CHAIN.HOST- && this.portToParsedProxyUrl[parsedChildProxyUrl.port]) {- const childProxyUrl = `${PROXY_CHAIN.PROTOCOL}//${PROXY_CHAIN.HOST}:${parsedChildProxyUrl.port}`;- console.log(`${PROXY_CHAIN.LOG_PREFIX}Removing proxy chain ${childProxyUrl}`);-- delete this.portToParsedProxyUrl[parsedChildProxyUrl.port];- return this._manageSquidProcess()- .then(() => true);- }- return Promise.resolve(false);- }-- static _findFreePort() {- return portastic.find({- min: PROXY_CHAIN.PORT_FROM,- max: PROXY_CHAIN.PORT_TO,- retrieve: 1,- })- .then((ports) => {- if (ports.length < 1) throw new Error(`There are no more free ports in range from ${PROXY_CHAIN.PORT_FROM} to ${PROXY_CHAIN.PORT_TO}`); // eslint-disable-line max-len- return ports[0];- });- }-- /**- * Determines whether the Squid process is still running.- * @return Boolean- * @private- */- _isSquidRunning() {- // Inspired by https://github.com/nisaacson/is-running/blob/master/index.js- if (!this.squidPid) return false;- try {- return !!process.kill(this.squidPid, 0);- } catch (e) {- return e.code === 'EPERM';- }- }-- /**- * Manages Squid proxy process, which means the function either starts it, updates its configuration or kills it,- * depending on the state of the `portToParsedProxyUrl` field.- * @private- */- _manageSquidProcess() {- // TODO: we should ensure that this method only runs once a time,- // to avoid conflicts in config settings, e.g. using async module's queue- // TODO: automatically restart squid process if it crashed, maybe using forever package? or simply using setInterval()-- // First, make sure that squidPid refers to the running Squid process- if (this.squidPid && !this._isSquidRunning()) {- this.squidPid = null;- }-- // If Squid is no longer needed but it is still running, kill it to save system resources- if (_.isEmpty(this.portToParsedProxyUrl)) {- if (this.squidPid) {- console.log(`${PROXY_CHAIN.LOG_PREFIX}Killing Squid process ${this.squidPid}`);- process.kill(this.squidPid, 'SIGKILL');- }- return;- }-- // If Squid is not running yet but should be, start it- if (!this.squidPid) {- return this._initialize()- .then(() => {- // Store configuration file to temp dir- return this._writeSquidConf();- })- .then((squidConfPath) => {- // Start Squid process- const cmd = PROXY_CHAIN.SQUID_CMD;- const args = ['-f', squidConfPath, '-N'];- const options = { cwd: this.tmpDir };- console.log(`${PROXY_CHAIN.LOG_PREFIX}Starting local Squid proxy using: ${cmd} ${args.join(' ')}`);- const proc = childProcess.spawn(PROXY_CHAIN.SQUID_CMD, args, options);-- this.squidPid = proc.pid;-- // Wait for Squid process to be running or fail- return new Promise((resolve, reject) => {- let isFinished = false;- const intervalId = setInterval(() => {- if (this._isSquidRunning()) {- clearInterval(intervalId);- isFinished = true;- resolve();- }- // console.log("NOT RUNNING");- }, 50);-- proc.on('exit', (code, signal) => {- if (isFinished) {- console.log(`${PROXY_CHAIN.LOG_PREFIX}Squid process ${this.squidPid} exited (code: ${code}, signal: ${signal})`);- return;- }-- clearInterval(intervalId);- isFinished = true;- this.squidPid = null;- reject(new Error(`Squid process ${this.squidPid} exited unexpectedly (code: ${code}, signal: ${signal})`)); // eslint-disable-line max-len- });-- proc.on('error', (err) => {- if (isFinished) {- console.log(`${PROXY_CHAIN.LOG_PREFIX}Squid process ${this.squidPid} failed: ${err}`);- return;- }-- clearInterval(intervalId);- isFinished = true;- this.squidPid = null;- reject(err);- });-- // Print stdout/stderr to simplify debugging- const printLog = (data) => {- console.log(`${PROXY_CHAIN.LOG_PREFIX}: Squid says: ${data}`);- };- proc.stdout.on('data', printLog);- proc.stderr.on('data', printLog);- });- });- }-- // Squid is already running, reconfigure it- return Promise.resolve()- .then(() => {- // Store configuration file to temp dir- return this._writeSquidConf();- })- .then((squidConfPath) => {- const args = ['-f', squidConfPath, '-k', 'reconfigure'];- const options = {- cwd: this.tmpDir,- timeout: PROXY_CHAIN.SQUID_BATCH_TIMEOUT,- };- return execFilePromised(PROXY_CHAIN.SQUID_CMD, args, options)- .then((arr) => {- console.dir(arr);-- // TODO- return new Promise((resolve) => {- setTimeout(resolve, 1000);- });- })- .catch((err) => {- // Use better error message- throw new Error(`Squid reconfiguration failed (${err})`);- });- });- }-- static _generateSquidConfForPort(parsedProxyUrl, squidPort) {- const peerName = `peer${squidPort}`;- const aclName = `acl${squidPort}`;- const str = `http_port ${squidPort}\n`- + `cache_peer ${parsedProxyUrl.hostname} parent ${parsedProxyUrl.port} 0 no-query login=${parsedProxyUrl.auth} connect-fail-limit=99999999 proxy-only name=${peerName}\n` // eslint-disable-line max-len- // + `acl ${aclName} myportname ${squidPort}\n`- + `acl ${aclName} myportname ${squidPort}\n`- + `cache_peer_access ${peerName} allow ${aclName}\n`- + `cache_peer_access ${peerName} deny all\n`;- return str;- }-- /**- * Generates Squid proxy configuration file and writes it to the temporary directory.- * @return Promise Promise resolving to the path to the configuration file.- * @private- */- _writeSquidConf() {- if (!this.tmpDir) throw new Error('Temporary directory not created yet');-- const chainConfs = _.values(_.mapObject(this.portToParsedProxyUrl, (parsedProxyUrl, port) => {- return ProxyChainManager._generateSquidConfForPort(parsedProxyUrl, port);- })).join('\n');-- // NOTE: set pid_filename to isolate our squid instance from others possibly running in the system- const conf = `-# debug_options 44,9 28,9-http_access allow all-never_direct allow all-via off # this probably requires --enable-http-violations compile option-forwarded_for transparent-#access_log none-access_log daemon:${path.join(this.tmpDir, 'access.log')} squid-cache_store_log none-#cache_log /dev/null-cache_log ${path.join(this.tmpDir, 'cache.log')}-logfile_rotate 0-pid_filename ${path.join(this.tmpDir, PROXY_CHAIN.PID_FILE_NAME)}--${chainConfs}-`;- const filePath = path.join(this.tmpDir, PROXY_CHAIN.CONF_FILE_NAME);-- console.log('CONFIG');- console.log(conf);-- return fsWriteFilePromised(filePath, conf)- .then(() => {- return filePath;- });- }-- /**- * Removes all proxy chains and terminates the squid process.- * @return {*}- */- shutdown() {- this.portToParsedProxyUrl = {};-- return this._manageSquidProcess();- }-}diff --git a/test/proxy_chain_manager.js b/test/proxy_chain.jssimilarity index 50%rename from test/proxy_chain_manager.jsrename to test/proxy_chain.jsindex 092ad9cee..9528d6eb1 100644--- a/test/proxy_chain_manager.js+++ b/test/proxy_chain.js@@ -1,3 +1,4 @@+import fs from 'fs';import _ from 'underscore';import { expect, assert } from 'chai';import proxy from 'proxy';@@ -8,7 +9,7 @@ import Promise from 'bluebird';import request from 'request';import { parseUrl } from '../build/utils';-import { ProxyChainManager, PROXY_CHAIN } from '../build/proxy_chain_manager';+import { ProxyChain, PROXY_CHAIN } from '../build/proxy_chain';/* globals process */@@ -16,7 +17,7 @@ const ORIG_PROXY_CHAIN = _.clone(PROXY_CHAIN);let proxyServer;let proxyPort; // eslint-disable-line no-unused-vars-let proxyAuth = { scheme: 'Basic', username: 'username', password: 'password' };+const proxyAuth = { scheme: 'Basic', username: 'username', password: 'password' };let wasProxyCalled = false; // eslint-disable-line no-unused-vars// Setup local proxy server for the tests@@ -38,7 +39,7 @@ before(() => {}const parsed = basicAuthParser(auth);const isEqual = _.isEqual(parsed, proxyAuth);- console.log('Parsed "Proxy-Authorization": parsed: %j expected: %j : %s', parsed, proxyAuth, isEqual);+ // console.log('Parsed "Proxy-Authorization": parsed: %j expected: %j : %s', parsed, proxyAuth, isEqual);if (isEqual) wasProxyCalled = true;fn(null, isEqual);};@@ -61,8 +62,8 @@ after(function () {const requestPromised = (opts) => {- console.log('requestPromised');- console.dir(opts);+ // console.log('requestPromised');+ // console.dir(opts);return new Promise((resolve, reject) => {request(opts, (error, response, body) => {if (error) return reject(error);@@ -80,18 +81,14 @@ const requestPromised = (opts) => {};-describe('ProxyChainManager.addProxyChain()', function () {+describe('ProxyChain', function () {// Need larger timeout for Travis CIthis.timeout(1000 * 1000);- let mng;- before(() => {- mng = new ProxyChainManager();- });-it('throws nice error when "squid" command not found', () => {PROXY_CHAIN.SQUID_CMD = 'command-that-does-not-exist';- return mng.addProxyChain(parseUrl('http://whatever.com:1234'))+ const pc = new ProxyChain(parseUrl('http://whatever.com:1234'));+ return pc.start().then(() => {assert.fail();})@@ -104,13 +101,14 @@ describe('ProxyChainManager.addProxyChain()', function () {});it('throws an error when "squid" command exits with non-zero code', () => {- PROXY_CHAIN.SQUID_CHECK_ARGS = ['-xbadargs'];- return mng.addProxyChain(parseUrl('http://whatever.com:1234'))+ PROXY_CHAIN.SQUID_CMD = 'false';+ const pc = new ProxyChain(parseUrl('http://whatever.com:1234'));+ return pc.start().then(() => {assert.fail();}).catch((err) => {- expect(err.message).to.contain('squid: illegal option');+ expect(err.message).to.contain('exited unexpectedly');}).finally(() => {Object.assign(PROXY_CHAIN, ORIG_PROXY_CHAIN);@@ -118,10 +116,11 @@ describe('ProxyChainManager.addProxyChain()', function () {});it('throws nice error when no more free ports available', () => {- // we're listening on proxyPort+ // Testing proxy is already listening on proxyPortPROXY_CHAIN.PORT_FROM = proxyPort;PROXY_CHAIN.PORT_TO = proxyPort;- return mng.addProxyChain(parseUrl(`http://${proxyAuth.username}:${proxyAuth.password}@127.0.0.1:${proxyPort}`))+ const pc = new ProxyChain(parseUrl('http://whatever.com:1234'));+ return pc.start().then(() => {assert.fail();})@@ -133,145 +132,136 @@ describe('ProxyChainManager.addProxyChain()', function () {});});+ it('throws for invalid args', () => {+ assert.throws(() => { new ProxyChain(null); }, Error); // eslint-disable-line no-new+ });+it('throws for unsupported proxy protocols', () => {- assert.throws(() => { mng.addProxyChain(parseUrl('socks://whatever.com')); }, Error);- assert.throws(() => { mng.addProxyChain(parseUrl('https://whatever.com')); }, Error);- assert.throws(() => { mng.addProxyChain(parseUrl('socks5://whatever.com')); }, Error);+ assert.throws(() => { new ProxyChain(parseUrl('socks://whatever.com')); }, Error); // eslint-disable-line no-new+ assert.throws(() => { new ProxyChain(parseUrl('https://whatever.com')); }, Error); // eslint-disable-line no-new+ assert.throws(() => { new ProxyChain(parseUrl('socks5://whatever.com')); }, Error); // eslint-disable-line no-new});it('throws for invalid URLs', () => {- assert.throws(() => { mng.addProxyChain(parseUrl('://whatever.com')); }, Error);- assert.throws(() => { mng.addProxyChain(parseUrl('https://whatever.com')); }, Error);- assert.throws(() => { mng.addProxyChain(parseUrl('socks5://whatever.com')); }, Error);-- assert.throws(() => { mng.addProxyChain(parseUrl('http://no-port-provided')); }, Error);+ assert.throws(() => { new ProxyChain(parseUrl('://whatever.com')); }, Error); // eslint-disable-line no-new+ assert.throws(() => { new ProxyChain(parseUrl('https://whatever.com')); }, Error); // eslint-disable-line no-new+ assert.throws(() => { new ProxyChain(parseUrl('socks5://whatever.com')); }, Error); // eslint-disable-line no-new+ assert.throws(() => { new ProxyChain(parseUrl('http://no-port-provided')); }, Error); // eslint-disable-line no-new});- it('correctly handles add and removal', () => {+ it('works well', () => {+ const proxyChain1 = new ProxyChain(parseUrl(`http://${proxyAuth.username}:${proxyAuth.password}@127.0.0.1:${proxyPort}`));+ const proxyChain2 = new ProxyChain(parseUrl(`http://${proxyAuth.username}:${proxyAuth.password}@127.0.0.1:${proxyPort}`));let parsedChildProxyUrl1;let parsedChildProxyUrl2;- let proxy1;- let proxy2;- const proxyAuth1 = { scheme: 'Basic', username: 'user1', password: 'password1' };- const proxyAuth2 = { scheme: 'Basic', username: 'user2', password: 'password2' };return Promise.resolve().then(() => {- // Add first proxy- console.log('*** Add first proxy');- proxyAuth = proxyAuth1;- return mng.addProxyChain(parseUrl(`http://${proxyAuth.username}:${proxyAuth.password}@127.0.0.1:${proxyPort}`));+ return Promise.all([proxyChain1.start(), proxyChain2.start()]);})- .then((parsedChildProxyUrl) => {- // Test first proxy works- console.log('*** Test first proxy works');- expect(parsedChildProxyUrl.port).to.not.equal(proxyPort);+ .then((results) => {+ parsedChildProxyUrl1 = results[0];+ parsedChildProxyUrl2 = results[1];+ expect(parsedChildProxyUrl1.port).to.not.equal(proxyPort);+ expect(parsedChildProxyUrl2.port).to.not.equal(proxyPort);+ expect(parsedChildProxyUrl1.port).to.not.equal(parsedChildProxyUrl2.port);++ // Test call through proxy 1wasProxyCalled = false;- parsedChildProxyUrl1 = parsedChildProxyUrl;- proxy1 = `${parsedChildProxyUrl.protocol}//${parsedChildProxyUrl.host}`;return requestPromised({uri: 'https://www.example.com', // Test HTTPS- proxy: proxy1,+ proxy: `${parsedChildProxyUrl1.protocol}//${parsedChildProxyUrl1.host}`,expectBodyContainsText: 'Example Domain',- })- .then(() => {- expect(wasProxyCalled).to.equal(true);- expect(mng._isSquidRunning()).to.equal(true);});}).then(() => {- // Add second proxy- // NOTE: the host must be different than the first proxy (e.g. 127.0.0.1 vs localhost) !!!- proxyAuth = proxyAuth2;- return mng.addProxyChain(parseUrl(`http://${proxyAuth.username}:${proxyAuth.password}@localhost:${proxyPort}`));+ expect(wasProxyCalled).to.equal(true);})- .then((parsedChildProxyUrl) => {- // Test second proxy works- console.log('*** Test second proxy works');- expect(parsedChildProxyUrl.port).to.not.equal(proxyPort);+ .then(() => {+ // Test call through proxy 2wasProxyCalled = false;- parsedChildProxyUrl2 = parsedChildProxyUrl;- proxy2 = `${parsedChildProxyUrl.protocol}//${parsedChildProxyUrl.host}}`;return requestPromised({uri: 'http://www.example.com', // Test HTTP- proxy: proxy2,+ proxy: `${parsedChildProxyUrl2.protocol}//${parsedChildProxyUrl2.host}`,expectBodyContainsText: 'Example Domain',- })- .then(() => {- expect(wasProxyCalled).to.equal(true);});}).then(() => {- // Test first proxy still works- console.log('*** Test first proxy still works');- return new Promise(() => {}); // TODO- proxyAuth = proxyAuth1;+ expect(wasProxyCalled).to.equal(true);+ })+ .then(() => {+ // Test again call through proxy 1wasProxyCalled = false;return requestPromised({uri: 'http://www.example.com',- proxy: proxy1,+ proxy: `${parsedChildProxyUrl1.protocol}//${parsedChildProxyUrl1.host}`,expectBodyContainsText: 'Example Domain',- })- .then(() => {- expect(wasProxyCalled).to.equal(true);- })- .catch((err) => {- console.dir(err);- throw err;});}).then(() => {- // Remove first proxy- console.log('*** Remove first proxy');- return mng.removeProxyChain(parsedChildProxyUrl1)- .then((wasRemoved) => {- expect(wasRemoved).to.equal(true);- });+ expect(wasProxyCalled).to.equal(true);}).then(() => {- // Remove first proxy again (should have no effect)- console.log('*** Remove first proxy again');- return mng.removeProxyChain(parsedChildProxyUrl1)- .then((wasRemoved) => {- expect(wasRemoved).to.equal(false);- });- })+ proxyChain1.shutdown();+ proxyChain2.shutdown();++ // Test these can be called multiple times+ proxyChain1.shutdown();+ proxyChain2.shutdown();+ });+ });++ it('fails with invalid proxy credentials', () => {+ const proxyChain = new ProxyChain(parseUrl(`http://username:[email protected]:${proxyPort}`));++ return Promise.resolve().then(() => {- // Check that second proxy still works- console.log('*** Check that second proxy still works');- proxyAuth = proxyAuth2;+ return proxyChain.start();+ })+ .then((parsedChildProxyUrl) => {+ expect(parsedChildProxyUrl.port).to.not.equal(proxyPort);wasProxyCalled = false;return requestPromised({- uri: 'http://www.example.com',- proxy: proxy2,+ uri: 'https://www.example.com',+ proxy: `${parsedChildProxyUrl.protocol}//${parsedChildProxyUrl.host}`,expectBodyContainsText: 'Example Domain',});}).then(() => {- // Check that first proxy no longer works- console.log('*** Check that first proxy no longer works');- proxyAuth = proxyAuth1;- expect(wasProxyCalled).to.equal(true);- return requestPromised({- uri: 'http://www.example.com',- proxy: proxy2,- expectBodyContainsText: 'Example Domain',- })- .then(() => {- assert.fail();- })- .catch((err) => {- expect(err.message).to.contain('There are no more free ports');+ assert.fail();+ })+ .catch((err) => {+ expect(err.message).to.contains('tunneling socket could not be established');+ expect(wasProxyCalled).to.equal(false);+ })+ .then(() => {+ proxyChain.shutdown();+ });+ });++ it('cleans up properly after shutdown', () => {+ const proxyChain = new ProxyChain(parseUrl(`http://any:[email protected]:${proxyPort}`));+ let tmpDir;++ return Promise.resolve()+ .then(() => {+ return proxyChain.start();+ })+ .then(() => {+ tmpDir = proxyChain.tmpDir;+ proxyChain.shutdown();+ })+ .then(() => {+ return new Promise((resolve) => {+ setTimeout(resolve, 100);});}).then(() => {- // Remove second proxy- return mng.removeProxyChain(parsedChildProxyUrl2);+ expect(fs.existsSync(tmpDir)).to.equal(false);+ expect(proxyChain._isSquidRunning()).to.equal(false);});});after(() => {Object.assign(PROXY_CHAIN, ORIG_PROXY_CHAIN);-- //return mng.shutdown();});});