Bug 6572: Use timestamp_created for liveness sanity checks.
[tor.git] / src / or / command.c
blob876ff526a6a6f82ece5b8990552ca0e066941a36
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file command.c
9 * \brief Functions for processing incoming cells.
10 **/
12 /* In-points to command.c:
14 * - command_process_cell(), called from
15 * incoming cell handlers of channel_t instances;
16 * callbacks registered in command_setup_channel(),
17 * called when channels are created in circuitbuild.c
19 #include "or.h"
20 #include "channel.h"
21 #include "circuitbuild.h"
22 #include "circuitlist.h"
23 #include "command.h"
24 #include "connection.h"
25 #include "connection_or.h"
26 #include "config.h"
27 #include "control.h"
28 #include "cpuworker.h"
29 #include "hibernate.h"
30 #include "nodelist.h"
31 #include "onion.h"
32 #include "relay.h"
33 #include "router.h"
34 #include "routerlist.h"
36 /** How many CELL_CREATE cells have we received, ever? */
37 uint64_t stats_n_create_cells_processed = 0;
38 /** How many CELL_CREATED cells have we received, ever? */
39 uint64_t stats_n_created_cells_processed = 0;
40 /** How many CELL_RELAY cells have we received, ever? */
41 uint64_t stats_n_relay_cells_processed = 0;
42 /** How many CELL_DESTROY cells have we received, ever? */
43 uint64_t stats_n_destroy_cells_processed = 0;
45 /* Handle an incoming channel */
46 static void command_handle_incoming_channel(channel_listener_t *listener,
47 channel_t *chan);
49 /* These are the main functions for processing cells */
50 static void command_process_create_cell(cell_t *cell, channel_t *chan);
51 static void command_process_created_cell(cell_t *cell, channel_t *chan);
52 static void command_process_relay_cell(cell_t *cell, channel_t *chan);
53 static void command_process_destroy_cell(cell_t *cell, channel_t *chan);
55 #ifdef KEEP_TIMING_STATS
56 /** This is a wrapper function around the actual function that processes the
57 * <b>cell</b> that just arrived on <b>conn</b>. Increment <b>*time</b>
58 * by the number of microseconds used by the call to <b>*func(cell, conn)</b>.
60 static void
61 command_time_process_cell(cell_t *cell, channel_t *chan, int *time,
62 void (*func)(cell_t *, channel_t *))
64 struct timeval start, end;
65 long time_passed;
67 tor_gettimeofday(&start);
69 (*func)(cell, chan);
71 tor_gettimeofday(&end);
72 time_passed = tv_udiff(&start, &end) ;
74 if (time_passed > 10000) { /* more than 10ms */
75 log_debug(LD_OR,"That call just took %ld ms.",time_passed/1000);
77 if (time_passed < 0) {
78 log_info(LD_GENERAL,"That call took us back in time!");
79 time_passed = 0;
81 *time += time_passed;
83 #endif
85 /** Process a <b>cell</b> that was just received on <b>chan</b>. Keep internal
86 * statistics about how many of each cell we've processed so far
87 * this second, and the total number of microseconds it took to
88 * process each type of cell.
90 void
91 command_process_cell(channel_t *chan, cell_t *cell)
93 #ifdef KEEP_TIMING_STATS
94 /* how many of each cell have we seen so far this second? needs better
95 * name. */
96 static int num_create=0, num_created=0, num_relay=0, num_destroy=0;
97 /* how long has it taken to process each type of cell? */
98 static int create_time=0, created_time=0, relay_time=0, destroy_time=0;
99 static time_t current_second = 0; /* from previous calls to time */
101 time_t now = time(NULL);
103 if (now > current_second) { /* the second has rolled over */
104 /* print stats */
105 log_info(LD_OR,
106 "At end of second: %d creates (%d ms), %d createds (%d ms), "
107 "%d relays (%d ms), %d destroys (%d ms)",
108 num_create, create_time/1000,
109 num_created, created_time/1000,
110 num_relay, relay_time/1000,
111 num_destroy, destroy_time/1000);
113 /* zero out stats */
114 num_create = num_created = num_relay = num_destroy = 0;
115 create_time = created_time = relay_time = destroy_time = 0;
117 /* remember which second it is, for next time */
118 current_second = now;
120 #endif
122 #ifdef KEEP_TIMING_STATS
123 #define PROCESS_CELL(tp, cl, cn) STMT_BEGIN { \
124 ++num ## tp; \
125 command_time_process_cell(cl, cn, & tp ## time , \
126 command_process_ ## tp ## _cell); \
127 } STMT_END
128 #else
129 #define PROCESS_CELL(tp, cl, cn) command_process_ ## tp ## _cell(cl, cn)
130 #endif
132 switch (cell->command) {
133 case CELL_CREATE:
134 case CELL_CREATE_FAST:
135 case CELL_CREATE2:
136 ++stats_n_create_cells_processed;
137 PROCESS_CELL(create, cell, chan);
138 break;
139 case CELL_CREATED:
140 case CELL_CREATED_FAST:
141 case CELL_CREATED2:
142 ++stats_n_created_cells_processed;
143 PROCESS_CELL(created, cell, chan);
144 break;
145 case CELL_RELAY:
146 case CELL_RELAY_EARLY:
147 ++stats_n_relay_cells_processed;
148 PROCESS_CELL(relay, cell, chan);
149 break;
150 case CELL_DESTROY:
151 ++stats_n_destroy_cells_processed;
152 PROCESS_CELL(destroy, cell, chan);
153 break;
154 default:
155 log_fn(LOG_INFO, LD_PROTOCOL,
156 "Cell of unknown or unexpected type (%d) received. "
157 "Dropping.",
158 cell->command);
159 break;
163 /** Process an incoming var_cell from a channel; in the current protocol all
164 * the var_cells are handshake-related and handled below the channel layer,
165 * so this just logs a warning and drops the cell.
168 void
169 command_process_var_cell(channel_t *chan, var_cell_t *var_cell)
171 tor_assert(chan);
172 tor_assert(var_cell);
174 log_info(LD_PROTOCOL,
175 "Received unexpected var_cell above the channel layer of type %d"
176 "; dropping it.",
177 var_cell->command);
180 /** Process a 'create' <b>cell</b> that just arrived from <b>chan</b>. Make a
181 * new circuit with the p_circ_id specified in cell. Put the circuit in state
182 * onionskin_pending, and pass the onionskin to the cpuworker. Circ will get
183 * picked up again when the cpuworker finishes decrypting it.
185 static void
186 command_process_create_cell(cell_t *cell, channel_t *chan)
188 or_circuit_t *circ;
189 const or_options_t *options = get_options();
190 int id_is_high;
191 create_cell_t *create_cell;
193 tor_assert(cell);
194 tor_assert(chan);
196 log_debug(LD_OR,
197 "Got a CREATE cell for circ_id %u on channel " U64_FORMAT
198 " (%p)",
199 (unsigned)cell->circ_id,
200 U64_PRINTF_ARG(chan->global_identifier), chan);
202 if (we_are_hibernating()) {
203 log_info(LD_OR,
204 "Received create cell but we're shutting down. Sending back "
205 "destroy.");
206 channel_send_destroy(cell->circ_id, chan,
207 END_CIRC_REASON_HIBERNATING);
208 return;
211 if (!server_mode(options) ||
212 (!public_server_mode(options) && channel_is_outgoing(chan))) {
213 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
214 "Received create cell (type %d) from %s, but we're connected "
215 "to it as a client. "
216 "Sending back a destroy.",
217 (int)cell->command, channel_get_canonical_remote_descr(chan));
218 channel_send_destroy(cell->circ_id, chan,
219 END_CIRC_REASON_TORPROTOCOL);
220 return;
223 if (cell->circ_id == 0) {
224 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
225 "Received a create cell (type %d) from %s with zero circID; "
226 " ignoring.", (int)cell->command,
227 channel_get_actual_remote_descr(chan));
228 return;
231 /* If the high bit of the circuit ID is not as expected, close the
232 * circ. */
233 if (chan->wide_circ_ids)
234 id_is_high = cell->circ_id & (1u<<31);
235 else
236 id_is_high = cell->circ_id & (1u<<15);
237 if ((id_is_high &&
238 chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ||
239 (!id_is_high &&
240 chan->circ_id_type == CIRC_ID_TYPE_LOWER)) {
241 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
242 "Received create cell with unexpected circ_id %u. Closing.",
243 (unsigned)cell->circ_id);
244 channel_send_destroy(cell->circ_id, chan,
245 END_CIRC_REASON_TORPROTOCOL);
246 return;
249 if (circuit_id_in_use_on_channel(cell->circ_id, chan)) {
250 const node_t *node = node_get_by_id(chan->identity_digest);
251 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
252 "Received CREATE cell (circID %u) for known circ. "
253 "Dropping (age %d).",
254 (unsigned)cell->circ_id,
255 (int)(time(NULL) - channel_when_created(chan)));
256 if (node) {
257 char *p = esc_for_log(node_get_platform(node));
258 log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
259 "Details: router %s, platform %s.",
260 node_describe(node), p);
261 tor_free(p);
263 return;
266 circ = or_circuit_new(cell->circ_id, chan);
267 circ->base_.purpose = CIRCUIT_PURPOSE_OR;
268 circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_ONIONSKIN_PENDING);
269 create_cell = tor_malloc_zero(sizeof(create_cell_t));
270 if (create_cell_parse(create_cell, cell) < 0) {
271 tor_free(create_cell);
272 log_fn(LOG_PROTOCOL_WARN, LD_OR,
273 "Bogus/unrecognized create cell; closing.");
274 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
275 return;
278 if (create_cell->handshake_type != ONION_HANDSHAKE_TYPE_FAST) {
279 /* hand it off to the cpuworkers, and then return. */
280 if (assign_onionskin_to_cpuworker(NULL, circ, create_cell) < 0) {
281 log_debug(LD_GENERAL,"Failed to hand off onionskin. Closing.");
282 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
283 return;
285 log_debug(LD_OR,"success: handed off onionskin.");
286 } else {
287 /* This is a CREATE_FAST cell; we can handle it immediately without using
288 * a CPU worker. */
289 uint8_t keys[CPATH_KEY_MATERIAL_LEN];
290 uint8_t rend_circ_nonce[DIGEST_LEN];
291 int len;
292 created_cell_t created_cell;
294 /* Make sure we never try to use the OR connection on which we
295 * received this cell to satisfy an EXTEND request, */
296 channel_mark_client(chan);
298 memset(&created_cell, 0, sizeof(created_cell));
299 len = onion_skin_server_handshake(ONION_HANDSHAKE_TYPE_FAST,
300 create_cell->onionskin,
301 create_cell->handshake_len,
302 NULL,
303 created_cell.reply,
304 keys, CPATH_KEY_MATERIAL_LEN,
305 rend_circ_nonce);
306 tor_free(create_cell);
307 if (len < 0) {
308 log_warn(LD_OR,"Failed to generate key material. Closing.");
309 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
310 tor_free(create_cell);
311 return;
313 created_cell.cell_type = CELL_CREATED_FAST;
314 created_cell.handshake_len = len;
316 if (onionskin_answer(circ, &created_cell,
317 (const char *)keys, rend_circ_nonce)<0) {
318 log_warn(LD_OR,"Failed to reply to CREATE_FAST cell. Closing.");
319 circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
320 return;
322 memwipe(keys, 0, sizeof(keys));
326 /** Process a 'created' <b>cell</b> that just arrived from <b>chan</b>.
327 * Find the circuit
328 * that it's intended for. If we're not the origin of the circuit, package
329 * the 'created' cell in an 'extended' relay cell and pass it back. If we
330 * are the origin of the circuit, send it to circuit_finish_handshake() to
331 * finish processing keys, and then call circuit_send_next_onion_skin() to
332 * extend to the next hop in the circuit if necessary.
334 static void
335 command_process_created_cell(cell_t *cell, channel_t *chan)
337 circuit_t *circ;
338 extended_cell_t extended_cell;
340 circ = circuit_get_by_circid_channel(cell->circ_id, chan);
342 if (!circ) {
343 log_info(LD_OR,
344 "(circID %u) unknown circ (probably got a destroy earlier). "
345 "Dropping.", (unsigned)cell->circ_id);
346 return;
349 if (circ->n_circ_id != cell->circ_id) {
350 log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
351 "got created cell from Tor client? Closing.");
352 circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
353 return;
356 if (created_cell_parse(&extended_cell.created_cell, cell) < 0) {
357 log_fn(LOG_PROTOCOL_WARN, LD_OR, "Unparseable created cell.");
358 circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
359 return;
362 if (CIRCUIT_IS_ORIGIN(circ)) { /* we're the OP. Handshake this. */
363 origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
364 int err_reason = 0;
365 log_debug(LD_OR,"at OP. Finishing handshake.");
366 if ((err_reason = circuit_finish_handshake(origin_circ,
367 &extended_cell.created_cell)) < 0) {
368 log_warn(LD_OR,"circuit_finish_handshake failed.");
369 circuit_mark_for_close(circ, -err_reason);
370 return;
372 log_debug(LD_OR,"Moving to next skin.");
373 if ((err_reason = circuit_send_next_onion_skin(origin_circ)) < 0) {
374 log_info(LD_OR,"circuit_send_next_onion_skin failed.");
375 /* XXX push this circuit_close lower */
376 circuit_mark_for_close(circ, -err_reason);
377 return;
379 } else { /* pack it into an extended relay cell, and send it. */
380 uint8_t command=0;
381 uint16_t len=0;
382 uint8_t payload[RELAY_PAYLOAD_SIZE];
383 log_debug(LD_OR,
384 "Converting created cell to extended relay cell, sending.");
385 memset(payload, 0, sizeof(payload));
386 if (extended_cell.created_cell.cell_type == CELL_CREATED2)
387 extended_cell.cell_type = RELAY_COMMAND_EXTENDED2;
388 else
389 extended_cell.cell_type = RELAY_COMMAND_EXTENDED;
390 if (extended_cell_format(&command, &len, payload, &extended_cell) < 0) {
391 log_fn(LOG_PROTOCOL_WARN, LD_OR, "Can't format extended cell.");
392 circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
393 return;
396 relay_send_command_from_edge(0, circ, command,
397 (const char*)payload, len, NULL);
401 /** Process a 'relay' or 'relay_early' <b>cell</b> that just arrived from
402 * <b>conn</b>. Make sure it came in with a recognized circ_id. Pass it on to
403 * circuit_receive_relay_cell() for actual processing.
405 static void
406 command_process_relay_cell(cell_t *cell, channel_t *chan)
408 circuit_t *circ;
409 int reason, direction;
411 circ = circuit_get_by_circid_channel(cell->circ_id, chan);
413 if (!circ) {
414 log_debug(LD_OR,
415 "unknown circuit %u on connection from %s. Dropping.",
416 (unsigned)cell->circ_id,
417 channel_get_canonical_remote_descr(chan));
418 return;
421 if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
422 log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,"circuit in create_wait. Closing.");
423 circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
424 return;
427 if (CIRCUIT_IS_ORIGIN(circ)) {
428 /* if we're a relay and treating connections with recent local
429 * traffic better, then this is one of them. */
430 channel_timestamp_client(chan);
433 if (!CIRCUIT_IS_ORIGIN(circ) &&
434 cell->circ_id == TO_OR_CIRCUIT(circ)->p_circ_id)
435 direction = CELL_DIRECTION_OUT;
436 else
437 direction = CELL_DIRECTION_IN;
439 /* If we have a relay_early cell, make sure that it's outbound, and we've
440 * gotten no more than MAX_RELAY_EARLY_CELLS_PER_CIRCUIT of them. */
441 if (cell->command == CELL_RELAY_EARLY) {
442 if (direction == CELL_DIRECTION_IN) {
443 /* Allow an unlimited number of inbound relay_early cells,
444 * for hidden service compatibility. There isn't any way to make
445 * a long circuit through inbound relay_early cells anyway. See
446 * bug 1038. -RD */
447 } else {
448 or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
449 if (or_circ->remaining_relay_early_cells == 0) {
450 log_fn(LOG_PROTOCOL_WARN, LD_OR,
451 "Received too many RELAY_EARLY cells on circ %u from %s."
452 " Closing circuit.",
453 (unsigned)cell->circ_id,
454 safe_str(channel_get_canonical_remote_descr(chan)));
455 circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
456 return;
458 --or_circ->remaining_relay_early_cells;
462 if ((reason = circuit_receive_relay_cell(cell, circ, direction)) < 0) {
463 log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,"circuit_receive_relay_cell "
464 "(%s) failed. Closing.",
465 direction==CELL_DIRECTION_OUT?"forward":"backward");
466 circuit_mark_for_close(circ, -reason);
470 /** Process a 'destroy' <b>cell</b> that just arrived from
471 * <b>chan</b>. Find the circ that it refers to (if any).
473 * If the circ is in state
474 * onionskin_pending, then call onion_pending_remove() to remove it
475 * from the pending onion list (note that if it's already being
476 * processed by the cpuworker, it won't be in the list anymore; but
477 * when the cpuworker returns it, the circuit will be gone, and the
478 * cpuworker response will be dropped).
480 * Then mark the circuit for close (which marks all edges for close,
481 * and passes the destroy cell onward if necessary).
483 static void
484 command_process_destroy_cell(cell_t *cell, channel_t *chan)
486 circuit_t *circ;
487 int reason;
489 circ = circuit_get_by_circid_channel(cell->circ_id, chan);
490 if (!circ) {
491 log_info(LD_OR,"unknown circuit %u on connection from %s. Dropping.",
492 (unsigned)cell->circ_id,
493 channel_get_canonical_remote_descr(chan));
494 return;
496 log_debug(LD_OR,"Received for circID %u.",(unsigned)cell->circ_id);
498 reason = (uint8_t)cell->payload[0];
500 if (!CIRCUIT_IS_ORIGIN(circ) &&
501 cell->circ_id == TO_OR_CIRCUIT(circ)->p_circ_id) {
502 /* the destroy came from behind */
503 circuit_set_p_circid_chan(TO_OR_CIRCUIT(circ), 0, NULL);
504 circuit_mark_for_close(circ, reason|END_CIRC_REASON_FLAG_REMOTE);
505 } else { /* the destroy came from ahead */
506 circuit_set_n_circid_chan(circ, 0, NULL);
507 if (CIRCUIT_IS_ORIGIN(circ)) {
508 circuit_mark_for_close(circ, reason|END_CIRC_REASON_FLAG_REMOTE);
509 } else {
510 char payload[1];
511 log_debug(LD_OR, "Delivering 'truncated' back.");
512 payload[0] = (char)reason;
513 relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
514 payload, sizeof(payload), NULL);
519 /** Callback to handle a new channel; call command_setup_channel() to give
520 * it the right cell handlers.
523 static void
524 command_handle_incoming_channel(channel_listener_t *listener, channel_t *chan)
526 tor_assert(listener);
527 tor_assert(chan);
529 command_setup_channel(chan);
532 /** Given a channel, install the right handlers to process incoming
533 * cells on it.
536 void
537 command_setup_channel(channel_t *chan)
539 tor_assert(chan);
541 channel_set_cell_handlers(chan,
542 command_process_cell,
543 command_process_var_cell);
546 /** Given a listener, install the right handler to process incoming
547 * channels on it.
550 void
551 command_setup_listener(channel_listener_t *listener)
553 tor_assert(listener);
554 tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
556 channel_listener_set_listener_fn(listener, command_handle_incoming_channel);