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