cpuworker.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /* Copyright 2003-2004 Roger Dingledine.
  2. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char cpuworker_c_id[] = "$Id$";
  6. /**
  7. * \file cpuworker.c
  8. * \brief Run computation-intensive tasks (generally for crypto) in
  9. * a separate execution context. [OR only.]
  10. *
  11. * Right now, we only use this for processing onionskins.
  12. **/
  13. #include "or.h"
  14. /** The maximum number of cpuworker processes we will keep around. */
  15. #define MAX_CPUWORKERS 16
  16. /** The minimum number of cpuworker processes we will keep around. */
  17. #define MIN_CPUWORKERS 1
  18. /** The tag specifies which circuit this onionskin was from. */
  19. #define TAG_LEN 8
  20. /** How many bytes are sent from tor to the cpuworker? */
  21. #define LEN_ONION_QUESTION (1+TAG_LEN+ONIONSKIN_CHALLENGE_LEN)
  22. /** How many bytes are sent from the cpuworker back to tor? */
  23. #define LEN_ONION_RESPONSE (1+TAG_LEN+ONIONSKIN_REPLY_LEN+40+32)
  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 int cpuworker_main(void *data);
  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 cpu_init(void) {
  39. last_rotation_time=time(NULL);
  40. spawn_enough_cpuworkers();
  41. }
  42. /** Called when we're done sending a request to a cpuworker. */
  43. int connection_cpu_finished_flushing(connection_t *conn) {
  44. tor_assert(conn);
  45. tor_assert(conn->type == CONN_TYPE_CPUWORKER);
  46. connection_stop_writing(conn);
  47. return 0;
  48. }
  49. /** Pack addr,port,and circ_id; set *tag to the result. (See note on
  50. * cpuworker_main for wire format.) */
  51. static void tag_pack(char *tag, uint32_t addr, uint16_t port, uint16_t circ_id) {
  52. *(uint32_t *)tag = addr;
  53. *(uint16_t *)(tag+4) = port;
  54. *(uint16_t *)(tag+6) = circ_id;
  55. }
  56. /** Unpack <b>tag</b> into addr, port, and circ_id.
  57. */
  58. static void tag_unpack(const char *tag, uint32_t *addr, uint16_t *port, uint16_t *circ_id) {
  59. struct in_addr in;
  60. char addrbuf[INET_NTOA_BUF_LEN];
  61. *addr = *(const uint32_t *)tag;
  62. *port = *(const uint16_t *)(tag+4);
  63. *circ_id = *(const uint16_t *)(tag+6);
  64. in.s_addr = htonl(*addr);
  65. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  66. log_fn(LOG_DEBUG,"onion was from %s:%d, circ_id %d.", addrbuf, *port, *circ_id);
  67. }
  68. /** Called when the onion key has changed and we need to spawn new
  69. * cpuworkers. Close all currently idle cpuworkers, and mark the last
  70. * rotation time as now.
  71. */
  72. void cpuworkers_rotate(void)
  73. {
  74. connection_t *cpuworker;
  75. while ((cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER,
  76. CPUWORKER_STATE_IDLE))) {
  77. connection_mark_for_close(cpuworker);
  78. --num_cpuworkers;
  79. }
  80. last_rotation_time = time(NULL);
  81. spawn_enough_cpuworkers();
  82. }
  83. /** If the cpuworker closes the connection,
  84. * mark it as closed and spawn a new one as needed. */
  85. int connection_cpu_reached_eof(connection_t *conn) {
  86. log_fn(LOG_WARN,"Read eof. Worker died unexpectedly.");
  87. if (conn->state != CPUWORKER_STATE_IDLE) {
  88. /* the circ associated with this cpuworker will have to wait until
  89. * it gets culled in run_connection_housekeeping(), since we have
  90. * no way to find out which circ it was. */
  91. log_fn(LOG_WARN,"...and it left a circuit queued; abandoning circ.");
  92. num_cpuworkers_busy--;
  93. }
  94. num_cpuworkers--;
  95. spawn_enough_cpuworkers(); /* try to regrow. hope we don't end up spinning. */
  96. connection_mark_for_close(conn);
  97. return 0;
  98. }
  99. /** Called when we get data from a cpuworker. If the answer is not complete,
  100. * wait for a complete answer. If the answer is complete,
  101. * process it as appropriate.
  102. */
  103. int connection_cpu_process_inbuf(connection_t *conn) {
  104. char success;
  105. unsigned char buf[LEN_ONION_RESPONSE];
  106. uint32_t addr;
  107. uint16_t port;
  108. uint16_t circ_id;
  109. connection_t *p_conn;
  110. circuit_t *circ;
  111. tor_assert(conn);
  112. tor_assert(conn->type == CONN_TYPE_CPUWORKER);
  113. if (!buf_datalen(conn->inbuf))
  114. return 0;
  115. if (conn->state == CPUWORKER_STATE_BUSY_ONION) {
  116. if (buf_datalen(conn->inbuf) < LEN_ONION_RESPONSE) /* entire answer available? */
  117. return 0; /* not yet */
  118. tor_assert(buf_datalen(conn->inbuf) == LEN_ONION_RESPONSE);
  119. connection_fetch_from_buf(&success,1,conn);
  120. connection_fetch_from_buf(buf,LEN_ONION_RESPONSE-1,conn);
  121. /* parse out the circ it was talking about */
  122. tag_unpack(buf, &addr, &port, &circ_id);
  123. circ = NULL;
  124. /* (Here we use connection_exact_get_by_addr_port rather than
  125. * get_by_identity_digest: we want a specific port here in
  126. * case there are multiple connections.) */
  127. p_conn = connection_exact_get_by_addr_port(addr,port);
  128. if (p_conn)
  129. circ = circuit_get_by_circ_id_conn(circ_id, p_conn);
  130. if (success == 0) {
  131. log_fn(LOG_INFO,"decoding onionskin failed. Closing.");
  132. if (circ)
  133. circuit_mark_for_close(circ);
  134. goto done_processing;
  135. }
  136. if (!circ) {
  137. log_fn(LOG_INFO,"processed onion for a circ that's gone. Dropping.");
  138. goto done_processing;
  139. }
  140. tor_assert(circ->p_conn);
  141. if (onionskin_answer(circ, buf+TAG_LEN, buf+TAG_LEN+ONIONSKIN_REPLY_LEN) < 0) {
  142. log_fn(LOG_WARN,"onionskin_answer failed. Closing.");
  143. circuit_mark_for_close(circ);
  144. goto done_processing;
  145. }
  146. log_fn(LOG_DEBUG,"onionskin_answer succeeded. Yay.");
  147. } else {
  148. tor_assert(0); /* don't ask me to do handshakes yet */
  149. }
  150. done_processing:
  151. conn->state = CPUWORKER_STATE_IDLE;
  152. num_cpuworkers_busy--;
  153. if (conn->timestamp_created < last_rotation_time) {
  154. connection_mark_for_close(conn);
  155. num_cpuworkers--;
  156. spawn_enough_cpuworkers();
  157. } else {
  158. process_pending_task(conn);
  159. }
  160. return 0;
  161. }
  162. /** Implement a cpuworker. 'data' is an fdarray as returned by socketpair.
  163. * Read and writes from fdarray[1]. Reads requests, writes answers.
  164. *
  165. * Request format:
  166. * Task type [1 byte, always CPUWORKER_TASK_ONION]
  167. * Opaque tag TAG_LEN
  168. * Onionskin challenge ONIONSKIN_CHALLENGE_LEN
  169. * Response format:
  170. * Success/failure [1 byte, boolean.]
  171. * Opaque tag TAG_LEN
  172. * Onionskin challenge ONIONSKIN_REPLY_LEN
  173. * Negotiated keys KEY_LEN*2+DIGEST_LEN*2
  174. *
  175. * (Note: this _should_ be by addr/port, since we're concerned with specific
  176. * connections, not with routers (where we'd use identity).)
  177. */
  178. static int cpuworker_main(void *data) {
  179. unsigned char question[ONIONSKIN_CHALLENGE_LEN];
  180. unsigned char question_type;
  181. int *fdarray = data;
  182. int fd;
  183. /* variables for onion processing */
  184. unsigned char keys[40+32];
  185. unsigned char reply_to_proxy[ONIONSKIN_REPLY_LEN];
  186. unsigned char buf[LEN_ONION_RESPONSE];
  187. char tag[TAG_LEN];
  188. crypto_pk_env_t *onion_key = NULL, *last_onion_key = NULL;
  189. fd = fdarray[1]; /* this side is ours */
  190. #ifndef TOR_IS_MULTITHREADED
  191. tor_close_socket(fdarray[0]); /* this is the side of the socketpair the parent uses */
  192. connection_free_all(); /* so the child doesn't hold the parent's fd's open */
  193. handle_signals(0); /* ignore interrupts from the keyboard, etc */
  194. #endif
  195. tor_free(data);
  196. dup_onion_keys(&onion_key, &last_onion_key);
  197. for (;;) {
  198. int r;
  199. if ((r = recv(fd, &question_type, 1, 0)) != 1) {
  200. // log_fn(LOG_ERR,"read type failed. Exiting.");
  201. if (r == 0) {
  202. log_fn(LOG_INFO,"CPU worker exiting because Tor process closed connection (either rotated keys or died).");
  203. } else {
  204. log_fn(LOG_INFO,"CPU worker editing because of error on connection to Tor process.");
  205. log_fn(LOG_INFO,"(Error on %d was %s)", fd, tor_socket_strerror(tor_socket_errno(fd)));
  206. }
  207. goto end;
  208. }
  209. tor_assert(question_type == CPUWORKER_TASK_ONION);
  210. if (read_all(fd, tag, TAG_LEN, 1) != TAG_LEN) {
  211. log_fn(LOG_ERR,"read tag failed. Exiting.");
  212. goto end;
  213. }
  214. if (read_all(fd, question, ONIONSKIN_CHALLENGE_LEN, 1) != ONIONSKIN_CHALLENGE_LEN) {
  215. log_fn(LOG_ERR,"read question failed. Exiting.");
  216. goto end;
  217. }
  218. if (question_type == CPUWORKER_TASK_ONION) {
  219. if (onion_skin_server_handshake(question, onion_key, last_onion_key,
  220. reply_to_proxy, keys, 40+32) < 0) {
  221. /* failure */
  222. log_fn(LOG_INFO,"onion_skin_server_handshake failed.");
  223. memset(buf,0,LEN_ONION_RESPONSE); /* send all zeros for failure */
  224. } else {
  225. /* success */
  226. log_fn(LOG_DEBUG,"onion_skin_server_handshake succeeded.");
  227. buf[0] = 1; /* 1 means success */
  228. memcpy(buf+1,tag,TAG_LEN);
  229. memcpy(buf+1+TAG_LEN,reply_to_proxy,ONIONSKIN_REPLY_LEN);
  230. memcpy(buf+1+TAG_LEN+ONIONSKIN_REPLY_LEN,keys,40+32);
  231. }
  232. if (write_all(fd, buf, LEN_ONION_RESPONSE, 1) != LEN_ONION_RESPONSE) {
  233. log_fn(LOG_ERR,"writing response buf failed. Exiting.");
  234. spawn_exit();
  235. }
  236. log_fn(LOG_DEBUG,"finished writing response.");
  237. }
  238. }
  239. end:
  240. if (onion_key)
  241. crypto_free_pk_env(onion_key);
  242. if (last_onion_key)
  243. crypto_free_pk_env(last_onion_key);
  244. spawn_exit();
  245. return 0; /* windows wants this function to return an int */
  246. }
  247. /** Launch a new cpuworker.
  248. */
  249. static int spawn_cpuworker(void) {
  250. int *fdarray;
  251. int fd;
  252. connection_t *conn;
  253. fdarray = tor_malloc(sizeof(int)*2);
  254. if (tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fdarray) < 0) {
  255. log(LOG_ERR, "Couldn't construct socketpair: %s",
  256. tor_socket_strerror(tor_socket_errno(-1)));
  257. tor_cleanup();
  258. tor_free(fdarray);
  259. exit(1);
  260. }
  261. fd = fdarray[0];
  262. spawn_func(cpuworker_main, (void*)fdarray);
  263. log_fn(LOG_DEBUG,"just spawned a worker.");
  264. #ifndef TOR_IS_MULTITHREADED
  265. tor_close_socket(fdarray[1]); /* we don't need the worker's side of the pipe */
  266. tor_free(fdarray);
  267. #endif
  268. conn = connection_new(CONN_TYPE_CPUWORKER);
  269. set_socket_nonblocking(fd);
  270. /* set up conn so it's got all the data we need to remember */
  271. conn->s = fd;
  272. conn->address = tor_strdup("localhost");
  273. if (connection_add(conn) < 0) { /* no space, forget it */
  274. log_fn(LOG_WARN,"connection_add failed. Giving up.");
  275. connection_free(conn); /* this closes fd */
  276. return -1;
  277. }
  278. conn->state = CPUWORKER_STATE_IDLE;
  279. connection_start_reading(conn);
  280. return 0; /* success */
  281. }
  282. /** If we have too few or too many active cpuworkers, try to spawn new ones
  283. * or kill idle ones.
  284. */
  285. static void spawn_enough_cpuworkers(void) {
  286. int num_cpuworkers_needed = get_options()->NumCpus;
  287. if (num_cpuworkers_needed < MIN_CPUWORKERS)
  288. num_cpuworkers_needed = MIN_CPUWORKERS;
  289. if (num_cpuworkers_needed > MAX_CPUWORKERS)
  290. num_cpuworkers_needed = MAX_CPUWORKERS;
  291. while (num_cpuworkers < num_cpuworkers_needed) {
  292. if (spawn_cpuworker() < 0) {
  293. log_fn(LOG_WARN,"spawn failed!");
  294. return;
  295. }
  296. num_cpuworkers++;
  297. }
  298. }
  299. /** Take a pending task from the queue and assign it to 'cpuworker'. */
  300. static void process_pending_task(connection_t *cpuworker) {
  301. circuit_t *circ;
  302. tor_assert(cpuworker);
  303. /* for now only process onion tasks */
  304. circ = onion_next_task();
  305. if (!circ)
  306. return;
  307. if (assign_to_cpuworker(cpuworker, CPUWORKER_TASK_ONION, circ) < 0)
  308. log_fn(LOG_WARN,"assign_to_cpuworker failed. Ignoring.");
  309. }
  310. /** if cpuworker is defined, assert that he's idle, and use him. else,
  311. * look for an idle cpuworker and use him. if none idle, queue task onto
  312. * the pending onion list and return.
  313. * If question_type is CPUWORKER_TASK_ONION then task is a circ.
  314. * No other question_types are allowed.
  315. */
  316. int assign_to_cpuworker(connection_t *cpuworker, unsigned char question_type,
  317. void *task) {
  318. circuit_t *circ;
  319. char tag[TAG_LEN];
  320. tor_assert(question_type == CPUWORKER_TASK_ONION);
  321. if (question_type == CPUWORKER_TASK_ONION) {
  322. circ = task;
  323. if (num_cpuworkers_busy == num_cpuworkers) {
  324. log_fn(LOG_DEBUG,"No idle cpuworkers. Queuing.");
  325. if (onion_pending_add(circ) < 0)
  326. return -1;
  327. return 0;
  328. }
  329. if (!cpuworker)
  330. cpuworker = connection_get_by_type_state(CONN_TYPE_CPUWORKER, CPUWORKER_STATE_IDLE);
  331. tor_assert(cpuworker);
  332. if (!circ->p_conn) {
  333. log_fn(LOG_INFO,"circ->p_conn gone. Failing circ.");
  334. return -1;
  335. }
  336. tag_pack(tag, circ->p_conn->addr, circ->p_conn->port, circ->p_circ_id);
  337. cpuworker->state = CPUWORKER_STATE_BUSY_ONION;
  338. num_cpuworkers_busy++;
  339. connection_write_to_buf(&question_type, 1, cpuworker);
  340. connection_write_to_buf(tag, sizeof(tag), cpuworker);
  341. connection_write_to_buf(circ->onionskin, ONIONSKIN_CHALLENGE_LEN, cpuworker);
  342. }
  343. return 0;
  344. }