cpuworker.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /* Copyright 2003-2004 Roger Dingledine.
  2. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char cpuworker_c_id[] = "$Id$";
  6. /**
  7. * \file cpuworker.c
  8. * \brief Implements a farm of 'CPU worker' processes to perform
  9. * CPU-intensive tasks in another thread or process, to not
  10. * interrupt the main thread.
  11. *
  12. * Right now, we only use this for processing onionskins.
  13. **/
  14. #include "or.h"
  15. /** The maximum number of cpuworker processes we will keep around. */
  16. #define MAX_CPUWORKERS 16
  17. /** The minimum number of cpuworker processes we will keep around. */
  18. #define MIN_CPUWORKERS 1
  19. /** The tag specifies which circuit this onionskin was from. */
  20. #define TAG_LEN 8
  21. /** How many bytes are sent from tor to the cpuworker? */
  22. #define LEN_ONION_QUESTION (1+TAG_LEN+ONIONSKIN_CHALLENGE_LEN)
  23. /** How many bytes are sent from the cpuworker back to tor? */
  24. #define LEN_ONION_RESPONSE (1+TAG_LEN+ONIONSKIN_REPLY_LEN+CPATH_KEY_MATERIAL_LEN)
  25. /** How many cpuworkers we have running right now. */
  26. static int num_cpuworkers=0;
  27. /** How many of the running cpuworkers have an assigned task right now. */
  28. static int num_cpuworkers_busy=0;
  29. /** We need to spawn new cpuworkers whenever we rotate the onion keys
  30. * on platforms where execution contexts==processes. This variable stores
  31. * the last time we got a key rotation event. */
  32. static time_t last_rotation_time=0;
  33. static int cpuworker_main(void *data);
  34. static int spawn_cpuworker(void);
  35. static void spawn_enough_cpuworkers(void);
  36. static void process_pending_task(connection_t *cpuworker);
  37. /** Initialize the cpuworker subsystem.
  38. */
  39. void
  40. cpu_init(void)
  41. {
  42. cpuworkers_rotate();
  43. }
  44. /** Called when we're done sending a request to a cpuworker. */
  45. int
  46. connection_cpu_finished_flushing(connection_t *conn)
  47. {
  48. tor_assert(conn);
  49. tor_assert(conn->type == CONN_TYPE_CPUWORKER);
  50. connection_stop_writing(conn);
  51. return 0;
  52. }
  53. /** Pack addr,port,and circ_id; set *tag to the result. (See note on
  54. * cpuworker_main for wire format.) */
  55. static void
  56. tag_pack(char *tag, uint32_t addr, uint16_t port, uint16_t circ_id)
  57. {
  58. *(uint32_t *)tag = addr;
  59. *(uint16_t *)(tag+4) = port;
  60. *(uint16_t *)(tag+6) = circ_id;
  61. }
  62. /** Unpack <b>tag</b> into addr, port, and circ_id.
  63. */
  64. static void
  65. tag_unpack(const char *tag, uint32_t *addr, uint16_t *port, uint16_t *circ_id)
  66. {
  67. struct in_addr in;
  68. char addrbuf[INET_NTOA_BUF_LEN];
  69. *addr = *(const uint32_t *)tag;
  70. *port = *(const uint16_t *)(tag+4);
  71. *circ_id = *(const uint16_t *)(tag+6);
  72. in.s_addr = htonl(*addr);
  73. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  74. debug(LD_OR,"onion was from %s:%d, circ_id %d.", addrbuf, *port, *circ_id);
  75. }
  76. /** Called when the onion key has changed and we need to spawn new
  77. * cpuworkers. Close all currently idle cpuworkers, and mark the last
  78. * rotation time as now.
  79. */
  80. void
  81. cpuworkers_rotate(void)
  82. {
  83. connection_t *cpuworker;
  84. while ((cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER,
  85. CPUWORKER_STATE_IDLE))) {
  86. connection_mark_for_close(cpuworker);
  87. --num_cpuworkers;
  88. }
  89. last_rotation_time = time(NULL);
  90. if (server_mode(get_options()))
  91. spawn_enough_cpuworkers();
  92. }
  93. /** If the cpuworker closes the connection,
  94. * mark it as closed and spawn a new one as needed. */
  95. int
  96. connection_cpu_reached_eof(connection_t *conn)
  97. {
  98. warn(LD_GENERAL,"Read eof. Worker died unexpectedly.");
  99. if (conn->state != CPUWORKER_STATE_IDLE) {
  100. /* the circ associated with this cpuworker will have to wait until
  101. * it gets culled in run_connection_housekeeping(), since we have
  102. * no way to find out which circ it was. */
  103. warn(LD_GENERAL,"...and it left a circuit queued; abandoning circ.");
  104. num_cpuworkers_busy--;
  105. }
  106. num_cpuworkers--;
  107. spawn_enough_cpuworkers(); /* try to regrow. hope we don't end up spinning. */
  108. connection_mark_for_close(conn);
  109. return 0;
  110. }
  111. /** Called when we get data from a cpuworker. If the answer is not complete,
  112. * wait for a complete answer. If the answer is complete,
  113. * process it as appropriate.
  114. */
  115. int
  116. connection_cpu_process_inbuf(connection_t *conn)
  117. {
  118. char success;
  119. char buf[LEN_ONION_RESPONSE];
  120. uint32_t addr;
  121. uint16_t port;
  122. uint16_t circ_id;
  123. connection_t *p_conn;
  124. circuit_t *circ;
  125. tor_assert(conn);
  126. tor_assert(conn->type == CONN_TYPE_CPUWORKER);
  127. if (!buf_datalen(conn->inbuf))
  128. return 0;
  129. if (conn->state == CPUWORKER_STATE_BUSY_ONION) {
  130. if (buf_datalen(conn->inbuf) < LEN_ONION_RESPONSE) /* entire answer available? */
  131. return 0; /* not yet */
  132. tor_assert(buf_datalen(conn->inbuf) == LEN_ONION_RESPONSE);
  133. connection_fetch_from_buf(&success,1,conn);
  134. connection_fetch_from_buf(buf,LEN_ONION_RESPONSE-1,conn);
  135. /* parse out the circ it was talking about */
  136. tag_unpack(buf, &addr, &port, &circ_id);
  137. circ = NULL;
  138. /* (Here we use connection_or_exact_get_by_addr_port rather than
  139. * get_by_identity_digest: we want a specific port here in
  140. * case there are multiple connections.) */
  141. p_conn = connection_or_exact_get_by_addr_port(addr,port);
  142. if (p_conn)
  143. circ = circuit_get_by_circid_orconn(circ_id, p_conn);
  144. if (success == 0) {
  145. debug(LD_OR,"decoding onionskin failed. (Old key or bad sw.) Closing.");
  146. if (circ)
  147. circuit_mark_for_close(circ);
  148. goto done_processing;
  149. }
  150. if (!circ) {
  151. /*XXXX Why does this happen?*/
  152. debug(LD_OR,"processed onion for a circ that's gone. Dropping.");
  153. goto done_processing;
  154. }
  155. tor_assert(circ->p_conn);
  156. if (onionskin_answer(circ, CELL_CREATED, buf+TAG_LEN, buf+TAG_LEN+ONIONSKIN_REPLY_LEN) < 0) {
  157. warn(LD_OR,"onionskin_answer failed. Closing.");
  158. circuit_mark_for_close(circ);
  159. goto done_processing;
  160. }
  161. debug(LD_OR,"onionskin_answer succeeded. Yay.");
  162. } else {
  163. tor_assert(0); /* don't ask me to do handshakes yet */
  164. }
  165. done_processing:
  166. conn->state = CPUWORKER_STATE_IDLE;
  167. num_cpuworkers_busy--;
  168. if (conn->timestamp_created < last_rotation_time) {
  169. connection_mark_for_close(conn);
  170. num_cpuworkers--;
  171. spawn_enough_cpuworkers();
  172. } else {
  173. process_pending_task(conn);
  174. }
  175. return 0;
  176. }
  177. /** Implement a cpuworker. 'data' is an fdarray as returned by socketpair.
  178. * Read and writes from fdarray[1]. Reads requests, writes answers.
  179. *
  180. * Request format:
  181. * Task type [1 byte, always CPUWORKER_TASK_ONION]
  182. * Opaque tag TAG_LEN
  183. * Onionskin challenge ONIONSKIN_CHALLENGE_LEN
  184. * Response format:
  185. * Success/failure [1 byte, boolean.]
  186. * Opaque tag TAG_LEN
  187. * Onionskin challenge ONIONSKIN_REPLY_LEN
  188. * Negotiated keys KEY_LEN*2+DIGEST_LEN*2
  189. *
  190. * (Note: this _should_ be by addr/port, since we're concerned with specific
  191. * connections, not with routers (where we'd use identity).)
  192. */
  193. static int
  194. cpuworker_main(void *data)
  195. {
  196. char question[ONIONSKIN_CHALLENGE_LEN];
  197. uint8_t question_type;
  198. int *fdarray = data;
  199. int fd;
  200. /* variables for onion processing */
  201. char keys[CPATH_KEY_MATERIAL_LEN];
  202. char reply_to_proxy[ONIONSKIN_REPLY_LEN];
  203. char buf[LEN_ONION_RESPONSE];
  204. char tag[TAG_LEN];
  205. crypto_pk_env_t *onion_key = NULL, *last_onion_key = NULL;
  206. fd = fdarray[1]; /* this side is ours */
  207. #ifndef TOR_IS_MULTITHREADED
  208. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
  209. tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  210. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  211. #endif
  212. tor_free(data);
  213. dup_onion_keys(&onion_key, &last_onion_key);
  214. for (;;) {
  215. int r;
  216. if ((r = recv(fd, &question_type, 1, 0)) != 1) {
  217. // log_fn(LOG_ERR,"read type failed. Exiting.");
  218. if (r == 0) {
  219. info(LD_OR,"CPU worker exiting because Tor process closed connection (either rotated keys or died).");
  220. } else {
  221. info(LD_OR,"CPU worker editing because of error on connection to Tor process.");
  222. info(LD_OR,"(Error on %d was %s)", fd, tor_socket_strerror(tor_socket_errno(fd)));
  223. }
  224. goto end;
  225. }
  226. tor_assert(question_type == CPUWORKER_TASK_ONION);
  227. if (read_all(fd, tag, TAG_LEN, 1) != TAG_LEN) {
  228. err(LD_BUG,"read tag failed. Exiting.");
  229. goto end;
  230. }
  231. if (read_all(fd, question, ONIONSKIN_CHALLENGE_LEN, 1) != ONIONSKIN_CHALLENGE_LEN) {
  232. info(LD_BUG,"read question failed. Exiting.");
  233. goto end;
  234. }
  235. if (question_type == CPUWORKER_TASK_ONION) {
  236. if (onion_skin_server_handshake(question, onion_key, last_onion_key,
  237. reply_to_proxy, keys, CPATH_KEY_MATERIAL_LEN) < 0) {
  238. /* failure */
  239. debug(LD_OR,"onion_skin_server_handshake failed.");
  240. memset(buf,0,LEN_ONION_RESPONSE); /* send all zeros for failure */
  241. } else {
  242. /* success */
  243. debug(LD_OR,"onion_skin_server_handshake succeeded.");
  244. buf[0] = 1; /* 1 means success */
  245. memcpy(buf+1,tag,TAG_LEN);
  246. memcpy(buf+1+TAG_LEN,reply_to_proxy,ONIONSKIN_REPLY_LEN);
  247. memcpy(buf+1+TAG_LEN+ONIONSKIN_REPLY_LEN,keys,CPATH_KEY_MATERIAL_LEN);
  248. }
  249. if (write_all(fd, buf, LEN_ONION_RESPONSE, 1) != LEN_ONION_RESPONSE) {
  250. err(LD_BUG,"writing response buf failed. Exiting.");
  251. goto end;
  252. }
  253. debug(LD_OR,"finished writing response.");
  254. }
  255. }
  256. end:
  257. if (onion_key)
  258. crypto_free_pk_env(onion_key);
  259. if (last_onion_key)
  260. crypto_free_pk_env(last_onion_key);
  261. tor_close_socket(fd);
  262. crypto_thread_cleanup();
  263. spawn_exit();
  264. return 0; /* windows wants this function to return an int */
  265. }
  266. /** Launch a new cpuworker. Return 0 if we're happy, -1 if we failed.
  267. */
  268. static int
  269. spawn_cpuworker(void)
  270. {
  271. int *fdarray;
  272. int fd;
  273. connection_t *conn;
  274. int err;
  275. fdarray = tor_malloc(sizeof(int)*2);
  276. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
  277. warn(LD_NET, "Couldn't construct socketpair: %s", tor_socket_strerror(-err));
  278. tor_free(fdarray);
  279. return -1;
  280. }
  281. fd = fdarray[0];
  282. spawn_func(cpuworker_main, (void*)fdarray);
  283. debug(LD_OR,"just spawned a worker.");
  284. #ifndef TOR_IS_MULTITHREADED
  285. tor_close_socket(fdarray[1]); /* we don't need the worker's side of the pipe */
  286. tor_free(fdarray);
  287. #endif
  288. conn = connection_new(CONN_TYPE_CPUWORKER);
  289. set_socket_nonblocking(fd);
  290. /* set up conn so it's got all the data we need to remember */
  291. conn->s = fd;
  292. conn->address = tor_strdup("localhost");
  293. if (connection_add(conn) < 0) { /* no space, forget it */
  294. warn(LD_NET,"connection_add failed. Giving up.");
  295. connection_free(conn); /* this closes fd */
  296. return -1;
  297. }
  298. conn->state = CPUWORKER_STATE_IDLE;
  299. connection_start_reading(conn);
  300. return 0; /* success */
  301. }
  302. /** If we have too few or too many active cpuworkers, try to spawn new ones
  303. * or kill idle ones.
  304. */
  305. static void
  306. spawn_enough_cpuworkers(void)
  307. {
  308. int num_cpuworkers_needed = get_options()->NumCpus;
  309. if (num_cpuworkers_needed < MIN_CPUWORKERS)
  310. num_cpuworkers_needed = MIN_CPUWORKERS;
  311. if (num_cpuworkers_needed > MAX_CPUWORKERS)
  312. num_cpuworkers_needed = MAX_CPUWORKERS;
  313. while (num_cpuworkers < num_cpuworkers_needed) {
  314. if (spawn_cpuworker() < 0) {
  315. warn(LD_GENERAL,"Spawn failed. Will try again later.");
  316. return;
  317. }
  318. num_cpuworkers++;
  319. }
  320. }
  321. /** Take a pending task from the queue and assign it to 'cpuworker'. */
  322. static void
  323. process_pending_task(connection_t *cpuworker)
  324. {
  325. circuit_t *circ;
  326. tor_assert(cpuworker);
  327. /* for now only process onion tasks */
  328. circ = onion_next_task();
  329. if (!circ)
  330. return;
  331. if (assign_to_cpuworker(cpuworker, CPUWORKER_TASK_ONION, circ) < 0)
  332. warn(LD_OR,"assign_to_cpuworker failed. Ignoring.");
  333. }
  334. #define CPUWORKER_BUSY_TIMEOUT 3600 /* seconds */
  335. /** We have a bug that I can't find. Sometimes, very rarely, cpuworkers
  336. * get stuck in the 'busy' state, even though the cpuworker process
  337. * thinks of itself as idle. I don't know why. But here's a workaround
  338. * to kill any cpuworker that's been busy for more than 3600 seconds. */
  339. static void
  340. cull_wedged_cpuworkers(void)
  341. {
  342. connection_t **carray;
  343. connection_t *conn;
  344. int n_conns, i;
  345. time_t now = time(NULL);
  346. get_connection_array(&carray, &n_conns);
  347. for (i = 0; i < n_conns; ++i) {
  348. conn = carray[i];
  349. if (!conn->marked_for_close &&
  350. conn->type == CONN_TYPE_CPUWORKER &&
  351. conn->state == CPUWORKER_STATE_BUSY_ONION &&
  352. conn->timestamp_lastwritten + CPUWORKER_BUSY_TIMEOUT < now) {
  353. notice(LD_BUG,"Bug: closing wedged cpuworker. Can somebody find the bug?");
  354. num_cpuworkers_busy--;
  355. num_cpuworkers--;
  356. connection_mark_for_close(conn);
  357. }
  358. }
  359. }
  360. /** If cpuworker is defined, assert that he's idle, and use him. Else,
  361. * look for an idle cpuworker and use him. If none idle, queue task onto
  362. * the pending onion list and return.
  363. * If question_type is CPUWORKER_TASK_ONION then task is a circ.
  364. * No other question_types are allowed.
  365. */
  366. int
  367. assign_to_cpuworker(connection_t *cpuworker, uint8_t question_type,
  368. void *task)
  369. {
  370. circuit_t *circ;
  371. char tag[TAG_LEN];
  372. tor_assert(question_type == CPUWORKER_TASK_ONION);
  373. cull_wedged_cpuworkers();
  374. spawn_enough_cpuworkers();
  375. if (question_type == CPUWORKER_TASK_ONION) {
  376. circ = task;
  377. tor_assert(circ->onionskin);
  378. if (num_cpuworkers_busy == num_cpuworkers) {
  379. debug(LD_OR,"No idle cpuworkers. Queuing.");
  380. if (onion_pending_add(circ) < 0)
  381. return -1;
  382. return 0;
  383. }
  384. if (!cpuworker)
  385. cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER, CPUWORKER_STATE_IDLE);
  386. tor_assert(cpuworker);
  387. if (!circ->p_conn) {
  388. info(LD_OR,"circ->p_conn gone. Failing circ.");
  389. return -1;
  390. }
  391. tag_pack(tag, circ->p_conn->addr, circ->p_conn->port, circ->p_circ_id);
  392. cpuworker->state = CPUWORKER_STATE_BUSY_ONION;
  393. num_cpuworkers_busy++;
  394. connection_write_to_buf((char*)&question_type, 1, cpuworker);
  395. connection_write_to_buf(tag, sizeof(tag), cpuworker);
  396. connection_write_to_buf(circ->onionskin, ONIONSKIN_CHALLENGE_LEN, cpuworker);
  397. tor_free(circ->onionskin);
  398. }
  399. return 0;
  400. }