cpuworker.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. /* Copyright (c) 2003-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2012, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file cpuworker.c
  7. * \brief Implements a farm of 'CPU worker' processes to perform
  8. * CPU-intensive tasks in another thread or process, to not
  9. * interrupt the main thread.
  10. *
  11. * Right now, we only use this for processing onionskins.
  12. **/
  13. #include "or.h"
  14. #include "buffers.h"
  15. #include "channel.h"
  16. #include "channeltls.h"
  17. #include "circuitbuild.h"
  18. #include "circuitlist.h"
  19. #include "config.h"
  20. #include "connection.h"
  21. #include "cpuworker.h"
  22. #include "main.h"
  23. #include "onion.h"
  24. #include "router.h"
  25. /** The maximum number of cpuworker processes we will keep around. */
  26. #define MAX_CPUWORKERS 16
  27. /** The minimum number of cpuworker processes we will keep around. */
  28. #define MIN_CPUWORKERS 1
  29. /** The tag specifies which circuit this onionskin was from. */
  30. #define TAG_LEN 10
  31. /** How many cpuworkers we have running right now. */
  32. static int num_cpuworkers=0;
  33. /** How many of the running cpuworkers have an assigned task right now. */
  34. static int num_cpuworkers_busy=0;
  35. /** We need to spawn new cpuworkers whenever we rotate the onion keys
  36. * on platforms where execution contexts==processes. This variable stores
  37. * the last time we got a key rotation event. */
  38. static time_t last_rotation_time=0;
  39. static void cpuworker_main(void *data) ATTR_NORETURN;
  40. static int spawn_cpuworker(void);
  41. static void spawn_enough_cpuworkers(void);
  42. static void process_pending_task(connection_t *cpuworker);
  43. /** Initialize the cpuworker subsystem.
  44. */
  45. void
  46. cpu_init(void)
  47. {
  48. cpuworkers_rotate();
  49. }
  50. /** Called when we're done sending a request to a cpuworker. */
  51. int
  52. connection_cpu_finished_flushing(connection_t *conn)
  53. {
  54. tor_assert(conn);
  55. tor_assert(conn->type == CONN_TYPE_CPUWORKER);
  56. return 0;
  57. }
  58. /** Pack global_id and circ_id; set *tag to the result. (See note on
  59. * cpuworker_main for wire format.) */
  60. static void
  61. tag_pack(uint8_t *tag, uint64_t chan_id, circid_t circ_id)
  62. {
  63. /*XXXX RETHINK THIS WHOLE MESS !!!! !NM NM NM NM*/
  64. /*XXXX DOUBLEPLUSTHIS!!!! AS AS AS AS*/
  65. set_uint64(tag, chan_id);
  66. set_uint16(tag+8, circ_id);
  67. }
  68. /** Unpack <b>tag</b> into addr, port, and circ_id.
  69. */
  70. static void
  71. tag_unpack(const uint8_t *tag, uint64_t *chan_id, circid_t *circ_id)
  72. {
  73. *chan_id = get_uint64(tag);
  74. *circ_id = get_uint16(tag+8);
  75. }
  76. /** Magic numbers to make sure our cpuworker_requests don't grow any
  77. * mis-framing bugs. */
  78. #define CPUWORKER_REQUEST_MAGIC 0xda4afeed
  79. #define CPUWORKER_REPLY_MAGIC 0x5eedf00d
  80. /** A request sent to a cpuworker. */
  81. typedef struct cpuworker_request_t {
  82. /** Magic number; must be CPUWORKER_REQUEST_MAGIC. */
  83. uint32_t magic;
  84. /** Opaque tag to identify the job */
  85. uint8_t tag[TAG_LEN];
  86. /** Task code. Must be one of CPUWORKER_TASK_* */
  87. uint8_t task;
  88. /** Flag: Are we timing this request? */
  89. unsigned timed : 1;
  90. /** If we're timing this request, when was it sent to the cpuworker? */
  91. struct timeval started_at;
  92. /** A create cell for the cpuworker to process. */
  93. create_cell_t create_cell;
  94. /* Turn the above into a tagged union if needed. */
  95. } cpuworker_request_t;
  96. /** A reply sent by a cpuworker. */
  97. typedef struct cpuworker_reply_t {
  98. /** Magic number; must be CPUWORKER_REPLY_MAGIC. */
  99. uint32_t magic;
  100. /** Opaque tag to identify the job; matches the request's tag.*/
  101. uint8_t tag[TAG_LEN];
  102. /** True iff we got a successful request. */
  103. uint8_t success;
  104. /** Are we timing this request? */
  105. unsigned int timed : 1;
  106. /** What handshake type was the request? (Used for timing) */
  107. uint16_t handshake_type;
  108. /** When did we send the request to the cpuworker? */
  109. struct timeval started_at;
  110. /** Once the cpuworker received the request, how many microseconds did it
  111. * take? (This shouldn't overflow; 4 billion micoseconds is over an hour,
  112. * and we'll never have an onion handshake that takes so long.) */
  113. uint32_t n_usec;
  114. /** Output of processing a create cell
  115. *
  116. * @{
  117. */
  118. /** The created cell to send back. */
  119. created_cell_t created_cell;
  120. /** The keys to use on this circuit. */
  121. uint8_t keys[CPATH_KEY_MATERIAL_LEN];
  122. /** Input to use for authenticating introduce1 cells. */
  123. uint8_t rend_auth_material[DIGEST_LEN];
  124. } cpuworker_reply_t;
  125. /** Called when the onion key has changed and we need to spawn new
  126. * cpuworkers. Close all currently idle cpuworkers, and mark the last
  127. * rotation time as now.
  128. */
  129. void
  130. cpuworkers_rotate(void)
  131. {
  132. connection_t *cpuworker;
  133. while ((cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER,
  134. CPUWORKER_STATE_IDLE))) {
  135. connection_mark_for_close(cpuworker);
  136. --num_cpuworkers;
  137. }
  138. last_rotation_time = time(NULL);
  139. if (server_mode(get_options()))
  140. spawn_enough_cpuworkers();
  141. }
  142. /** If the cpuworker closes the connection,
  143. * mark it as closed and spawn a new one as needed. */
  144. int
  145. connection_cpu_reached_eof(connection_t *conn)
  146. {
  147. log_warn(LD_GENERAL,"Read eof. CPU worker died unexpectedly.");
  148. if (conn->state != CPUWORKER_STATE_IDLE) {
  149. /* the circ associated with this cpuworker will have to wait until
  150. * it gets culled in run_connection_housekeeping(), since we have
  151. * no way to find out which circ it was. */
  152. log_warn(LD_GENERAL,"...and it left a circuit queued; abandoning circ.");
  153. num_cpuworkers_busy--;
  154. }
  155. num_cpuworkers--;
  156. spawn_enough_cpuworkers(); /* try to regrow. hope we don't end up
  157. spinning. */
  158. connection_mark_for_close(conn);
  159. return 0;
  160. }
  161. /** Indexed by handshake type: how many onionskins have we processed and
  162. * counted of that type? */
  163. static uint64_t onionskins_n_processed[MAX_ONION_HANDSHAKE_TYPE+1];
  164. /** Indexed by handshake type, corresponding to the onionskins counted in
  165. * onionskins_n_processed: how many microseconds have we spent in cpuworkers
  166. * processing that kind of onionskin? */
  167. static uint64_t onionskins_usec_internal[MAX_ONION_HANDSHAKE_TYPE+1];
  168. /** Indexed by handshake type, corresponding to onionskins counted in
  169. * onionskins_n_processed: how many microseconds have we spent waiting for
  170. * cpuworkers to give us answers for that kind of onionskin?
  171. */
  172. static uint64_t onionskins_usec_roundtrip[MAX_ONION_HANDSHAKE_TYPE+1];
  173. /** If any onionskin takes longer than this, we clip them to this
  174. * time. (microseconds) */
  175. #define MAX_BELIEVABLE_ONIONSKIN_DELAY (2*1000*1000)
  176. /** Return true iff we'd like to measure a handshake of type
  177. * <b>onionskin_type</b>. */
  178. static int
  179. should_time_request(uint16_t onionskin_type)
  180. {
  181. /* If we've never heard of this type, we shouldn't even be here. */
  182. if (onionskin_type > MAX_ONION_HANDSHAKE_TYPE)
  183. return 0;
  184. /* Measure the first N handshakes of each type, to ensure we have a
  185. * sample */
  186. if (onionskins_n_processed[onionskin_type] < 4096)
  187. return 1;
  188. /** Otherwise, measure with P=1/128. We avoid doing this for every
  189. * handshake, since the measurement itself can take a little time. */
  190. return tor_weak_random() < (TOR_RAND_MAX/128);
  191. }
  192. /** Return an estimate of how many microseconds we will need for a single
  193. * cpuworker to to process <b>n_requests</b> onionskins of type
  194. * <b>onionskin_type</b>. */
  195. uint64_t
  196. estimated_usec_for_onionskins(uint32_t n_requests, uint16_t onionskin_type)
  197. {
  198. if (onionskin_type > MAX_ONION_HANDSHAKE_TYPE) /* should be impossible */
  199. return 1000 * n_requests;
  200. if (PREDICT_UNLIKELY(onionskins_n_processed[onionskin_type] < 100)) {
  201. /* Until we have 100 data points, just asssume everything takes 1 msec. */
  202. return 1000 * n_requests;
  203. } else {
  204. /* This can't overflow: we'll never have more than 500000 onionskins
  205. * measured in onionskin_usec_internal, and they won't take anything near
  206. * 1 sec each, and we won't have anything like 1 million queued
  207. * onionskins. But that's 5e5 * 1e6 * 1e6, which is still less than
  208. * UINT64_MAX. */
  209. return (onionskins_usec_internal[onionskin_type] * n_requests) /
  210. onionskins_n_processed[onionskin_type];
  211. }
  212. }
  213. /** Called when we get data from a cpuworker. If the answer is not complete,
  214. * wait for a complete answer. If the answer is complete,
  215. * process it as appropriate.
  216. */
  217. int
  218. connection_cpu_process_inbuf(connection_t *conn)
  219. {
  220. uint64_t chan_id;
  221. circid_t circ_id;
  222. channel_t *p_chan = NULL;
  223. circuit_t *circ;
  224. tor_assert(conn);
  225. tor_assert(conn->type == CONN_TYPE_CPUWORKER);
  226. if (!connection_get_inbuf_len(conn))
  227. return 0;
  228. if (conn->state == CPUWORKER_STATE_BUSY_ONION) {
  229. cpuworker_reply_t rpl;
  230. if (connection_get_inbuf_len(conn) < sizeof(cpuworker_reply_t))
  231. return 0; /* not yet */
  232. tor_assert(connection_get_inbuf_len(conn) == sizeof(cpuworker_reply_t));
  233. connection_fetch_from_buf((void*)&rpl,sizeof(cpuworker_reply_t),conn);
  234. tor_assert(rpl.magic == CPUWORKER_REPLY_MAGIC);
  235. if (rpl.timed && rpl.success &&
  236. rpl.handshake_type <= MAX_ONION_HANDSHAKE_TYPE) {
  237. /* Time how long this request took. The handshake_type check should be
  238. needless, but let's leave it in to be safe. */
  239. struct timeval tv_end, tv_diff;
  240. int64_t usec_roundtrip;
  241. tor_gettimeofday(&tv_end);
  242. timersub(&tv_end, &rpl.started_at, &tv_diff);
  243. usec_roundtrip = ((int64_t)tv_diff.tv_sec)*1000000 + tv_diff.tv_usec;
  244. if (usec_roundtrip < 0 ||
  245. usec_roundtrip > MAX_BELIEVABLE_ONIONSKIN_DELAY) {
  246. usec_roundtrip = MAX_BELIEVABLE_ONIONSKIN_DELAY;
  247. }
  248. ++onionskins_n_processed[rpl.handshake_type];
  249. onionskins_usec_internal[rpl.handshake_type] += rpl.n_usec;
  250. onionskins_usec_roundtrip[rpl.handshake_type] += usec_roundtrip;
  251. if (onionskins_n_processed[rpl.handshake_type] >= 500000) {
  252. /* Scale down every 500000 handshakes. On a busy server, that's
  253. * less impressive than it sounds. */
  254. onionskins_n_processed[rpl.handshake_type] /= 2;
  255. onionskins_usec_internal[rpl.handshake_type] /= 2;
  256. onionskins_usec_roundtrip[rpl.handshake_type] /= 2;
  257. }
  258. }
  259. /* parse out the circ it was talking about */
  260. tag_unpack(rpl.tag, &chan_id, &circ_id);
  261. circ = NULL;
  262. log_debug(LD_OR,
  263. "Unpacking cpuworker reply, chan_id is " U64_FORMAT
  264. ", circ_id is %d",
  265. U64_PRINTF_ARG(chan_id), circ_id);
  266. p_chan = channel_find_by_global_id(chan_id);
  267. if (p_chan)
  268. circ = circuit_get_by_circid_channel(circ_id, p_chan);
  269. if (rpl.success == 0) {
  270. log_debug(LD_OR,
  271. "decoding onionskin failed. "
  272. "(Old key or bad software.) Closing.");
  273. if (circ)
  274. circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  275. goto done_processing;
  276. }
  277. if (!circ) {
  278. /* This happens because somebody sends us a destroy cell and the
  279. * circuit goes away, while the cpuworker is working. This is also
  280. * why our tag doesn't include a pointer to the circ, because we'd
  281. * never know if it's still valid.
  282. */
  283. log_debug(LD_OR,"processed onion for a circ that's gone. Dropping.");
  284. goto done_processing;
  285. }
  286. tor_assert(! CIRCUIT_IS_ORIGIN(circ));
  287. if (onionskin_answer(TO_OR_CIRCUIT(circ),
  288. &rpl.created_cell,
  289. (const char*)rpl.keys,
  290. rpl.rend_auth_material) < 0) {
  291. log_warn(LD_OR,"onionskin_answer failed. Closing.");
  292. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  293. goto done_processing;
  294. }
  295. log_debug(LD_OR,"onionskin_answer succeeded. Yay.");
  296. } else {
  297. tor_assert(0); /* don't ask me to do handshakes yet */
  298. }
  299. done_processing:
  300. conn->state = CPUWORKER_STATE_IDLE;
  301. num_cpuworkers_busy--;
  302. if (conn->timestamp_created < last_rotation_time) {
  303. connection_mark_for_close(conn);
  304. num_cpuworkers--;
  305. spawn_enough_cpuworkers();
  306. } else {
  307. process_pending_task(conn);
  308. }
  309. return 0;
  310. }
  311. /** Implement a cpuworker. 'data' is an fdarray as returned by socketpair.
  312. * Read and writes from fdarray[1]. Reads requests, writes answers.
  313. *
  314. * Request format:
  315. * cpuworker_request_t.
  316. * Response format:
  317. * cpuworker_reply_t
  318. */
  319. static void
  320. cpuworker_main(void *data)
  321. {
  322. /* For talking to the parent thread/process */
  323. tor_socket_t *fdarray = data;
  324. tor_socket_t fd;
  325. /* variables for onion processing */
  326. server_onion_keys_t onion_keys;
  327. cpuworker_request_t req;
  328. cpuworker_reply_t rpl;
  329. fd = fdarray[1]; /* this side is ours */
  330. #ifndef TOR_IS_MULTITHREADED
  331. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
  332. * parent uses */
  333. tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  334. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  335. #endif
  336. tor_free(data);
  337. setup_server_onion_keys(&onion_keys);
  338. for (;;) {
  339. if (read_all(fd, (void *)&req, sizeof(req), 1) != sizeof(req)) {
  340. log_info(LD_OR, "read request failed. Exiting.");
  341. goto end;
  342. }
  343. tor_assert(req.magic == CPUWORKER_REQUEST_MAGIC);
  344. memset(&rpl, 0, sizeof(rpl));
  345. if (req.task == CPUWORKER_TASK_ONION) {
  346. const create_cell_t *cc = &req.create_cell;
  347. created_cell_t *cell_out = &rpl.created_cell;
  348. struct timeval tv_start, tv_end;
  349. int n;
  350. rpl.timed = req.timed;
  351. rpl.started_at = req.started_at;
  352. rpl.handshake_type = cc->handshake_type;
  353. if (req.timed)
  354. tor_gettimeofday(&tv_start);
  355. n = onion_skin_server_handshake(cc->handshake_type,
  356. cc->onionskin, cc->handshake_len,
  357. &onion_keys,
  358. cell_out->reply,
  359. rpl.keys, CPATH_KEY_MATERIAL_LEN,
  360. rpl.rend_auth_material);
  361. if (n < 0) {
  362. /* failure */
  363. log_debug(LD_OR,"onion_skin_server_handshake failed.");
  364. memset(&rpl, 0, sizeof(rpl));
  365. memcpy(rpl.tag, req.tag, TAG_LEN);
  366. rpl.success = 0;
  367. } else {
  368. /* success */
  369. log_debug(LD_OR,"onion_skin_server_handshake succeeded.");
  370. memcpy(rpl.tag, req.tag, TAG_LEN);
  371. cell_out->handshake_len = n;
  372. switch (cc->cell_type) {
  373. case CELL_CREATE:
  374. cell_out->cell_type = CELL_CREATED; break;
  375. case CELL_CREATE2:
  376. cell_out->cell_type = CELL_CREATED2; break;
  377. case CELL_CREATE_FAST:
  378. cell_out->cell_type = CELL_CREATED_FAST; break;
  379. default:
  380. tor_assert(0);
  381. goto end;
  382. }
  383. rpl.success = 1;
  384. }
  385. rpl.magic = CPUWORKER_REPLY_MAGIC;
  386. if (req.timed) {
  387. struct timeval tv_diff;
  388. int64_t usec;
  389. tor_gettimeofday(&tv_end);
  390. timersub(&tv_end, &tv_start, &tv_diff);
  391. usec = ((int64_t)tv_diff.tv_sec)*1000000 + tv_diff.tv_usec;
  392. if (usec < 0 || usec > MAX_BELIEVABLE_ONIONSKIN_DELAY)
  393. rpl.n_usec = MAX_BELIEVABLE_ONIONSKIN_DELAY;
  394. else
  395. rpl.n_usec = (uint32_t) usec;
  396. }
  397. if (write_all(fd, (void*)&rpl, sizeof(rpl), 1) != sizeof(rpl)) {
  398. log_err(LD_BUG,"writing response buf failed. Exiting.");
  399. goto end;
  400. }
  401. log_debug(LD_OR,"finished writing response.");
  402. } else if (req.task == CPUWORKER_TASK_SHUTDOWN) {
  403. log_info(LD_OR,"Clean shutdown: exiting");
  404. goto end;
  405. }
  406. memwipe(&req, 0, sizeof(req));
  407. memwipe(&rpl, 0, sizeof(req));
  408. }
  409. end:
  410. memwipe(&req, 0, sizeof(req));
  411. memwipe(&rpl, 0, sizeof(req));
  412. release_server_onion_keys(&onion_keys);
  413. tor_close_socket(fd);
  414. crypto_thread_cleanup();
  415. spawn_exit();
  416. }
  417. /** Launch a new cpuworker. Return 0 if we're happy, -1 if we failed.
  418. */
  419. static int
  420. spawn_cpuworker(void)
  421. {
  422. tor_socket_t *fdarray;
  423. tor_socket_t fd;
  424. connection_t *conn;
  425. int err;
  426. fdarray = tor_malloc(sizeof(tor_socket_t)*2);
  427. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
  428. log_warn(LD_NET, "Couldn't construct socketpair for cpuworker: %s",
  429. tor_socket_strerror(-err));
  430. tor_free(fdarray);
  431. return -1;
  432. }
  433. tor_assert(SOCKET_OK(fdarray[0]));
  434. tor_assert(SOCKET_OK(fdarray[1]));
  435. fd = fdarray[0];
  436. spawn_func(cpuworker_main, (void*)fdarray);
  437. log_debug(LD_OR,"just spawned a cpu worker.");
  438. #ifndef TOR_IS_MULTITHREADED
  439. tor_close_socket(fdarray[1]); /* don't need the worker's side of the pipe */
  440. tor_free(fdarray);
  441. #endif
  442. conn = connection_new(CONN_TYPE_CPUWORKER, AF_UNIX);
  443. set_socket_nonblocking(fd);
  444. /* set up conn so it's got all the data we need to remember */
  445. conn->s = fd;
  446. conn->address = tor_strdup("localhost");
  447. tor_addr_make_unspec(&conn->addr);
  448. if (connection_add(conn) < 0) { /* no space, forget it */
  449. log_warn(LD_NET,"connection_add for cpuworker failed. Giving up.");
  450. connection_free(conn); /* this closes fd */
  451. return -1;
  452. }
  453. conn->state = CPUWORKER_STATE_IDLE;
  454. connection_start_reading(conn);
  455. return 0; /* success */
  456. }
  457. /** If we have too few or too many active cpuworkers, try to spawn new ones
  458. * or kill idle ones.
  459. */
  460. static void
  461. spawn_enough_cpuworkers(void)
  462. {
  463. int num_cpuworkers_needed = get_num_cpus(get_options());
  464. if (num_cpuworkers_needed < MIN_CPUWORKERS)
  465. num_cpuworkers_needed = MIN_CPUWORKERS;
  466. if (num_cpuworkers_needed > MAX_CPUWORKERS)
  467. num_cpuworkers_needed = MAX_CPUWORKERS;
  468. while (num_cpuworkers < num_cpuworkers_needed) {
  469. if (spawn_cpuworker() < 0) {
  470. log_warn(LD_GENERAL,"Cpuworker spawn failed. Will try again later.");
  471. return;
  472. }
  473. num_cpuworkers++;
  474. }
  475. }
  476. /** Take a pending task from the queue and assign it to 'cpuworker'. */
  477. static void
  478. process_pending_task(connection_t *cpuworker)
  479. {
  480. or_circuit_t *circ;
  481. create_cell_t *onionskin = NULL;
  482. tor_assert(cpuworker);
  483. /* for now only process onion tasks */
  484. circ = onion_next_task(&onionskin);
  485. if (!circ)
  486. return;
  487. if (assign_onionskin_to_cpuworker(cpuworker, circ, onionskin))
  488. log_warn(LD_OR,"assign_to_cpuworker failed. Ignoring.");
  489. }
  490. /** How long should we let a cpuworker stay busy before we give
  491. * up on it and decide that we have a bug or infinite loop?
  492. * This value is high because some servers with low memory/cpu
  493. * sometimes spend an hour or more swapping, and Tor starves. */
  494. #define CPUWORKER_BUSY_TIMEOUT (60*60*12)
  495. /** We have a bug that I can't find. Sometimes, very rarely, cpuworkers get
  496. * stuck in the 'busy' state, even though the cpuworker process thinks of
  497. * itself as idle. I don't know why. But here's a workaround to kill any
  498. * cpuworker that's been busy for more than CPUWORKER_BUSY_TIMEOUT.
  499. */
  500. static void
  501. cull_wedged_cpuworkers(void)
  502. {
  503. time_t now = time(NULL);
  504. smartlist_t *conns = get_connection_array();
  505. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  506. if (!conn->marked_for_close &&
  507. conn->type == CONN_TYPE_CPUWORKER &&
  508. conn->state == CPUWORKER_STATE_BUSY_ONION &&
  509. conn->timestamp_lastwritten + CPUWORKER_BUSY_TIMEOUT < now) {
  510. log_notice(LD_BUG,
  511. "closing wedged cpuworker. Can somebody find the bug?");
  512. num_cpuworkers_busy--;
  513. num_cpuworkers--;
  514. connection_mark_for_close(conn);
  515. }
  516. } SMARTLIST_FOREACH_END(conn);
  517. }
  518. /** Try to tell a cpuworker to perform the public key operations necessary to
  519. * respond to <b>onionskin</b> for the circuit <b>circ</b>.
  520. *
  521. * If <b>cpuworker</b> is defined, assert that he's idle, and use him. Else,
  522. * look for an idle cpuworker and use him. If none idle, queue task onto the
  523. * pending onion list and return. Return 0 if we successfully assign the
  524. * task, or -1 on failure.
  525. */
  526. int
  527. assign_onionskin_to_cpuworker(connection_t *cpuworker,
  528. or_circuit_t *circ,
  529. create_cell_t *onionskin)
  530. {
  531. cpuworker_request_t req;
  532. time_t now = approx_time();
  533. static time_t last_culled_cpuworkers = 0;
  534. int should_time;
  535. /* Checking for wedged cpuworkers requires a linear search over all
  536. * connections, so let's do it only once a minute.
  537. */
  538. #define CULL_CPUWORKERS_INTERVAL 60
  539. if (last_culled_cpuworkers + CULL_CPUWORKERS_INTERVAL <= now) {
  540. cull_wedged_cpuworkers();
  541. spawn_enough_cpuworkers();
  542. last_culled_cpuworkers = now;
  543. }
  544. if (1) {
  545. if (num_cpuworkers_busy == num_cpuworkers) {
  546. log_debug(LD_OR,"No idle cpuworkers. Queuing.");
  547. if (onion_pending_add(circ, onionskin) < 0) {
  548. tor_free(onionskin);
  549. return -1;
  550. }
  551. return 0;
  552. }
  553. if (!cpuworker)
  554. cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER,
  555. CPUWORKER_STATE_IDLE);
  556. tor_assert(cpuworker);
  557. if (!circ->p_chan) {
  558. log_info(LD_OR,"circ->p_chan gone. Failing circ.");
  559. tor_free(onionskin);
  560. return -1;
  561. }
  562. should_time = should_time_request(onionskin->handshake_type);
  563. memset(&req, 0, sizeof(req));
  564. req.magic = CPUWORKER_REQUEST_MAGIC;
  565. tag_pack(req.tag, circ->p_chan->global_identifier,
  566. circ->p_circ_id);
  567. req.timed = should_time;
  568. cpuworker->state = CPUWORKER_STATE_BUSY_ONION;
  569. /* touch the lastwritten timestamp, since that's how we check to
  570. * see how long it's been since we asked the question, and sometimes
  571. * we check before the first call to connection_handle_write(). */
  572. cpuworker->timestamp_lastwritten = now;
  573. num_cpuworkers_busy++;
  574. req.task = CPUWORKER_TASK_ONION;
  575. memcpy(&req.create_cell, onionskin, sizeof(create_cell_t));
  576. tor_free(onionskin);
  577. if (should_time)
  578. tor_gettimeofday(&req.started_at);
  579. connection_write_to_buf((void*)&req, sizeof(req), cpuworker);
  580. memwipe(&req, 0, sizeof(req));
  581. }
  582. return 0;
  583. }