cpuworker.c 16 KB

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