cpuworker.c 15 KB

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