TorPool.js.html 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>TorPool.js - Documentation</title>
  6. <script src="scripts/prettify/prettify.js"></script>
  7. <script src="scripts/prettify/lang-css.js"></script>
  8. <!--[if lt IE 9]>
  9. <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  10. <![endif]-->
  11. <link type="text/css" rel="stylesheet" href="styles/prettify.css">
  12. <link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
  13. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  14. </head>
  15. <body>
  16. <input type="checkbox" id="nav-trigger" class="nav-trigger" />
  17. <label for="nav-trigger" class="navicon-button x">
  18. <div class="navicon"></div>
  19. </label>
  20. <label for="nav-trigger" class="overlay"></label>
  21. <nav>
  22. <h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="ControlServer.html">ControlServer</a><ul class='methods'><li data-type='method'><a href="ControlServer.html#.instance_info">instance_info</a></li><li data-type='method'><a href="ControlServer.html#close">close</a></li><li data-type='method'><a href="ControlServer.html#createDNSServer">createDNSServer</a></li><li data-type='method'><a href="ControlServer.html#createHTTPServer">createHTTPServer</a></li><li data-type='method'><a href="ControlServer.html#createSOCKSServer">createSOCKSServer</a></li><li data-type='method'><a href="ControlServer.html#createTorPool">createTorPool</a></li><li data-type='method'><a href="ControlServer.html#listen">listen</a></li><li data-type='method'><a href="ControlServer.html#listenTcp">listenTcp</a></li><li data-type='method'><a href="ControlServer.html#listenWs">listenWs</a></li></ul></li><li><a href="DNSServer.html">DNSServer</a><ul class='methods'><li data-type='method'><a href="DNSServer.html#listen">listen</a></li></ul></li><li><a href="HTTPServer.html">HTTPServer</a><ul class='methods'><li data-type='method'><a href="HTTPServer.html#listen">listen</a></li></ul></li><li><a href="SOCKSServer.html">SOCKSServer</a><ul class='methods'><li data-type='method'><a href="SOCKSServer.html#listen">listen</a></li></ul></li><li><a href="TorPool.html">TorPool</a><ul class='methods'><li data-type='method'><a href="TorPool.html#add">add</a></li><li data-type='method'><a href="TorPool.html#add_instance_to_group">add_instance_to_group</a></li><li data-type='method'><a href="TorPool.html#add_instance_to_group_at">add_instance_to_group_at</a></li><li data-type='method'><a href="TorPool.html#add_instance_to_group_by_name">add_instance_to_group_by_name</a></li><li data-type='method'><a href="TorPool.html#create">create</a></li><li data-type='method'><a href="TorPool.html#create_instance">create_instance</a></li><li data-type='method'><a href="TorPool.html#exit">exit</a></li><li data-type='method'><a href="TorPool.html#get_config_at">get_config_at</a></li><li data-type='method'><a href="TorPool.html#get_config_by_name">get_config_by_name</a></li><li data-type='method'><a href="TorPool.html#instance_at">instance_at</a></li><li data-type='method'><a href="TorPool.html#instance_by_name">instance_by_name</a></li><li data-type='method'><a href="TorPool.html#instances_by_group">instances_by_group</a></li><li data-type='method'><a href="TorPool.html#new_identites">new_identites</a></li><li data-type='method'><a href="TorPool.html#new_identites_by_group">new_identites_by_group</a></li><li data-type='method'><a href="TorPool.html#new_identity_at">new_identity_at</a></li><li data-type='method'><a href="TorPool.html#new_identity_by_name">new_identity_by_name</a></li><li data-type='method'><a href="TorPool.html#next">next</a></li><li data-type='method'><a href="TorPool.html#next_by_group">next_by_group</a></li><li data-type='method'><a href="TorPool.html#remove">remove</a></li><li data-type='method'><a href="TorPool.html#remove_at">remove_at</a></li><li data-type='method'><a href="TorPool.html#remove_by_name">remove_by_name</a></li><li data-type='method'><a href="TorPool.html#remove_instance_from_group">remove_instance_from_group</a></li><li data-type='method'><a href="TorPool.html#remove_instance_from_group_at">remove_instance_from_group_at</a></li><li data-type='method'><a href="TorPool.html#remove_instance_from_group_by_name">remove_instance_from_group_by_name</a></li><li data-type='method'><a href="TorPool.html#set_config_all">set_config_all</a></li><li data-type='method'><a href="TorPool.html#set_config_at">set_config_at</a></li><li data-type='method'><a href="TorPool.html#set_config_by_group">set_config_by_group</a></li><li data-type='method'><a href="TorPool.html#set_config_by_name">set_config_by_name</a></li><li data-type='method'><a href="TorPool.html#signal_all">signal_all</a></li><li data-type='method'><a href="TorPool.html#signal_at">signal_at</a></li><li data-type='method'><a href="TorPool.html#signal_by_group">signal_by_group</a></li><li data-type='method'><a href="TorPool.html#signal_by_name">signal_by_name</a></li></ul></li><li><a href="TorProcess.html">TorProcess</a><ul class='methods'><li data-type='method'><a href="TorProcess.html#create">create</a></li><li data-type='method'><a href="TorProcess.html#exit">exit</a></li><li data-type='method'><a href="TorProcess.html#get_config">get_config</a></li><li data-type='method'><a href="TorProcess.html#new_identity">new_identity</a></li><li data-type='method'><a href="TorProcess.html#set_config">set_config</a></li><li data-type='method'><a href="TorProcess.html#signal">signal</a></li></ul></li></ul><h3>Modules</h3><ul><li><a href="module-tor-router.html">tor-router</a></li><li><a href="module-tor-router_ControlServer.html">tor-router/ControlServer</a></li><li><a href="module-tor-router_default_config.html">tor-router/default_config</a></li><li><a href="module-tor-router_default_ports.html">tor-router/default_ports</a></li><li><a href="module-tor-router_DNSServer.html">tor-router/DNSServer</a></li><li><a href="module-tor-router_HTTPServer.html">tor-router/HTTPServer</a></li><li><a href="module-tor-router_launch.html">tor-router/launch</a></li><li><a href="module-tor-router_nconf_load_env.html">tor-router/nconf_load_env</a></li><li><a href="module-tor-router_SOCKSServer.html">tor-router/SOCKSServer</a></li><li><a href="module-tor-router_TorPool.html">tor-router/TorPool</a></li><li><a href="module-tor-router_TorProcess.html">tor-router/TorProcess</a></li><li><a href="module-tor-router_winston_silent_logger.html">tor-router/winston_silent_logger</a></li></ul><h3>Events</h3><ul><li><a href="DNSServer.html#event:instance-connection">instance-connection</a></li><li><a href="HTTPServer.html#event:instance-connection">instance-connection</a></li><li><a href="SOCKSServer.html#event:instance-connection">instance-connection</a></li><li><a href="TorPool.html#event:instance_created">instance_created</a></li><li><a href="TorProcess.html#event:control_listen">control_listen</a></li><li><a href="TorProcess.html#event:controller_ready">controller_ready</a></li><li><a href="TorProcess.html#event:dns_listen">dns_listen</a></li><li><a href="TorProcess.html#event:error">error</a></li><li><a href="TorProcess.html#event:process_exit">process_exit</a></li><li><a href="TorProcess.html#event:ready">ready</a></li><li><a href="TorProcess.html#event:socks_listen">socks_listen</a></li></ul><h3>Global</h3><ul><li><a href="global.html#assembleHost">assembleHost</a></li><li><a href="global.html#cleanUp">cleanUp</a></li><li><a href="global.html#env_whitelist">env_whitelist</a></li><li><a href="global.html#logger">logger</a></li><li><a href="global.html#main">main</a></li><li><a href="global.html#nconf">nconf</a></li><li><a href="global.html#REALM">REALM</a></li><li><a href="global.html#setup_nconf_env">setup_nconf_env</a></li><li><a href="global.html#TOR_ROUTER_PROXY_AGENT">TOR_ROUTER_PROXY_AGENT</a></li></ul>
  23. </nav>
  24. <div id="main">
  25. <h1 class="page-title">TorPool.js</h1>
  26. <section>
  27. <article>
  28. <pre class="prettyprint source linenums"><code>/**
  29. * @author Christoph and Marco Bonelli on Stackoverflow &lt;https://bit.ly/2p6gedO>
  30. */
  31. Array.prototype.rotate = (function() {
  32. // save references to array functions to make lookup faster
  33. var push = Array.prototype.push,
  34. splice = Array.prototype.splice;
  35. return function(count) {
  36. var len = this.length >>> 0, // convert to uint
  37. count = count >> 0; // convert to int
  38. // convert count to value in range [0, len)
  39. count = ((count % len) + len) % len;
  40. // use splice.call() instead of this.splice() to make function generic
  41. push.apply(this, splice.call(this, 0, count));
  42. return this;
  43. };
  44. })();
  45. const path = require('path');
  46. const fs = require('fs');
  47. const { EventEmitter } = require('eventemitter3');
  48. const Promise = require("bluebird");
  49. const _ = require('lodash');
  50. const WeightedList = require('js-weighted-list');
  51. const TorProcess = require('./TorProcess');
  52. Promise.promisifyAll(fs);
  53. /**
  54. * Class that represents a pool of Tor processes.
  55. * @extends EventEmitter
  56. */
  57. class TorPool extends EventEmitter {
  58. /**
  59. * Creates an instance of `TorPool`.
  60. *
  61. * @param {string} tor_path - Path to the Tor executable.
  62. * @param {Object|Function} [default_config] - Default configuration that will be passed to all Tor instances created. Can be a function. See {@link https://bit.ly/2QrmI3o|Tor Documentation} for all possible options
  63. * @param {string} data_directory - Parent directory for the data directory of each proccess.
  64. * @param {string} load_balance_method - Name of the load balance method to use. See {@link TorPool#load_balance_methods}.
  65. * @param {string} [granax_options] - Object containing options that will be passed to granax for each instance.
  66. * @param {string} [logger] - A winston logger. If not provided no logging will occur.
  67. *
  68. * @throws If "data_directory" is not provided.
  69. */
  70. constructor(tor_path, default_config, data_directory, load_balance_method, granax_options, logger) {
  71. if (!data_directory)
  72. throw new Error('Invalid "data_directory"');
  73. super();
  74. this._instances = [];
  75. this._default_tor_config = default_config;
  76. /**
  77. * Parent directory for the data directory of each proccess.
  78. *
  79. * @type {string}
  80. * @public
  81. */
  82. this.data_directory = data_directory;
  83. /**
  84. * Name of the load balance method to use.
  85. *
  86. * @type {string}
  87. * @public
  88. */
  89. this.load_balance_method = load_balance_method;
  90. /**
  91. * Path to the Tor executable.
  92. *
  93. * @type {string}
  94. * @public
  95. */
  96. this.tor_path = tor_path;
  97. /**
  98. * The winston logger.
  99. *
  100. * @type {Logger}
  101. * @public
  102. */
  103. this.logger = logger || require('./winston_silent_logger');
  104. /**
  105. * Object containing options that will be passed to granax for each instance.
  106. *
  107. * @type {Logger}
  108. * @public
  109. */
  110. this.granax_options = granax_options;
  111. }
  112. /**
  113. * Returns a Set containing the names of all of the groups.
  114. *
  115. * @readonly
  116. * @type {Set&lt;string>}
  117. */
  118. get group_names() {
  119. return new Set(_.flatten(this.instances.map((instance) => instance.instance_group).filter(Boolean)));
  120. }
  121. /**
  122. * Returns an array containing all of the instances in a group.
  123. *
  124. * @param {string} group_name - The group to query.
  125. * @returns {string[]}
  126. *
  127. * @throws If the provided group does not exist
  128. */
  129. instances_by_group(group_name) {
  130. if (!this.group_names.has(group_name))
  131. throw new Error(`Group "${group_name}" doesn't exist`);
  132. let group = this.groups[group_name];
  133. let arr = [];
  134. for (let i = 0; i &lt; group.length; i++) {
  135. arr.push(group[i]);
  136. }
  137. return arr;
  138. }
  139. /**
  140. * Adds an instance to a group. If the group doesn't exist it will be created.
  141. *
  142. * @param {string} group - The group to add the instance to.
  143. * @param {TorProcess} instance - The instance in question.
  144. */
  145. add_instance_to_group(group, instance) {
  146. instance.definition.Group = _.union(instance.instance_group, [group]);
  147. }
  148. /**
  149. * Adds an instance to a group by the {@link TorProcess#instance_name} property on the instance. If the group doesn't exist it will be created.
  150. *
  151. * @param {string} group - The group to add the instance to.
  152. * @param {string} instance_name - The name of the instance in question.
  153. *
  154. * @throws If an instance with the name provided does not exist
  155. */
  156. add_instance_to_group_by_name(group, instance_name) {
  157. let instance = this.instance_by_name(instance_name);
  158. if (!instance) throw new Error(`Instance "${instance_name}" not found`);
  159. return this.add_instance_to_group(group, instance);
  160. }
  161. /**
  162. * Adds an instance to a group by the index of the instance in the pool. If the group doesn't exist it will be created.
  163. *
  164. * @param {string} group - The group to add the instance to.
  165. * @param {number} instance_index - The index of the instance in question.
  166. *
  167. * @throws If an instance with the index provided does not exist.
  168. */
  169. add_instance_to_group_at(group, instance_index) {
  170. let instance = this.instance_at(instance_index);
  171. if (!instance) throw new Error(`Instance at "${instance_index}" not found`);
  172. return this.add_instance_to_group(group, instance);
  173. }
  174. /**
  175. * Removes an instance from a group.
  176. *
  177. * @param {string} group - The group to remove the instance from.
  178. * @param {TorProcess} instance - The instance in question.
  179. */
  180. remove_instance_from_group(group, instance) {
  181. _.remove(instance.definition.Group, (g) => g === group);
  182. }
  183. /**
  184. * Removes an instance from a group by the {@link TorProcess#instance_name} property on the instance.
  185. *
  186. * @param {string} group - The group to remove the instance from.
  187. * @param {string} instance_name - The name of the instance in question.
  188. *
  189. * @throws If an instance with the name provided does not exist.
  190. */
  191. remove_instance_from_group_by_name(group, instance_name) {
  192. let instance = this.instance_by_name(instance_name);
  193. if (!instance) throw new Error(`Instance "${instance_name}" not found`);
  194. return this.remove_instance_from_group(group, instance);
  195. }
  196. /**
  197. * Removes an instance from a group by the index of the instance in the pool.
  198. *
  199. * @param {string} group - The group to remove the instance from.
  200. * @param {number} instance_index - The index of the instance in question.
  201. *
  202. * @throws If an instance with the index provided does not exist.
  203. */
  204. remove_instance_from_group_at(group, instance_index) {
  205. let instance = this.instance_at(instance_index);
  206. if (!instance) throw new Error(`Instance at "${instance_index}" not found`);
  207. return this.remove_instance_from_group(group, instance);
  208. }
  209. /**
  210. * Represents a group of instances. Group is a Proxy with an array as its object. The array is generated by calling {@link TorPool#instances_in_group}.
  211. * When called with an index (e.g. `Group[0]`) will return the instance at that index.
  212. * Helper functions are available as properties.
  213. * @typedef {TorProcess[]} InstanceGroup
  214. *
  215. * @property {Function} add - Adds an instance to the group.
  216. * @property {Function} remove - Removes an instance from the group.
  217. * @property {Function} add_by_name - Adds an instance to the group by the {@link TorProcess#instance_name} property on the instance.
  218. * @property {Function} remove_by_name - Removes an instance from the group by the {@link TorProcess#instance_name} property on the instance.
  219. * @property {Function} remove_at - Removes an instance from the group by the index of the instance in the group.
  220. * @property {number} length - The size of the group of instances
  221. * @property {Function} rotate - Rotates the array of instances
  222. */
  223. /**
  224. * Represents a collection of groups as an associative array. GroupCollection is a Proxy with a Set as its object. The Set is {@link TorPool#group_names}.
  225. * If a non-existant group is referenced (e.g. `Groups["doesn't exist"]`) it will be created. So `Groups["doesn't exist"].add(my_instance)` will create the group and add the instance to it.
  226. * @typedef {InstanceGroup[]} InstanceGroupCollection
  227. */
  228. /**
  229. * Represents all groups currently in the pool.
  230. *
  231. * @readonly
  232. * @type {InstanceGroupCollection}
  233. */
  234. get groups() {
  235. let groupHandler = {
  236. get: (instances, prop) => {
  237. if (!Number.isNaN(Number(prop)))
  238. return instances[prop];
  239. let save_index = () => {
  240. instances = instances.map((instance, index) => {
  241. instance._index = index;
  242. return instance;
  243. });
  244. };
  245. let { group_name } = instances;
  246. if (prop === 'add')
  247. return (instance) => {
  248. this.add_instance_to_group(group_name, instance);
  249. save_index();
  250. };
  251. if (prop === 'add_by_name') {
  252. return (instance_name) => {
  253. this.add_instance_to_group_by_name(group_name, instance_name);
  254. save_index();
  255. };
  256. }
  257. if (prop === 'remove')
  258. return (instance) => {
  259. this.remove_instance_from_group(group_name, instance);
  260. save_index();
  261. };
  262. if (prop === 'remove_by_name') {
  263. return (instance_name) => {
  264. this.remove_instance_from_group_by_name(group_name, instance_name);
  265. save_index();
  266. };
  267. }
  268. if (prop === 'remove_at')
  269. return (instance_index) => {
  270. this.remove_instance_from_group(group_name, instances[instance_index]);
  271. save_index();
  272. };
  273. if (prop === 'length')
  274. return instances.length;
  275. if (prop === 'rotate') {
  276. return (num) => {
  277. instances.rotate(typeof(num) === 'undefined' ? 1 : num);
  278. save_index();
  279. };
  280. }
  281. return void(0);
  282. }
  283. };
  284. let groupsHandler = {
  285. get: (group_names, prop) => {
  286. let instances_in_group = [];
  287. if (group_names.has(prop)) {
  288. instances_in_group = this.instances.filter((instance) => instance.instance_group.indexOf(prop) !== -1);
  289. }
  290. instances_in_group = _.sortBy(instances_in_group, ['_index', 'instance_name']);
  291. instances_in_group.group_name = prop;
  292. return new Proxy(instances_in_group, groupHandler);
  293. }
  294. };
  295. return new Proxy(this.group_names, groupsHandler);
  296. }
  297. /**
  298. * The default configuration that will be passed to each instance. Values from "definition.Config" on each instance will override the default config
  299. *
  300. */
  301. /** Getter
  302. *
  303. * @type {Object|Function}
  304. */
  305. get default_tor_config() {
  306. if (typeof(this._default_tor_config) === 'function')
  307. return this._default_tor_config();
  308. else if (this._default_tor_config)
  309. return _.cloneDeep(this._default_tor_config);
  310. else
  311. return {};
  312. }
  313. /**
  314. * Setter
  315. *
  316. * @param {Object|Function} value
  317. */
  318. set default_tor_config(value) { this._default_tor_config = value; }
  319. /**
  320. * Returns an enumeration of load balance methods as functions
  321. *
  322. * @readonly
  323. * @enum {Function}
  324. * @static
  325. */
  326. static get load_balance_methods() {
  327. return Object.freeze({
  328. round_robin: function (instances) {
  329. return instances.rotate(1);
  330. },
  331. weighted: function (instances) {
  332. if (!instances._weighted_list) {
  333. instances._weighted_list = new WeightedList(
  334. instances.map((instance) => {
  335. return [ instance.id, instance.definition.Weight, instance ]
  336. })
  337. );
  338. };
  339. let i = instances._weighted_list.peek(instances.length).map((element) => element.data);
  340. i._weighted_list = instances._weighted_list;
  341. return i;
  342. }
  343. });
  344. }
  345. /**
  346. * An array containing all instances in the pool.
  347. *
  348. * @readonly
  349. * @type {TorProcess[]}
  350. */
  351. get instances() {
  352. return this._instances.slice(0);
  353. }
  354. /**
  355. * An array containing the names of the instances in the pool.
  356. *
  357. * @readonly
  358. * @type {string[]}
  359. */
  360. get instance_names() {
  361. return this.instances.map((i) => i.instance_name);
  362. }
  363. /**
  364. * Creates an instance then adds it to the pool from the provided definiton.
  365. * Instance will be added (and Promise will resolve) after the instance is fully bootstrapped.
  366. *
  367. * @async
  368. * @param {InstanceDefinition} [instance_definition={}] - Instance definition that will be used to create the instance.
  369. * @returns {Promise&lt;TorProcess>} - The instance that was created.
  370. *
  371. * @throws If an instance with the same {@link InstanceDefinition#Name} already exists.
  372. */
  373. async create_instance(instance_definition) {
  374. if (!(fs.existsSync(this.data_directory)))
  375. await fs.mkdirAsync(this.data_directory);
  376. instance_definition = instance_definition || {};
  377. if (instance_definition.Name &amp;&amp; this.instance_names.indexOf(instance_definition.Name) !== -1)
  378. throw new Error(`Instance named ${instance_definition.Name} already exists`);
  379. this._instances._weighted_list = void(0);
  380. instance_definition.Config = _.extend(_.cloneDeep(this.default_tor_config), (instance_definition.Config || {}));
  381. let instance = new TorProcess(this.tor_path, instance_definition, this.granax_options, this.logger);
  382. instance.definition.Config.DataDirectory = instance.definition.Config.DataDirectory || path.join(this.data_directory, instance.instance_name);
  383. await instance.create();
  384. this._instances.push(instance);
  385. return await new Promise((resolve, reject) => {
  386. instance.once('error', reject);
  387. instance.once('ready', () => {
  388. /**
  389. * Fires when an instance has been created.
  390. *
  391. * @event TorPool#instance_created
  392. * @type {TorProcess}
  393. * @param {TorProcess} instance - The instance that was created.
  394. */
  395. this.emit('instance_created', instance);
  396. resolve(instance);
  397. });
  398. });
  399. }
  400. /**
  401. * Adds one or more instances to the pool from an array of definitions or single definition.
  402. * @param {InstanceDefinition[]|InstanceDefinition} instance_definitions
  403. *
  404. * @async
  405. * @return {Promise&lt;TorProcess[]>}
  406. * @throws If `instance_definitions` is falsy.
  407. */
  408. async add(instance_definitions) {
  409. if (!instance_definitions)
  410. throw new Error('Invalid "instance_definitions"');
  411. return await Promise.all([].concat(instance_definitions).map((instance_definition) => this.create_instance(instance_definition)));
  412. }
  413. /**
  414. * Creates one or more instances to the pool from either an array of definitions, a single definition or a number.
  415. * If a number is provided it will create n instances with empty definitions (e.g. `TorPool.create(5)` will create 5 instances).
  416. * @param {InstanceDefinition[]|InstanceDefinition|number} instance_definitions
  417. *
  418. * @async
  419. * @return {Promise&lt;TorProcess[]>}
  420. * @throws If `instances` is falsy.
  421. */
  422. async create(instances) {
  423. if (!instances)
  424. throw new Error('Invalid "instances"');
  425. if (typeof(instances) === 'number') {
  426. instances = Array.from(Array(instances)).map(() => ({}));
  427. }
  428. return await this.add(instances);
  429. }
  430. /**
  431. * Searches for an instance with the matching {@link TorProcess#instance_name} property.
  432. * @param {string} name - Name of the instance to search for
  433. * @returns {TorProcess} - Matching instance
  434. */
  435. instance_by_name(name) {
  436. return this._instances.filter((i) => i.instance_name === name)[0];
  437. }
  438. /**
  439. * Returns the instance located at the provided index in the pool.
  440. * Is equivalent to `{@link TorPool#instances}[index]`
  441. * @param {number} index - Index of the instance in the pool
  442. * @returns {TorProcess} - Matching instance
  443. */
  444. instance_at(index) {
  445. return this._instances[index];
  446. }
  447. /**
  448. * Removes a number of instances from the pool and kills their Tor processes.
  449. * @param {number} instances - Number of instances to remove
  450. * @param {number} [start_at=0] - Index to start removing from
  451. * @async
  452. * @returns {Promise} - Promise will resolve when the processes are dead
  453. */
  454. async remove(instances, start_at) {
  455. this._instances._weighted_list = void(0);
  456. let instances_to_remove = this._instances.splice((start_at || 0), instances);
  457. await Promise.all(instances_to_remove.map((instance) => instance.exit()));
  458. }
  459. /**
  460. * Removes an instance at the provided index and kills its Tor process.
  461. * @param {number} instance_index - Index of the instance to remove
  462. * @async
  463. * @returns {Promise} - Promise will resolve when the process is dead
  464. */
  465. async remove_at(instance_index) {
  466. this._instances._weighted_list = void(0);
  467. let instance = this._instances.splice(instance_index, 1)[0];
  468. if (!instance)
  469. throw new Error(`No instance at "${instance_index}"`);
  470. await instance.exit();
  471. }
  472. /**
  473. * Removes an instance whose {@link TorProcess#instance_name} property matches the provided name and kills its Tor process.
  474. * @param {string} instance_name - Name of the instance to remove
  475. * @async
  476. * @returns {Promise} - Promise will resolve when the process is dead
  477. */
  478. async remove_by_name(instance_name) {
  479. let instance = this.instance_by_name(instance_name);
  480. if (!instance)
  481. throw new Error(`Instance "${name}" not found`);
  482. let instance_index = (this.instances.indexOf(instance));
  483. await this.remove_at(instance_index);
  484. }
  485. /**
  486. * Runs the load balance function ({@link TorPool#load_balance_method}) on the array of instances in the pool and returns the first instance in the array.
  487. *
  488. * @returns {TorProcess} - The first instance in the modified array.
  489. */
  490. next() {
  491. this._instances = TorPool.load_balance_methods[this.load_balance_method](this._instances);
  492. return this.instances[0];
  493. }
  494. /**
  495. * Rotates the array containing instances in the group provided so that the second element becomes the first element and the first element becomes the last element.
  496. * [1,2,3] -> [2,3,1]
  497. * @todo Load balance methods other than "round_robin" to be used
  498. * @param {string} group - Name of the group
  499. * @returns {TorProcess} - The first element in the modified array
  500. */
  501. next_by_group(group) {
  502. this.groups[group].rotate(1);
  503. return this.groups[group][0];
  504. }
  505. /**
  506. * Kills the Tor processes of all instances in the pool.
  507. *
  508. * @async
  509. * @returns {Promise} - Resolves when all instances have been killed.
  510. */
  511. async exit() {
  512. await Promise.all(this._instances.map((instance) => instance.exit()));
  513. this._instances = [];
  514. }
  515. /**
  516. * Gets new identities for all instances in the pool.
  517. *
  518. * @async
  519. * @returns {Promise} - Resolves when all instances have new identities.
  520. */
  521. async new_identites() {
  522. await Promise.all(this.instances.map((instance) => instance.new_identity()));
  523. }
  524. /**
  525. * Gets new identities for all instances in a group.
  526. *
  527. * @async
  528. * @param {string} - Name of the group.
  529. * @returns {Promise} - Resolves when all instances in the group have new identities.
  530. */
  531. async new_identites_by_group(group) {
  532. await Promise.all(this.instances_by_group(group).map((instance) => instance.new_identity()));
  533. }
  534. /**
  535. * Gets a new identity for the instance at the provided index in the pool.
  536. *
  537. * @async
  538. * @param {number} - Index of the instance in the pool.
  539. * @returns {Promise} - Resolves when the instance has a new identity.
  540. */
  541. async new_identity_at(index) {
  542. await this.instances[index].new_identity();
  543. }
  544. /**
  545. * Gets a new identity for the instance whose {@link TorProcess.instance_name} matches the provided name.
  546. *
  547. * @async
  548. * @param {string} - Name of the instance.
  549. * @returns {Promise} - Resolves when the instance has a new identity.
  550. *
  551. * @throws When no instance matched the provided name.
  552. */
  553. async new_identity_by_name(name) {
  554. let instance = this.instance_by_name(name);
  555. if (!instance)
  556. throw new Error(`Instance "${name}" not found`);
  557. await instance.new_identity();
  558. }
  559. /**
  560. * Get a configuration value from the instance whose {@link TorProcess.instance_name} matches the provided name via the control protocol.
  561. *
  562. * @async
  563. * @param {string} name - Name of the instance.
  564. * @param {string} keyword - Name of the configuration property.
  565. *
  566. * @returns {Promise&lt;string[]>} - The configuration property's value.
  567. * @throws When no instance matched the provided name.
  568. */
  569. async get_config_by_name(name, keyword) {
  570. let instance = this.instance_by_name(name);
  571. if (!instance)
  572. throw new Error(`Instance "${name}" not found`);
  573. return await instance.get_config(keyword);
  574. }
  575. /**
  576. * Set a configuration value for the instance whose {@link TorProcess.instance_name} matches the provided name via the control protocol.
  577. *
  578. * @async
  579. * @param {string} name - Name of the instance.
  580. * @param {string} keyword - Name of the configuration property.
  581. * @param {any} value - Value to set the configuration property to.
  582. *
  583. * @returns {Promise}
  584. * @throws When no instance matched the provided name.
  585. */
  586. async set_config_by_name(name, keyword, value) {
  587. let instance = this.instance_by_name(name);
  588. if (!instance)
  589. throw new Error(`Instance "${name}" not found`);
  590. return await instance.set_config(keyword, value);
  591. }
  592. /**
  593. * Get a configuration value from the instance at the index in the pool via the control protocol.
  594. *
  595. * @async
  596. * @param {number} index - Index of the instance in the pool.
  597. * @param {string} keyword - Name of the configuration property.
  598. *
  599. * @returns {Promise&lt;string[]>} - The configuration property's value.
  600. * @throws When no instance exists at the provided index.
  601. */
  602. async get_config_at(index, keyword) {
  603. let instance = this.instances[index];
  604. if (!instance)
  605. throw new Error(`Instance at ${index} not found`);
  606. return await instance.get_config(keyword);
  607. }
  608. /**
  609. * Set a configuration value for the instance at the index in the pool via the control protocol.
  610. *
  611. * @async
  612. * @param {number} index - Index of the instance in the pool.
  613. * @param {string} keyword - Name of the configuration property.
  614. * @param {any} value - Value to set the configuration property to.
  615. *
  616. * @returns {Promise}
  617. * @throws When no instance exists at the provided index.
  618. */
  619. async set_config_at(index, keyword, value) {
  620. let instance = this.instances[index];
  621. if (!instance)
  622. throw new Error(`Instance at ${index} not found`);
  623. return await instance.set_config(keyword, value);
  624. }
  625. /**
  626. * Set a configuration value for all instances in the provided group via the control protocol.
  627. *
  628. * @async
  629. * @param {string} group - Name of the group.
  630. * @param {string} keyword - Name of the configuration property.
  631. * @param {any} value - Value to set the configuration property to.
  632. *
  633. * @returns {Promise}
  634. * @throws When the provided group does not exist.
  635. */
  636. async set_config_by_group(group, keyword, value) {
  637. return await Promise.all(this.instances_by_group(group).map((instance) => instance.set_config(keyword, value)));
  638. }
  639. /**
  640. * Set a configuration value for all instances in the pool via the control protocol.
  641. *
  642. * @async
  643. * @param {string} keyword - Name of the configuration property.
  644. * @param {any} value - Value to set the configuration property to.
  645. *
  646. * @returns {Promise}
  647. */
  648. async set_config_all(keyword, value) {
  649. return await Promise.all(this.instances.map((instance) => instance.set_config(keyword, value)));
  650. }
  651. /**
  652. * Send a signal via the control protocol to all instances in the pool.
  653. *
  654. * @async
  655. * @param {string} signal - The signal to send.
  656. *
  657. * @returns {Promise}
  658. */
  659. async signal_all(signal) {
  660. await Promise.all(this.instances.map((instance) => instance.signal(signal)));
  661. }
  662. /**
  663. * Send a signal via the control protocol to an instance whose {@link TorProcess#instance_name} property matches the provided name.
  664. *
  665. * @async
  666. * @param {string} name - Name of the instance.
  667. * @param {string} signal - The signal to send.
  668. *
  669. * @returns {Promise}
  670. */
  671. async signal_by_name(name, signal) {
  672. let instance = this.instance_by_name(name);
  673. if (!instance)
  674. throw new Error(`Instance "${name}" not found`);
  675. await instance.signal(signal);
  676. }
  677. /**
  678. * Send a signal via the control protocol to an instance at the provided index in the pool.
  679. *
  680. * @async
  681. * @param {number} index - Index of the instance in the pool.
  682. * @param {string} signal - The signal to send.
  683. *
  684. * @returns {Promise}
  685. */
  686. async signal_at(index, signal) {
  687. let instance = this.instances[index];
  688. if (!instance)
  689. throw new Error(`Instance at ${index} not found`);
  690. await instance.signal(signal);
  691. }
  692. /**
  693. * Send a signal via the control protocol to all instances in the provided group.
  694. *
  695. * @async
  696. * @param {string} group - Name of the group.
  697. * @param {string} signal - The signal to send.
  698. *
  699. * @returns {Promise}
  700. * @throws When the provided group does not exist.
  701. */
  702. async signal_by_group(group, signal) {
  703. await Promise.all(this.instances_by_group(group).map((instance) => instance.signal(signal)));
  704. }
  705. };
  706. /**
  707. * Module that contains the {@link TorPool} class.
  708. * @module tor-router/TorPool
  709. * @see TorPool
  710. */
  711. module.exports = TorPool;</code></pre>
  712. </article>
  713. </section>
  714. </div>
  715. <br class="clear">
  716. <footer>
  717. Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Tue Sep 25 2018 12:53:23 GMT-0400 (Eastern Daylight Time) using the <a href="https://github.com/clenemt/docdash">docdash</a> theme.
  718. </footer>
  719. <script>prettyPrint();</script>
  720. <script src="scripts/linenumber.js"></script>
  721. </body>
  722. </html>