cpuworker.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /* Copyright (c) 2003-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2013, 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. /** A create cell for the cpuworker to process. */
  89. create_cell_t create_cell;
  90. /* Turn the above into a tagged union if needed. */
  91. } cpuworker_request_t;
  92. /** A reply sent by a cpuworker. */
  93. typedef struct cpuworker_reply_t {
  94. /** Magic number; must be CPUWORKER_REPLY_MAGIC. */
  95. uint32_t magic;
  96. /** Opaque tag to identify the job; matches the request's tag.*/
  97. uint8_t tag[TAG_LEN];
  98. /** True iff we got a successful request. */
  99. uint8_t success;
  100. /** Output of processing a create cell
  101. *
  102. * @{
  103. */
  104. /** The created cell to send back. */
  105. created_cell_t created_cell;
  106. /** The keys to use on this circuit. */
  107. uint8_t keys[CPATH_KEY_MATERIAL_LEN];
  108. /** Input to use for authenticating introduce1 cells. */
  109. uint8_t rend_auth_material[DIGEST_LEN];
  110. } cpuworker_reply_t;
  111. /** Called when the onion key has changed and we need to spawn new
  112. * cpuworkers. Close all currently idle cpuworkers, and mark the last
  113. * rotation time as now.
  114. */
  115. void
  116. cpuworkers_rotate(void)
  117. {
  118. connection_t *cpuworker;
  119. while ((cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER,
  120. CPUWORKER_STATE_IDLE))) {
  121. connection_mark_for_close(cpuworker);
  122. --num_cpuworkers;
  123. }
  124. last_rotation_time = time(NULL);
  125. if (server_mode(get_options()))
  126. spawn_enough_cpuworkers();
  127. }
  128. /** If the cpuworker closes the connection,
  129. * mark it as closed and spawn a new one as needed. */
  130. int
  131. connection_cpu_reached_eof(connection_t *conn)
  132. {
  133. log_warn(LD_GENERAL,"Read eof. CPU worker died unexpectedly.");
  134. if (conn->state != CPUWORKER_STATE_IDLE) {
  135. /* the circ associated with this cpuworker will have to wait until
  136. * it gets culled in run_connection_housekeeping(), since we have
  137. * no way to find out which circ it was. */
  138. log_warn(LD_GENERAL,"...and it left a circuit queued; abandoning circ.");
  139. num_cpuworkers_busy--;
  140. }
  141. num_cpuworkers--;
  142. spawn_enough_cpuworkers(); /* try to regrow. hope we don't end up
  143. spinning. */
  144. connection_mark_for_close(conn);
  145. return 0;
  146. }
  147. /** Called when we get data from a cpuworker. If the answer is not complete,
  148. * wait for a complete answer. If the answer is complete,
  149. * process it as appropriate.
  150. */
  151. int
  152. connection_cpu_process_inbuf(connection_t *conn)
  153. {
  154. uint64_t chan_id;
  155. circid_t circ_id;
  156. channel_t *p_chan = NULL;
  157. circuit_t *circ;
  158. tor_assert(conn);
  159. tor_assert(conn->type == CONN_TYPE_CPUWORKER);
  160. if (!connection_get_inbuf_len(conn))
  161. return 0;
  162. if (conn->state == CPUWORKER_STATE_BUSY_ONION) {
  163. cpuworker_reply_t rpl;
  164. if (connection_get_inbuf_len(conn) < sizeof(cpuworker_reply_t))
  165. return 0; /* not yet */
  166. tor_assert(connection_get_inbuf_len(conn) == sizeof(cpuworker_reply_t));
  167. connection_fetch_from_buf((void*)&rpl,sizeof(cpuworker_reply_t),conn);
  168. tor_assert(rpl.magic == CPUWORKER_REPLY_MAGIC);
  169. /* parse out the circ it was talking about */
  170. tag_unpack(rpl.tag, &chan_id, &circ_id);
  171. circ = NULL;
  172. log_debug(LD_OR,
  173. "Unpacking cpuworker reply, chan_id is " U64_FORMAT
  174. ", circ_id is %d",
  175. U64_PRINTF_ARG(chan_id), circ_id);
  176. p_chan = channel_find_by_global_id(chan_id);
  177. if (p_chan)
  178. circ = circuit_get_by_circid_channel(circ_id, p_chan);
  179. if (rpl.success == 0) {
  180. log_debug(LD_OR,
  181. "decoding onionskin failed. "
  182. "(Old key or bad software.) Closing.");
  183. if (circ)
  184. circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  185. goto done_processing;
  186. }
  187. if (!circ) {
  188. /* This happens because somebody sends us a destroy cell and the
  189. * circuit goes away, while the cpuworker is working. This is also
  190. * why our tag doesn't include a pointer to the circ, because we'd
  191. * never know if it's still valid.
  192. */
  193. log_debug(LD_OR,"processed onion for a circ that's gone. Dropping.");
  194. goto done_processing;
  195. }
  196. tor_assert(! CIRCUIT_IS_ORIGIN(circ));
  197. if (onionskin_answer(TO_OR_CIRCUIT(circ),
  198. &rpl.created_cell,
  199. (const char*)rpl.keys,
  200. rpl.rend_auth_material) < 0) {
  201. log_warn(LD_OR,"onionskin_answer failed. Closing.");
  202. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  203. goto done_processing;
  204. }
  205. log_debug(LD_OR,"onionskin_answer succeeded. Yay.");
  206. } else {
  207. tor_assert(0); /* don't ask me to do handshakes yet */
  208. }
  209. done_processing:
  210. conn->state = CPUWORKER_STATE_IDLE;
  211. num_cpuworkers_busy--;
  212. if (conn->timestamp_created < last_rotation_time) {
  213. connection_mark_for_close(conn);
  214. num_cpuworkers--;
  215. spawn_enough_cpuworkers();
  216. } else {
  217. process_pending_task(conn);
  218. }
  219. return 0;
  220. }
  221. /** Implement a cpuworker. 'data' is an fdarray as returned by socketpair.
  222. * Read and writes from fdarray[1]. Reads requests, writes answers.
  223. *
  224. * Request format:
  225. * cpuworker_request_t.
  226. * Response format:
  227. * cpuworker_reply_t
  228. */
  229. static void
  230. cpuworker_main(void *data)
  231. {
  232. /* For talking to the parent thread/process */
  233. tor_socket_t *fdarray = data;
  234. tor_socket_t fd;
  235. /* variables for onion processing */
  236. server_onion_keys_t onion_keys;
  237. cpuworker_request_t req;
  238. cpuworker_reply_t rpl;
  239. fd = fdarray[1]; /* this side is ours */
  240. #ifndef TOR_IS_MULTITHREADED
  241. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
  242. * parent uses */
  243. tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  244. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  245. #endif
  246. tor_free(data);
  247. setup_server_onion_keys(&onion_keys);
  248. for (;;) {
  249. if (read_all(fd, (void *)&req, sizeof(req), 1) != sizeof(req)) {
  250. log_info(LD_OR, "read request failed. Exiting.");
  251. goto end;
  252. }
  253. tor_assert(req.magic == CPUWORKER_REQUEST_MAGIC);
  254. memset(&rpl, 0, sizeof(rpl));
  255. if (req.task == CPUWORKER_TASK_ONION) {
  256. const create_cell_t *cc = &req.create_cell;
  257. created_cell_t *cell_out = &rpl.created_cell;
  258. int n;
  259. n = onion_skin_server_handshake(cc->handshake_type,
  260. cc->onionskin, cc->handshake_len,
  261. &onion_keys,
  262. cell_out->reply,
  263. rpl.keys, CPATH_KEY_MATERIAL_LEN,
  264. rpl.rend_auth_material);
  265. if (n < 0) {
  266. /* failure */
  267. log_debug(LD_OR,"onion_skin_server_handshake failed.");
  268. memset(&rpl, 0, sizeof(rpl));
  269. memcpy(rpl.tag, req.tag, TAG_LEN);
  270. rpl.success = 0;
  271. } else {
  272. /* success */
  273. log_debug(LD_OR,"onion_skin_server_handshake succeeded.");
  274. memcpy(rpl.tag, req.tag, TAG_LEN);
  275. cell_out->handshake_len = n;
  276. switch (cc->cell_type) {
  277. case CELL_CREATE:
  278. cell_out->cell_type = CELL_CREATED; break;
  279. case CELL_CREATE2:
  280. cell_out->cell_type = CELL_CREATED2; break;
  281. case CELL_CREATE_FAST:
  282. cell_out->cell_type = CELL_CREATED_FAST; break;
  283. default:
  284. tor_assert(0);
  285. goto end;
  286. }
  287. rpl.success = 1;
  288. }
  289. rpl.magic = CPUWORKER_REPLY_MAGIC;
  290. if (write_all(fd, (void*)&rpl, sizeof(rpl), 1) != sizeof(rpl)) {
  291. log_err(LD_BUG,"writing response buf failed. Exiting.");
  292. goto end;
  293. }
  294. log_debug(LD_OR,"finished writing response.");
  295. } else if (req.task == CPUWORKER_TASK_SHUTDOWN) {
  296. log_info(LD_OR,"Clean shutdown: exiting");
  297. goto end;
  298. }
  299. memwipe(&req, 0, sizeof(req));
  300. memwipe(&rpl, 0, sizeof(req));
  301. }
  302. end:
  303. memwipe(&req, 0, sizeof(req));
  304. memwipe(&rpl, 0, sizeof(req));
  305. release_server_onion_keys(&onion_keys);
  306. tor_close_socket(fd);
  307. crypto_thread_cleanup();
  308. spawn_exit();
  309. }
  310. /** Launch a new cpuworker. Return 0 if we're happy, -1 if we failed.
  311. */
  312. static int
  313. spawn_cpuworker(void)
  314. {
  315. tor_socket_t *fdarray;
  316. tor_socket_t fd;
  317. connection_t *conn;
  318. int err;
  319. fdarray = tor_malloc(sizeof(tor_socket_t)*2);
  320. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
  321. log_warn(LD_NET, "Couldn't construct socketpair for cpuworker: %s",
  322. tor_socket_strerror(-err));
  323. tor_free(fdarray);
  324. return -1;
  325. }
  326. tor_assert(SOCKET_OK(fdarray[0]));
  327. tor_assert(SOCKET_OK(fdarray[1]));
  328. fd = fdarray[0];
  329. spawn_func(cpuworker_main, (void*)fdarray);
  330. log_debug(LD_OR,"just spawned a cpu worker.");
  331. #ifndef TOR_IS_MULTITHREADED
  332. tor_close_socket(fdarray[1]); /* don't need the worker's side of the pipe */
  333. tor_free(fdarray);
  334. #endif
  335. conn = connection_new(CONN_TYPE_CPUWORKER, AF_UNIX);
  336. set_socket_nonblocking(fd);
  337. /* set up conn so it's got all the data we need to remember */
  338. conn->s = fd;
  339. conn->address = tor_strdup("localhost");
  340. tor_addr_make_unspec(&conn->addr);
  341. if (connection_add(conn) < 0) { /* no space, forget it */
  342. log_warn(LD_NET,"connection_add for cpuworker failed. Giving up.");
  343. connection_free(conn); /* this closes fd */
  344. return -1;
  345. }
  346. conn->state = CPUWORKER_STATE_IDLE;
  347. connection_start_reading(conn);
  348. return 0; /* success */
  349. }
  350. /** If we have too few or too many active cpuworkers, try to spawn new ones
  351. * or kill idle ones.
  352. */
  353. static void
  354. spawn_enough_cpuworkers(void)
  355. {
  356. int num_cpuworkers_needed = get_num_cpus(get_options());
  357. if (num_cpuworkers_needed < MIN_CPUWORKERS)
  358. num_cpuworkers_needed = MIN_CPUWORKERS;
  359. if (num_cpuworkers_needed > MAX_CPUWORKERS)
  360. num_cpuworkers_needed = MAX_CPUWORKERS;
  361. while (num_cpuworkers < num_cpuworkers_needed) {
  362. if (spawn_cpuworker() < 0) {
  363. log_warn(LD_GENERAL,"Cpuworker spawn failed. Will try again later.");
  364. return;
  365. }
  366. num_cpuworkers++;
  367. }
  368. }
  369. /** Take a pending task from the queue and assign it to 'cpuworker'. */
  370. static void
  371. process_pending_task(connection_t *cpuworker)
  372. {
  373. or_circuit_t *circ;
  374. create_cell_t *onionskin = NULL;
  375. tor_assert(cpuworker);
  376. /* for now only process onion tasks */
  377. circ = onion_next_task(&onionskin);
  378. if (!circ)
  379. return;
  380. if (assign_onionskin_to_cpuworker(cpuworker, circ, onionskin))
  381. log_warn(LD_OR,"assign_to_cpuworker failed. Ignoring.");
  382. }
  383. /** How long should we let a cpuworker stay busy before we give
  384. * up on it and decide that we have a bug or infinite loop?
  385. * This value is high because some servers with low memory/cpu
  386. * sometimes spend an hour or more swapping, and Tor starves. */
  387. #define CPUWORKER_BUSY_TIMEOUT (60*60*12)
  388. /** We have a bug that I can't find. Sometimes, very rarely, cpuworkers get
  389. * stuck in the 'busy' state, even though the cpuworker process thinks of
  390. * itself as idle. I don't know why. But here's a workaround to kill any
  391. * cpuworker that's been busy for more than CPUWORKER_BUSY_TIMEOUT.
  392. */
  393. static void
  394. cull_wedged_cpuworkers(void)
  395. {
  396. time_t now = time(NULL);
  397. smartlist_t *conns = get_connection_array();
  398. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  399. if (!conn->marked_for_close &&
  400. conn->type == CONN_TYPE_CPUWORKER &&
  401. conn->state == CPUWORKER_STATE_BUSY_ONION &&
  402. conn->timestamp_lastwritten + CPUWORKER_BUSY_TIMEOUT < now) {
  403. log_notice(LD_BUG,
  404. "closing wedged cpuworker. Can somebody find the bug?");
  405. num_cpuworkers_busy--;
  406. num_cpuworkers--;
  407. connection_mark_for_close(conn);
  408. }
  409. } SMARTLIST_FOREACH_END(conn);
  410. }
  411. /** Try to tell a cpuworker to perform the public key operations necessary to
  412. * respond to <b>onionskin</b> for the circuit <b>circ</b>.
  413. *
  414. * If <b>cpuworker</b> is defined, assert that he's idle, and use him. Else,
  415. * look for an idle cpuworker and use him. If none idle, queue task onto the
  416. * pending onion list and return. Return 0 if we successfully assign the
  417. * task, or -1 on failure.
  418. */
  419. int
  420. assign_onionskin_to_cpuworker(connection_t *cpuworker,
  421. or_circuit_t *circ,
  422. create_cell_t *onionskin)
  423. {
  424. cpuworker_request_t req;
  425. time_t now = approx_time();
  426. static time_t last_culled_cpuworkers = 0;
  427. /* Checking for wedged cpuworkers requires a linear search over all
  428. * connections, so let's do it only once a minute.
  429. */
  430. #define CULL_CPUWORKERS_INTERVAL 60
  431. if (last_culled_cpuworkers + CULL_CPUWORKERS_INTERVAL <= now) {
  432. cull_wedged_cpuworkers();
  433. spawn_enough_cpuworkers();
  434. last_culled_cpuworkers = now;
  435. }
  436. if (1) {
  437. if (num_cpuworkers_busy == num_cpuworkers) {
  438. log_debug(LD_OR,"No idle cpuworkers. Queuing.");
  439. if (onion_pending_add(circ, onionskin) < 0) {
  440. tor_free(onionskin);
  441. return -1;
  442. }
  443. return 0;
  444. }
  445. if (!cpuworker)
  446. cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER,
  447. CPUWORKER_STATE_IDLE);
  448. tor_assert(cpuworker);
  449. if (!circ->p_chan) {
  450. log_info(LD_OR,"circ->p_chan gone. Failing circ.");
  451. tor_free(onionskin);
  452. return -1;
  453. }
  454. memset(&req, 0, sizeof(req));
  455. req.magic = CPUWORKER_REQUEST_MAGIC;
  456. tag_pack(req.tag, circ->p_chan->global_identifier,
  457. circ->p_circ_id);
  458. cpuworker->state = CPUWORKER_STATE_BUSY_ONION;
  459. /* touch the lastwritten timestamp, since that's how we check to
  460. * see how long it's been since we asked the question, and sometimes
  461. * we check before the first call to connection_handle_write(). */
  462. cpuworker->timestamp_lastwritten = time(NULL);
  463. num_cpuworkers_busy++;
  464. req.task = CPUWORKER_TASK_ONION;
  465. memcpy(&req.create_cell, onionskin, sizeof(create_cell_t));
  466. tor_free(onionskin);
  467. connection_write_to_buf((void*)&req, sizeof(req), cpuworker);
  468. memwipe(&req, 0, sizeof(req));
  469. }
  470. return 0;
  471. }