cpuworker.c 15 KB

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