cpuworker.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 bytes are sent from the cpuworker back to tor? */
  32. #define LEN_ONION_RESPONSE \
  33. (1+TAG_LEN+ONIONSKIN_REPLY_LEN+CPATH_KEY_MATERIAL_LEN)
  34. /** How many cpuworkers we have running right now. */
  35. static int num_cpuworkers=0;
  36. /** How many of the running cpuworkers have an assigned task right now. */
  37. static int num_cpuworkers_busy=0;
  38. /** We need to spawn new cpuworkers whenever we rotate the onion keys
  39. * on platforms where execution contexts==processes. This variable stores
  40. * the last time we got a key rotation event. */
  41. static time_t last_rotation_time=0;
  42. static void cpuworker_main(void *data) ATTR_NORETURN;
  43. static int spawn_cpuworker(void);
  44. static void spawn_enough_cpuworkers(void);
  45. static void process_pending_task(connection_t *cpuworker);
  46. /** Initialize the cpuworker subsystem.
  47. */
  48. void
  49. cpu_init(void)
  50. {
  51. cpuworkers_rotate();
  52. }
  53. /** Called when we're done sending a request to a cpuworker. */
  54. int
  55. connection_cpu_finished_flushing(connection_t *conn)
  56. {
  57. tor_assert(conn);
  58. tor_assert(conn->type == CONN_TYPE_CPUWORKER);
  59. return 0;
  60. }
  61. /** Pack global_id and circ_id; set *tag to the result. (See note on
  62. * cpuworker_main for wire format.) */
  63. static void
  64. tag_pack(char *tag, uint64_t chan_id, circid_t circ_id)
  65. {
  66. /*XXXX RETHINK THIS WHOLE MESS !!!! !NM NM NM NM*/
  67. /*XXXX DOUBLEPLUSTHIS!!!! AS AS AS AS*/
  68. set_uint64(tag, chan_id);
  69. set_uint16(tag+8, circ_id);
  70. }
  71. /** Unpack <b>tag</b> into addr, port, and circ_id.
  72. */
  73. static void
  74. tag_unpack(const char *tag, uint64_t *chan_id, circid_t *circ_id)
  75. {
  76. *chan_id = get_uint64(tag);
  77. *circ_id = get_uint16(tag+8);
  78. }
  79. /** Called when the onion key has changed and we need to spawn new
  80. * cpuworkers. Close all currently idle cpuworkers, and mark the last
  81. * rotation time as now.
  82. */
  83. void
  84. cpuworkers_rotate(void)
  85. {
  86. connection_t *cpuworker;
  87. while ((cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER,
  88. CPUWORKER_STATE_IDLE))) {
  89. connection_mark_for_close(cpuworker);
  90. --num_cpuworkers;
  91. }
  92. last_rotation_time = time(NULL);
  93. if (server_mode(get_options()))
  94. spawn_enough_cpuworkers();
  95. }
  96. /** If the cpuworker closes the connection,
  97. * mark it as closed and spawn a new one as needed. */
  98. int
  99. connection_cpu_reached_eof(connection_t *conn)
  100. {
  101. log_warn(LD_GENERAL,"Read eof. CPU worker died unexpectedly.");
  102. if (conn->state != CPUWORKER_STATE_IDLE) {
  103. /* the circ associated with this cpuworker will have to wait until
  104. * it gets culled in run_connection_housekeeping(), since we have
  105. * no way to find out which circ it was. */
  106. log_warn(LD_GENERAL,"...and it left a circuit queued; abandoning circ.");
  107. num_cpuworkers_busy--;
  108. }
  109. num_cpuworkers--;
  110. spawn_enough_cpuworkers(); /* try to regrow. hope we don't end up
  111. spinning. */
  112. connection_mark_for_close(conn);
  113. return 0;
  114. }
  115. /** Called when we get data from a cpuworker. If the answer is not complete,
  116. * wait for a complete answer. If the answer is complete,
  117. * process it as appropriate.
  118. */
  119. int
  120. connection_cpu_process_inbuf(connection_t *conn)
  121. {
  122. char success;
  123. char buf[LEN_ONION_RESPONSE];
  124. uint64_t chan_id;
  125. circid_t circ_id;
  126. channel_t *p_chan = NULL;
  127. circuit_t *circ;
  128. tor_assert(conn);
  129. tor_assert(conn->type == CONN_TYPE_CPUWORKER);
  130. if (!connection_get_inbuf_len(conn))
  131. return 0;
  132. if (conn->state == CPUWORKER_STATE_BUSY_ONION) {
  133. if (connection_get_inbuf_len(conn) < LEN_ONION_RESPONSE)
  134. return 0; /* not yet */
  135. tor_assert(connection_get_inbuf_len(conn) == LEN_ONION_RESPONSE);
  136. connection_fetch_from_buf(&success,1,conn);
  137. connection_fetch_from_buf(buf,LEN_ONION_RESPONSE-1,conn);
  138. /* parse out the circ it was talking about */
  139. tag_unpack(buf, &chan_id, &circ_id);
  140. circ = NULL;
  141. log_debug(LD_OR,
  142. "Unpacking cpuworker reply, chan_id is " U64_FORMAT
  143. ", circ_id is %d",
  144. U64_PRINTF_ARG(chan_id), circ_id);
  145. p_chan = channel_find_by_global_id(chan_id);
  146. if (p_chan)
  147. circ = circuit_get_by_circid_channel(circ_id, p_chan);
  148. if (success == 0) {
  149. log_debug(LD_OR,
  150. "decoding onionskin failed. "
  151. "(Old key or bad software.) Closing.");
  152. if (circ)
  153. circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  154. goto done_processing;
  155. }
  156. if (!circ) {
  157. /* This happens because somebody sends us a destroy cell and the
  158. * circuit goes away, while the cpuworker is working. This is also
  159. * why our tag doesn't include a pointer to the circ, because we'd
  160. * never know if it's still valid.
  161. */
  162. log_debug(LD_OR,"processed onion for a circ that's gone. Dropping.");
  163. goto done_processing;
  164. }
  165. tor_assert(! CIRCUIT_IS_ORIGIN(circ));
  166. if (onionskin_answer(TO_OR_CIRCUIT(circ), CELL_CREATED, buf+TAG_LEN,
  167. buf+TAG_LEN+ONIONSKIN_REPLY_LEN) < 0) {
  168. log_warn(LD_OR,"onionskin_answer failed. Closing.");
  169. circuit_mark_for_close(circ, END_CIRC_REASON_INTERNAL);
  170. goto done_processing;
  171. }
  172. log_debug(LD_OR,"onionskin_answer succeeded. Yay.");
  173. } else {
  174. tor_assert(0); /* don't ask me to do handshakes yet */
  175. }
  176. done_processing:
  177. conn->state = CPUWORKER_STATE_IDLE;
  178. num_cpuworkers_busy--;
  179. if (conn->timestamp_created < last_rotation_time) {
  180. connection_mark_for_close(conn);
  181. num_cpuworkers--;
  182. spawn_enough_cpuworkers();
  183. } else {
  184. process_pending_task(conn);
  185. }
  186. return 0;
  187. }
  188. /** Implement a cpuworker. 'data' is an fdarray as returned by socketpair.
  189. * Read and writes from fdarray[1]. Reads requests, writes answers.
  190. *
  191. * Request format:
  192. * Task type [1 byte, always CPUWORKER_TASK_ONION]
  193. * Opaque tag TAG_LEN
  194. * Onionskin challenge ONIONSKIN_CHALLENGE_LEN
  195. * Response format:
  196. * Success/failure [1 byte, boolean.]
  197. * Opaque tag TAG_LEN
  198. * Onionskin challenge ONIONSKIN_REPLY_LEN
  199. * Negotiated keys KEY_LEN*2+DIGEST_LEN*2
  200. *
  201. * (Note: this _should_ be by addr/port, since we're concerned with specific
  202. * connections, not with routers (where we'd use identity).)
  203. */
  204. static void
  205. cpuworker_main(void *data)
  206. {
  207. char question[ONIONSKIN_CHALLENGE_LEN];
  208. uint8_t question_type;
  209. tor_socket_t *fdarray = data;
  210. tor_socket_t fd;
  211. /* variables for onion processing */
  212. char keys[CPATH_KEY_MATERIAL_LEN];
  213. char reply_to_proxy[ONIONSKIN_REPLY_LEN];
  214. char buf[LEN_ONION_RESPONSE];
  215. char tag[TAG_LEN];
  216. crypto_pk_t *onion_key = NULL, *last_onion_key = NULL;
  217. fd = fdarray[1]; /* this side is ours */
  218. #ifndef TOR_IS_MULTITHREADED
  219. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the
  220. * parent uses */
  221. tor_free_all(1); /* so the child doesn't hold the parent's fd's open */
  222. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  223. #endif
  224. tor_free(data);
  225. dup_onion_keys(&onion_key, &last_onion_key);
  226. for (;;) {
  227. ssize_t r;
  228. if ((r = recv(fd, (void *)&question_type, 1, 0)) != 1) {
  229. // log_fn(LOG_ERR,"read type failed. Exiting.");
  230. if (r == 0) {
  231. log_info(LD_OR,
  232. "CPU worker exiting because Tor process closed connection "
  233. "(either rotated keys or died).");
  234. } else {
  235. log_info(LD_OR,
  236. "CPU worker exiting because of error on connection to Tor "
  237. "process.");
  238. log_info(LD_OR,"(Error on "TOR_SOCKET_T_FORMAT" was %s)",
  239. fd, tor_socket_strerror(tor_socket_errno(fd)));
  240. }
  241. goto end;
  242. }
  243. tor_assert(question_type == CPUWORKER_TASK_ONION);
  244. if (read_all(fd, tag, TAG_LEN, 1) != TAG_LEN) {
  245. log_err(LD_BUG,"read tag failed. Exiting.");
  246. goto end;
  247. }
  248. if (read_all(fd, question, ONIONSKIN_CHALLENGE_LEN, 1) !=
  249. ONIONSKIN_CHALLENGE_LEN) {
  250. log_err(LD_BUG,"read question failed. Exiting.");
  251. goto end;
  252. }
  253. if (question_type == CPUWORKER_TASK_ONION) {
  254. if (onion_skin_server_handshake(question, onion_key, last_onion_key,
  255. reply_to_proxy, keys, CPATH_KEY_MATERIAL_LEN) < 0) {
  256. /* failure */
  257. log_debug(LD_OR,"onion_skin_server_handshake failed.");
  258. *buf = 0; /* indicate failure in first byte */
  259. memcpy(buf+1,tag,TAG_LEN);
  260. /* send all zeros as answer */
  261. memset(buf+1+TAG_LEN, 0, LEN_ONION_RESPONSE-(1+TAG_LEN));
  262. } else {
  263. /* success */
  264. log_debug(LD_OR,"onion_skin_server_handshake succeeded.");
  265. buf[0] = 1; /* 1 means success */
  266. memcpy(buf+1,tag,TAG_LEN);
  267. memcpy(buf+1+TAG_LEN,reply_to_proxy,ONIONSKIN_REPLY_LEN);
  268. memcpy(buf+1+TAG_LEN+ONIONSKIN_REPLY_LEN,keys,CPATH_KEY_MATERIAL_LEN);
  269. }
  270. if (write_all(fd, buf, LEN_ONION_RESPONSE, 1) != LEN_ONION_RESPONSE) {
  271. log_err(LD_BUG,"writing response buf failed. Exiting.");
  272. goto end;
  273. }
  274. log_debug(LD_OR,"finished writing response.");
  275. }
  276. }
  277. end:
  278. if (onion_key)
  279. crypto_pk_free(onion_key);
  280. if (last_onion_key)
  281. crypto_pk_free(last_onion_key);
  282. tor_close_socket(fd);
  283. crypto_thread_cleanup();
  284. spawn_exit();
  285. }
  286. /** Launch a new cpuworker. Return 0 if we're happy, -1 if we failed.
  287. */
  288. static int
  289. spawn_cpuworker(void)
  290. {
  291. tor_socket_t *fdarray;
  292. tor_socket_t fd;
  293. connection_t *conn;
  294. int err;
  295. fdarray = tor_malloc(sizeof(tor_socket_t)*2);
  296. if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray)) < 0) {
  297. log_warn(LD_NET, "Couldn't construct socketpair for cpuworker: %s",
  298. tor_socket_strerror(-err));
  299. tor_free(fdarray);
  300. return -1;
  301. }
  302. tor_assert(SOCKET_OK(fdarray[0]));
  303. tor_assert(SOCKET_OK(fdarray[1]));
  304. fd = fdarray[0];
  305. spawn_func(cpuworker_main, (void*)fdarray);
  306. log_debug(LD_OR,"just spawned a cpu worker.");
  307. #ifndef TOR_IS_MULTITHREADED
  308. tor_close_socket(fdarray[1]); /* don't need the worker's side of the pipe */
  309. tor_free(fdarray);
  310. #endif
  311. conn = connection_new(CONN_TYPE_CPUWORKER, AF_UNIX);
  312. set_socket_nonblocking(fd);
  313. /* set up conn so it's got all the data we need to remember */
  314. conn->s = fd;
  315. conn->address = tor_strdup("localhost");
  316. tor_addr_make_unspec(&conn->addr);
  317. if (connection_add(conn) < 0) { /* no space, forget it */
  318. log_warn(LD_NET,"connection_add for cpuworker failed. Giving up.");
  319. connection_free(conn); /* this closes fd */
  320. return -1;
  321. }
  322. conn->state = CPUWORKER_STATE_IDLE;
  323. connection_start_reading(conn);
  324. return 0; /* success */
  325. }
  326. /** If we have too few or too many active cpuworkers, try to spawn new ones
  327. * or kill idle ones.
  328. */
  329. static void
  330. spawn_enough_cpuworkers(void)
  331. {
  332. int num_cpuworkers_needed = get_num_cpus(get_options());
  333. if (num_cpuworkers_needed < MIN_CPUWORKERS)
  334. num_cpuworkers_needed = MIN_CPUWORKERS;
  335. if (num_cpuworkers_needed > MAX_CPUWORKERS)
  336. num_cpuworkers_needed = MAX_CPUWORKERS;
  337. while (num_cpuworkers < num_cpuworkers_needed) {
  338. if (spawn_cpuworker() < 0) {
  339. log_warn(LD_GENERAL,"Cpuworker spawn failed. Will try again later.");
  340. return;
  341. }
  342. num_cpuworkers++;
  343. }
  344. }
  345. /** Take a pending task from the queue and assign it to 'cpuworker'. */
  346. static void
  347. process_pending_task(connection_t *cpuworker)
  348. {
  349. or_circuit_t *circ;
  350. char *onionskin = NULL;
  351. tor_assert(cpuworker);
  352. /* for now only process onion tasks */
  353. circ = onion_next_task(&onionskin);
  354. if (!circ)
  355. return;
  356. if (assign_onionskin_to_cpuworker(cpuworker, circ, onionskin))
  357. log_warn(LD_OR,"assign_to_cpuworker failed. Ignoring.");
  358. }
  359. /** How long should we let a cpuworker stay busy before we give
  360. * up on it and decide that we have a bug or infinite loop?
  361. * This value is high because some servers with low memory/cpu
  362. * sometimes spend an hour or more swapping, and Tor starves. */
  363. #define CPUWORKER_BUSY_TIMEOUT (60*60*12)
  364. /** We have a bug that I can't find. Sometimes, very rarely, cpuworkers get
  365. * stuck in the 'busy' state, even though the cpuworker process thinks of
  366. * itself as idle. I don't know why. But here's a workaround to kill any
  367. * cpuworker that's been busy for more than CPUWORKER_BUSY_TIMEOUT.
  368. */
  369. static void
  370. cull_wedged_cpuworkers(void)
  371. {
  372. time_t now = time(NULL);
  373. smartlist_t *conns = get_connection_array();
  374. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  375. if (!conn->marked_for_close &&
  376. conn->type == CONN_TYPE_CPUWORKER &&
  377. conn->state == CPUWORKER_STATE_BUSY_ONION &&
  378. conn->timestamp_lastwritten + CPUWORKER_BUSY_TIMEOUT < now) {
  379. log_notice(LD_BUG,
  380. "closing wedged cpuworker. Can somebody find the bug?");
  381. num_cpuworkers_busy--;
  382. num_cpuworkers--;
  383. connection_mark_for_close(conn);
  384. }
  385. } SMARTLIST_FOREACH_END(conn);
  386. }
  387. /** Try to tell a cpuworker to perform the public key operations necessary to
  388. * respond to <b>onionskin</b> for the circuit <b>circ</b>.
  389. *
  390. * If <b>cpuworker</b> is defined, assert that he's idle, and use him. Else,
  391. * look for an idle cpuworker and use him. If none idle, queue task onto the
  392. * pending onion list and return. Return 0 if we successfully assign the
  393. * task, or -1 on failure.
  394. */
  395. int
  396. assign_onionskin_to_cpuworker(connection_t *cpuworker,
  397. or_circuit_t *circ, char *onionskin)
  398. {
  399. char qbuf[1];
  400. char tag[TAG_LEN];
  401. time_t now = approx_time();
  402. static time_t last_culled_cpuworkers = 0;
  403. /* Checking for wedged cpuworkers requires a linear search over all
  404. * connections, so let's do it only once a minute.
  405. */
  406. #define CULL_CPUWORKERS_INTERVAL 60
  407. if (last_culled_cpuworkers + CULL_CPUWORKERS_INTERVAL <= now) {
  408. cull_wedged_cpuworkers();
  409. spawn_enough_cpuworkers();
  410. last_culled_cpuworkers = now;
  411. }
  412. if (1) {
  413. if (num_cpuworkers_busy == num_cpuworkers) {
  414. log_debug(LD_OR,"No idle cpuworkers. Queuing.");
  415. if (onion_pending_add(circ, onionskin) < 0) {
  416. tor_free(onionskin);
  417. return -1;
  418. }
  419. return 0;
  420. }
  421. if (!cpuworker)
  422. cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER,
  423. CPUWORKER_STATE_IDLE);
  424. tor_assert(cpuworker);
  425. if (!circ->p_chan) {
  426. log_info(LD_OR,"circ->p_chan gone. Failing circ.");
  427. tor_free(onionskin);
  428. return -1;
  429. }
  430. tag_pack(tag, circ->p_chan->global_identifier,
  431. circ->p_circ_id);
  432. cpuworker->state = CPUWORKER_STATE_BUSY_ONION;
  433. /* touch the lastwritten timestamp, since that's how we check to
  434. * see how long it's been since we asked the question, and sometimes
  435. * we check before the first call to connection_handle_write(). */
  436. cpuworker->timestamp_lastwritten = time(NULL);
  437. num_cpuworkers_busy++;
  438. qbuf[0] = CPUWORKER_TASK_ONION;
  439. connection_write_to_buf(qbuf, 1, cpuworker);
  440. connection_write_to_buf(tag, sizeof(tag), cpuworker);
  441. connection_write_to_buf(onionskin, ONIONSKIN_CHALLENGE_LEN, cpuworker);
  442. tor_free(onionskin);
  443. }
  444. return 0;
  445. }