cpuworker.c 15 KB

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