"Fossies" - the Fresh Open Source Software Archive

Member "tor-0.4.1.6/src/core/or/command.c" (10 Jun 2019, 25814 Bytes) of package /linux/misc/tor-0.4.1.6.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) C and C++ source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "command.c" see the Fossies "Dox" file reference documentation and the last Fossies "Diffs" side-by-side code changes report: 0.4.0.5_vs_0.4.1.5.

    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-2019, The Tor Project, Inc. */
    5 /* See LICENSE for licensing information */
    6 
    7 /**
    8  * \file command.c
    9  * \brief Functions for processing incoming cells.
   10  *
   11  * When we receive a cell from a client or a relay, it arrives on some
   12  * channel, and tells us what to do with it. In this module, we dispatch based
   13  * on the cell type using the functions command_process_cell() and
   14  * command_process_var_cell(), and deal with the cell accordingly.  (These
   15  * handlers are installed on a channel with the command_setup_channel()
   16  * function.)
   17  *
   18  * Channels have a chance to handle some cell types on their own before they
   19  * are ever passed here --- typically, they do this for cells that are
   20  * specific to a given channel type.  For example, in channeltls.c, the cells
   21  * for the initial connection handshake are handled before we get here.  (Of
   22  * course, the fact that there _is_ only one channel type for now means that
   23  * we may have gotten the factoring wrong here.)
   24  *
   25  * Handling other cell types is mainly farmed off to other modules, after
   26  * initial sanity-checking.  CREATE* cells are handled ultimately in onion.c,
   27  * CREATED* cells trigger circuit creation in circuitbuild.c, DESTROY cells
   28  * are handled here (since they're simple), and RELAY cells, in all their
   29  * complexity, are passed off to relay.c.
   30  **/
   31 
   32 /* In-points to command.c:
   33  *
   34  * - command_process_cell(), called from
   35  *   incoming cell handlers of channel_t instances;
   36  *   callbacks registered in command_setup_channel(),
   37  *   called when channels are created in circuitbuild.c
   38  */
   39 #include "core/or/or.h"
   40 #include "app/config/config.h"
   41 #include "core/crypto/onion_crypto.h"
   42 #include "core/mainloop/connection.h"
   43 #include "core/mainloop/cpuworker.h"
   44 #include "core/or/channel.h"
   45 #include "core/or/circuitbuild.h"
   46 #include "core/or/circuitlist.h"
   47 #include "core/or/command.h"
   48 #include "core/or/connection_or.h"
   49 #include "core/or/dos.h"
   50 #include "core/or/onion.h"
   51 #include "core/or/relay.h"
   52 #include "feature/control/control_events.h"
   53 #include "feature/hibernate/hibernate.h"
   54 #include "feature/nodelist/describe.h"
   55 #include "feature/nodelist/nodelist.h"
   56 #include "feature/nodelist/routerlist.h"
   57 #include "feature/relay/routermode.h"
   58 #include "feature/stats/rephist.h"
   59 #include "lib/crypt_ops/crypto_util.h"
   60 
   61 #include "core/or/cell_st.h"
   62 #include "core/or/or_circuit_st.h"
   63 #include "core/or/origin_circuit_st.h"
   64 #include "core/or/var_cell_st.h"
   65 
   66 /** How many CELL_CREATE cells have we received, ever? */
   67 uint64_t stats_n_create_cells_processed = 0;
   68 /** How many CELL_CREATED cells have we received, ever? */
   69 uint64_t stats_n_created_cells_processed = 0;
   70 /** How many CELL_RELAY cells have we received, ever? */
   71 uint64_t stats_n_relay_cells_processed = 0;
   72 /** How many CELL_DESTROY cells have we received, ever? */
   73 uint64_t stats_n_destroy_cells_processed = 0;
   74 
   75 /* Handle an incoming channel */
   76 static void command_handle_incoming_channel(channel_listener_t *listener,
   77                                             channel_t *chan);
   78 
   79 /* These are the main functions for processing cells */
   80 static void command_process_create_cell(cell_t *cell, channel_t *chan);
   81 static void command_process_created_cell(cell_t *cell, channel_t *chan);
   82 static void command_process_relay_cell(cell_t *cell, channel_t *chan);
   83 static void command_process_destroy_cell(cell_t *cell, channel_t *chan);
   84 
   85 /** Convert the cell <b>command</b> into a lower-case, human-readable
   86  * string. */
   87 const char *
   88 cell_command_to_string(uint8_t command)
   89 {
   90   switch (command) {
   91     case CELL_PADDING: return "padding";
   92     case CELL_CREATE: return "create";
   93     case CELL_CREATED: return "created";
   94     case CELL_RELAY: return "relay";
   95     case CELL_DESTROY: return "destroy";
   96     case CELL_CREATE_FAST: return "create_fast";
   97     case CELL_CREATED_FAST: return "created_fast";
   98     case CELL_VERSIONS: return "versions";
   99     case CELL_NETINFO: return "netinfo";
  100     case CELL_RELAY_EARLY: return "relay_early";
  101     case CELL_CREATE2: return "create2";
  102     case CELL_CREATED2: return "created2";
  103     case CELL_VPADDING: return "vpadding";
  104     case CELL_CERTS: return "certs";
  105     case CELL_AUTH_CHALLENGE: return "auth_challenge";
  106     case CELL_AUTHENTICATE: return "authenticate";
  107     case CELL_AUTHORIZE: return "authorize";
  108     default: return "unrecognized";
  109   }
  110 }
  111 
  112 #ifdef KEEP_TIMING_STATS
  113 /** This is a wrapper function around the actual function that processes the
  114  * <b>cell</b> that just arrived on <b>conn</b>. Increment <b>*time</b>
  115  * by the number of microseconds used by the call to <b>*func(cell, conn)</b>.
  116  */
  117 static void
  118 command_time_process_cell(cell_t *cell, channel_t *chan, int *time,
  119                                void (*func)(cell_t *, channel_t *))
  120 {
  121   struct timeval start, end;
  122   long time_passed;
  123 
  124   tor_gettimeofday(&start);
  125 
  126   (*func)(cell, chan);
  127 
  128   tor_gettimeofday(&end);
  129   time_passed = tv_udiff(&start, &end) ;
  130 
  131   if (time_passed > 10000) { /* more than 10ms */
  132     log_debug(LD_OR,"That call just took %ld ms.",time_passed/1000);
  133   }
  134   if (time_passed < 0) {
  135     log_info(LD_GENERAL,"That call took us back in time!");
  136     time_passed = 0;
  137   }
  138   *time += time_passed;
  139 }
  140 #endif /* defined(KEEP_TIMING_STATS) */
  141 
  142 /** Process a <b>cell</b> that was just received on <b>chan</b>. Keep internal
  143  * statistics about how many of each cell we've processed so far
  144  * this second, and the total number of microseconds it took to
  145  * process each type of cell.
  146  */
  147 void
  148 command_process_cell(channel_t *chan, cell_t *cell)
  149 {
  150 #ifdef KEEP_TIMING_STATS
  151   /* how many of each cell have we seen so far this second? needs better
  152    * name. */
  153   static int num_create=0, num_created=0, num_relay=0, num_destroy=0;
  154   /* how long has it taken to process each type of cell? */
  155   static int create_time=0, created_time=0, relay_time=0, destroy_time=0;
  156   static time_t current_second = 0; /* from previous calls to time */
  157 
  158   time_t now = time(NULL);
  159 
  160   if (now > current_second) { /* the second has rolled over */
  161     /* print stats */
  162     log_info(LD_OR,
  163          "At end of second: %d creates (%d ms), %d createds (%d ms), "
  164          "%d relays (%d ms), %d destroys (%d ms)",
  165          num_create, create_time/1000,
  166          num_created, created_time/1000,
  167          num_relay, relay_time/1000,
  168          num_destroy, destroy_time/1000);
  169 
  170     /* zero out stats */
  171     num_create = num_created = num_relay = num_destroy = 0;
  172     create_time = created_time = relay_time = destroy_time = 0;
  173 
  174     /* remember which second it is, for next time */
  175     current_second = now;
  176   }
  177 #endif /* defined(KEEP_TIMING_STATS) */
  178 
  179 #ifdef KEEP_TIMING_STATS
  180 #define PROCESS_CELL(tp, cl, cn) STMT_BEGIN {                   \
  181     ++num ## tp;                                                \
  182     command_time_process_cell(cl, cn, & tp ## time ,            \
  183                               command_process_ ## tp ## _cell);  \
  184   } STMT_END
  185 #else /* !(defined(KEEP_TIMING_STATS)) */
  186 #define PROCESS_CELL(tp, cl, cn) command_process_ ## tp ## _cell(cl, cn)
  187 #endif /* defined(KEEP_TIMING_STATS) */
  188 
  189   switch (cell->command) {
  190     case CELL_CREATE:
  191     case CELL_CREATE_FAST:
  192     case CELL_CREATE2:
  193       ++stats_n_create_cells_processed;
  194       PROCESS_CELL(create, cell, chan);
  195       break;
  196     case CELL_CREATED:
  197     case CELL_CREATED_FAST:
  198     case CELL_CREATED2:
  199       ++stats_n_created_cells_processed;
  200       PROCESS_CELL(created, cell, chan);
  201       break;
  202     case CELL_RELAY:
  203     case CELL_RELAY_EARLY:
  204       ++stats_n_relay_cells_processed;
  205       PROCESS_CELL(relay, cell, chan);
  206       break;
  207     case CELL_DESTROY:
  208       ++stats_n_destroy_cells_processed;
  209       PROCESS_CELL(destroy, cell, chan);
  210       break;
  211     default:
  212       log_fn(LOG_INFO, LD_PROTOCOL,
  213              "Cell of unknown or unexpected type (%d) received.  "
  214              "Dropping.",
  215              cell->command);
  216       break;
  217   }
  218 }
  219 
  220 /** Process an incoming var_cell from a channel; in the current protocol all
  221  * the var_cells are handshake-related and handled below the channel layer,
  222  * so this just logs a warning and drops the cell.
  223  */
  224 
  225 void
  226 command_process_var_cell(channel_t *chan, var_cell_t *var_cell)
  227 {
  228   tor_assert(chan);
  229   tor_assert(var_cell);
  230 
  231   log_info(LD_PROTOCOL,
  232            "Received unexpected var_cell above the channel layer of type %d"
  233            "; dropping it.",
  234            var_cell->command);
  235 }
  236 
  237 /** Process a 'create' <b>cell</b> that just arrived from <b>chan</b>. Make a
  238  * new circuit with the p_circ_id specified in cell. Put the circuit in state
  239  * onionskin_pending, and pass the onionskin to the cpuworker. Circ will get
  240  * picked up again when the cpuworker finishes decrypting it.
  241  */
  242 static void
  243 command_process_create_cell(cell_t *cell, channel_t *chan)
  244 {
  245   or_circuit_t *circ;
  246   const or_options_t *options = get_options();
  247   int id_is_high;
  248   create_cell_t *create_cell;
  249 
  250   tor_assert(cell);
  251   tor_assert(chan);
  252 
  253   log_debug(LD_OR,
  254             "Got a CREATE cell for circ_id %u on channel %"PRIu64
  255             " (%p)",
  256             (unsigned)cell->circ_id,
  257             (chan->global_identifier), chan);
  258 
  259   /* First thing we do, even though the cell might be invalid, is inform the
  260    * DoS mitigation subsystem layer of this event. Validation is done by this
  261    * function. */
  262   dos_cc_new_create_cell(chan);
  263 
  264   /* We check for the conditions that would make us drop the cell before
  265    * we check for the conditions that would make us send a DESTROY back,
  266    * since those conditions would make a DESTROY nonsensical. */
  267   if (cell->circ_id == 0) {
  268     log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  269            "Received a create cell (type %d) from %s with zero circID; "
  270            " ignoring.", (int)cell->command,
  271            channel_get_actual_remote_descr(chan));
  272     return;
  273   }
  274 
  275   if (circuit_id_in_use_on_channel(cell->circ_id, chan)) {
  276     const node_t *node = node_get_by_id(chan->identity_digest);
  277     log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  278            "Received CREATE cell (circID %u) for known circ. "
  279            "Dropping (age %d).",
  280            (unsigned)cell->circ_id,
  281            (int)(time(NULL) - channel_when_created(chan)));
  282     if (node) {
  283       char *p = esc_for_log(node_get_platform(node));
  284       log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  285              "Details: router %s, platform %s.",
  286              node_describe(node), p);
  287       tor_free(p);
  288     }
  289     return;
  290   }
  291 
  292   if (we_are_hibernating()) {
  293     log_info(LD_OR,
  294              "Received create cell but we're shutting down. Sending back "
  295              "destroy.");
  296     channel_send_destroy(cell->circ_id, chan,
  297                          END_CIRC_REASON_HIBERNATING);
  298     return;
  299   }
  300 
  301   /* Check if we should apply a defense for this channel. */
  302   if (dos_cc_get_defense_type(chan) == DOS_CC_DEFENSE_REFUSE_CELL) {
  303     channel_send_destroy(cell->circ_id, chan,
  304                          END_CIRC_REASON_RESOURCELIMIT);
  305     return;
  306   }
  307 
  308   if (!server_mode(options) ||
  309       (!public_server_mode(options) && channel_is_outgoing(chan))) {
  310     log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  311            "Received create cell (type %d) from %s, but we're connected "
  312            "to it as a client. "
  313            "Sending back a destroy.",
  314            (int)cell->command, channel_get_canonical_remote_descr(chan));
  315     channel_send_destroy(cell->circ_id, chan,
  316                          END_CIRC_REASON_TORPROTOCOL);
  317     return;
  318   }
  319 
  320   /* If the high bit of the circuit ID is not as expected, close the
  321    * circ. */
  322   if (chan->wide_circ_ids)
  323     id_is_high = cell->circ_id & (1u<<31);
  324   else
  325     id_is_high = cell->circ_id & (1u<<15);
  326   if ((id_is_high &&
  327        chan->circ_id_type == CIRC_ID_TYPE_HIGHER) ||
  328       (!id_is_high &&
  329        chan->circ_id_type == CIRC_ID_TYPE_LOWER)) {
  330     log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  331            "Received create cell with unexpected circ_id %u. Closing.",
  332            (unsigned)cell->circ_id);
  333     channel_send_destroy(cell->circ_id, chan,
  334                          END_CIRC_REASON_TORPROTOCOL);
  335     return;
  336   }
  337 
  338   circ = or_circuit_new(cell->circ_id, chan);
  339   circ->base_.purpose = CIRCUIT_PURPOSE_OR;
  340   circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_ONIONSKIN_PENDING);
  341   create_cell = tor_malloc_zero(sizeof(create_cell_t));
  342   if (create_cell_parse(create_cell, cell) < 0) {
  343     tor_free(create_cell);
  344     log_fn(LOG_PROTOCOL_WARN, LD_OR,
  345            "Bogus/unrecognized create cell; closing.");
  346     circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  347     return;
  348   }
  349 
  350   if (!channel_is_client(chan)) {
  351     /* remember create types we've seen, but don't remember them from
  352      * clients, to be extra conservative about client statistics. */
  353     rep_hist_note_circuit_handshake_requested(create_cell->handshake_type);
  354   }
  355 
  356   if (create_cell->handshake_type != ONION_HANDSHAKE_TYPE_FAST) {
  357     /* hand it off to the cpuworkers, and then return. */
  358 
  359     if (assign_onionskin_to_cpuworker(circ, create_cell) < 0) {
  360       log_debug(LD_GENERAL,"Failed to hand off onionskin. Closing.");
  361       circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_RESOURCELIMIT);
  362       return;
  363     }
  364     log_debug(LD_OR,"success: handed off onionskin.");
  365   } else {
  366     /* This is a CREATE_FAST cell; we can handle it immediately without using
  367      * a CPU worker. */
  368     uint8_t keys[CPATH_KEY_MATERIAL_LEN];
  369     uint8_t rend_circ_nonce[DIGEST_LEN];
  370     int len;
  371     created_cell_t created_cell;
  372 
  373     memset(&created_cell, 0, sizeof(created_cell));
  374     len = onion_skin_server_handshake(ONION_HANDSHAKE_TYPE_FAST,
  375                                        create_cell->onionskin,
  376                                        create_cell->handshake_len,
  377                                        NULL,
  378                                        created_cell.reply,
  379                                        keys, CPATH_KEY_MATERIAL_LEN,
  380                                        rend_circ_nonce);
  381     tor_free(create_cell);
  382     if (len < 0) {
  383       log_warn(LD_OR,"Failed to generate key material. Closing.");
  384       circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  385       return;
  386     }
  387     created_cell.cell_type = CELL_CREATED_FAST;
  388     created_cell.handshake_len = len;
  389 
  390     if (onionskin_answer(circ, &created_cell,
  391                          (const char *)keys, sizeof(keys),
  392                          rend_circ_nonce)<0) {
  393       log_warn(LD_OR,"Failed to reply to CREATE_FAST cell. Closing.");
  394       circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  395       return;
  396     }
  397     memwipe(keys, 0, sizeof(keys));
  398   }
  399 }
  400 
  401 /** Process a 'created' <b>cell</b> that just arrived from <b>chan</b>.
  402  * Find the circuit
  403  * that it's intended for. If we're not the origin of the circuit, package
  404  * the 'created' cell in an 'extended' relay cell and pass it back. If we
  405  * are the origin of the circuit, send it to circuit_finish_handshake() to
  406  * finish processing keys, and then call circuit_send_next_onion_skin() to
  407  * extend to the next hop in the circuit if necessary.
  408  */
  409 static void
  410 command_process_created_cell(cell_t *cell, channel_t *chan)
  411 {
  412   circuit_t *circ;
  413   extended_cell_t extended_cell;
  414 
  415   circ = circuit_get_by_circid_channel(cell->circ_id, chan);
  416 
  417   if (!circ) {
  418     log_info(LD_OR,
  419              "(circID %u) unknown circ (probably got a destroy earlier). "
  420              "Dropping.", (unsigned)cell->circ_id);
  421     return;
  422   }
  423 
  424   if (circ->n_circ_id != cell->circ_id || circ->n_chan != chan) {
  425     log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,
  426            "got created cell from Tor client? Closing.");
  427     circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  428     return;
  429   }
  430 
  431   if (created_cell_parse(&extended_cell.created_cell, cell) < 0) {
  432     log_fn(LOG_PROTOCOL_WARN, LD_OR, "Unparseable created cell.");
  433     circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  434     return;
  435   }
  436 
  437   if (CIRCUIT_IS_ORIGIN(circ)) { /* we're the OP. Handshake this. */
  438     origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
  439     int err_reason = 0;
  440     log_debug(LD_OR,"at OP. Finishing handshake.");
  441     if ((err_reason = circuit_finish_handshake(origin_circ,
  442                                         &extended_cell.created_cell)) < 0) {
  443       circuit_mark_for_close(circ, -err_reason);
  444       return;
  445     }
  446     log_debug(LD_OR,"Moving to next skin.");
  447     if ((err_reason = circuit_send_next_onion_skin(origin_circ)) < 0) {
  448       log_info(LD_OR,"circuit_send_next_onion_skin failed.");
  449       /* XXX push this circuit_close lower */
  450       circuit_mark_for_close(circ, -err_reason);
  451       return;
  452     }
  453   } else { /* pack it into an extended relay cell, and send it. */
  454     uint8_t command=0;
  455     uint16_t len=0;
  456     uint8_t payload[RELAY_PAYLOAD_SIZE];
  457     log_debug(LD_OR,
  458               "Converting created cell to extended relay cell, sending.");
  459     memset(payload, 0, sizeof(payload));
  460     if (extended_cell.created_cell.cell_type == CELL_CREATED2)
  461       extended_cell.cell_type = RELAY_COMMAND_EXTENDED2;
  462     else
  463       extended_cell.cell_type = RELAY_COMMAND_EXTENDED;
  464     if (extended_cell_format(&command, &len, payload, &extended_cell) < 0) {
  465       log_fn(LOG_PROTOCOL_WARN, LD_OR, "Can't format extended cell.");
  466       circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  467       return;
  468     }
  469 
  470     relay_send_command_from_edge(0, circ, command,
  471                                  (const char*)payload, len, NULL);
  472   }
  473 }
  474 
  475 /** Process a 'relay' or 'relay_early' <b>cell</b> that just arrived from
  476  * <b>conn</b>. Make sure it came in with a recognized circ_id. Pass it on to
  477  * circuit_receive_relay_cell() for actual processing.
  478  */
  479 static void
  480 command_process_relay_cell(cell_t *cell, channel_t *chan)
  481 {
  482   const or_options_t *options = get_options();
  483   circuit_t *circ;
  484   int reason, direction;
  485   uint32_t orig_delivered_bw = 0;
  486   uint32_t orig_overhead_bw = 0;
  487 
  488   circ = circuit_get_by_circid_channel(cell->circ_id, chan);
  489 
  490   if (!circ) {
  491     log_debug(LD_OR,
  492               "unknown circuit %u on connection from %s. Dropping.",
  493               (unsigned)cell->circ_id,
  494               channel_get_canonical_remote_descr(chan));
  495     return;
  496   }
  497 
  498   if (circ->state == CIRCUIT_STATE_ONIONSKIN_PENDING) {
  499     log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,"circuit in create_wait. Closing.");
  500     circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  501     return;
  502   }
  503 
  504   if (CIRCUIT_IS_ORIGIN(circ)) {
  505     /* if we're a relay and treating connections with recent local
  506      * traffic better, then this is one of them. */
  507     channel_timestamp_client(chan);
  508 
  509     /* Count all circuit bytes here for control port accuracy. We want
  510      * to count even invalid/dropped relay cells, hence counting
  511      * before the recognized check and the connection_edge_process_relay
  512      * cell checks.
  513      */
  514     origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  515 
  516     /* Count the payload bytes only. We don't care about cell headers */
  517     ocirc->n_read_circ_bw = tor_add_u32_nowrap(ocirc->n_read_circ_bw,
  518                                                CELL_PAYLOAD_SIZE);
  519 
  520     /* Stash the original delivered and overhead values. These values are
  521      * updated by circuit_read_valid_data() during cell processing by
  522      * connection_edge_process_relay_cell(), called from
  523      * circuit_receive_relay_cell() below. If they do not change, we inform
  524      * the control port about dropped cells immediately after the call
  525      * to circuit_receive_relay_cell() below. */
  526     orig_delivered_bw = ocirc->n_delivered_read_circ_bw;
  527     orig_overhead_bw = ocirc->n_overhead_read_circ_bw;
  528   }
  529 
  530   if (!CIRCUIT_IS_ORIGIN(circ) &&
  531       chan == TO_OR_CIRCUIT(circ)->p_chan &&
  532       cell->circ_id == TO_OR_CIRCUIT(circ)->p_circ_id)
  533     direction = CELL_DIRECTION_OUT;
  534   else
  535     direction = CELL_DIRECTION_IN;
  536 
  537   /* If we have a relay_early cell, make sure that it's outbound, and we've
  538    * gotten no more than MAX_RELAY_EARLY_CELLS_PER_CIRCUIT of them. */
  539   if (cell->command == CELL_RELAY_EARLY) {
  540     if (direction == CELL_DIRECTION_IN) {
  541       /* Inbound early cells could once be encountered as a result of
  542        * bug 1038; but relays running versions before 0.2.1.19 are long
  543        * gone from the network, so any such cells now are surprising. */
  544       log_warn(LD_OR,
  545                "Received an inbound RELAY_EARLY cell on circuit %u."
  546                " Closing circuit. Please report this event,"
  547                " along with the following message.",
  548                (unsigned)cell->circ_id);
  549       if (CIRCUIT_IS_ORIGIN(circ)) {
  550         circuit_log_path(LOG_WARN, LD_OR, TO_ORIGIN_CIRCUIT(circ));
  551         /* Always emit a bandwidth event for closed circs */
  552         control_event_circ_bandwidth_used_for_circ(TO_ORIGIN_CIRCUIT(circ));
  553       } else if (circ->n_chan) {
  554         log_warn(LD_OR, " upstream=%s",
  555                  channel_get_actual_remote_descr(circ->n_chan));
  556       }
  557       circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  558       return;
  559     } else {
  560       or_circuit_t *or_circ = TO_OR_CIRCUIT(circ);
  561       if (or_circ->remaining_relay_early_cells == 0) {
  562         log_fn(LOG_PROTOCOL_WARN, LD_OR,
  563                "Received too many RELAY_EARLY cells on circ %u from %s."
  564                "  Closing circuit.",
  565                (unsigned)cell->circ_id,
  566                safe_str(channel_get_canonical_remote_descr(chan)));
  567         circuit_mark_for_close(circ, END_CIRC_REASON_TORPROTOCOL);
  568         return;
  569       }
  570       --or_circ->remaining_relay_early_cells;
  571     }
  572   }
  573 
  574   if ((reason = circuit_receive_relay_cell(cell, circ, direction)) < 0) {
  575     log_fn(LOG_PROTOCOL_WARN,LD_PROTOCOL,"circuit_receive_relay_cell "
  576            "(%s) failed. Closing.",
  577            direction==CELL_DIRECTION_OUT?"forward":"backward");
  578     /* Always emit a bandwidth event for closed circs */
  579     if (CIRCUIT_IS_ORIGIN(circ)) {
  580       control_event_circ_bandwidth_used_for_circ(TO_ORIGIN_CIRCUIT(circ));
  581     }
  582     circuit_mark_for_close(circ, -reason);
  583   }
  584 
  585   if (CIRCUIT_IS_ORIGIN(circ)) {
  586     origin_circuit_t *ocirc = TO_ORIGIN_CIRCUIT(circ);
  587 
  588     /* If neither the delivered nor overhead values changed, this cell
  589      * was dropped due to being invalid by one of the error codepaths in
  590      * connection_edge_process_relay_cell(), called by
  591      * circuit_receive_relay_cell().
  592      *
  593      * Valid cells, on the other hand, call circuit_read_valid_data()
  594      * to update these values upon processing them.
  595      *
  596      * So, if the values are the same as those stored above,
  597      * emit a control port event for CIRC_BW, so the controller can
  598      * react quickly to invalid cells. */
  599     if (orig_delivered_bw == ocirc->n_delivered_read_circ_bw &&
  600         orig_overhead_bw == ocirc->n_overhead_read_circ_bw) {
  601       control_event_circ_bandwidth_used_for_circ(ocirc);
  602     }
  603   }
  604 
  605   /* If this is a cell in an RP circuit, count it as part of the
  606      hidden service stats */
  607   if (options->HiddenServiceStatistics &&
  608       !CIRCUIT_IS_ORIGIN(circ) &&
  609       TO_OR_CIRCUIT(circ)->circuit_carries_hs_traffic_stats) {
  610     rep_hist_seen_new_rp_cell();
  611   }
  612 }
  613 
  614 /** Process a 'destroy' <b>cell</b> that just arrived from
  615  * <b>chan</b>. Find the circ that it refers to (if any).
  616  *
  617  * If the circ is in state
  618  * onionskin_pending, then call onion_pending_remove() to remove it
  619  * from the pending onion list (note that if it's already being
  620  * processed by the cpuworker, it won't be in the list anymore; but
  621  * when the cpuworker returns it, the circuit will be gone, and the
  622  * cpuworker response will be dropped).
  623  *
  624  * Then mark the circuit for close (which marks all edges for close,
  625  * and passes the destroy cell onward if necessary).
  626  */
  627 static void
  628 command_process_destroy_cell(cell_t *cell, channel_t *chan)
  629 {
  630   circuit_t *circ;
  631   int reason;
  632 
  633   circ = circuit_get_by_circid_channel(cell->circ_id, chan);
  634   if (!circ) {
  635     log_info(LD_OR,"unknown circuit %u on connection from %s. Dropping.",
  636              (unsigned)cell->circ_id,
  637              channel_get_canonical_remote_descr(chan));
  638     return;
  639   }
  640   log_debug(LD_OR,"Received for circID %u.",(unsigned)cell->circ_id);
  641 
  642   reason = (uint8_t)cell->payload[0];
  643   circ->received_destroy = 1;
  644 
  645   if (!CIRCUIT_IS_ORIGIN(circ) &&
  646       chan == TO_OR_CIRCUIT(circ)->p_chan &&
  647       cell->circ_id == TO_OR_CIRCUIT(circ)->p_circ_id) {
  648     /* the destroy came from behind */
  649     circuit_set_p_circid_chan(TO_OR_CIRCUIT(circ), 0, NULL);
  650     circuit_mark_for_close(circ, reason|END_CIRC_REASON_FLAG_REMOTE);
  651   } else { /* the destroy came from ahead */
  652     circuit_set_n_circid_chan(circ, 0, NULL);
  653     if (CIRCUIT_IS_ORIGIN(circ)) {
  654       circuit_mark_for_close(circ, reason|END_CIRC_REASON_FLAG_REMOTE);
  655     } else {
  656       char payload[1];
  657       log_debug(LD_OR, "Delivering 'truncated' back.");
  658       payload[0] = (char)reason;
  659       relay_send_command_from_edge(0, circ, RELAY_COMMAND_TRUNCATED,
  660                                    payload, sizeof(payload), NULL);
  661     }
  662   }
  663 }
  664 
  665 /** Callback to handle a new channel; call command_setup_channel() to give
  666  * it the right cell handlers.
  667  */
  668 
  669 static void
  670 command_handle_incoming_channel(channel_listener_t *listener, channel_t *chan)
  671 {
  672   tor_assert(listener);
  673   tor_assert(chan);
  674 
  675   command_setup_channel(chan);
  676 }
  677 
  678 /** Given a channel, install the right handlers to process incoming
  679  * cells on it.
  680  */
  681 
  682 void
  683 command_setup_channel(channel_t *chan)
  684 {
  685   tor_assert(chan);
  686 
  687   channel_set_cell_handlers(chan,
  688                             command_process_cell,
  689                             command_process_var_cell);
  690 }
  691 
  692 /** Given a listener, install the right handler to process incoming
  693  * channels on it.
  694  */
  695 
  696 void
  697 command_setup_listener(channel_listener_t *listener)
  698 {
  699   tor_assert(listener);
  700   tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
  701 
  702   channel_listener_set_listener_fn(listener, command_handle_incoming_channel);
  703 }