Back to index

tor  0.2.3.18-rc
control.c
Go to the documentation of this file.
00001 /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
00002  * Copyright (c) 2007-2012, The Tor Project, Inc. */
00003 /* See LICENSE for licensing information */
00004 
00011 #define CONTROL_PRIVATE
00012 
00013 #include "or.h"
00014 #include "buffers.h"
00015 #include "circuitbuild.h"
00016 #include "circuitlist.h"
00017 #include "circuituse.h"
00018 #include "config.h"
00019 #include "connection.h"
00020 #include "connection_edge.h"
00021 #include "connection_or.h"
00022 #include "control.h"
00023 #include "directory.h"
00024 #include "dirserv.h"
00025 #include "dnsserv.h"
00026 #include "geoip.h"
00027 #include "hibernate.h"
00028 #include "main.h"
00029 #include "networkstatus.h"
00030 #include "nodelist.h"
00031 #include "policies.h"
00032 #include "reasons.h"
00033 #include "rephist.h"
00034 #include "router.h"
00035 #include "routerlist.h"
00036 #include "routerparse.h"
00037 
00038 #ifndef _WIN32
00039 #include <pwd.h>
00040 #include <sys/resource.h>
00041 #endif
00042 
00043 #include "procmon.h"
00044 
00047 #define STATE_IS_OPEN(s) ((s) == CONTROL_CONN_STATE_OPEN)
00048 
00049 /* Recognized asynchronous event types.  It's okay to expand this list
00050  * because it is used both as a list of v0 event types, and as indices
00051  * into the bitfield to determine which controllers want which events.
00052  */
00053 #define _EVENT_MIN             0x0001
00054 #define EVENT_CIRCUIT_STATUS   0x0001
00055 #define EVENT_STREAM_STATUS    0x0002
00056 #define EVENT_OR_CONN_STATUS   0x0003
00057 #define EVENT_BANDWIDTH_USED   0x0004
00058 #define EVENT_CIRCUIT_STATUS_MINOR 0x0005
00059 #define EVENT_NEW_DESC         0x0006
00060 #define EVENT_DEBUG_MSG        0x0007
00061 #define EVENT_INFO_MSG         0x0008
00062 #define EVENT_NOTICE_MSG       0x0009
00063 #define EVENT_WARN_MSG         0x000A
00064 #define EVENT_ERR_MSG          0x000B
00065 #define EVENT_ADDRMAP          0x000C
00066 // #define EVENT_AUTHDIR_NEWDESCS 0x000D
00067 #define EVENT_DESCCHANGED      0x000E
00068 // #define EVENT_NS               0x000F
00069 #define EVENT_STATUS_CLIENT    0x0010
00070 #define EVENT_STATUS_SERVER    0x0011
00071 #define EVENT_STATUS_GENERAL   0x0012
00072 #define EVENT_GUARD            0x0013
00073 #define EVENT_STREAM_BANDWIDTH_USED   0x0014
00074 #define EVENT_CLIENTS_SEEN     0x0015
00075 #define EVENT_NEWCONSENSUS     0x0016
00076 #define EVENT_BUILDTIMEOUT_SET     0x0017
00077 #define EVENT_SIGNAL           0x0018
00078 #define EVENT_CONF_CHANGED     0x0019
00079 #define _EVENT_MAX             0x0019
00080 /* If _EVENT_MAX ever hits 0x0020, we need to make the mask wider. */
00081 
00088 typedef uint32_t event_mask_t;
00089 
00092 static event_mask_t global_event_mask = 0;
00093 
00095 static int disable_log_messages = 0;
00096 
00099 #define EVENT_IS_INTERESTING(e) \
00100   (global_event_mask & (1<<(e)))
00101 
00104 #define AUTHENTICATION_COOKIE_LEN 32
00105 
00108 static int authentication_cookie_is_set = 0;
00112 static char authentication_cookie[AUTHENTICATION_COOKIE_LEN];
00113 
00114 #define SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT \
00115   "Tor safe cookie authentication server-to-controller hash"
00116 #define SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT \
00117   "Tor safe cookie authentication controller-to-server hash"
00118 #define SAFECOOKIE_SERVER_NONCE_LEN DIGEST256_LEN
00119 
00121 #define BOOTSTRAP_MSG_LEN 1024
00122 
00125 static char last_sent_bootstrap_message[BOOTSTRAP_MSG_LEN];
00126 
00130 #define ALL_FORMATS 1
00131 
00134 typedef int event_format_t;
00135 
00136 static void connection_printf_to_buf(control_connection_t *conn,
00137                                      const char *format, ...)
00138   CHECK_PRINTF(2,3);
00139 static void send_control_event_impl(uint16_t event, event_format_t which,
00140                                     const char *format, va_list ap)
00141   CHECK_PRINTF(3,0);
00142 static int control_event_status(int type, int severity, const char *format,
00143                                 va_list args)
00144   CHECK_PRINTF(3,0);
00145 
00146 static void send_control_done(control_connection_t *conn);
00147 static void send_control_event(uint16_t event, event_format_t which,
00148                                const char *format, ...)
00149   CHECK_PRINTF(3,4);
00150 static int handle_control_setconf(control_connection_t *conn, uint32_t len,
00151                                   char *body);
00152 static int handle_control_resetconf(control_connection_t *conn, uint32_t len,
00153                                     char *body);
00154 static int handle_control_getconf(control_connection_t *conn, uint32_t len,
00155                                   const char *body);
00156 static int handle_control_loadconf(control_connection_t *conn, uint32_t len,
00157                                   const char *body);
00158 static int handle_control_setevents(control_connection_t *conn, uint32_t len,
00159                                     const char *body);
00160 static int handle_control_authenticate(control_connection_t *conn,
00161                                        uint32_t len,
00162                                        const char *body);
00163 static int handle_control_signal(control_connection_t *conn, uint32_t len,
00164                                  const char *body);
00165 static int handle_control_mapaddress(control_connection_t *conn, uint32_t len,
00166                                      const char *body);
00167 static char *list_getinfo_options(void);
00168 static int handle_control_getinfo(control_connection_t *conn, uint32_t len,
00169                                   const char *body);
00170 static int handle_control_extendcircuit(control_connection_t *conn,
00171                                         uint32_t len,
00172                                         const char *body);
00173 static int handle_control_setcircuitpurpose(control_connection_t *conn,
00174                                             uint32_t len, const char *body);
00175 static int handle_control_attachstream(control_connection_t *conn,
00176                                        uint32_t len,
00177                                         const char *body);
00178 static int handle_control_postdescriptor(control_connection_t *conn,
00179                                          uint32_t len,
00180                                          const char *body);
00181 static int handle_control_redirectstream(control_connection_t *conn,
00182                                          uint32_t len,
00183                                          const char *body);
00184 static int handle_control_closestream(control_connection_t *conn, uint32_t len,
00185                                       const char *body);
00186 static int handle_control_closecircuit(control_connection_t *conn,
00187                                        uint32_t len,
00188                                        const char *body);
00189 static int handle_control_resolve(control_connection_t *conn, uint32_t len,
00190                                   const char *body);
00191 static int handle_control_usefeature(control_connection_t *conn,
00192                                      uint32_t len,
00193                                      const char *body);
00194 static int write_stream_target_to_buf(entry_connection_t *conn, char *buf,
00195                                       size_t len);
00196 static void orconn_target_get_name(char *buf, size_t len,
00197                                    or_connection_t *conn);
00198 static char *get_cookie_file(void);
00199 
00202 static INLINE int
00203 event_to_log_severity(int event)
00204 {
00205   switch (event) {
00206     case EVENT_DEBUG_MSG: return LOG_DEBUG;
00207     case EVENT_INFO_MSG: return LOG_INFO;
00208     case EVENT_NOTICE_MSG: return LOG_NOTICE;
00209     case EVENT_WARN_MSG: return LOG_WARN;
00210     case EVENT_ERR_MSG: return LOG_ERR;
00211     default: return -1;
00212   }
00213 }
00214 
00216 static INLINE int
00217 log_severity_to_event(int severity)
00218 {
00219   switch (severity) {
00220     case LOG_DEBUG: return EVENT_DEBUG_MSG;
00221     case LOG_INFO: return EVENT_INFO_MSG;
00222     case LOG_NOTICE: return EVENT_NOTICE_MSG;
00223     case LOG_WARN: return EVENT_WARN_MSG;
00224     case LOG_ERR: return EVENT_ERR_MSG;
00225     default: return -1;
00226   }
00227 }
00228 
00231 void
00232 control_update_global_event_mask(void)
00233 {
00234   smartlist_t *conns = get_connection_array();
00235   event_mask_t old_mask, new_mask;
00236   old_mask = global_event_mask;
00237 
00238   global_event_mask = 0;
00239   SMARTLIST_FOREACH(conns, connection_t *, _conn,
00240   {
00241     if (_conn->type == CONN_TYPE_CONTROL &&
00242         STATE_IS_OPEN(_conn->state)) {
00243       control_connection_t *conn = TO_CONTROL_CONN(_conn);
00244       global_event_mask |= conn->event_mask;
00245     }
00246   });
00247 
00248   new_mask = global_event_mask;
00249 
00250   /* Handle the aftermath.  Set up the log callback to tell us only what
00251    * we want to hear...*/
00252   control_adjust_event_log_severity();
00253 
00254   /* ...then, if we've started logging stream bw, clear the appropriate
00255    * fields. */
00256   if (! (old_mask & EVENT_STREAM_BANDWIDTH_USED) &&
00257       (new_mask & EVENT_STREAM_BANDWIDTH_USED)) {
00258     SMARTLIST_FOREACH(conns, connection_t *, conn,
00259     {
00260       if (conn->type == CONN_TYPE_AP) {
00261         edge_connection_t *edge_conn = TO_EDGE_CONN(conn);
00262         edge_conn->n_written = edge_conn->n_read = 0;
00263       }
00264     });
00265   }
00266 }
00267 
00271 void
00272 control_adjust_event_log_severity(void)
00273 {
00274   int i;
00275   int min_log_event=EVENT_ERR_MSG, max_log_event=EVENT_DEBUG_MSG;
00276 
00277   for (i = EVENT_DEBUG_MSG; i <= EVENT_ERR_MSG; ++i) {
00278     if (EVENT_IS_INTERESTING(i)) {
00279       min_log_event = i;
00280       break;
00281     }
00282   }
00283   for (i = EVENT_ERR_MSG; i >= EVENT_DEBUG_MSG; --i) {
00284     if (EVENT_IS_INTERESTING(i)) {
00285       max_log_event = i;
00286       break;
00287     }
00288   }
00289   if (EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL)) {
00290     if (min_log_event > EVENT_NOTICE_MSG)
00291       min_log_event = EVENT_NOTICE_MSG;
00292     if (max_log_event < EVENT_ERR_MSG)
00293       max_log_event = EVENT_ERR_MSG;
00294   }
00295   if (min_log_event <= max_log_event)
00296     change_callback_log_severity(event_to_log_severity(min_log_event),
00297                                  event_to_log_severity(max_log_event),
00298                                  control_event_logmsg);
00299   else
00300     change_callback_log_severity(LOG_ERR, LOG_ERR,
00301                                  control_event_logmsg);
00302 }
00303 
00308 int
00309 control_event_is_interesting(int event)
00310 {
00311   return EVENT_IS_INTERESTING(event);
00312 }
00313 
00317 static INLINE void
00318 connection_write_str_to_buf(const char *s, control_connection_t *conn)
00319 {
00320   size_t len = strlen(s);
00321   connection_write_to_buf(s, len, TO_CONN(conn));
00322 }
00323 
00331 /* static */ size_t
00332 write_escaped_data(const char *data, size_t len, char **out)
00333 {
00334   size_t sz_out = len+8;
00335   char *outp;
00336   const char *start = data, *end;
00337   int i;
00338   int start_of_line;
00339   for (i=0; i<(int)len; ++i) {
00340     if (data[i]== '\n')
00341       sz_out += 2; /* Maybe add a CR; maybe add a dot. */
00342   }
00343   *out = outp = tor_malloc(sz_out+1);
00344   end = data+len;
00345   start_of_line = 1;
00346   while (data < end) {
00347     if (*data == '\n') {
00348       if (data > start && data[-1] != '\r')
00349         *outp++ = '\r';
00350       start_of_line = 1;
00351     } else if (*data == '.') {
00352       if (start_of_line) {
00353         start_of_line = 0;
00354         *outp++ = '.';
00355       }
00356     } else {
00357       start_of_line = 0;
00358     }
00359     *outp++ = *data++;
00360   }
00361   if (outp < *out+2 || fast_memcmp(outp-2, "\r\n", 2)) {
00362     *outp++ = '\r';
00363     *outp++ = '\n';
00364   }
00365   *outp++ = '.';
00366   *outp++ = '\r';
00367   *outp++ = '\n';
00368   *outp = '\0'; /* NUL-terminate just in case. */
00369   tor_assert((outp - *out) <= (int)sz_out);
00370   return outp - *out;
00371 }
00372 
00379 /* static */ size_t
00380 read_escaped_data(const char *data, size_t len, char **out)
00381 {
00382   char *outp;
00383   const char *next;
00384   const char *end;
00385 
00386   *out = outp = tor_malloc(len+1);
00387 
00388   end = data+len;
00389 
00390   while (data < end) {
00391     /* we're at the start of a line. */
00392     if (*data == '.')
00393       ++data;
00394     next = memchr(data, '\n', end-data);
00395     if (next) {
00396       size_t n_to_copy = next-data;
00397       /* Don't copy a CR that precedes this LF. */
00398       if (n_to_copy && *(next-1) == '\r')
00399         --n_to_copy;
00400       memcpy(outp, data, n_to_copy);
00401       outp += n_to_copy;
00402       data = next+1; /* This will point at the start of the next line,
00403                       * or the end of the string, or a period. */
00404     } else {
00405       memcpy(outp, data, end-data);
00406       outp += (end-data);
00407       *outp = '\0';
00408       return outp - *out;
00409     }
00410     *outp++ = '\n';
00411   }
00412 
00413   *outp = '\0';
00414   return outp - *out;
00415 }
00416 
00420 static INLINE int
00421 get_escaped_string_length(const char *start, size_t in_len_max,
00422                           int *chars_out)
00423 {
00424   const char *cp, *end;
00425   int chars = 0;
00426 
00427   if (*start != '\"')
00428     return -1;
00429 
00430   cp = start+1;
00431   end = start+in_len_max;
00432 
00433   /* Calculate length. */
00434   while (1) {
00435     if (cp >= end) {
00436       return -1; /* Too long. */
00437     } else if (*cp == '\\') {
00438       if (++cp == end)
00439         return -1; /* Can't escape EOS. */
00440       ++cp;
00441       ++chars;
00442     } else if (*cp == '\"') {
00443       break;
00444     } else {
00445       ++cp;
00446       ++chars;
00447     }
00448   }
00449   if (chars_out)
00450     *chars_out = chars;
00451   return (int)(cp - start+1);
00452 }
00453 
00456 static const char *
00457 extract_escaped_string(const char *start, size_t in_len_max,
00458                        char **out, size_t *out_len)
00459 {
00460   int length = get_escaped_string_length(start, in_len_max, NULL);
00461   if (length<0)
00462     return NULL;
00463   *out_len = length;
00464   *out = tor_strndup(start, *out_len);
00465   return start+length;
00466 }
00467 
00476 static const char *
00477 decode_escaped_string(const char *start, size_t in_len_max,
00478                    char **out, size_t *out_len)
00479 {
00480   const char *cp, *end;
00481   char *outp;
00482   int len, n_chars = 0;
00483 
00484   len = get_escaped_string_length(start, in_len_max, &n_chars);
00485   if (len<0)
00486     return NULL;
00487 
00488   end = start+len-1; /* Index of last quote. */
00489   tor_assert(*end == '\"');
00490   outp = *out = tor_malloc(len+1);
00491   *out_len = n_chars;
00492 
00493   cp = start+1;
00494   while (cp < end) {
00495     if (*cp == '\\')
00496       ++cp;
00497     *outp++ = *cp++;
00498   }
00499   *outp = '\0';
00500   tor_assert((outp - *out) == (int)*out_len);
00501 
00502   return end+1;
00503 }
00504 
00507 static void
00508 connection_printf_to_buf(control_connection_t *conn, const char *format, ...)
00509 {
00510   va_list ap;
00511   char *buf = NULL;
00512   int len;
00513 
00514   va_start(ap,format);
00515   len = tor_vasprintf(&buf, format, ap);
00516   va_end(ap);
00517 
00518   if (len < 0) {
00519     log_err(LD_BUG, "Unable to format string for controller.");
00520     tor_assert(0);
00521   }
00522 
00523   connection_write_to_buf(buf, (size_t)len, TO_CONN(conn));
00524 
00525   tor_free(buf);
00526 }
00527 
00529 void
00530 control_ports_write_to_file(void)
00531 {
00532   smartlist_t *lines;
00533   char *joined = NULL;
00534   const or_options_t *options = get_options();
00535 
00536   if (!options->ControlPortWriteToFile)
00537     return;
00538 
00539   lines = smartlist_new();
00540 
00541   SMARTLIST_FOREACH_BEGIN(get_connection_array(), const connection_t *, conn) {
00542     if (conn->type != CONN_TYPE_CONTROL_LISTENER || conn->marked_for_close)
00543       continue;
00544 #ifdef AF_UNIX
00545     if (conn->socket_family == AF_UNIX) {
00546       smartlist_add_asprintf(lines, "UNIX_PORT=%s\n", conn->address);
00547       continue;
00548     }
00549 #endif
00550     smartlist_add_asprintf(lines, "PORT=%s:%d\n", conn->address, conn->port);
00551   } SMARTLIST_FOREACH_END(conn);
00552 
00553   joined = smartlist_join_strings(lines, "", 0, NULL);
00554 
00555   if (write_str_to_file(options->ControlPortWriteToFile, joined, 0) < 0) {
00556     log_warn(LD_CONTROL, "Writing %s failed: %s",
00557              options->ControlPortWriteToFile, strerror(errno));
00558   }
00559 #ifndef _WIN32
00560   if (options->ControlPortFileGroupReadable) {
00561     if (chmod(options->ControlPortWriteToFile, 0640)) {
00562       log_warn(LD_FS,"Unable to make %s group-readable.",
00563                options->ControlPortWriteToFile);
00564     }
00565   }
00566 #endif
00567   tor_free(joined);
00568   SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
00569   smartlist_free(lines);
00570 }
00571 
00573 static void
00574 send_control_done(control_connection_t *conn)
00575 {
00576   connection_write_str_to_buf("250 OK\r\n", conn);
00577 }
00578 
00589 static void
00590 send_control_event_string(uint16_t event, event_format_t which,
00591                           const char *msg)
00592 {
00593   smartlist_t *conns = get_connection_array();
00594   (void)which;
00595   tor_assert(event >= _EVENT_MIN && event <= _EVENT_MAX);
00596 
00597   SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
00598     if (conn->type == CONN_TYPE_CONTROL &&
00599         !conn->marked_for_close &&
00600         conn->state == CONTROL_CONN_STATE_OPEN) {
00601       control_connection_t *control_conn = TO_CONTROL_CONN(conn);
00602 
00603       if (control_conn->event_mask & (1<<event)) {
00604         int is_err = 0;
00605         connection_write_to_buf(msg, strlen(msg), TO_CONN(control_conn));
00606         if (event == EVENT_ERR_MSG)
00607           is_err = 1;
00608         else if (event == EVENT_STATUS_GENERAL)
00609           is_err = !strcmpstart(msg, "STATUS_GENERAL ERR ");
00610         else if (event == EVENT_STATUS_CLIENT)
00611           is_err = !strcmpstart(msg, "STATUS_CLIENT ERR ");
00612         else if (event == EVENT_STATUS_SERVER)
00613           is_err = !strcmpstart(msg, "STATUS_SERVER ERR ");
00614         if (is_err)
00615           connection_flush(TO_CONN(control_conn));
00616       }
00617     }
00618   } SMARTLIST_FOREACH_END(conn);
00619 }
00620 
00625 static void
00626 send_control_event_impl(uint16_t event, event_format_t which,
00627                          const char *format, va_list ap)
00628 {
00629   char *buf = NULL;
00630   int len;
00631 
00632   len = tor_vasprintf(&buf, format, ap);
00633   if (len < 0) {
00634     log_warn(LD_BUG, "Unable to format event for controller.");
00635     return;
00636   }
00637 
00638   send_control_event_string(event, which|ALL_FORMATS, buf);
00639 
00640   tor_free(buf);
00641 }
00642 
00646 static void
00647 send_control_event(uint16_t event, event_format_t which,
00648                    const char *format, ...)
00649 {
00650   va_list ap;
00651   va_start(ap, format);
00652   send_control_event_impl(event, which, format, ap);
00653   va_end(ap);
00654 }
00655 
00657 static origin_circuit_t *
00658 get_circ(const char *id)
00659 {
00660   uint32_t n_id;
00661   int ok;
00662   n_id = (uint32_t) tor_parse_ulong(id, 10, 0, UINT32_MAX, &ok, NULL);
00663   if (!ok)
00664     return NULL;
00665   return circuit_get_by_global_id(n_id);
00666 }
00667 
00669 static entry_connection_t *
00670 get_stream(const char *id)
00671 {
00672   uint64_t n_id;
00673   int ok;
00674   connection_t *conn;
00675   n_id = tor_parse_uint64(id, 10, 0, UINT64_MAX, &ok, NULL);
00676   if (!ok)
00677     return NULL;
00678   conn = connection_get_by_global_id(n_id);
00679   if (!conn || conn->type != CONN_TYPE_AP || conn->marked_for_close)
00680     return NULL;
00681   return TO_ENTRY_CONN(conn);
00682 }
00683 
00688 static int
00689 control_setconf_helper(control_connection_t *conn, uint32_t len, char *body,
00690                        int use_defaults)
00691 {
00692   setopt_err_t opt_err;
00693   config_line_t *lines=NULL;
00694   char *start = body;
00695   char *errstring = NULL;
00696   const int clear_first = 1;
00697 
00698   char *config;
00699   smartlist_t *entries = smartlist_new();
00700 
00701   /* We have a string, "body", of the format '(key(=val|="val")?)' entries
00702    * separated by space.  break it into a list of configuration entries. */
00703   while (*body) {
00704     char *eq = body;
00705     char *key;
00706     char *entry;
00707     while (!TOR_ISSPACE(*eq) && *eq != '=')
00708       ++eq;
00709     key = tor_strndup(body, eq-body);
00710     body = eq+1;
00711     if (*eq == '=') {
00712       char *val=NULL;
00713       size_t val_len=0;
00714       if (*body != '\"') {
00715         char *val_start = body;
00716         while (!TOR_ISSPACE(*body))
00717           body++;
00718         val = tor_strndup(val_start, body-val_start);
00719         val_len = strlen(val);
00720       } else {
00721         body = (char*)extract_escaped_string(body, (len - (body-start)),
00722                                              &val, &val_len);
00723         if (!body) {
00724           connection_write_str_to_buf("551 Couldn't parse string\r\n", conn);
00725           SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
00726           smartlist_free(entries);
00727           tor_free(key);
00728           return 0;
00729         }
00730       }
00731       tor_asprintf(&entry, "%s %s", key, val);
00732       tor_free(key);
00733       tor_free(val);
00734     } else {
00735       entry = key;
00736     }
00737     smartlist_add(entries, entry);
00738     while (TOR_ISSPACE(*body))
00739       ++body;
00740   }
00741 
00742   smartlist_add(entries, tor_strdup(""));
00743   config = smartlist_join_strings(entries, "\n", 0, NULL);
00744   SMARTLIST_FOREACH(entries, char *, cp, tor_free(cp));
00745   smartlist_free(entries);
00746 
00747   if (config_get_lines(config, &lines, 0) < 0) {
00748     log_warn(LD_CONTROL,"Controller gave us config lines we can't parse.");
00749     connection_write_str_to_buf("551 Couldn't parse configuration\r\n",
00750                                 conn);
00751     tor_free(config);
00752     return 0;
00753   }
00754   tor_free(config);
00755 
00756   opt_err = options_trial_assign(lines, use_defaults, clear_first, &errstring);
00757   {
00758     const char *msg;
00759     switch (opt_err) {
00760       case SETOPT_ERR_MISC:
00761         msg = "552 Unrecognized option";
00762         break;
00763       case SETOPT_ERR_PARSE:
00764         msg = "513 Unacceptable option value";
00765         break;
00766       case SETOPT_ERR_TRANSITION:
00767         msg = "553 Transition not allowed";
00768         break;
00769       case SETOPT_ERR_SETTING:
00770       default:
00771         msg = "553 Unable to set option";
00772         break;
00773       case SETOPT_OK:
00774         config_free_lines(lines);
00775         send_control_done(conn);
00776         return 0;
00777     }
00778     log_warn(LD_CONTROL,
00779              "Controller gave us config lines that didn't validate: %s",
00780              errstring);
00781     connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
00782     config_free_lines(lines);
00783     tor_free(errstring);
00784     return 0;
00785   }
00786 }
00787 
00791 static int
00792 handle_control_setconf(control_connection_t *conn, uint32_t len, char *body)
00793 {
00794   return control_setconf_helper(conn, len, body, 0);
00795 }
00796 
00800 static int
00801 handle_control_resetconf(control_connection_t *conn, uint32_t len, char *body)
00802 {
00803   return control_setconf_helper(conn, len, body, 1);
00804 }
00805 
00808 static int
00809 handle_control_getconf(control_connection_t *conn, uint32_t body_len,
00810                        const char *body)
00811 {
00812   smartlist_t *questions = smartlist_new();
00813   smartlist_t *answers = smartlist_new();
00814   smartlist_t *unrecognized = smartlist_new();
00815   char *msg = NULL;
00816   size_t msg_len;
00817   const or_options_t *options = get_options();
00818   int i, len;
00819 
00820   (void) body_len; /* body is NUL-terminated; so we can ignore len. */
00821   smartlist_split_string(questions, body, " ",
00822                          SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
00823   SMARTLIST_FOREACH(questions, const char *, q,
00824   {
00825     if (!option_is_recognized(q)) {
00826       smartlist_add(unrecognized, (char*) q);
00827     } else {
00828       config_line_t *answer = option_get_assignment(options,q);
00829       if (!answer) {
00830         const char *name = option_get_canonical_name(q);
00831         smartlist_add_asprintf(answers, "250-%s\r\n", name);
00832       }
00833 
00834       while (answer) {
00835         config_line_t *next;
00836         smartlist_add_asprintf(answers, "250-%s=%s\r\n",
00837                      answer->key, answer->value);
00838 
00839         next = answer->next;
00840         tor_free(answer->key);
00841         tor_free(answer->value);
00842         tor_free(answer);
00843         answer = next;
00844       }
00845     }
00846   });
00847 
00848   if ((len = smartlist_len(unrecognized))) {
00849     for (i=0; i < len-1; ++i)
00850       connection_printf_to_buf(conn,
00851                                "552-Unrecognized configuration key \"%s\"\r\n",
00852                                (char*)smartlist_get(unrecognized, i));
00853     connection_printf_to_buf(conn,
00854                              "552 Unrecognized configuration key \"%s\"\r\n",
00855                              (char*)smartlist_get(unrecognized, len-1));
00856   } else if ((len = smartlist_len(answers))) {
00857     char *tmp = smartlist_get(answers, len-1);
00858     tor_assert(strlen(tmp)>4);
00859     tmp[3] = ' ';
00860     msg = smartlist_join_strings(answers, "", 0, &msg_len);
00861     connection_write_to_buf(msg, msg_len, TO_CONN(conn));
00862   } else {
00863     connection_write_str_to_buf("250 OK\r\n", conn);
00864   }
00865 
00866   SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
00867   smartlist_free(answers);
00868   SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
00869   smartlist_free(questions);
00870   smartlist_free(unrecognized);
00871 
00872   tor_free(msg);
00873 
00874   return 0;
00875 }
00876 
00878 static int
00879 handle_control_loadconf(control_connection_t *conn, uint32_t len,
00880                          const char *body)
00881 {
00882   setopt_err_t retval;
00883   char *errstring = NULL;
00884   const char *msg = NULL;
00885   (void) len;
00886 
00887   retval = options_init_from_string(NULL, body, CMD_RUN_TOR, NULL, &errstring);
00888 
00889   if (retval != SETOPT_OK)
00890     log_warn(LD_CONTROL,
00891              "Controller gave us config file that didn't validate: %s",
00892              errstring);
00893 
00894   switch (retval) {
00895   case SETOPT_ERR_PARSE:
00896     msg = "552 Invalid config file";
00897     break;
00898   case SETOPT_ERR_TRANSITION:
00899     msg = "553 Transition not allowed";
00900     break;
00901   case SETOPT_ERR_SETTING:
00902     msg = "553 Unable to set option";
00903     break;
00904   case SETOPT_ERR_MISC:
00905   default:
00906     msg = "550 Unable to load config";
00907     break;
00908   case SETOPT_OK:
00909     break;
00910   }
00911   if (msg) {
00912     if (errstring)
00913       connection_printf_to_buf(conn, "%s: %s\r\n", msg, errstring);
00914     else
00915       connection_printf_to_buf(conn, "%s\r\n", msg);
00916   } else {
00917     send_control_done(conn);
00918   }
00919   tor_free(errstring);
00920   return 0;
00921 }
00922 
00924 struct control_event_t {
00925   uint16_t event_code;
00926   const char *event_name;
00927 };
00930 static const struct control_event_t control_event_table[] = {
00931   { EVENT_CIRCUIT_STATUS, "CIRC" },
00932   { EVENT_CIRCUIT_STATUS_MINOR, "CIRC_MINOR" },
00933   { EVENT_STREAM_STATUS, "STREAM" },
00934   { EVENT_OR_CONN_STATUS, "ORCONN" },
00935   { EVENT_BANDWIDTH_USED, "BW" },
00936   { EVENT_DEBUG_MSG, "DEBUG" },
00937   { EVENT_INFO_MSG, "INFO" },
00938   { EVENT_NOTICE_MSG, "NOTICE" },
00939   { EVENT_WARN_MSG, "WARN" },
00940   { EVENT_ERR_MSG, "ERR" },
00941   { EVENT_NEW_DESC, "NEWDESC" },
00942   { EVENT_ADDRMAP, "ADDRMAP" },
00943   { EVENT_AUTHDIR_NEWDESCS, "AUTHDIR_NEWDESCS" },
00944   { EVENT_DESCCHANGED, "DESCCHANGED" },
00945   { EVENT_NS, "NS" },
00946   { EVENT_STATUS_GENERAL, "STATUS_GENERAL" },
00947   { EVENT_STATUS_CLIENT, "STATUS_CLIENT" },
00948   { EVENT_STATUS_SERVER, "STATUS_SERVER" },
00949   { EVENT_GUARD, "GUARD" },
00950   { EVENT_STREAM_BANDWIDTH_USED, "STREAM_BW" },
00951   { EVENT_CLIENTS_SEEN, "CLIENTS_SEEN" },
00952   { EVENT_NEWCONSENSUS, "NEWCONSENSUS" },
00953   { EVENT_BUILDTIMEOUT_SET, "BUILDTIMEOUT_SET" },
00954   { EVENT_SIGNAL, "SIGNAL" },
00955   { EVENT_CONF_CHANGED, "CONF_CHANGED"},
00956   { 0, NULL },
00957 };
00958 
00961 static int
00962 handle_control_setevents(control_connection_t *conn, uint32_t len,
00963                          const char *body)
00964 {
00965   int event_code = -1;
00966   uint32_t event_mask = 0;
00967   smartlist_t *events = smartlist_new();
00968 
00969   (void) len;
00970 
00971   smartlist_split_string(events, body, " ",
00972                          SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
00973   SMARTLIST_FOREACH_BEGIN(events, const char *, ev)
00974     {
00975       if (!strcasecmp(ev, "EXTENDED")) {
00976         continue;
00977       } else {
00978         int i;
00979         for (i = 0; control_event_table[i].event_name != NULL; ++i) {
00980           if (!strcasecmp(ev, control_event_table[i].event_name)) {
00981             event_code = control_event_table[i].event_code;
00982             break;
00983           }
00984         }
00985 
00986         if (event_code == -1) {
00987           connection_printf_to_buf(conn, "552 Unrecognized event \"%s\"\r\n",
00988                                    ev);
00989           SMARTLIST_FOREACH(events, char *, e, tor_free(e));
00990           smartlist_free(events);
00991           return 0;
00992         }
00993       }
00994       event_mask |= (1 << event_code);
00995     }
00996   SMARTLIST_FOREACH_END(ev);
00997   SMARTLIST_FOREACH(events, char *, e, tor_free(e));
00998   smartlist_free(events);
00999 
01000   conn->event_mask = event_mask;
01001 
01002   control_update_global_event_mask();
01003   send_control_done(conn);
01004   return 0;
01005 }
01006 
01011 smartlist_t *
01012 decode_hashed_passwords(config_line_t *passwords)
01013 {
01014   char decoded[64];
01015   config_line_t *cl;
01016   smartlist_t *sl = smartlist_new();
01017 
01018   tor_assert(passwords);
01019 
01020   for (cl = passwords; cl; cl = cl->next) {
01021     const char *hashed = cl->value;
01022 
01023     if (!strcmpstart(hashed, "16:")) {
01024       if (base16_decode(decoded, sizeof(decoded), hashed+3, strlen(hashed+3))<0
01025           || strlen(hashed+3) != (S2K_SPECIFIER_LEN+DIGEST_LEN)*2) {
01026         goto err;
01027       }
01028     } else {
01029         if (base64_decode(decoded, sizeof(decoded), hashed, strlen(hashed))
01030             != S2K_SPECIFIER_LEN+DIGEST_LEN) {
01031           goto err;
01032         }
01033     }
01034     smartlist_add(sl, tor_memdup(decoded, S2K_SPECIFIER_LEN+DIGEST_LEN));
01035   }
01036 
01037   return sl;
01038 
01039  err:
01040   SMARTLIST_FOREACH(sl, char*, cp, tor_free(cp));
01041   smartlist_free(sl);
01042   return NULL;
01043 }
01044 
01049 static int
01050 handle_control_authenticate(control_connection_t *conn, uint32_t len,
01051                             const char *body)
01052 {
01053   int used_quoted_string = 0;
01054   const or_options_t *options = get_options();
01055   const char *errstr = NULL;
01056   char *password;
01057   size_t password_len;
01058   const char *cp;
01059   int i;
01060   int bad_cookie=0, bad_password=0;
01061   smartlist_t *sl = NULL;
01062 
01063   if (!len) {
01064     password = tor_strdup("");
01065     password_len = 0;
01066   } else if (TOR_ISXDIGIT(body[0])) {
01067     cp = body;
01068     while (TOR_ISXDIGIT(*cp))
01069       ++cp;
01070     i = (int)(cp - body);
01071     tor_assert(i>0);
01072     password_len = i/2;
01073     password = tor_malloc(password_len + 1);
01074     if (base16_decode(password, password_len+1, body, i)<0) {
01075       connection_write_str_to_buf(
01076             "551 Invalid hexadecimal encoding.  Maybe you tried a plain text "
01077             "password?  If so, the standard requires that you put it in "
01078             "double quotes.\r\n", conn);
01079       connection_mark_for_close(TO_CONN(conn));
01080       tor_free(password);
01081       return 0;
01082     }
01083   } else {
01084     if (!decode_escaped_string(body, len, &password, &password_len)) {
01085       connection_write_str_to_buf("551 Invalid quoted string.  You need "
01086             "to put the password in double quotes.\r\n", conn);
01087       connection_mark_for_close(TO_CONN(conn));
01088       return 0;
01089     }
01090     used_quoted_string = 1;
01091   }
01092 
01093   if (conn->safecookie_client_hash != NULL) {
01094     /* The controller has chosen safe cookie authentication; the only
01095      * acceptable authentication value is the controller-to-server
01096      * response. */
01097 
01098     tor_assert(authentication_cookie_is_set);
01099 
01100     if (password_len != DIGEST256_LEN) {
01101       log_warn(LD_CONTROL,
01102                "Got safe cookie authentication response with wrong length "
01103                "(%d)", (int)password_len);
01104       errstr = "Wrong length for safe cookie response.";
01105       goto err;
01106     }
01107 
01108     if (tor_memneq(conn->safecookie_client_hash, password, DIGEST256_LEN)) {
01109       log_warn(LD_CONTROL,
01110                "Got incorrect safe cookie authentication response");
01111       errstr = "Safe cookie response did not match expected value.";
01112       goto err;
01113     }
01114 
01115     tor_free(conn->safecookie_client_hash);
01116     goto ok;
01117   }
01118 
01119   if (!options->CookieAuthentication && !options->HashedControlPassword &&
01120       !options->HashedControlSessionPassword) {
01121     /* if Tor doesn't demand any stronger authentication, then
01122      * the controller can get in with anything. */
01123     goto ok;
01124   }
01125 
01126   if (options->CookieAuthentication) {
01127     int also_password = options->HashedControlPassword != NULL ||
01128       options->HashedControlSessionPassword != NULL;
01129     if (password_len != AUTHENTICATION_COOKIE_LEN) {
01130       if (!also_password) {
01131         log_warn(LD_CONTROL, "Got authentication cookie with wrong length "
01132                  "(%d)", (int)password_len);
01133         errstr = "Wrong length on authentication cookie.";
01134         goto err;
01135       }
01136       bad_cookie = 1;
01137     } else if (tor_memneq(authentication_cookie, password, password_len)) {
01138       if (!also_password) {
01139         log_warn(LD_CONTROL, "Got mismatched authentication cookie");
01140         errstr = "Authentication cookie did not match expected value.";
01141         goto err;
01142       }
01143       bad_cookie = 1;
01144     } else {
01145       goto ok;
01146     }
01147   }
01148 
01149   if (options->HashedControlPassword ||
01150       options->HashedControlSessionPassword) {
01151     int bad = 0;
01152     smartlist_t *sl_tmp;
01153     char received[DIGEST_LEN];
01154     int also_cookie = options->CookieAuthentication;
01155     sl = smartlist_new();
01156     if (options->HashedControlPassword) {
01157       sl_tmp = decode_hashed_passwords(options->HashedControlPassword);
01158       if (!sl_tmp)
01159         bad = 1;
01160       else {
01161         smartlist_add_all(sl, sl_tmp);
01162         smartlist_free(sl_tmp);
01163       }
01164     }
01165     if (options->HashedControlSessionPassword) {
01166       sl_tmp = decode_hashed_passwords(options->HashedControlSessionPassword);
01167       if (!sl_tmp)
01168         bad = 1;
01169       else {
01170         smartlist_add_all(sl, sl_tmp);
01171         smartlist_free(sl_tmp);
01172       }
01173     }
01174     if (bad) {
01175       if (!also_cookie) {
01176         log_warn(LD_CONTROL,
01177                  "Couldn't decode HashedControlPassword: invalid base16");
01178         errstr="Couldn't decode HashedControlPassword value in configuration.";
01179       }
01180       bad_password = 1;
01181       SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
01182       smartlist_free(sl);
01183     } else {
01184       SMARTLIST_FOREACH(sl, char *, expected,
01185       {
01186         secret_to_key(received,DIGEST_LEN,password,password_len,expected);
01187         if (tor_memeq(expected+S2K_SPECIFIER_LEN, received, DIGEST_LEN))
01188           goto ok;
01189       });
01190       SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
01191       smartlist_free(sl);
01192 
01193       if (used_quoted_string)
01194         errstr = "Password did not match HashedControlPassword value from "
01195           "configuration";
01196       else
01197         errstr = "Password did not match HashedControlPassword value from "
01198           "configuration. Maybe you tried a plain text password? "
01199           "If so, the standard requires that you put it in double quotes.";
01200       bad_password = 1;
01201       if (!also_cookie)
01202         goto err;
01203     }
01204   }
01205 
01207   tor_assert(bad_password && bad_cookie);
01208   log_warn(LD_CONTROL, "Bad password or authentication cookie on controller.");
01209   errstr = "Password did not match HashedControlPassword *or* authentication "
01210     "cookie.";
01211 
01212  err:
01213   tor_free(password);
01214   connection_printf_to_buf(conn, "515 Authentication failed: %s\r\n",
01215                            errstr ? errstr : "Unknown reason.");
01216   connection_mark_for_close(TO_CONN(conn));
01217   return 0;
01218  ok:
01219   log_info(LD_CONTROL, "Authenticated control connection (%d)", conn->_base.s);
01220   send_control_done(conn);
01221   conn->_base.state = CONTROL_CONN_STATE_OPEN;
01222   tor_free(password);
01223   if (sl) { /* clean up */
01224     SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
01225     smartlist_free(sl);
01226   }
01227   return 0;
01228 }
01229 
01232 static int
01233 handle_control_saveconf(control_connection_t *conn, uint32_t len,
01234                         const char *body)
01235 {
01236   (void) len;
01237   (void) body;
01238   if (options_save_current()<0) {
01239     connection_write_str_to_buf(
01240       "551 Unable to write configuration to disk.\r\n", conn);
01241   } else {
01242     send_control_done(conn);
01243   }
01244   return 0;
01245 }
01246 
01250 static int
01251 handle_control_signal(control_connection_t *conn, uint32_t len,
01252                       const char *body)
01253 {
01254   int sig;
01255   int n = 0;
01256   char *s;
01257 
01258   (void) len;
01259 
01260   while (body[n] && ! TOR_ISSPACE(body[n]))
01261     ++n;
01262   s = tor_strndup(body, n);
01263   if (!strcasecmp(s, "RELOAD") || !strcasecmp(s, "HUP"))
01264     sig = SIGHUP;
01265   else if (!strcasecmp(s, "SHUTDOWN") || !strcasecmp(s, "INT"))
01266     sig = SIGINT;
01267   else if (!strcasecmp(s, "DUMP") || !strcasecmp(s, "USR1"))
01268     sig = SIGUSR1;
01269   else if (!strcasecmp(s, "DEBUG") || !strcasecmp(s, "USR2"))
01270     sig = SIGUSR2;
01271   else if (!strcasecmp(s, "HALT") || !strcasecmp(s, "TERM"))
01272     sig = SIGTERM;
01273   else if (!strcasecmp(s, "NEWNYM"))
01274     sig = SIGNEWNYM;
01275   else if (!strcasecmp(s, "CLEARDNSCACHE"))
01276     sig = SIGCLEARDNSCACHE;
01277   else {
01278     connection_printf_to_buf(conn, "552 Unrecognized signal code \"%s\"\r\n",
01279                              s);
01280     sig = -1;
01281   }
01282   tor_free(s);
01283   if (sig<0)
01284     return 0;
01285 
01286   send_control_done(conn);
01287   /* Flush the "done" first if the signal might make us shut down. */
01288   if (sig == SIGTERM || sig == SIGINT)
01289     connection_flush(TO_CONN(conn));
01290 
01291   process_signal(sig);
01292 
01293   return 0;
01294 }
01295 
01299 static int
01300 handle_control_takeownership(control_connection_t *conn, uint32_t len,
01301                              const char *body)
01302 {
01303   (void)len;
01304   (void)body;
01305 
01306   conn->is_owning_control_connection = 1;
01307 
01308   log_info(LD_CONTROL, "Control connection %d has taken ownership of this "
01309            "Tor instance.",
01310            (int)(conn->_base.s));
01311 
01312   send_control_done(conn);
01313   return 0;
01314 }
01315 
01318 static int
01319 address_is_invalid_mapaddress_target(const char *addr)
01320 {
01321   if (!strcmpstart(addr, "*."))
01322     return address_is_invalid_destination(addr+2, 1);
01323   else
01324     return address_is_invalid_destination(addr, 1);
01325 }
01326 
01329 static int
01330 handle_control_mapaddress(control_connection_t *conn, uint32_t len,
01331                           const char *body)
01332 {
01333   smartlist_t *elts;
01334   smartlist_t *lines;
01335   smartlist_t *reply;
01336   char *r;
01337   size_t sz;
01338   (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
01339 
01340   lines = smartlist_new();
01341   elts = smartlist_new();
01342   reply = smartlist_new();
01343   smartlist_split_string(lines, body, " ",
01344                          SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
01345   SMARTLIST_FOREACH_BEGIN(lines, char *, line) {
01346     tor_strlower(line);
01347     smartlist_split_string(elts, line, "=", 0, 2);
01348     if (smartlist_len(elts) == 2) {
01349       const char *from = smartlist_get(elts,0);
01350       const char *to = smartlist_get(elts,1);
01351       if (address_is_invalid_mapaddress_target(to)) {
01352         smartlist_add_asprintf(reply,
01353                      "512-syntax error: invalid address '%s'", to);
01354         log_warn(LD_CONTROL,
01355                  "Skipping invalid argument '%s' in MapAddress msg", to);
01356       } else if (!strcmp(from, ".") || !strcmp(from, "0.0.0.0")) {
01357         const char *address = addressmap_register_virtual_address(
01358               !strcmp(from,".") ? RESOLVED_TYPE_HOSTNAME : RESOLVED_TYPE_IPV4,
01359                tor_strdup(to));
01360         if (!address) {
01361           smartlist_add_asprintf(reply,
01362                        "451-resource exhausted: skipping '%s'", line);
01363           log_warn(LD_CONTROL,
01364                    "Unable to allocate address for '%s' in MapAddress msg",
01365                    safe_str_client(line));
01366         } else {
01367           smartlist_add_asprintf(reply, "250-%s=%s", address, to);
01368         }
01369       } else {
01370         addressmap_register(from, tor_strdup(to), 1,
01371                             ADDRMAPSRC_CONTROLLER, 0, 0);
01372         smartlist_add_asprintf(reply, "250-%s", line);
01373       }
01374     } else {
01375       smartlist_add_asprintf(reply, "512-syntax error: mapping '%s' is "
01376                    "not of expected form 'foo=bar'.", line);
01377       log_info(LD_CONTROL, "Skipping MapAddress '%s': wrong "
01378                            "number of items.",
01379                            safe_str_client(line));
01380     }
01381     SMARTLIST_FOREACH(elts, char *, cp, tor_free(cp));
01382     smartlist_clear(elts);
01383   } SMARTLIST_FOREACH_END(line);
01384   SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
01385   smartlist_free(lines);
01386   smartlist_free(elts);
01387 
01388   if (smartlist_len(reply)) {
01389     ((char*)smartlist_get(reply,smartlist_len(reply)-1))[3] = ' ';
01390     r = smartlist_join_strings(reply, "\r\n", 1, &sz);
01391     connection_write_to_buf(r, sz, TO_CONN(conn));
01392     tor_free(r);
01393   } else {
01394     const char *response =
01395       "512 syntax error: not enough arguments to mapaddress.\r\n";
01396     connection_write_to_buf(response, strlen(response), TO_CONN(conn));
01397   }
01398 
01399   SMARTLIST_FOREACH(reply, char *, cp, tor_free(cp));
01400   smartlist_free(reply);
01401   return 0;
01402 }
01403 
01406 static int
01407 getinfo_helper_misc(control_connection_t *conn, const char *question,
01408                     char **answer, const char **errmsg)
01409 {
01410   (void) conn;
01411   if (!strcmp(question, "version")) {
01412     *answer = tor_strdup(get_version());
01413   } else if (!strcmp(question, "config-file")) {
01414     *answer = tor_strdup(get_torrc_fname(0));
01415   } else if (!strcmp(question, "config-defaults-file")) {
01416     *answer = tor_strdup(get_torrc_fname(1));
01417   } else if (!strcmp(question, "config-text")) {
01418     *answer = options_dump(get_options(), 1);
01419   } else if (!strcmp(question, "info/names")) {
01420     *answer = list_getinfo_options();
01421   } else if (!strcmp(question, "dormant")) {
01422     int dormant = rep_hist_circbuilding_dormant(time(NULL));
01423     *answer = tor_strdup(dormant ? "1" : "0");
01424   } else if (!strcmp(question, "events/names")) {
01425     int i;
01426     smartlist_t *event_names = smartlist_new();
01427 
01428     for (i = 0; control_event_table[i].event_name != NULL; ++i) {
01429       smartlist_add(event_names, (char *)control_event_table[i].event_name);
01430     }
01431 
01432     *answer = smartlist_join_strings(event_names, " ", 0, NULL);
01433 
01434     smartlist_free(event_names);
01435   } else if (!strcmp(question, "features/names")) {
01436     *answer = tor_strdup("VERBOSE_NAMES EXTENDED_EVENTS");
01437   } else if (!strcmp(question, "address")) {
01438     uint32_t addr;
01439     if (router_pick_published_address(get_options(), &addr) < 0) {
01440       *errmsg = "Address unknown";
01441       return -1;
01442     }
01443     *answer = tor_dup_ip(addr);
01444   } else if (!strcmp(question, "traffic/read")) {
01445     tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_read()));
01446   } else if (!strcmp(question, "traffic/written")) {
01447     tor_asprintf(answer, U64_FORMAT, U64_PRINTF_ARG(get_bytes_written()));
01448   } else if (!strcmp(question, "process/pid")) {
01449     int myPid = -1;
01450 
01451     #ifdef _WIN32
01452       myPid = _getpid();
01453     #else
01454       myPid = getpid();
01455     #endif
01456 
01457     tor_asprintf(answer, "%d", myPid);
01458   } else if (!strcmp(question, "process/uid")) {
01459     #ifdef _WIN32
01460       *answer = tor_strdup("-1");
01461     #else
01462       int myUid = geteuid();
01463       tor_asprintf(answer, "%d", myUid);
01464     #endif
01465   } else if (!strcmp(question, "process/user")) {
01466     #ifdef _WIN32
01467       *answer = tor_strdup("");
01468     #else
01469       int myUid = geteuid();
01470       struct passwd *myPwEntry = getpwuid(myUid);
01471 
01472       if (myPwEntry) {
01473         *answer = tor_strdup(myPwEntry->pw_name);
01474       } else {
01475         *answer = tor_strdup("");
01476       }
01477     #endif
01478   } else if (!strcmp(question, "process/descriptor-limit")) {
01479     int max_fds=-1;
01480     set_max_file_descriptors(0, &max_fds);
01481     tor_asprintf(answer, "%d", max_fds);
01482   } else if (!strcmp(question, "dir-usage")) {
01483     *answer = directory_dump_request_log();
01484   } else if (!strcmp(question, "fingerprint")) {
01485     crypto_pk_t *server_key;
01486     if (!server_mode(get_options())) {
01487       *errmsg = "Not running in server mode";
01488       return -1;
01489     }
01490     server_key = get_server_identity_key();
01491     *answer = tor_malloc(HEX_DIGEST_LEN+1);
01492     crypto_pk_get_fingerprint(server_key, *answer, 0);
01493   }
01494   return 0;
01495 }
01496 
01506 static char *
01507 munge_extrainfo_into_routerinfo(const char *ri_body,
01508                                 const signed_descriptor_t *ri,
01509                                 const signed_descriptor_t *ei)
01510 {
01511   char *out = NULL, *outp;
01512   int i;
01513   const char *router_sig;
01514   const char *ei_body = signed_descriptor_get_body(ei);
01515   size_t ri_len = ri->signed_descriptor_len;
01516   size_t ei_len = ei->signed_descriptor_len;
01517   if (!ei_body)
01518     goto bail;
01519 
01520   outp = out = tor_malloc(ri_len+ei_len+1);
01521   if (!(router_sig = tor_memstr(ri_body, ri_len, "\nrouter-signature")))
01522     goto bail;
01523   ++router_sig;
01524   memcpy(out, ri_body, router_sig-ri_body);
01525   outp += router_sig-ri_body;
01526 
01527   for (i=0; i < 2; ++i) {
01528     const char *kwd = i?"\nwrite-history ":"\nread-history ";
01529     const char *cp, *eol;
01530     if (!(cp = tor_memstr(ei_body, ei_len, kwd)))
01531       continue;
01532     ++cp;
01533     eol = memchr(cp, '\n', ei_len - (cp-ei_body));
01534     memcpy(outp, cp, eol-cp+1);
01535     outp += eol-cp+1;
01536   }
01537   memcpy(outp, router_sig, ri_len - (router_sig-ri_body));
01538   *outp++ = '\0';
01539   tor_assert(outp-out < (int)(ri_len+ei_len+1));
01540 
01541   return out;
01542  bail:
01543   tor_free(out);
01544   return tor_strndup(ri_body, ri->signed_descriptor_len);
01545 }
01546 
01549 static int
01550 getinfo_helper_listeners(control_connection_t *control_conn,
01551                          const char *question,
01552                          char **answer, const char **errmsg)
01553 {
01554   int type;
01555   smartlist_t *res;
01556 
01557   (void)control_conn;
01558   (void)errmsg;
01559 
01560   if (!strcmp(question, "net/listeners/or"))
01561     type = CONN_TYPE_OR_LISTENER;
01562   else if (!strcmp(question, "net/listeners/dir"))
01563     type = CONN_TYPE_DIR_LISTENER;
01564   else if (!strcmp(question, "net/listeners/socks"))
01565     type = CONN_TYPE_AP_LISTENER;
01566   else if (!strcmp(question, "net/listeners/trans"))
01567     type = CONN_TYPE_AP_TRANS_LISTENER;
01568   else if (!strcmp(question, "net/listeners/natd"))
01569     type = CONN_TYPE_AP_NATD_LISTENER;
01570   else if (!strcmp(question, "net/listeners/dns"))
01571     type = CONN_TYPE_AP_DNS_LISTENER;
01572   else if (!strcmp(question, "net/listeners/control"))
01573     type = CONN_TYPE_CONTROL_LISTENER;
01574   else
01575     return 0; /* unknown key */
01576 
01577   res = smartlist_new();
01578   SMARTLIST_FOREACH_BEGIN(get_connection_array(), connection_t *, conn) {
01579     struct sockaddr_storage ss;
01580     socklen_t ss_len = sizeof(ss);
01581 
01582     if (conn->type != type || conn->marked_for_close || !SOCKET_OK(conn->s))
01583       continue;
01584 
01585     if (getsockname(conn->s, (struct sockaddr *)&ss, &ss_len) < 0) {
01586       smartlist_add_asprintf(res, "%s:%d", conn->address, (int)conn->port);
01587     } else {
01588       char *tmp = tor_sockaddr_to_str((struct sockaddr *)&ss);
01589       smartlist_add(res, esc_for_log(tmp));
01590       tor_free(tmp);
01591     }
01592 
01593   } SMARTLIST_FOREACH_END(conn);
01594 
01595   *answer = smartlist_join_strings(res, " ", 0, NULL);
01596 
01597   SMARTLIST_FOREACH(res, char *, cp, tor_free(cp));
01598   smartlist_free(res);
01599   return 0;
01600 }
01601 
01604 static int
01605 getinfo_helper_dir(control_connection_t *control_conn,
01606                    const char *question, char **answer,
01607                    const char **errmsg)
01608 {
01609   const routerinfo_t *ri;
01610   (void) control_conn;
01611   if (!strcmpstart(question, "desc/id/")) {
01612     ri = router_get_by_hexdigest(question+strlen("desc/id/"));
01613     if (ri) {
01614       const char *body = signed_descriptor_get_body(&ri->cache_info);
01615       if (body)
01616         *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
01617     }
01618   } else if (!strcmpstart(question, "desc/name/")) {
01619     /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
01620      * warning goes to the user, not to the controller. */
01621     ri = router_get_by_nickname(question+strlen("desc/name/"),1);
01622     if (ri) {
01623       const char *body = signed_descriptor_get_body(&ri->cache_info);
01624       if (body)
01625         *answer = tor_strndup(body, ri->cache_info.signed_descriptor_len);
01626     }
01627   } else if (!strcmp(question, "desc/all-recent")) {
01628     routerlist_t *routerlist = router_get_routerlist();
01629     smartlist_t *sl = smartlist_new();
01630     if (routerlist && routerlist->routers) {
01631       SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
01632       {
01633         const char *body = signed_descriptor_get_body(&ri->cache_info);
01634         if (body)
01635           smartlist_add(sl,
01636                   tor_strndup(body, ri->cache_info.signed_descriptor_len));
01637       });
01638     }
01639     *answer = smartlist_join_strings(sl, "", 0, NULL);
01640     SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
01641     smartlist_free(sl);
01642   } else if (!strcmp(question, "desc/all-recent-extrainfo-hack")) {
01643     /* XXXX Remove this once Torstat asks for extrainfos. */
01644     routerlist_t *routerlist = router_get_routerlist();
01645     smartlist_t *sl = smartlist_new();
01646     if (routerlist && routerlist->routers) {
01647       SMARTLIST_FOREACH(routerlist->routers, const routerinfo_t *, ri,
01648       {
01649         const char *body = signed_descriptor_get_body(&ri->cache_info);
01650         signed_descriptor_t *ei = extrainfo_get_by_descriptor_digest(
01651                                      ri->cache_info.extra_info_digest);
01652         if (ei && body) {
01653           smartlist_add(sl, munge_extrainfo_into_routerinfo(body,
01654                                                         &ri->cache_info, ei));
01655         } else if (body) {
01656           smartlist_add(sl,
01657                   tor_strndup(body, ri->cache_info.signed_descriptor_len));
01658         }
01659       });
01660     }
01661     *answer = smartlist_join_strings(sl, "", 0, NULL);
01662     SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
01663     smartlist_free(sl);
01664   } else if (!strcmpstart(question, "md/id/")) {
01665     const node_t *node = node_get_by_hex_id(question+strlen("md/id/"));
01666     const microdesc_t *md = NULL;
01667     if (node) md = node->md;
01668     if (md) {
01669       tor_assert(md->body);
01670       *answer = tor_strndup(md->body, md->bodylen);
01671     }
01672   } else if (!strcmpstart(question, "md/name/")) {
01673     /* XXX023 Setting 'warn_if_unnamed' here is a bit silly -- the
01674      * warning goes to the user, not to the controller. */
01675     const node_t *node = node_get_by_nickname(question+strlen("md/name/"), 1);
01676     /* XXXX duplicated code */
01677     const microdesc_t *md = NULL;
01678     if (node) md = node->md;
01679     if (md) {
01680       tor_assert(md->body);
01681       *answer = tor_strndup(md->body, md->bodylen);
01682     }
01683   } else if (!strcmpstart(question, "desc-annotations/id/")) {
01684     ri = router_get_by_hexdigest(question+
01685                                  strlen("desc-annotations/id/"));
01686     if (ri) {
01687       const char *annotations =
01688         signed_descriptor_get_annotations(&ri->cache_info);
01689       if (annotations)
01690         *answer = tor_strndup(annotations,
01691                               ri->cache_info.annotations_len);
01692     }
01693   } else if (!strcmpstart(question, "dir/server/")) {
01694     size_t answer_len = 0;
01695     char *url = NULL;
01696     smartlist_t *descs = smartlist_new();
01697     const char *msg;
01698     int res;
01699     char *cp;
01700     tor_asprintf(&url, "/tor/%s", question+4);
01701     res = dirserv_get_routerdescs(descs, url, &msg);
01702     if (res) {
01703       log_warn(LD_CONTROL, "getinfo '%s': %s", question, msg);
01704       smartlist_free(descs);
01705       tor_free(url);
01706       *errmsg = msg;
01707       return -1;
01708     }
01709     SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
01710                       answer_len += sd->signed_descriptor_len);
01711     cp = *answer = tor_malloc(answer_len+1);
01712     SMARTLIST_FOREACH(descs, signed_descriptor_t *, sd,
01713                       {
01714                         memcpy(cp, signed_descriptor_get_body(sd),
01715                                sd->signed_descriptor_len);
01716                         cp += sd->signed_descriptor_len;
01717                       });
01718     *cp = '\0';
01719     tor_free(url);
01720     smartlist_free(descs);
01721   } else if (!strcmpstart(question, "dir/status/")) {
01722     if (directory_permits_controller_requests(get_options())) {
01723       size_t len=0;
01724       char *cp;
01725       smartlist_t *status_list = smartlist_new();
01726       dirserv_get_networkstatus_v2(status_list,
01727                                    question+strlen("dir/status/"));
01728       SMARTLIST_FOREACH(status_list, cached_dir_t *, d, len += d->dir_len);
01729       cp = *answer = tor_malloc(len+1);
01730       SMARTLIST_FOREACH(status_list, cached_dir_t *, d, {
01731           memcpy(cp, d->dir, d->dir_len);
01732           cp += d->dir_len;
01733         });
01734       *cp = '\0';
01735       smartlist_free(status_list);
01736     } else {
01737       smartlist_t *fp_list = smartlist_new();
01738       smartlist_t *status_list = smartlist_new();
01739       dirserv_get_networkstatus_v2_fingerprints(
01740                              fp_list, question+strlen("dir/status/"));
01741       SMARTLIST_FOREACH(fp_list, const char *, fp, {
01742           char *s;
01743           char *fname = networkstatus_get_cache_filename(fp);
01744           s = read_file_to_str(fname, 0, NULL);
01745           if (s)
01746             smartlist_add(status_list, s);
01747           tor_free(fname);
01748         });
01749       SMARTLIST_FOREACH(fp_list, char *, fp, tor_free(fp));
01750       smartlist_free(fp_list);
01751       *answer = smartlist_join_strings(status_list, "", 0, NULL);
01752       SMARTLIST_FOREACH(status_list, char *, s, tor_free(s));
01753       smartlist_free(status_list);
01754     }
01755   } else if (!strcmp(question, "dir/status-vote/current/consensus")) { /* v3 */
01756     if (directory_caches_dir_info(get_options())) {
01757       const cached_dir_t *consensus = dirserv_get_consensus("ns");
01758       if (consensus)
01759         *answer = tor_strdup(consensus->dir);
01760     }
01761     if (!*answer) { /* try loading it from disk */
01762       char *filename = get_datadir_fname("cached-consensus");
01763       *answer = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
01764       tor_free(filename);
01765     }
01766   } else if (!strcmp(question, "network-status")) { /* v1 */
01767     routerlist_t *routerlist = router_get_routerlist();
01768     if (!routerlist || !routerlist->routers ||
01769         list_server_status_v1(routerlist->routers, answer, 1) < 0) {
01770       return -1;
01771     }
01772   } else if (!strcmpstart(question, "extra-info/digest/")) {
01773     question += strlen("extra-info/digest/");
01774     if (strlen(question) == HEX_DIGEST_LEN) {
01775       char d[DIGEST_LEN];
01776       signed_descriptor_t *sd = NULL;
01777       if (base16_decode(d, sizeof(d), question, strlen(question))==0) {
01778         /* XXXX this test should move into extrainfo_get_by_descriptor_digest,
01779          * but I don't want to risk affecting other parts of the code,
01780          * especially since the rules for using our own extrainfo (including
01781          * when it might be freed) are different from those for using one
01782          * we have downloaded. */
01783         if (router_extrainfo_digest_is_me(d))
01784           sd = &(router_get_my_extrainfo()->cache_info);
01785         else
01786           sd = extrainfo_get_by_descriptor_digest(d);
01787       }
01788       if (sd) {
01789         const char *body = signed_descriptor_get_body(sd);
01790         if (body)
01791           *answer = tor_strndup(body, sd->signed_descriptor_len);
01792       }
01793     }
01794   }
01795 
01796   return 0;
01797 }
01798 
01801 static char *
01802 circuit_describe_status_for_controller(origin_circuit_t *circ)
01803 {
01804   char *rv;
01805   smartlist_t *descparts = smartlist_new();
01806 
01807   {
01808     char *vpath = circuit_list_path_for_controller(circ);
01809     if (*vpath) {
01810       smartlist_add(descparts, vpath);
01811     } else {
01812       tor_free(vpath); /* empty path; don't put an extra space in the result */
01813     }
01814   }
01815 
01816   {
01817     cpath_build_state_t *build_state = circ->build_state;
01818     smartlist_t *flaglist = smartlist_new();
01819     char *flaglist_joined;
01820 
01821     if (build_state->onehop_tunnel)
01822       smartlist_add(flaglist, (void *)"ONEHOP_TUNNEL");
01823     if (build_state->is_internal)
01824       smartlist_add(flaglist, (void *)"IS_INTERNAL");
01825     if (build_state->need_capacity)
01826       smartlist_add(flaglist, (void *)"NEED_CAPACITY");
01827     if (build_state->need_uptime)
01828       smartlist_add(flaglist, (void *)"NEED_UPTIME");
01829 
01830     /* Only emit a BUILD_FLAGS argument if it will have a non-empty value. */
01831     if (smartlist_len(flaglist)) {
01832       flaglist_joined = smartlist_join_strings(flaglist, ",", 0, NULL);
01833 
01834       smartlist_add_asprintf(descparts, "BUILD_FLAGS=%s", flaglist_joined);
01835 
01836       tor_free(flaglist_joined);
01837     }
01838 
01839     smartlist_free(flaglist);
01840   }
01841 
01842   smartlist_add_asprintf(descparts, "PURPOSE=%s",
01843                     circuit_purpose_to_controller_string(circ->_base.purpose));
01844 
01845   {
01846     const char *hs_state =
01847       circuit_purpose_to_controller_hs_state_string(circ->_base.purpose);
01848 
01849     if (hs_state != NULL) {
01850       smartlist_add_asprintf(descparts, "HS_STATE=%s", hs_state);
01851     }
01852   }
01853 
01854   if (circ->rend_data != NULL) {
01855     smartlist_add_asprintf(descparts, "REND_QUERY=%s",
01856                  circ->rend_data->onion_address);
01857   }
01858 
01859   {
01860     char tbuf[ISO_TIME_USEC_LEN+1];
01861     format_iso_time_nospace_usec(tbuf, &circ->_base.timestamp_created);
01862 
01863     smartlist_add_asprintf(descparts, "TIME_CREATED=%s", tbuf);
01864   }
01865 
01866   rv = smartlist_join_strings(descparts, " ", 0, NULL);
01867 
01868   SMARTLIST_FOREACH(descparts, char *, cp, tor_free(cp));
01869   smartlist_free(descparts);
01870 
01871   return rv;
01872 }
01873 
01876 static int
01877 getinfo_helper_events(control_connection_t *control_conn,
01878                       const char *question, char **answer,
01879                       const char **errmsg)
01880 {
01881   (void) control_conn;
01882   if (!strcmp(question, "circuit-status")) {
01883     circuit_t *circ_;
01884     smartlist_t *status = smartlist_new();
01885     for (circ_ = _circuit_get_global_list(); circ_; circ_ = circ_->next) {
01886       origin_circuit_t *circ;
01887       char *circdesc;
01888       const char *state;
01889       if (! CIRCUIT_IS_ORIGIN(circ_) || circ_->marked_for_close)
01890         continue;
01891       circ = TO_ORIGIN_CIRCUIT(circ_);
01892 
01893       if (circ->_base.state == CIRCUIT_STATE_OPEN)
01894         state = "BUILT";
01895       else if (circ->cpath)
01896         state = "EXTENDED";
01897       else
01898         state = "LAUNCHED";
01899 
01900       circdesc = circuit_describe_status_for_controller(circ);
01901 
01902       smartlist_add_asprintf(status, "%lu %s%s%s",
01903                    (unsigned long)circ->global_identifier,
01904                    state, *circdesc ? " " : "", circdesc);
01905       tor_free(circdesc);
01906     }
01907     *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
01908     SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
01909     smartlist_free(status);
01910   } else if (!strcmp(question, "stream-status")) {
01911     smartlist_t *conns = get_connection_array();
01912     smartlist_t *status = smartlist_new();
01913     char buf[256];
01914     SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
01915       const char *state;
01916       entry_connection_t *conn;
01917       circuit_t *circ;
01918       origin_circuit_t *origin_circ = NULL;
01919       if (base_conn->type != CONN_TYPE_AP ||
01920           base_conn->marked_for_close ||
01921           base_conn->state == AP_CONN_STATE_SOCKS_WAIT ||
01922           base_conn->state == AP_CONN_STATE_NATD_WAIT)
01923         continue;
01924       conn = TO_ENTRY_CONN(base_conn);
01925       switch (base_conn->state)
01926         {
01927         case AP_CONN_STATE_CONTROLLER_WAIT:
01928         case AP_CONN_STATE_CIRCUIT_WAIT:
01929           if (conn->socks_request &&
01930               SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
01931             state = "NEWRESOLVE";
01932           else
01933             state = "NEW";
01934           break;
01935         case AP_CONN_STATE_RENDDESC_WAIT:
01936         case AP_CONN_STATE_CONNECT_WAIT:
01937           state = "SENTCONNECT"; break;
01938         case AP_CONN_STATE_RESOLVE_WAIT:
01939           state = "SENTRESOLVE"; break;
01940         case AP_CONN_STATE_OPEN:
01941           state = "SUCCEEDED"; break;
01942         default:
01943           log_warn(LD_BUG, "Asked for stream in unknown state %d",
01944                    base_conn->state);
01945           continue;
01946         }
01947       circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
01948       if (circ && CIRCUIT_IS_ORIGIN(circ))
01949         origin_circ = TO_ORIGIN_CIRCUIT(circ);
01950       write_stream_target_to_buf(conn, buf, sizeof(buf));
01951       smartlist_add_asprintf(status, "%lu %s %lu %s",
01952                    (unsigned long) base_conn->global_identifier,state,
01953                    origin_circ?
01954                          (unsigned long)origin_circ->global_identifier : 0ul,
01955                    buf);
01956     } SMARTLIST_FOREACH_END(base_conn);
01957     *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
01958     SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
01959     smartlist_free(status);
01960   } else if (!strcmp(question, "orconn-status")) {
01961     smartlist_t *conns = get_connection_array();
01962     smartlist_t *status = smartlist_new();
01963     SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
01964       const char *state;
01965       char name[128];
01966       or_connection_t *conn;
01967       if (base_conn->type != CONN_TYPE_OR || base_conn->marked_for_close)
01968         continue;
01969       conn = TO_OR_CONN(base_conn);
01970       if (conn->_base.state == OR_CONN_STATE_OPEN)
01971         state = "CONNECTED";
01972       else if (conn->nickname)
01973         state = "LAUNCHED";
01974       else
01975         state = "NEW";
01976       orconn_target_get_name(name, sizeof(name), conn);
01977       smartlist_add_asprintf(status, "%s %s", name, state);
01978     } SMARTLIST_FOREACH_END(base_conn);
01979     *answer = smartlist_join_strings(status, "\r\n", 0, NULL);
01980     SMARTLIST_FOREACH(status, char *, cp, tor_free(cp));
01981     smartlist_free(status);
01982   } else if (!strcmpstart(question, "address-mappings/")) {
01983     time_t min_e, max_e;
01984     smartlist_t *mappings;
01985     question += strlen("address-mappings/");
01986     if (!strcmp(question, "all")) {
01987       min_e = 0; max_e = TIME_MAX;
01988     } else if (!strcmp(question, "cache")) {
01989       min_e = 2; max_e = TIME_MAX;
01990     } else if (!strcmp(question, "config")) {
01991       min_e = 0; max_e = 0;
01992     } else if (!strcmp(question, "control")) {
01993       min_e = 1; max_e = 1;
01994     } else {
01995       return 0;
01996     }
01997     mappings = smartlist_new();
01998     addressmap_get_mappings(mappings, min_e, max_e, 1);
01999     *answer = smartlist_join_strings(mappings, "\r\n", 0, NULL);
02000     SMARTLIST_FOREACH(mappings, char *, cp, tor_free(cp));
02001     smartlist_free(mappings);
02002   } else if (!strcmpstart(question, "status/")) {
02003     /* Note that status/ is not a catch-all for events; there's only supposed
02004      * to be a status GETINFO if there's a corresponding STATUS event. */
02005     if (!strcmp(question, "status/circuit-established")) {
02006       *answer = tor_strdup(can_complete_circuit ? "1" : "0");
02007     } else if (!strcmp(question, "status/enough-dir-info")) {
02008       *answer = tor_strdup(router_have_minimum_dir_info() ? "1" : "0");
02009     } else if (!strcmp(question, "status/good-server-descriptor") ||
02010                !strcmp(question, "status/accepted-server-descriptor")) {
02011       /* They're equivalent for now, until we can figure out how to make
02012        * good-server-descriptor be what we want. See comment in
02013        * control-spec.txt. */
02014       *answer = tor_strdup(directories_have_accepted_server_descriptor()
02015                            ? "1" : "0");
02016     } else if (!strcmp(question, "status/reachability-succeeded/or")) {
02017       *answer = tor_strdup(check_whether_orport_reachable() ? "1" : "0");
02018     } else if (!strcmp(question, "status/reachability-succeeded/dir")) {
02019       *answer = tor_strdup(check_whether_dirport_reachable() ? "1" : "0");
02020     } else if (!strcmp(question, "status/reachability-succeeded")) {
02021       tor_asprintf(answer, "OR=%d DIR=%d",
02022                    check_whether_orport_reachable() ? 1 : 0,
02023                    check_whether_dirport_reachable() ? 1 : 0);
02024     } else if (!strcmp(question, "status/bootstrap-phase")) {
02025       *answer = tor_strdup(last_sent_bootstrap_message);
02026     } else if (!strcmpstart(question, "status/version/")) {
02027       int is_server = server_mode(get_options());
02028       networkstatus_t *c = networkstatus_get_latest_consensus();
02029       version_status_t status;
02030       const char *recommended;
02031       if (c) {
02032         recommended = is_server ? c->server_versions : c->client_versions;
02033         status = tor_version_is_obsolete(VERSION, recommended);
02034       } else {
02035         recommended = "?";
02036         status = VS_UNKNOWN;
02037       }
02038 
02039       if (!strcmp(question, "status/version/recommended")) {
02040         *answer = tor_strdup(recommended);
02041         return 0;
02042       }
02043       if (!strcmp(question, "status/version/current")) {
02044         switch (status)
02045           {
02046           case VS_RECOMMENDED: *answer = tor_strdup("recommended"); break;
02047           case VS_OLD: *answer = tor_strdup("obsolete"); break;
02048           case VS_NEW: *answer = tor_strdup("new"); break;
02049           case VS_NEW_IN_SERIES: *answer = tor_strdup("new in series"); break;
02050           case VS_UNRECOMMENDED: *answer = tor_strdup("unrecommended"); break;
02051           case VS_EMPTY: *answer = tor_strdup("none recommended"); break;
02052           case VS_UNKNOWN: *answer = tor_strdup("unknown"); break;
02053           default: tor_fragile_assert();
02054           }
02055       } else if (!strcmp(question, "status/version/num-versioning") ||
02056                  !strcmp(question, "status/version/num-concurring")) {
02057         tor_asprintf(answer, "%d", get_n_authorities(V3_DIRINFO));
02058         log_warn(LD_GENERAL, "%s is deprecated; it no longer gives useful "
02059                  "information", question);
02060       }
02061     } else if (!strcmp(question, "status/clients-seen")) {
02062       char *bridge_stats = geoip_get_bridge_stats_controller(time(NULL));
02063       if (!bridge_stats) {
02064         *errmsg = "No bridge-client stats available";
02065         return -1;
02066       }
02067       *answer = bridge_stats;
02068     } else {
02069       return 0;
02070     }
02071   }
02072   return 0;
02073 }
02074 
02082 typedef int (*getinfo_helper_t)(control_connection_t *,
02083                                 const char *q, char **a,
02084                                 const char **error_out);
02085 
02087 typedef struct getinfo_item_t {
02088   const char *varname; 
02089   getinfo_helper_t fn; 
02091   const char *desc; 
02092   int is_prefix; 
02093 } getinfo_item_t;
02094 
02095 #define ITEM(name, fn, desc) { name, getinfo_helper_##fn, desc, 0 }
02096 #define PREFIX(name, fn, desc) { name, getinfo_helper_##fn, desc, 1 }
02097 #define DOC(name, desc) { name, NULL, desc, 0 }
02098 
02101 static const getinfo_item_t getinfo_items[] = {
02102   ITEM("version", misc, "The current version of Tor."),
02103   ITEM("config-file", misc, "Current location of the \"torrc\" file."),
02104   ITEM("config-defaults-file", misc, "Current location of the defaults file."),
02105   ITEM("config-text", misc,
02106        "Return the string that would be written by a saveconf command."),
02107   ITEM("accounting/bytes", accounting,
02108        "Number of bytes read/written so far in the accounting interval."),
02109   ITEM("accounting/bytes-left", accounting,
02110       "Number of bytes left to write/read so far in the accounting interval."),
02111   ITEM("accounting/enabled", accounting, "Is accounting currently enabled?"),
02112   ITEM("accounting/hibernating", accounting, "Are we hibernating or awake?"),
02113   ITEM("accounting/interval-start", accounting,
02114        "Time when the accounting period starts."),
02115   ITEM("accounting/interval-end", accounting,
02116        "Time when the accounting period ends."),
02117   ITEM("accounting/interval-wake", accounting,
02118        "Time to wake up in this accounting period."),
02119   ITEM("helper-nodes", entry_guards, NULL), /* deprecated */
02120   ITEM("entry-guards", entry_guards,
02121        "Which nodes are we using as entry guards?"),
02122   ITEM("fingerprint", misc, NULL),
02123   PREFIX("config/", config, "Current configuration values."),
02124   DOC("config/names",
02125       "List of configuration options, types, and documentation."),
02126   ITEM("info/names", misc,
02127        "List of GETINFO options, types, and documentation."),
02128   ITEM("events/names", misc,
02129        "Events that the controller can ask for with SETEVENTS."),
02130   ITEM("features/names", misc, "What arguments can USEFEATURE take?"),
02131   PREFIX("desc/id/", dir, "Router descriptors by ID."),
02132   PREFIX("desc/name/", dir, "Router descriptors by nickname."),
02133   ITEM("desc/all-recent", dir,
02134        "All non-expired, non-superseded router descriptors."),
02135   ITEM("desc/all-recent-extrainfo-hack", dir, NULL), /* Hack. */
02136   PREFIX("md/id/", dir, "Microdescriptors by ID"),
02137   PREFIX("md/name/", dir, "Microdescriptors by name"),
02138   PREFIX("extra-info/digest/", dir, "Extra-info documents by digest."),
02139   PREFIX("net/listeners/", listeners, "Bound addresses by type"),
02140   ITEM("ns/all", networkstatus,
02141        "Brief summary of router status (v2 directory format)"),
02142   PREFIX("ns/id/", networkstatus,
02143          "Brief summary of router status by ID (v2 directory format)."),
02144   PREFIX("ns/name/", networkstatus,
02145          "Brief summary of router status by nickname (v2 directory format)."),
02146   PREFIX("ns/purpose/", networkstatus,
02147          "Brief summary of router status by purpose (v2 directory format)."),
02148   ITEM("network-status", dir,
02149        "Brief summary of router status (v1 directory format)"),
02150   ITEM("circuit-status", events, "List of current circuits originating here."),
02151   ITEM("stream-status", events,"List of current streams."),
02152   ITEM("orconn-status", events, "A list of current OR connections."),
02153   ITEM("dormant", misc,
02154        "Is Tor dormant (not building circuits because it's idle)?"),
02155   PREFIX("address-mappings/", events, NULL),
02156   DOC("address-mappings/all", "Current address mappings."),
02157   DOC("address-mappings/cache", "Current cached DNS replies."),
02158   DOC("address-mappings/config",
02159       "Current address mappings from configuration."),
02160   DOC("address-mappings/control", "Current address mappings from controller."),
02161   PREFIX("status/", events, NULL),
02162   DOC("status/circuit-established",
02163       "Whether we think client functionality is working."),
02164   DOC("status/enough-dir-info",
02165       "Whether we have enough up-to-date directory information to build "
02166       "circuits."),
02167   DOC("status/bootstrap-phase",
02168       "The last bootstrap phase status event that Tor sent."),
02169   DOC("status/clients-seen",
02170       "Breakdown of client countries seen by a bridge."),
02171   DOC("status/version/recommended", "List of currently recommended versions."),
02172   DOC("status/version/current", "Status of the current version."),
02173   DOC("status/version/num-versioning", "Number of versioning authorities."),
02174   DOC("status/version/num-concurring",
02175       "Number of versioning authorities agreeing on the status of the "
02176       "current version"),
02177   ITEM("address", misc, "IP address of this Tor host, if we can guess it."),
02178   ITEM("traffic/read", misc,"Bytes read since the process was started."),
02179   ITEM("traffic/written", misc,
02180        "Bytes written since the process was started."),
02181   ITEM("process/pid", misc, "Process id belonging to the main tor process."),
02182   ITEM("process/uid", misc, "User id running the tor process."),
02183   ITEM("process/user", misc,
02184        "Username under which the tor process is running."),
02185   ITEM("process/descriptor-limit", misc, "File descriptor limit."),
02186   ITEM("dir-usage", misc, "Breakdown of bytes transferred over DirPort."),
02187   PREFIX("desc-annotations/id/", dir, "Router annotations by hexdigest."),
02188   PREFIX("dir/server/", dir,"Router descriptors as retrieved from a DirPort."),
02189   PREFIX("dir/status/", dir,
02190          "v2 networkstatus docs as retrieved from a DirPort."),
02191   ITEM("dir/status-vote/current/consensus", dir,
02192        "v3 Networkstatus consensus as retrieved from a DirPort."),
02193   ITEM("exit-policy/default", policies,
02194        "The default value appended to the configured exit policy."),
02195   PREFIX("ip-to-country/", geoip, "Perform a GEOIP lookup"),
02196   { NULL, NULL, NULL, 0 }
02197 };
02198 
02200 static char *
02201 list_getinfo_options(void)
02202 {
02203   int i;
02204   smartlist_t *lines = smartlist_new();
02205   char *ans;
02206   for (i = 0; getinfo_items[i].varname; ++i) {
02207     if (!getinfo_items[i].desc)
02208       continue;
02209 
02210     smartlist_add_asprintf(lines, "%s%s -- %s\n",
02211                  getinfo_items[i].varname,
02212                  getinfo_items[i].is_prefix ? "*" : "",
02213                  getinfo_items[i].desc);
02214   }
02215   smartlist_sort_strings(lines);
02216 
02217   ans = smartlist_join_strings(lines, "", 0, NULL);
02218   SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
02219   smartlist_free(lines);
02220 
02221   return ans;
02222 }
02223 
02228 static int
02229 handle_getinfo_helper(control_connection_t *control_conn,
02230                       const char *question, char **answer,
02231                       const char **err_out)
02232 {
02233   int i;
02234   *answer = NULL; /* unrecognized key by default */
02235 
02236   for (i = 0; getinfo_items[i].varname; ++i) {
02237     int match;
02238     if (getinfo_items[i].is_prefix)
02239       match = !strcmpstart(question, getinfo_items[i].varname);
02240     else
02241       match = !strcmp(question, getinfo_items[i].varname);
02242     if (match) {
02243       tor_assert(getinfo_items[i].fn);
02244       return getinfo_items[i].fn(control_conn, question, answer, err_out);
02245     }
02246   }
02247 
02248   return 0; /* unrecognized */
02249 }
02250 
02253 static int
02254 handle_control_getinfo(control_connection_t *conn, uint32_t len,
02255                        const char *body)
02256 {
02257   smartlist_t *questions = smartlist_new();
02258   smartlist_t *answers = smartlist_new();
02259   smartlist_t *unrecognized = smartlist_new();
02260   char *msg = NULL, *ans = NULL;
02261   int i;
02262   (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
02263 
02264   smartlist_split_string(questions, body, " ",
02265                          SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
02266   SMARTLIST_FOREACH_BEGIN(questions, const char *, q) {
02267     const char *errmsg = NULL;
02268     if (handle_getinfo_helper(conn, q, &ans, &errmsg) < 0) {
02269       if (!errmsg)
02270         errmsg = "Internal error";
02271       connection_printf_to_buf(conn, "551 %s\r\n", errmsg);
02272       goto done;
02273     }
02274     if (!ans) {
02275       smartlist_add(unrecognized, (char*)q);
02276     } else {
02277       smartlist_add(answers, tor_strdup(q));
02278       smartlist_add(answers, ans);
02279     }
02280   } SMARTLIST_FOREACH_END(q);
02281   if (smartlist_len(unrecognized)) {
02282     for (i=0; i < smartlist_len(unrecognized)-1; ++i)
02283       connection_printf_to_buf(conn,
02284                                "552-Unrecognized key \"%s\"\r\n",
02285                                (char*)smartlist_get(unrecognized, i));
02286     connection_printf_to_buf(conn,
02287                              "552 Unrecognized key \"%s\"\r\n",
02288                              (char*)smartlist_get(unrecognized, i));
02289     goto done;
02290   }
02291 
02292   for (i = 0; i < smartlist_len(answers); i += 2) {
02293     char *k = smartlist_get(answers, i);
02294     char *v = smartlist_get(answers, i+1);
02295     if (!strchr(v, '\n') && !strchr(v, '\r')) {
02296       connection_printf_to_buf(conn, "250-%s=", k);
02297       connection_write_str_to_buf(v, conn);
02298       connection_write_str_to_buf("\r\n", conn);
02299     } else {
02300       char *esc = NULL;
02301       size_t esc_len;
02302       esc_len = write_escaped_data(v, strlen(v), &esc);
02303       connection_printf_to_buf(conn, "250+%s=\r\n", k);
02304       connection_write_to_buf(esc, esc_len, TO_CONN(conn));
02305       tor_free(esc);
02306     }
02307   }
02308   connection_write_str_to_buf("250 OK\r\n", conn);
02309 
02310  done:
02311   SMARTLIST_FOREACH(answers, char *, cp, tor_free(cp));
02312   smartlist_free(answers);
02313   SMARTLIST_FOREACH(questions, char *, cp, tor_free(cp));
02314   smartlist_free(questions);
02315   smartlist_free(unrecognized);
02316   tor_free(msg);
02317 
02318   return 0;
02319 }
02320 
02322 static uint8_t
02323 circuit_purpose_from_string(const char *string)
02324 {
02325   if (!strcasecmpstart(string, "purpose="))
02326     string += strlen("purpose=");
02327 
02328   if (!strcasecmp(string, "general"))
02329     return CIRCUIT_PURPOSE_C_GENERAL;
02330   else if (!strcasecmp(string, "controller"))
02331     return CIRCUIT_PURPOSE_CONTROLLER;
02332   else
02333     return CIRCUIT_PURPOSE_UNKNOWN;
02334 }
02335 
02341 static smartlist_t *
02342 getargs_helper(const char *command, control_connection_t *conn,
02343                const char *body, int min_args, int max_args)
02344 {
02345   smartlist_t *args = smartlist_new();
02346   smartlist_split_string(args, body, " ",
02347                          SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
02348   if (smartlist_len(args) < min_args) {
02349     connection_printf_to_buf(conn, "512 Missing argument to %s\r\n",command);
02350     goto err;
02351   } else if (max_args >= 0 && smartlist_len(args) > max_args) {
02352     connection_printf_to_buf(conn, "512 Too many arguments to %s\r\n",command);
02353     goto err;
02354   }
02355   return args;
02356  err:
02357   SMARTLIST_FOREACH(args, char *, s, tor_free(s));
02358   smartlist_free(args);
02359   return NULL;
02360 }
02361 
02365 static const char *
02366 find_element_starting_with(smartlist_t *sl, int start_at, const char *prefix)
02367 {
02368   int i;
02369   for (i = start_at; i < smartlist_len(sl); ++i) {
02370     const char *elt = smartlist_get(sl, i);
02371     if (!strcasecmpstart(elt, prefix))
02372       return elt;
02373   }
02374   return NULL;
02375 }
02376 
02379 static int
02380 is_keyval_pair(const char *s)
02381 {
02382   /* An argument is a key-value pair if it has an =, and it isn't of the form
02383    * $fingeprint=name */
02384   return strchr(s, '=') && s[0] != '$';
02385 }
02386 
02389 static int
02390 handle_control_extendcircuit(control_connection_t *conn, uint32_t len,
02391                              const char *body)
02392 {
02393   smartlist_t *router_nicknames=NULL, *nodes=NULL;
02394   origin_circuit_t *circ = NULL;
02395   int zero_circ;
02396   uint8_t intended_purpose = CIRCUIT_PURPOSE_C_GENERAL;
02397   smartlist_t *args;
02398   (void) len;
02399 
02400   router_nicknames = smartlist_new();
02401 
02402   args = getargs_helper("EXTENDCIRCUIT", conn, body, 1, -1);
02403   if (!args)
02404     goto done;
02405 
02406   zero_circ = !strcmp("0", (char*)smartlist_get(args,0));
02407 
02408   if (zero_circ) {
02409     const char *purp = find_element_starting_with(args, 1, "PURPOSE=");
02410 
02411     if (purp) {
02412       intended_purpose = circuit_purpose_from_string(purp);
02413       if (intended_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
02414         connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
02415         SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
02416         smartlist_free(args);
02417         goto done;
02418       }
02419     }
02420 
02421     if ((smartlist_len(args) == 1) ||
02422         (smartlist_len(args) >= 2 && is_keyval_pair(smartlist_get(args, 1)))) {
02423       // "EXTENDCIRCUIT 0" || EXTENDCIRCUIT 0 foo=bar"
02424       circ = circuit_launch(intended_purpose, CIRCLAUNCH_NEED_CAPACITY);
02425       if (!circ) {
02426         connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
02427       } else {
02428         connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
02429                   (unsigned long)circ->global_identifier);
02430       }
02431       SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
02432       smartlist_free(args);
02433       goto done;
02434     }
02435     // "EXTENDCIRCUIT 0 router1,router2" ||
02436     // "EXTENDCIRCUIT 0 router1,router2 PURPOSE=foo"
02437   }
02438 
02439   if (!zero_circ && !(circ = get_circ(smartlist_get(args,0)))) {
02440     connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
02441                              (char*)smartlist_get(args, 0));
02442     SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
02443     smartlist_free(args);
02444     goto done;
02445   }
02446 
02447   smartlist_split_string(router_nicknames, smartlist_get(args,1), ",", 0, 0);
02448 
02449   SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
02450   smartlist_free(args);
02451 
02452   nodes = smartlist_new();
02453   SMARTLIST_FOREACH(router_nicknames, const char *, n,
02454   {
02455     const node_t *node = node_get_by_nickname(n, 1);
02456     if (!node) {
02457       connection_printf_to_buf(conn, "552 No such router \"%s\"\r\n", n);
02458       goto done;
02459     }
02460     if (!node_has_descriptor(node)) {
02461       connection_printf_to_buf(conn, "552 descriptor for \"%s\"\r\n", n);
02462       goto done;
02463     }
02464     smartlist_add(nodes, (void*)node);
02465   });
02466   if (!smartlist_len(nodes)) {
02467     connection_write_str_to_buf("512 No router names provided\r\n", conn);
02468     goto done;
02469   }
02470 
02471   if (zero_circ) {
02472     /* start a new circuit */
02473     circ = origin_circuit_init(intended_purpose, 0);
02474   }
02475 
02476   /* now circ refers to something that is ready to be extended */
02477   SMARTLIST_FOREACH(nodes, const node_t *, node,
02478   {
02479     extend_info_t *info = extend_info_from_node(node, 0);
02480     tor_assert(info); /* True, since node_has_descriptor(node) == true */
02481     circuit_append_new_exit(circ, info);
02482     extend_info_free(info);
02483   });
02484 
02485   /* now that we've populated the cpath, start extending */
02486   if (zero_circ) {
02487     int err_reason = 0;
02488     if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
02489       circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
02490       connection_write_str_to_buf("551 Couldn't start circuit\r\n", conn);
02491       goto done;
02492     }
02493   } else {
02494     if (circ->_base.state == CIRCUIT_STATE_OPEN) {
02495       int err_reason = 0;
02496       circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
02497       if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
02498         log_info(LD_CONTROL,
02499                  "send_next_onion_skin failed; circuit marked for closing.");
02500         circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
02501         connection_write_str_to_buf("551 Couldn't send onion skin\r\n", conn);
02502         goto done;
02503       }
02504     }
02505   }
02506 
02507   connection_printf_to_buf(conn, "250 EXTENDED %lu\r\n",
02508                              (unsigned long)circ->global_identifier);
02509   if (zero_circ) /* send a 'launched' event, for completeness */
02510     control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);
02511  done:
02512   SMARTLIST_FOREACH(router_nicknames, char *, n, tor_free(n));
02513   smartlist_free(router_nicknames);
02514   smartlist_free(nodes);
02515   return 0;
02516 }
02517 
02520 static int
02521 handle_control_setcircuitpurpose(control_connection_t *conn,
02522                                  uint32_t len, const char *body)
02523 {
02524   origin_circuit_t *circ = NULL;
02525   uint8_t new_purpose;
02526   smartlist_t *args;
02527   (void) len; /* body is NUL-terminated, so it's safe to ignore the length. */
02528 
02529   args = getargs_helper("SETCIRCUITPURPOSE", conn, body, 2, -1);
02530   if (!args)
02531     goto done;
02532 
02533   if (!(circ = get_circ(smartlist_get(args,0)))) {
02534     connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
02535                              (char*)smartlist_get(args, 0));
02536     goto done;
02537   }
02538 
02539   {
02540     const char *purp = find_element_starting_with(args,1,"PURPOSE=");
02541     if (!purp) {
02542       connection_write_str_to_buf("552 No purpose given\r\n", conn);
02543       goto done;
02544     }
02545     new_purpose = circuit_purpose_from_string(purp);
02546     if (new_purpose == CIRCUIT_PURPOSE_UNKNOWN) {
02547       connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n", purp);
02548       goto done;
02549     }
02550   }
02551 
02552   circuit_change_purpose(TO_CIRCUIT(circ), new_purpose);
02553   connection_write_str_to_buf("250 OK\r\n", conn);
02554 
02555  done:
02556   if (args) {
02557     SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
02558     smartlist_free(args);
02559   }
02560   return 0;
02561 }
02562 
02565 static int
02566 handle_control_attachstream(control_connection_t *conn, uint32_t len,
02567                             const char *body)
02568 {
02569   entry_connection_t *ap_conn = NULL;
02570   origin_circuit_t *circ = NULL;
02571   int zero_circ;
02572   smartlist_t *args;
02573   crypt_path_t *cpath=NULL;
02574   int hop=0, hop_line_ok=1;
02575   (void) len;
02576 
02577   args = getargs_helper("ATTACHSTREAM", conn, body, 2, -1);
02578   if (!args)
02579     return 0;
02580 
02581   zero_circ = !strcmp("0", (char*)smartlist_get(args,1));
02582 
02583   if (!(ap_conn = get_stream(smartlist_get(args, 0)))) {
02584     connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
02585                              (char*)smartlist_get(args, 0));
02586   } else if (!zero_circ && !(circ = get_circ(smartlist_get(args, 1)))) {
02587     connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
02588                              (char*)smartlist_get(args, 1));
02589   } else if (circ) {
02590     const char *hopstring = find_element_starting_with(args,2,"HOP=");
02591     if (hopstring) {
02592       hopstring += strlen("HOP=");
02593       hop = (int) tor_parse_ulong(hopstring, 10, 0, INT_MAX,
02594                                   &hop_line_ok, NULL);
02595       if (!hop_line_ok) { /* broken hop line */
02596         connection_printf_to_buf(conn, "552 Bad value hop=%s\r\n", hopstring);
02597       }
02598     }
02599   }
02600   SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
02601   smartlist_free(args);
02602   if (!ap_conn || (!zero_circ && !circ) || !hop_line_ok)
02603     return 0;
02604 
02605   if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT &&
02606       ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONNECT_WAIT &&
02607       ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_RESOLVE_WAIT) {
02608     connection_write_str_to_buf(
02609                     "555 Connection is not managed by controller.\r\n",
02610                     conn);
02611     return 0;
02612   }
02613 
02614   /* Do we need to detach it first? */
02615   if (ENTRY_TO_CONN(ap_conn)->state != AP_CONN_STATE_CONTROLLER_WAIT) {
02616     edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
02617     circuit_t *tmpcirc = circuit_get_by_edge_conn(edge_conn);
02618     connection_edge_end(edge_conn, END_STREAM_REASON_TIMEOUT);
02619     /* Un-mark it as ending, since we're going to reuse it. */
02620     edge_conn->edge_has_sent_end = 0;
02621     edge_conn->end_reason = 0;
02622     if (tmpcirc)
02623       circuit_detach_stream(tmpcirc, edge_conn);
02624     TO_CONN(edge_conn)->state = AP_CONN_STATE_CONTROLLER_WAIT;
02625   }
02626 
02627   if (circ && (circ->_base.state != CIRCUIT_STATE_OPEN)) {
02628     connection_write_str_to_buf(
02629                     "551 Can't attach stream to non-open origin circuit\r\n",
02630                     conn);
02631     return 0;
02632   }
02633   /* Is this a single hop circuit? */
02634   if (circ && (circuit_get_cpath_len(circ)<2 || hop==1)) {
02635     const node_t *node = NULL;
02636     char *exit_digest;
02637     if (circ->build_state &&
02638         circ->build_state->chosen_exit &&
02639         !tor_digest_is_zero(circ->build_state->chosen_exit->identity_digest)) {
02640       exit_digest = circ->build_state->chosen_exit->identity_digest;
02641       node = node_get_by_id(exit_digest);
02642     }
02643     /* Do both the client and relay allow one-hop exit circuits? */
02644     if (!node ||
02645         !node_allows_single_hop_exits(node) ||
02646         !get_options()->AllowSingleHopCircuits) {
02647       connection_write_str_to_buf(
02648       "551 Can't attach stream to this one-hop circuit.\r\n", conn);
02649       return 0;
02650     }
02651     ap_conn->chosen_exit_name = tor_strdup(hex_str(exit_digest, DIGEST_LEN));
02652   }
02653 
02654   if (circ && hop>0) {
02655     /* find this hop in the circuit, and set cpath */
02656     cpath = circuit_get_cpath_hop(circ, hop);
02657     if (!cpath) {
02658       connection_printf_to_buf(conn,
02659                                "551 Circuit doesn't have %d hops.\r\n", hop);
02660       return 0;
02661     }
02662   }
02663   if (connection_ap_handshake_rewrite_and_attach(ap_conn, circ, cpath) < 0) {
02664     connection_write_str_to_buf("551 Unable to attach stream\r\n", conn);
02665     return 0;
02666   }
02667   send_control_done(conn);
02668   return 0;
02669 }
02670 
02673 static int
02674 handle_control_postdescriptor(control_connection_t *conn, uint32_t len,
02675                               const char *body)
02676 {
02677   char *desc;
02678   const char *msg=NULL;
02679   uint8_t purpose = ROUTER_PURPOSE_GENERAL;
02680   int cache = 0; /* eventually, we may switch this to 1 */
02681 
02682   char *cp = memchr(body, '\n', len);
02683   smartlist_t *args = smartlist_new();
02684   tor_assert(cp);
02685   *cp++ = '\0';
02686 
02687   smartlist_split_string(args, body, " ",
02688                          SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
02689   SMARTLIST_FOREACH(args, char *, option,
02690   {
02691     if (!strcasecmpstart(option, "purpose=")) {
02692       option += strlen("purpose=");
02693       purpose = router_purpose_from_string(option);
02694       if (purpose == ROUTER_PURPOSE_UNKNOWN) {
02695         connection_printf_to_buf(conn, "552 Unknown purpose \"%s\"\r\n",
02696                                  option);
02697         goto done;
02698       }
02699     } else if (!strcasecmpstart(option, "cache=")) {
02700       option += strlen("cache=");
02701       if (!strcasecmp(option, "no"))
02702         cache = 0;
02703       else if (!strcasecmp(option, "yes"))
02704         cache = 1;
02705       else {
02706         connection_printf_to_buf(conn, "552 Unknown cache request \"%s\"\r\n",
02707                                  option);
02708         goto done;
02709       }
02710     } else { /* unrecognized argument? */
02711       connection_printf_to_buf(conn,
02712         "512 Unexpected argument \"%s\" to postdescriptor\r\n", option);
02713       goto done;
02714     }
02715   });
02716 
02717   read_escaped_data(cp, len-(cp-body), &desc);
02718 
02719   switch (router_load_single_router(desc, purpose, cache, &msg)) {
02720   case -1:
02721     if (!msg) msg = "Could not parse descriptor";
02722     connection_printf_to_buf(conn, "554 %s\r\n", msg);
02723     break;
02724   case 0:
02725     if (!msg) msg = "Descriptor not added";
02726     connection_printf_to_buf(conn, "251 %s\r\n",msg);
02727     break;
02728   case 1:
02729     send_control_done(conn);
02730     break;
02731   }
02732 
02733   tor_free(desc);
02734  done:
02735   SMARTLIST_FOREACH(args, char *, arg, tor_free(arg));
02736   smartlist_free(args);
02737   return 0;
02738 }
02739 
02742 static int
02743 handle_control_redirectstream(control_connection_t *conn, uint32_t len,
02744                               const char *body)
02745 {
02746   entry_connection_t *ap_conn = NULL;
02747   char *new_addr = NULL;
02748   uint16_t new_port = 0;
02749   smartlist_t *args;
02750   (void) len;
02751 
02752   args = getargs_helper("REDIRECTSTREAM", conn, body, 2, -1);
02753   if (!args)
02754     return 0;
02755 
02756   if (!(ap_conn = get_stream(smartlist_get(args, 0)))
02757            || !ap_conn->socks_request) {
02758     connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
02759                              (char*)smartlist_get(args, 0));
02760   } else {
02761     int ok = 1;
02762     if (smartlist_len(args) > 2) { /* they included a port too */
02763       new_port = (uint16_t) tor_parse_ulong(smartlist_get(args, 2),
02764                                             10, 1, 65535, &ok, NULL);
02765     }
02766     if (!ok) {
02767       connection_printf_to_buf(conn, "512 Cannot parse port \"%s\"\r\n",
02768                                (char*)smartlist_get(args, 2));
02769     } else {
02770       new_addr = tor_strdup(smartlist_get(args, 1));
02771     }
02772   }
02773 
02774   SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
02775   smartlist_free(args);
02776   if (!new_addr)
02777     return 0;
02778 
02779   strlcpy(ap_conn->socks_request->address, new_addr,
02780           sizeof(ap_conn->socks_request->address));
02781   if (new_port)
02782     ap_conn->socks_request->port = new_port;
02783   tor_free(new_addr);
02784   send_control_done(conn);
02785   return 0;
02786 }
02787 
02790 static int
02791 handle_control_closestream(control_connection_t *conn, uint32_t len,
02792                            const char *body)
02793 {
02794   entry_connection_t *ap_conn=NULL;
02795   uint8_t reason=0;
02796   smartlist_t *args;
02797   int ok;
02798   (void) len;
02799 
02800   args = getargs_helper("CLOSESTREAM", conn, body, 2, -1);
02801   if (!args)
02802     return 0;
02803 
02804   else if (!(ap_conn = get_stream(smartlist_get(args, 0))))
02805     connection_printf_to_buf(conn, "552 Unknown stream \"%s\"\r\n",
02806                              (char*)smartlist_get(args, 0));
02807   else {
02808     reason = (uint8_t) tor_parse_ulong(smartlist_get(args,1), 10, 0, 255,
02809                                        &ok, NULL);
02810     if (!ok) {
02811       connection_printf_to_buf(conn, "552 Unrecognized reason \"%s\"\r\n",
02812                                (char*)smartlist_get(args, 1));
02813       ap_conn = NULL;
02814     }
02815   }
02816   SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
02817   smartlist_free(args);
02818   if (!ap_conn)
02819     return 0;
02820 
02821   connection_mark_unattached_ap(ap_conn, reason);
02822   send_control_done(conn);
02823   return 0;
02824 }
02825 
02828 static int
02829 handle_control_closecircuit(control_connection_t *conn, uint32_t len,
02830                             const char *body)
02831 {
02832   origin_circuit_t *circ = NULL;
02833   int safe = 0;
02834   smartlist_t *args;
02835   (void) len;
02836 
02837   args = getargs_helper("CLOSECIRCUIT", conn, body, 1, -1);
02838   if (!args)
02839     return 0;
02840 
02841   if (!(circ=get_circ(smartlist_get(args, 0))))
02842     connection_printf_to_buf(conn, "552 Unknown circuit \"%s\"\r\n",
02843                              (char*)smartlist_get(args, 0));
02844   else {
02845     int i;
02846     for (i=1; i < smartlist_len(args); ++i) {
02847       if (!strcasecmp(smartlist_get(args, i), "IfUnused"))
02848         safe = 1;
02849       else
02850         log_info(LD_CONTROL, "Skipping unknown option %s",
02851                  (char*)smartlist_get(args,i));
02852     }
02853   }
02854   SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
02855   smartlist_free(args);
02856   if (!circ)
02857     return 0;
02858 
02859   if (!safe || !circ->p_streams) {
02860     circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_REQUESTED);
02861   }
02862 
02863   send_control_done(conn);
02864   return 0;
02865 }
02866 
02869 static int
02870 handle_control_resolve(control_connection_t *conn, uint32_t len,
02871                        const char *body)
02872 {
02873   smartlist_t *args, *failed;
02874   int is_reverse = 0;
02875   (void) len; /* body is nul-terminated; it's safe to ignore the length */
02876 
02877   if (!(conn->event_mask & ((uint32_t)1L<<EVENT_ADDRMAP))) {
02878     log_warn(LD_CONTROL, "Controller asked us to resolve an address, but "
02879              "isn't listening for ADDRMAP events.  It probably won't see "
02880              "the answer.");
02881   }
02882   args = smartlist_new();
02883   smartlist_split_string(args, body, " ",
02884                          SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
02885   {
02886     const char *modearg = find_element_starting_with(args, 0, "mode=");
02887     if (modearg && !strcasecmp(modearg, "mode=reverse"))
02888       is_reverse = 1;
02889   }
02890   failed = smartlist_new();
02891   SMARTLIST_FOREACH(args, const char *, arg, {
02892       if (!is_keyval_pair(arg)) {
02893           if (dnsserv_launch_request(arg, is_reverse)<0)
02894             smartlist_add(failed, (char*)arg);
02895       }
02896   });
02897 
02898   send_control_done(conn);
02899   SMARTLIST_FOREACH(failed, const char *, arg, {
02900       control_event_address_mapped(arg, arg, time(NULL),
02901                                    "Unable to launch resolve request");
02902   });
02903 
02904   SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
02905   smartlist_free(args);
02906   smartlist_free(failed);
02907   return 0;
02908 }
02909 
02911 static int
02912 handle_control_protocolinfo(control_connection_t *conn, uint32_t len,
02913                             const char *body)
02914 {
02915   const char *bad_arg = NULL;
02916   smartlist_t *args;
02917   (void)len;
02918 
02919   conn->have_sent_protocolinfo = 1;
02920   args = smartlist_new();
02921   smartlist_split_string(args, body, " ",
02922                          SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
02923   SMARTLIST_FOREACH(args, const char *, arg, {
02924       int ok;
02925       tor_parse_long(arg, 10, 0, LONG_MAX, &ok, NULL);
02926       if (!ok) {
02927         bad_arg = arg;
02928         break;
02929       }
02930     });
02931   if (bad_arg) {
02932     connection_printf_to_buf(conn, "513 No such version %s\r\n",
02933                              escaped(bad_arg));
02934     /* Don't tolerate bad arguments when not authenticated. */
02935     if (!STATE_IS_OPEN(TO_CONN(conn)->state))
02936       connection_mark_for_close(TO_CONN(conn));
02937     goto done;
02938   } else {
02939     const or_options_t *options = get_options();
02940     int cookies = options->CookieAuthentication;
02941     char *cfile = get_cookie_file();
02942     char *abs_cfile;
02943     char *esc_cfile;
02944     char *methods;
02945     abs_cfile = make_path_absolute(cfile);
02946     esc_cfile = esc_for_log(abs_cfile);
02947     {
02948       int passwd = (options->HashedControlPassword != NULL ||
02949                     options->HashedControlSessionPassword != NULL);
02950       smartlist_t *mlist = smartlist_new();
02951       if (cookies) {
02952         smartlist_add(mlist, (char*)"COOKIE");
02953         smartlist_add(mlist, (char*)"SAFECOOKIE");
02954       }
02955       if (passwd)
02956         smartlist_add(mlist, (char*)"HASHEDPASSWORD");
02957       if (!cookies && !passwd)
02958         smartlist_add(mlist, (char*)"NULL");
02959       methods = smartlist_join_strings(mlist, ",", 0, NULL);
02960       smartlist_free(mlist);
02961     }
02962 
02963     connection_printf_to_buf(conn,
02964                              "250-PROTOCOLINFO 1\r\n"
02965                              "250-AUTH METHODS=%s%s%s\r\n"
02966                              "250-VERSION Tor=%s\r\n"
02967                              "250 OK\r\n",
02968                              methods,
02969                              cookies?" COOKIEFILE=":"",
02970                              cookies?esc_cfile:"",
02971                              escaped(VERSION));
02972     tor_free(methods);
02973     tor_free(cfile);
02974     tor_free(abs_cfile);
02975     tor_free(esc_cfile);
02976   }
02977  done:
02978   SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
02979   smartlist_free(args);
02980   return 0;
02981 }
02982 
02984 static int
02985 handle_control_authchallenge(control_connection_t *conn, uint32_t len,
02986                              const char *body)
02987 {
02988   const char *cp = body;
02989   char *client_nonce;
02990   size_t client_nonce_len;
02991   char server_hash[DIGEST256_LEN];
02992   char server_hash_encoded[HEX_DIGEST256_LEN+1];
02993   char server_nonce[SAFECOOKIE_SERVER_NONCE_LEN];
02994   char server_nonce_encoded[(2*SAFECOOKIE_SERVER_NONCE_LEN) + 1];
02995 
02996   cp += strspn(cp, " \t\n\r");
02997   if (!strcasecmpstart(cp, "SAFECOOKIE")) {
02998     cp += strlen("SAFECOOKIE");
02999   } else {
03000     connection_write_str_to_buf("513 AUTHCHALLENGE only supports SAFECOOKIE "
03001                                 "authentication\r\n", conn);
03002     connection_mark_for_close(TO_CONN(conn));
03003     return -1;
03004   }
03005 
03006   if (!authentication_cookie_is_set) {
03007     connection_write_str_to_buf("515 Cookie authentication is disabled\r\n",
03008                                 conn);
03009     connection_mark_for_close(TO_CONN(conn));
03010     return -1;
03011   }
03012 
03013   cp += strspn(cp, " \t\n\r");
03014   if (*cp == '"') {
03015     const char *newcp =
03016       decode_escaped_string(cp, len - (cp - body),
03017                             &client_nonce, &client_nonce_len);
03018     if (newcp == NULL) {
03019       connection_write_str_to_buf("513 Invalid quoted client nonce\r\n",
03020                                   conn);
03021       connection_mark_for_close(TO_CONN(conn));
03022       return -1;
03023     }
03024     cp = newcp;
03025   } else {
03026     size_t client_nonce_encoded_len = strspn(cp, "0123456789ABCDEFabcdef");
03027 
03028     client_nonce_len = client_nonce_encoded_len / 2;
03029     client_nonce = tor_malloc_zero(client_nonce_len);
03030 
03031     if (base16_decode(client_nonce, client_nonce_len,
03032                       cp, client_nonce_encoded_len) < 0) {
03033       connection_write_str_to_buf("513 Invalid base16 client nonce\r\n",
03034                                   conn);
03035       connection_mark_for_close(TO_CONN(conn));
03036       tor_free(client_nonce);
03037       return -1;
03038     }
03039 
03040     cp += client_nonce_encoded_len;
03041   }
03042 
03043   cp += strspn(cp, " \t\n\r");
03044   if (*cp != '\0' ||
03045       cp != body + len) {
03046     connection_write_str_to_buf("513 Junk at end of AUTHCHALLENGE command\r\n",
03047                                 conn);
03048     connection_mark_for_close(TO_CONN(conn));
03049     tor_free(client_nonce);
03050     return -1;
03051   }
03052 
03053   tor_assert(!crypto_rand(server_nonce, SAFECOOKIE_SERVER_NONCE_LEN));
03054 
03055   /* Now compute and send the server-to-controller response, and the
03056    * server's nonce. */
03057   tor_assert(authentication_cookie != NULL);
03058 
03059   {
03060     size_t tmp_len = (AUTHENTICATION_COOKIE_LEN +
03061                       client_nonce_len +
03062                       SAFECOOKIE_SERVER_NONCE_LEN);
03063     char *tmp = tor_malloc_zero(tmp_len);
03064     char *client_hash = tor_malloc_zero(DIGEST256_LEN);
03065     memcpy(tmp, authentication_cookie, AUTHENTICATION_COOKIE_LEN);
03066     memcpy(tmp + AUTHENTICATION_COOKIE_LEN, client_nonce, client_nonce_len);
03067     memcpy(tmp + AUTHENTICATION_COOKIE_LEN + client_nonce_len,
03068            server_nonce, SAFECOOKIE_SERVER_NONCE_LEN);
03069 
03070     crypto_hmac_sha256(server_hash,
03071                        SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT,
03072                        strlen(SAFECOOKIE_SERVER_TO_CONTROLLER_CONSTANT),
03073                        tmp,
03074                        tmp_len);
03075 
03076     crypto_hmac_sha256(client_hash,
03077                        SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT,
03078                        strlen(SAFECOOKIE_CONTROLLER_TO_SERVER_CONSTANT),
03079                        tmp,
03080                        tmp_len);
03081 
03082     conn->safecookie_client_hash = client_hash;
03083 
03084     tor_free(tmp);
03085   }
03086 
03087   base16_encode(server_hash_encoded, sizeof(server_hash_encoded),
03088                 server_hash, sizeof(server_hash));
03089   base16_encode(server_nonce_encoded, sizeof(server_nonce_encoded),
03090                 server_nonce, sizeof(server_nonce));
03091 
03092   connection_printf_to_buf(conn,
03093                            "250 AUTHCHALLENGE SERVERHASH=%s "
03094                            "SERVERNONCE=%s\r\n",
03095                            server_hash_encoded,
03096                            server_nonce_encoded);
03097   return 0;
03098 }
03099 
03102 static int
03103 handle_control_usefeature(control_connection_t *conn,
03104                           uint32_t len,
03105                           const char *body)
03106 {
03107   smartlist_t *args;
03108   int bad = 0;
03109   (void) len; /* body is nul-terminated; it's safe to ignore the length */
03110   args = smartlist_new();
03111   smartlist_split_string(args, body, " ",
03112                          SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
03113   SMARTLIST_FOREACH(args, const char *, arg, {
03114       if (!strcasecmp(arg, "VERBOSE_NAMES"))
03115         ;
03116       else if (!strcasecmp(arg, "EXTENDED_EVENTS"))
03117         ;
03118       else {
03119         connection_printf_to_buf(conn, "552 Unrecognized feature \"%s\"\r\n",
03120                                  arg);
03121         bad = 1;
03122         break;
03123       }
03124     });
03125 
03126   if (!bad) {
03127     send_control_done(conn);
03128   }
03129 
03130   SMARTLIST_FOREACH(args, char *, cp, tor_free(cp));
03131   smartlist_free(args);
03132   return 0;
03133 }
03134 
03136 int
03137 connection_control_finished_flushing(control_connection_t *conn)
03138 {
03139   tor_assert(conn);
03140   return 0;
03141 }
03142 
03144 int
03145 connection_control_reached_eof(control_connection_t *conn)
03146 {
03147   tor_assert(conn);
03148 
03149   log_info(LD_CONTROL,"Control connection reached EOF. Closing.");
03150   connection_mark_for_close(TO_CONN(conn));
03151   return 0;
03152 }
03153 
03156 static void
03157 lost_owning_controller(const char *owner_type, const char *loss_manner)
03158 {
03159   int shutdown_slowly = server_mode(get_options());
03160 
03161   log_notice(LD_CONTROL, "Owning controller %s has %s -- %s.",
03162              owner_type, loss_manner,
03163              shutdown_slowly ? "shutting down" : "exiting now");
03164 
03165   /* XXXX Perhaps this chunk of code should be a separate function,
03166    * called here and by process_signal(SIGINT). */
03167 
03168   if (!shutdown_slowly) {
03169     tor_cleanup();
03170     exit(0);
03171   }
03172   /* XXXX This will close all listening sockets except control-port
03173    * listeners.  Perhaps we should close those too. */
03174   hibernate_begin_shutdown();
03175 }
03176 
03178 void
03179 connection_control_closed(control_connection_t *conn)
03180 {
03181   tor_assert(conn);
03182 
03183   conn->event_mask = 0;
03184   control_update_global_event_mask();
03185 
03186   if (conn->is_owning_control_connection) {
03187     lost_owning_controller("connection", "closed");
03188   }
03189 }
03190 
03193 static int
03194 is_valid_initial_command(control_connection_t *conn, const char *cmd)
03195 {
03196   if (conn->_base.state == CONTROL_CONN_STATE_OPEN)
03197     return 1;
03198   if (!strcasecmp(cmd, "PROTOCOLINFO"))
03199     return (!conn->have_sent_protocolinfo &&
03200             conn->safecookie_client_hash == NULL);
03201   if (!strcasecmp(cmd, "AUTHCHALLENGE"))
03202     return (conn->safecookie_client_hash == NULL);
03203   if (!strcasecmp(cmd, "AUTHENTICATE") ||
03204       !strcasecmp(cmd, "QUIT"))
03205     return 1;
03206   return 0;
03207 }
03208 
03212 #define MAX_COMMAND_LINE_LENGTH (1024*1024)
03213 
03218 static int
03219 peek_connection_has_control0_command(connection_t *conn)
03220 {
03221   IF_HAS_BUFFEREVENT(conn, {
03222     struct evbuffer *input = bufferevent_get_input(conn->bufev);
03223     return peek_evbuffer_has_control0_command(input);
03224   }) ELSE_IF_NO_BUFFEREVENT {
03225     return peek_buf_has_control0_command(conn->inbuf);
03226   }
03227 }
03228 
03232 int
03233 connection_control_process_inbuf(control_connection_t *conn)
03234 {
03235   size_t data_len;
03236   uint32_t cmd_data_len;
03237   int cmd_len;
03238   char *args;
03239 
03240   tor_assert(conn);
03241   tor_assert(conn->_base.state == CONTROL_CONN_STATE_OPEN ||
03242              conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH);
03243 
03244   if (!conn->incoming_cmd) {
03245     conn->incoming_cmd = tor_malloc(1024);
03246     conn->incoming_cmd_len = 1024;
03247     conn->incoming_cmd_cur_len = 0;
03248   }
03249 
03250   if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
03251       peek_connection_has_control0_command(TO_CONN(conn))) {
03252     /* Detect v0 commands and send a "no more v0" message. */
03253     size_t body_len;
03254     char buf[128];
03255     set_uint16(buf+2, htons(0x0000)); /* type == error */
03256     set_uint16(buf+4, htons(0x0001)); /* code == internal error */
03257     strlcpy(buf+6, "The v0 control protocol is not supported by Tor 0.1.2.17 "
03258             "and later; upgrade your controller.",
03259             sizeof(buf)-6);
03260     body_len = 2+strlen(buf+6)+2; /* code, msg, nul. */
03261     set_uint16(buf+0, htons(body_len));
03262     connection_write_to_buf(buf, 4+body_len, TO_CONN(conn));
03263 
03264     connection_mark_and_flush(TO_CONN(conn));
03265     return 0;
03266   }
03267 
03268  again:
03269   while (1) {
03270     size_t last_idx;
03271     int r;
03272     /* First, fetch a line. */
03273     do {
03274       data_len = conn->incoming_cmd_len - conn->incoming_cmd_cur_len;
03275       r = connection_fetch_from_buf_line(TO_CONN(conn),
03276                               conn->incoming_cmd+conn->incoming_cmd_cur_len,
03277                               &data_len);
03278       if (r == 0)
03279         /* Line not all here yet. Wait. */
03280         return 0;
03281       else if (r == -1) {
03282         if (data_len + conn->incoming_cmd_cur_len > MAX_COMMAND_LINE_LENGTH) {
03283           connection_write_str_to_buf("500 Line too long.\r\n", conn);
03284           connection_stop_reading(TO_CONN(conn));
03285           connection_mark_and_flush(TO_CONN(conn));
03286         }
03287         while (conn->incoming_cmd_len < data_len+conn->incoming_cmd_cur_len)
03288           conn->incoming_cmd_len *= 2;
03289         conn->incoming_cmd = tor_realloc(conn->incoming_cmd,
03290                                          conn->incoming_cmd_len);
03291       }
03292     } while (r != 1);
03293 
03294     tor_assert(data_len);
03295 
03296     last_idx = conn->incoming_cmd_cur_len;
03297     conn->incoming_cmd_cur_len += (int)data_len;
03298 
03299     /* We have appended a line to incoming_cmd.  Is the command done? */
03300     if (last_idx == 0 && *conn->incoming_cmd != '+')
03301       /* One line command, didn't start with '+'. */
03302       break;
03303     /* XXXX this code duplication is kind of dumb. */
03304     if (last_idx+3 == conn->incoming_cmd_cur_len &&
03305         tor_memeq(conn->incoming_cmd + last_idx, ".\r\n", 3)) {
03306       /* Just appended ".\r\n"; we're done. Remove it. */
03307       conn->incoming_cmd[last_idx] = '\0';
03308       conn->incoming_cmd_cur_len -= 3;
03309       break;
03310     } else if (last_idx+2 == conn->incoming_cmd_cur_len &&
03311                tor_memeq(conn->incoming_cmd + last_idx, ".\n", 2)) {
03312       /* Just appended ".\n"; we're done. Remove it. */
03313       conn->incoming_cmd[last_idx] = '\0';
03314       conn->incoming_cmd_cur_len -= 2;
03315       break;
03316     }
03317     /* Otherwise, read another line. */
03318   }
03319   data_len = conn->incoming_cmd_cur_len;
03320   /* Okay, we now have a command sitting on conn->incoming_cmd. See if we
03321    * recognize it.
03322    */
03323   cmd_len = 0;
03324   while ((size_t)cmd_len < data_len
03325          && !TOR_ISSPACE(conn->incoming_cmd[cmd_len]))
03326     ++cmd_len;
03327 
03328   conn->incoming_cmd[cmd_len]='\0';
03329   args = conn->incoming_cmd+cmd_len+1;
03330   tor_assert(data_len>(size_t)cmd_len);
03331   data_len -= (cmd_len+1); /* skip the command and NUL we added after it */
03332   while (TOR_ISSPACE(*args)) {
03333     ++args;
03334     --data_len;
03335   }
03336 
03337   /* If the connection is already closing, ignore further commands */
03338   if (TO_CONN(conn)->marked_for_close) {
03339     return 0;
03340   }
03341 
03342   /* Otherwise, Quit is always valid. */
03343   if (!strcasecmp(conn->incoming_cmd, "QUIT")) {
03344     connection_write_str_to_buf("250 closing connection\r\n", conn);
03345     connection_mark_and_flush(TO_CONN(conn));
03346     return 0;
03347   }
03348 
03349   if (conn->_base.state == CONTROL_CONN_STATE_NEEDAUTH &&
03350       !is_valid_initial_command(conn, conn->incoming_cmd)) {
03351     connection_write_str_to_buf("514 Authentication required.\r\n", conn);
03352     connection_mark_for_close(TO_CONN(conn));
03353     return 0;
03354   }
03355 
03356   if (data_len >= UINT32_MAX) {
03357     connection_write_str_to_buf("500 A 4GB command? Nice try.\r\n", conn);
03358     connection_mark_for_close(TO_CONN(conn));
03359     return 0;
03360   }
03361 
03362   /* XXXX Why is this not implemented as a table like the GETINFO
03363    * items are?  Even handling the plus signs at the beginnings of
03364    * commands wouldn't be very hard with proper macros. */
03365   cmd_data_len = (uint32_t)data_len;
03366   if (!strcasecmp(conn->incoming_cmd, "SETCONF")) {
03367     if (handle_control_setconf(conn, cmd_data_len, args))
03368       return -1;
03369   } else if (!strcasecmp(conn->incoming_cmd, "RESETCONF")) {
03370     if (handle_control_resetconf(conn, cmd_data_len, args))
03371       return -1;
03372   } else if (!strcasecmp(conn->incoming_cmd, "GETCONF")) {
03373     if (handle_control_getconf(conn, cmd_data_len, args))
03374       return -1;
03375   } else if (!strcasecmp(conn->incoming_cmd, "+LOADCONF")) {
03376     if (handle_control_loadconf(conn, cmd_data_len, args))
03377       return -1;
03378   } else if (!strcasecmp(conn->incoming_cmd, "SETEVENTS")) {
03379     if (handle_control_setevents(conn, cmd_data_len, args))
03380       return -1;
03381   } else if (!strcasecmp(conn->incoming_cmd, "AUTHENTICATE")) {
03382     if (handle_control_authenticate(conn, cmd_data_len, args))
03383       return -1;
03384   } else if (!strcasecmp(conn->incoming_cmd, "SAVECONF")) {
03385     if (handle_control_saveconf(conn, cmd_data_len, args))
03386       return -1;
03387   } else if (!strcasecmp(conn->incoming_cmd, "SIGNAL")) {
03388     if (handle_control_signal(conn, cmd_data_len, args))
03389       return -1;
03390   } else if (!strcasecmp(conn->incoming_cmd, "TAKEOWNERSHIP")) {
03391     if (handle_control_takeownership(conn, cmd_data_len, args))
03392       return -1;
03393   } else if (!strcasecmp(conn->incoming_cmd, "MAPADDRESS")) {
03394     if (handle_control_mapaddress(conn, cmd_data_len, args))
03395       return -1;
03396   } else if (!strcasecmp(conn->incoming_cmd, "GETINFO")) {
03397     if (handle_control_getinfo(conn, cmd_data_len, args))
03398       return -1;
03399   } else if (!strcasecmp(conn->incoming_cmd, "EXTENDCIRCUIT")) {
03400     if (handle_control_extendcircuit(conn, cmd_data_len, args))
03401       return -1;
03402   } else if (!strcasecmp(conn->incoming_cmd, "SETCIRCUITPURPOSE")) {
03403     if (handle_control_setcircuitpurpose(conn, cmd_data_len, args))
03404       return -1;
03405   } else if (!strcasecmp(conn->incoming_cmd, "SETROUTERPURPOSE")) {
03406     connection_write_str_to_buf("511 SETROUTERPURPOSE is obsolete.\r\n", conn);
03407   } else if (!strcasecmp(conn->incoming_cmd, "ATTACHSTREAM")) {
03408     if (handle_control_attachstream(conn, cmd_data_len, args))
03409       return -1;
03410   } else if (!strcasecmp(conn->incoming_cmd, "+POSTDESCRIPTOR")) {
03411     if (handle_control_postdescriptor(conn, cmd_data_len, args))
03412       return -1;
03413   } else if (!strcasecmp(conn->incoming_cmd, "REDIRECTSTREAM")) {
03414     if (handle_control_redirectstream(conn, cmd_data_len, args))
03415       return -1;
03416   } else if (!strcasecmp(conn->incoming_cmd, "CLOSESTREAM")) {
03417     if (handle_control_closestream(conn, cmd_data_len, args))
03418       return -1;
03419   } else if (!strcasecmp(conn->incoming_cmd, "CLOSECIRCUIT")) {
03420     if (handle_control_closecircuit(conn, cmd_data_len, args))
03421       return -1;
03422   } else if (!strcasecmp(conn->incoming_cmd, "USEFEATURE")) {
03423     if (handle_control_usefeature(conn, cmd_data_len, args))
03424       return -1;
03425   } else if (!strcasecmp(conn->incoming_cmd, "RESOLVE")) {
03426     if (handle_control_resolve(conn, cmd_data_len, args))
03427       return -1;
03428   } else if (!strcasecmp(conn->incoming_cmd, "PROTOCOLINFO")) {
03429     if (handle_control_protocolinfo(conn, cmd_data_len, args))
03430       return -1;
03431   } else if (!strcasecmp(conn->incoming_cmd, "AUTHCHALLENGE")) {
03432     if (handle_control_authchallenge(conn, cmd_data_len, args))
03433       return -1;
03434   } else {
03435     connection_printf_to_buf(conn, "510 Unrecognized command \"%s\"\r\n",
03436                              conn->incoming_cmd);
03437   }
03438 
03439   conn->incoming_cmd_cur_len = 0;
03440   goto again;
03441 }
03442 
03445 int
03446 control_event_circuit_status(origin_circuit_t *circ, circuit_status_event_t tp,
03447                              int reason_code)
03448 {
03449   const char *status;
03450   char reasons[64] = "";
03451   if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS))
03452     return 0;
03453   tor_assert(circ);
03454 
03455   switch (tp)
03456     {
03457     case CIRC_EVENT_LAUNCHED: status = "LAUNCHED"; break;
03458     case CIRC_EVENT_BUILT: status = "BUILT"; break;
03459     case CIRC_EVENT_EXTENDED: status = "EXTENDED"; break;
03460     case CIRC_EVENT_FAILED: status = "FAILED"; break;
03461     case CIRC_EVENT_CLOSED: status = "CLOSED"; break;
03462     default:
03463       log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
03464       tor_fragile_assert();
03465       return 0;
03466     }
03467 
03468   if (tp == CIRC_EVENT_FAILED || tp == CIRC_EVENT_CLOSED) {
03469     const char *reason_str = circuit_end_reason_to_control_string(reason_code);
03470     char unk_reason_buf[16];
03471     if (!reason_str) {
03472       tor_snprintf(unk_reason_buf, 16, "UNKNOWN_%d", reason_code);
03473       reason_str = unk_reason_buf;
03474     }
03475     if (reason_code > 0 && reason_code & END_CIRC_REASON_FLAG_REMOTE) {
03476       tor_snprintf(reasons, sizeof(reasons),
03477                    " REASON=DESTROYED REMOTE_REASON=%s", reason_str);
03478     } else {
03479       tor_snprintf(reasons, sizeof(reasons),
03480                    " REASON=%s", reason_str);
03481     }
03482   }
03483 
03484   {
03485     char *circdesc = circuit_describe_status_for_controller(circ);
03486     const char *sp = strlen(circdesc) ? " " : "";
03487     send_control_event(EVENT_CIRCUIT_STATUS, ALL_FORMATS,
03488                                 "650 CIRC %lu %s%s%s%s\r\n",
03489                                 (unsigned long)circ->global_identifier,
03490                                 status, sp,
03491                                 circdesc,
03492                                 reasons);
03493     tor_free(circdesc);
03494   }
03495 
03496   return 0;
03497 }
03498 
03501 static int
03502 control_event_circuit_status_minor(origin_circuit_t *circ,
03503                                    circuit_status_minor_event_t e,
03504                                    int purpose, const struct timeval *tv)
03505 {
03506   const char *event_desc;
03507   char event_tail[160] = "";
03508   if (!EVENT_IS_INTERESTING(EVENT_CIRCUIT_STATUS_MINOR))
03509     return 0;
03510   tor_assert(circ);
03511 
03512   switch (e)
03513     {
03514     case CIRC_MINOR_EVENT_PURPOSE_CHANGED:
03515       event_desc = "PURPOSE_CHANGED";
03516 
03517       {
03518         /* event_tail can currently be up to 68 chars long */
03519         const char *hs_state_str =
03520           circuit_purpose_to_controller_hs_state_string(purpose);
03521         tor_snprintf(event_tail, sizeof(event_tail),
03522                      " OLD_PURPOSE=%s%s%s",
03523                      circuit_purpose_to_controller_string(purpose),
03524                      (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
03525                      (hs_state_str != NULL) ? hs_state_str : "");
03526       }
03527 
03528       break;
03529     case CIRC_MINOR_EVENT_CANNIBALIZED:
03530       event_desc = "CANNIBALIZED";
03531 
03532       {
03533         /* event_tail can currently be up to 130 chars long */
03534         const char *hs_state_str =
03535           circuit_purpose_to_controller_hs_state_string(purpose);
03536         const struct timeval *old_timestamp_created = tv;
03537         char tbuf[ISO_TIME_USEC_LEN+1];
03538         format_iso_time_nospace_usec(tbuf, old_timestamp_created);
03539 
03540         tor_snprintf(event_tail, sizeof(event_tail),
03541                      " OLD_PURPOSE=%s%s%s OLD_TIME_CREATED=%s",
03542                      circuit_purpose_to_controller_string(purpose),
03543                      (hs_state_str != NULL) ? " OLD_HS_STATE=" : "",
03544                      (hs_state_str != NULL) ? hs_state_str : "",
03545                      tbuf);
03546       }
03547 
03548       break;
03549     default:
03550       log_warn(LD_BUG, "Unrecognized status code %d", (int)e);
03551       tor_fragile_assert();
03552       return 0;
03553     }
03554 
03555   {
03556     char *circdesc = circuit_describe_status_for_controller(circ);
03557     const char *sp = strlen(circdesc) ? " " : "";
03558     send_control_event(EVENT_CIRCUIT_STATUS_MINOR, ALL_FORMATS,
03559                        "650 CIRC_MINOR %lu %s%s%s%s\r\n",
03560                        (unsigned long)circ->global_identifier,
03561                        event_desc, sp,
03562                        circdesc,
03563                        event_tail);
03564     tor_free(circdesc);
03565   }
03566 
03567   return 0;
03568 }
03569 
03574 int
03575 control_event_circuit_purpose_changed(origin_circuit_t *circ,
03576                                       int old_purpose)
03577 {
03578   return control_event_circuit_status_minor(circ,
03579                                             CIRC_MINOR_EVENT_PURPOSE_CHANGED,
03580                                             old_purpose,
03581                                             NULL);
03582 }
03583 
03588 int
03589 control_event_circuit_cannibalized(origin_circuit_t *circ,
03590                                    int old_purpose,
03591                                    const struct timeval *old_tv_created)
03592 {
03593   return control_event_circuit_status_minor(circ,
03594                                             CIRC_MINOR_EVENT_CANNIBALIZED,
03595                                             old_purpose,
03596                                             old_tv_created);
03597 }
03598 
03603 static int
03604 write_stream_target_to_buf(entry_connection_t *conn, char *buf, size_t len)
03605 {
03606   char buf2[256];
03607   if (conn->chosen_exit_name)
03608     if (tor_snprintf(buf2, sizeof(buf2), ".%s.exit", conn->chosen_exit_name)<0)
03609       return -1;
03610   if (!conn->socks_request)
03611     return -1;
03612   if (tor_snprintf(buf, len, "%s%s%s:%d",
03613                conn->socks_request->address,
03614                conn->chosen_exit_name ? buf2 : "",
03615                !conn->chosen_exit_name && connection_edge_is_rendezvous_stream(
03616                                      ENTRY_TO_EDGE_CONN(conn)) ? ".onion" : "",
03617                conn->socks_request->port)<0)
03618     return -1;
03619   return 0;
03620 }
03621 
03624 int
03625 control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp,
03626                             int reason_code)
03627 {
03628   char reason_buf[64];
03629   char addrport_buf[64];
03630   const char *status;
03631   circuit_t *circ;
03632   origin_circuit_t *origin_circ = NULL;
03633   char buf[256];
03634   const char *purpose = "";
03635   tor_assert(conn->socks_request);
03636 
03637   if (!EVENT_IS_INTERESTING(EVENT_STREAM_STATUS))
03638     return 0;
03639 
03640   if (tp == STREAM_EVENT_CLOSED &&
03641       (reason_code & END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED))
03642     return 0;
03643 
03644   write_stream_target_to_buf(conn, buf, sizeof(buf));
03645 
03646   reason_buf[0] = '\0';
03647   switch (tp)
03648     {
03649     case STREAM_EVENT_SENT_CONNECT: status = "SENTCONNECT"; break;
03650     case STREAM_EVENT_SENT_RESOLVE: status = "SENTRESOLVE"; break;
03651     case STREAM_EVENT_SUCCEEDED: status = "SUCCEEDED"; break;
03652     case STREAM_EVENT_FAILED: status = "FAILED"; break;
03653     case STREAM_EVENT_CLOSED: status = "CLOSED"; break;
03654     case STREAM_EVENT_NEW: status = "NEW"; break;
03655     case STREAM_EVENT_NEW_RESOLVE: status = "NEWRESOLVE"; break;
03656     case STREAM_EVENT_FAILED_RETRIABLE: status = "DETACHED"; break;
03657     case STREAM_EVENT_REMAP: status = "REMAP"; break;
03658     default:
03659       log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
03660       return 0;
03661     }
03662   if (reason_code && (tp == STREAM_EVENT_FAILED ||
03663                       tp == STREAM_EVENT_CLOSED ||
03664                       tp == STREAM_EVENT_FAILED_RETRIABLE)) {
03665     const char *reason_str = stream_end_reason_to_control_string(reason_code);
03666     char *r = NULL;
03667     if (!reason_str) {
03668       tor_asprintf(&r, " UNKNOWN_%d", reason_code);
03669       reason_str = r;
03670     }
03671     if (reason_code & END_STREAM_REASON_FLAG_REMOTE)
03672       tor_snprintf(reason_buf, sizeof(reason_buf),
03673                    " REASON=END REMOTE_REASON=%s", reason_str);
03674     else
03675       tor_snprintf(reason_buf, sizeof(reason_buf),
03676                    " REASON=%s", reason_str);
03677     tor_free(r);
03678   } else if (reason_code && tp == STREAM_EVENT_REMAP) {
03679     switch (reason_code) {
03680     case REMAP_STREAM_SOURCE_CACHE:
03681       strlcpy(reason_buf, " SOURCE=CACHE", sizeof(reason_buf));
03682       break;
03683     case REMAP_STREAM_SOURCE_EXIT:
03684       strlcpy(reason_buf, " SOURCE=EXIT", sizeof(reason_buf));
03685       break;
03686     default:
03687       tor_snprintf(reason_buf, sizeof(reason_buf), " REASON=UNKNOWN_%d",
03688                    reason_code);
03689       /* XXX do we want SOURCE=UNKNOWN_%d above instead? -RD */
03690       break;
03691     }
03692   }
03693 
03694   if (tp == STREAM_EVENT_NEW) {
03695     tor_snprintf(addrport_buf,sizeof(addrport_buf), " SOURCE_ADDR=%s:%d",
03696                  ENTRY_TO_CONN(conn)->address, ENTRY_TO_CONN(conn)->port);
03697   } else {
03698     addrport_buf[0] = '\0';
03699   }
03700 
03701   if (tp == STREAM_EVENT_NEW_RESOLVE) {
03702     purpose = " PURPOSE=DNS_REQUEST";
03703   } else if (tp == STREAM_EVENT_NEW) {
03704     if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request ||
03705         (conn->socks_request &&
03706          SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)))
03707       purpose = " PURPOSE=DNS_REQUEST";
03708     else if (conn->use_begindir) {
03709       connection_t *linked = ENTRY_TO_CONN(conn)->linked_conn;
03710       int linked_dir_purpose = -1;
03711       if (linked && linked->type == CONN_TYPE_DIR)
03712         linked_dir_purpose = linked->purpose;
03713       if (DIR_PURPOSE_IS_UPLOAD(linked_dir_purpose))
03714         purpose = " PURPOSE=DIR_UPLOAD";
03715       else
03716         purpose = " PURPOSE=DIR_FETCH";
03717     } else
03718       purpose = " PURPOSE=USER";
03719   }
03720 
03721   circ = circuit_get_by_edge_conn(ENTRY_TO_EDGE_CONN(conn));
03722   if (circ && CIRCUIT_IS_ORIGIN(circ))
03723     origin_circ = TO_ORIGIN_CIRCUIT(circ);
03724   send_control_event(EVENT_STREAM_STATUS, ALL_FORMATS,
03725                         "650 STREAM "U64_FORMAT" %s %lu %s%s%s%s\r\n",
03726                      U64_PRINTF_ARG(ENTRY_TO_CONN(conn)->global_identifier),
03727                      status,
03728                         origin_circ?
03729                            (unsigned long)origin_circ->global_identifier : 0ul,
03730                         buf, reason_buf, addrport_buf, purpose);
03731 
03732   /* XXX need to specify its intended exit, etc? */
03733 
03734   return 0;
03735 }
03736 
03740 static void
03741 orconn_target_get_name(char *name, size_t len, or_connection_t *conn)
03742 {
03743   const node_t *node = node_get_by_id(conn->identity_digest);
03744   if (node) {
03745     tor_assert(len > MAX_VERBOSE_NICKNAME_LEN);
03746     node_get_verbose_nickname(node, name);
03747   } else if (! tor_digest_is_zero(conn->identity_digest)) {
03748     name[0] = '$';
03749     base16_encode(name+1, len-1, conn->identity_digest,
03750                   DIGEST_LEN);
03751   } else {
03752     tor_snprintf(name, len, "%s:%d",
03753                  conn->_base.address, conn->_base.port);
03754   }
03755 }
03756 
03762 int
03763 control_event_or_conn_status(or_connection_t *conn, or_conn_status_event_t tp,
03764                              int reason)
03765 {
03766   int ncircs = 0;
03767   const char *status;
03768   char name[128];
03769   char ncircs_buf[32] = {0}; /* > 8 + log10(2^32)=10 + 2 */
03770 
03771   if (!EVENT_IS_INTERESTING(EVENT_OR_CONN_STATUS))
03772     return 0;
03773 
03774   switch (tp)
03775     {
03776     case OR_CONN_EVENT_LAUNCHED: status = "LAUNCHED"; break;
03777     case OR_CONN_EVENT_CONNECTED: status = "CONNECTED"; break;
03778     case OR_CONN_EVENT_FAILED: status = "FAILED"; break;
03779     case OR_CONN_EVENT_CLOSED: status = "CLOSED"; break;
03780     case OR_CONN_EVENT_NEW: status = "NEW"; break;
03781     default:
03782       log_warn(LD_BUG, "Unrecognized status code %d", (int)tp);
03783       return 0;
03784     }
03785   ncircs = circuit_count_pending_on_or_conn(conn);
03786   ncircs += conn->n_circuits;
03787   if (ncircs && (tp == OR_CONN_EVENT_FAILED || tp == OR_CONN_EVENT_CLOSED)) {
03788     tor_snprintf(ncircs_buf, sizeof(ncircs_buf), "%sNCIRCS=%d",
03789                  reason ? " " : "", ncircs);
03790   }
03791 
03792   orconn_target_get_name(name, sizeof(name), conn);
03793   send_control_event(EVENT_OR_CONN_STATUS, ALL_FORMATS,
03794                               "650 ORCONN %s %s %s%s%s\r\n",
03795                               name, status,
03796                               reason ? "REASON=" : "",
03797                               orconn_end_reason_to_control_string(reason),
03798                               ncircs_buf);
03799 
03800   return 0;
03801 }
03802 
03806 int
03807 control_event_stream_bandwidth(edge_connection_t *edge_conn)
03808 {
03809   if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
03810     if (!edge_conn->n_read && !edge_conn->n_written)
03811       return 0;
03812 
03813     send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
03814                        "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
03815                        U64_PRINTF_ARG(edge_conn->_base.global_identifier),
03816                        (unsigned long)edge_conn->n_read,
03817                        (unsigned long)edge_conn->n_written);
03818 
03819     edge_conn->n_written = edge_conn->n_read = 0;
03820   }
03821 
03822   return 0;
03823 }
03824 
03827 int
03828 control_event_stream_bandwidth_used(void)
03829 {
03830   if (EVENT_IS_INTERESTING(EVENT_STREAM_BANDWIDTH_USED)) {
03831     smartlist_t *conns = get_connection_array();
03832     edge_connection_t *edge_conn;
03833 
03834     SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn)
03835     {
03836         if (conn->type != CONN_TYPE_AP)
03837           continue;
03838         edge_conn = TO_EDGE_CONN(conn);
03839         if (!edge_conn->n_read && !edge_conn->n_written)
03840           continue;
03841 
03842         send_control_event(EVENT_STREAM_BANDWIDTH_USED, ALL_FORMATS,
03843                            "650 STREAM_BW "U64_FORMAT" %lu %lu\r\n",
03844                            U64_PRINTF_ARG(edge_conn->_base.global_identifier),
03845                            (unsigned long)edge_conn->n_read,
03846                            (unsigned long)edge_conn->n_written);
03847 
03848         edge_conn->n_written = edge_conn->n_read = 0;
03849     }
03850     SMARTLIST_FOREACH_END(conn);
03851   }
03852 
03853   return 0;
03854 }
03855 
03858 int
03859 control_event_bandwidth_used(uint32_t n_read, uint32_t n_written)
03860 {
03861   if (EVENT_IS_INTERESTING(EVENT_BANDWIDTH_USED)) {
03862     send_control_event(EVENT_BANDWIDTH_USED, ALL_FORMATS,
03863                        "650 BW %lu %lu\r\n",
03864                        (unsigned long)n_read,
03865                        (unsigned long)n_written);
03866   }
03867 
03868   return 0;
03869 }
03870 
03874 void
03875 disable_control_logging(void)
03876 {
03877   ++disable_log_messages;
03878 }
03879 
03882 void
03883 enable_control_logging(void)
03884 {
03885   if (--disable_log_messages < 0)
03886     tor_assert(0);
03887 }
03888 
03890 void
03891 control_event_logmsg(int severity, uint32_t domain, const char *msg)
03892 {
03893   int event;
03894 
03895   /* Don't even think of trying to add stuff to a buffer from a cpuworker
03896    * thread. */
03897   if (! in_main_thread())
03898     return;
03899 
03900   if (disable_log_messages)
03901     return;
03902 
03903   if (domain == LD_BUG && EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL) &&
03904       severity <= LOG_NOTICE) {
03905     char *esc = esc_for_log(msg);
03906     ++disable_log_messages;
03907     control_event_general_status(severity, "BUG REASON=%s", esc);
03908     --disable_log_messages;
03909     tor_free(esc);
03910   }
03911 
03912   event = log_severity_to_event(severity);
03913   if (event >= 0 && EVENT_IS_INTERESTING(event)) {
03914     char *b = NULL;
03915     const char *s;
03916     if (strchr(msg, '\n')) {
03917       char *cp;
03918       b = tor_strdup(msg);
03919       for (cp = b; *cp; ++cp)
03920         if (*cp == '\r' || *cp == '\n')
03921           *cp = ' ';
03922     }
03923     switch (severity) {
03924       case LOG_DEBUG: s = "DEBUG"; break;
03925       case LOG_INFO: s = "INFO"; break;
03926       case LOG_NOTICE: s = "NOTICE"; break;
03927       case LOG_WARN: s = "WARN"; break;
03928       case LOG_ERR: s = "ERR"; break;
03929       default: s = "UnknownLogSeverity"; break;
03930     }
03931     ++disable_log_messages;
03932     send_control_event(event, ALL_FORMATS, "650 %s %s\r\n", s, b?b:msg);
03933     --disable_log_messages;
03934     tor_free(b);
03935   }
03936 }
03937 
03942 int
03943 control_event_descriptors_changed(smartlist_t *routers)
03944 {
03945   char *msg;
03946 
03947   if (!EVENT_IS_INTERESTING(EVENT_NEW_DESC))
03948     return 0;
03949 
03950   {
03951     smartlist_t *names = smartlist_new();
03952     char *ids;
03953     SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
03954         char *b = tor_malloc(MAX_VERBOSE_NICKNAME_LEN+1);
03955         router_get_verbose_nickname(b, ri);
03956         smartlist_add(names, b);
03957       });
03958     ids = smartlist_join_strings(names, " ", 0, NULL);
03959     tor_asprintf(&msg, "650 NEWDESC %s\r\n", ids);
03960     send_control_event_string(EVENT_NEW_DESC, ALL_FORMATS, msg);
03961     tor_free(ids);
03962     tor_free(msg);
03963     SMARTLIST_FOREACH(names, char *, cp, tor_free(cp));
03964     smartlist_free(names);
03965   }
03966   return 0;
03967 }
03968 
03974 int
03975 control_event_address_mapped(const char *from, const char *to, time_t expires,
03976                              const char *error)
03977 {
03978   if (!EVENT_IS_INTERESTING(EVENT_ADDRMAP))
03979     return 0;
03980 
03981   if (expires < 3 || expires == TIME_MAX)
03982     send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
03983                                 "650 ADDRMAP %s %s NEVER %s\r\n", from, to,
03984                                 error?error:"");
03985   else {
03986     char buf[ISO_TIME_LEN+1];
03987     char buf2[ISO_TIME_LEN+1];
03988     format_local_iso_time(buf,expires);
03989     format_iso_time(buf2,expires);
03990     send_control_event(EVENT_ADDRMAP, ALL_FORMATS,
03991                                 "650 ADDRMAP %s %s \"%s\""
03992                                 " %s%sEXPIRES=\"%s\"\r\n",
03993                                 from, to, buf,
03994                                 error?error:"", error?" ":"",
03995                                 buf2);
03996   }
03997 
03998   return 0;
03999 }
04000 
04006 int
04007 control_event_or_authdir_new_descriptor(const char *action,
04008                                         const char *desc, size_t desclen,
04009                                         const char *msg)
04010 {
04011   char firstline[1024];
04012   char *buf;
04013   size_t totallen;
04014   char *esc = NULL;
04015   size_t esclen;
04016 
04017   if (!EVENT_IS_INTERESTING(EVENT_AUTHDIR_NEWDESCS))
04018     return 0;
04019 
04020   tor_snprintf(firstline, sizeof(firstline),
04021                "650+AUTHDIR_NEWDESC=\r\n%s\r\n%s\r\n",
04022                action,
04023                msg ? msg : "");
04024 
04025   /* Escape the server descriptor properly */
04026   esclen = write_escaped_data(desc, desclen, &esc);
04027 
04028   totallen = strlen(firstline) + esclen + 1;
04029   buf = tor_malloc(totallen);
04030   strlcpy(buf, firstline, totallen);
04031   strlcpy(buf+strlen(firstline), esc, totallen);
04032   send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
04033                             buf);
04034   send_control_event_string(EVENT_AUTHDIR_NEWDESCS, ALL_FORMATS,
04035                             "650 OK\r\n");
04036   tor_free(esc);
04037   tor_free(buf);
04038 
04039   return 0;
04040 }
04041 
04046 static int
04047 control_event_networkstatus_changed_helper(smartlist_t *statuses,
04048                                            uint16_t event,
04049                                            const char *event_string)
04050 {
04051   smartlist_t *strs;
04052   char *s, *esc = NULL;
04053   if (!EVENT_IS_INTERESTING(event) || !smartlist_len(statuses))
04054     return 0;
04055 
04056   strs = smartlist_new();
04057   smartlist_add(strs, tor_strdup("650+"));
04058   smartlist_add(strs, tor_strdup(event_string));
04059   smartlist_add(strs, tor_strdup("\r\n"));
04060   SMARTLIST_FOREACH(statuses, const routerstatus_t *, rs,
04061     {
04062       s = networkstatus_getinfo_helper_single(rs);
04063       if (!s) continue;
04064       smartlist_add(strs, s);
04065     });
04066 
04067   s = smartlist_join_strings(strs, "", 0, NULL);
04068   write_escaped_data(s, strlen(s), &esc);
04069   SMARTLIST_FOREACH(strs, char *, cp, tor_free(cp));
04070   smartlist_free(strs);
04071   tor_free(s);
04072   send_control_event_string(event, ALL_FORMATS, esc);
04073   send_control_event_string(event, ALL_FORMATS,
04074                             "650 OK\r\n");
04075 
04076   tor_free(esc);
04077   return 0;
04078 }
04079 
04082 int
04083 control_event_networkstatus_changed(smartlist_t *statuses)
04084 {
04085   return control_event_networkstatus_changed_helper(statuses, EVENT_NS, "NS");
04086 }
04087 
04090 int
04091 control_event_newconsensus(const networkstatus_t *consensus)
04092 {
04093   if (!control_event_is_interesting(EVENT_NEWCONSENSUS))
04094     return 0;
04095   return control_event_networkstatus_changed_helper(
04096            consensus->routerstatus_list, EVENT_NEWCONSENSUS, "NEWCONSENSUS");
04097 }
04098 
04100 int
04101 control_event_buildtimeout_set(const circuit_build_times_t *cbt,
04102                         buildtimeout_set_event_t type)
04103 {
04104   const char *type_string = NULL;
04105   double qnt;
04106 
04107   if (!control_event_is_interesting(EVENT_BUILDTIMEOUT_SET))
04108     return 0;
04109 
04110   qnt = circuit_build_times_quantile_cutoff();
04111 
04112   switch (type) {
04113     case BUILDTIMEOUT_SET_EVENT_COMPUTED:
04114       type_string = "COMPUTED";
04115       break;
04116     case BUILDTIMEOUT_SET_EVENT_RESET:
04117       type_string = "RESET";
04118       qnt = 1.0;
04119       break;
04120     case BUILDTIMEOUT_SET_EVENT_SUSPENDED:
04121       type_string = "SUSPENDED";
04122       qnt = 1.0;
04123       break;
04124     case BUILDTIMEOUT_SET_EVENT_DISCARD:
04125       type_string = "DISCARD";
04126       qnt = 1.0;
04127       break;
04128     case BUILDTIMEOUT_SET_EVENT_RESUME:
04129       type_string = "RESUME";
04130       break;
04131     default:
04132       type_string = "UNKNOWN";
04133       break;
04134   }
04135 
04136   send_control_event(EVENT_BUILDTIMEOUT_SET, ALL_FORMATS,
04137                      "650 BUILDTIMEOUT_SET %s TOTAL_TIMES=%lu "
04138                      "TIMEOUT_MS=%lu XM=%lu ALPHA=%f CUTOFF_QUANTILE=%f "
04139                      "TIMEOUT_RATE=%f CLOSE_MS=%lu CLOSE_RATE=%f\r\n",
04140                      type_string, (unsigned long)cbt->total_build_times,
04141                      (unsigned long)cbt->timeout_ms,
04142                      (unsigned long)cbt->Xm, cbt->alpha, qnt,
04143                      circuit_build_times_timeout_rate(cbt),
04144                      (unsigned long)cbt->close_ms,
04145                      circuit_build_times_close_rate(cbt));
04146 
04147   return 0;
04148 }
04149 
04151 int
04152 control_event_signal(uintptr_t signal)
04153 {
04154   const char *signal_string = NULL;
04155 
04156   if (!control_event_is_interesting(EVENT_SIGNAL))
04157     return 0;
04158 
04159   switch (signal) {
04160     case SIGHUP:
04161       signal_string = "RELOAD";
04162       break;
04163     case SIGUSR1:
04164       signal_string = "DUMP";
04165       break;
04166     case SIGUSR2:
04167       signal_string = "DEBUG";
04168       break;
04169     case SIGNEWNYM:
04170       signal_string = "NEWNYM";
04171       break;
04172     case SIGCLEARDNSCACHE:
04173       signal_string = "CLEARDNSCACHE";
04174       break;
04175     default:
04176       log_warn(LD_BUG, "Unrecognized signal %lu in control_event_signal",
04177                (unsigned long)signal);
04178       return -1;
04179   }
04180 
04181   send_control_event(EVENT_SIGNAL, ALL_FORMATS, "650 SIGNAL %s\r\n",
04182                      signal_string);
04183   return 0;
04184 }
04185 
04188 int
04189 control_event_networkstatus_changed_single(const routerstatus_t *rs)
04190 {
04191   smartlist_t *statuses;
04192   int r;
04193 
04194   if (!EVENT_IS_INTERESTING(EVENT_NS))
04195     return 0;
04196 
04197   statuses = smartlist_new();
04198   smartlist_add(statuses, (void*)rs);
04199   r = control_event_networkstatus_changed(statuses);
04200   smartlist_free(statuses);
04201   return r;
04202 }
04203 
04206 int
04207 control_event_my_descriptor_changed(void)
04208 {
04209   send_control_event(EVENT_DESCCHANGED, ALL_FORMATS, "650 DESCCHANGED\r\n");
04210   return 0;
04211 }
04212 
04217 static int
04218 control_event_status(int type, int severity, const char *format, va_list args)
04219 {
04220   char *user_buf = NULL;
04221   char format_buf[160];
04222   const char *status, *sev;
04223 
04224   switch (type) {
04225     case EVENT_STATUS_GENERAL:
04226       status = "STATUS_GENERAL";
04227       break;
04228     case EVENT_STATUS_CLIENT:
04229       status = "STATUS_CLIENT";
04230       break;
04231     case EVENT_STATUS_SERVER:
04232       status = "STATUS_SERVER";
04233       break;
04234     default:
04235       log_warn(LD_BUG, "Unrecognized status type %d", type);
04236       return -1;
04237   }
04238   switch (severity) {
04239     case LOG_NOTICE:
04240       sev = "NOTICE";
04241       break;
04242     case LOG_WARN:
04243       sev = "WARN";
04244       break;
04245     case LOG_ERR:
04246       sev = "ERR";
04247       break;
04248     default:
04249       log_warn(LD_BUG, "Unrecognized status severity %d", severity);
04250       return -1;
04251   }
04252   if (tor_snprintf(format_buf, sizeof(format_buf), "650 %s %s",
04253                    status, sev)<0) {
04254     log_warn(LD_BUG, "Format string too long.");
04255     return -1;
04256   }
04257   tor_vasprintf(&user_buf, format, args);
04258 
04259   send_control_event(type, ALL_FORMATS, "%s %s\r\n", format_buf, user_buf);
04260   tor_free(user_buf);
04261   return 0;
04262 }
04263 
04266 int
04267 control_event_general_status(int severity, const char *format, ...)
04268 {
04269   va_list ap;
04270   int r;
04271   if (!EVENT_IS_INTERESTING(EVENT_STATUS_GENERAL))
04272     return 0;
04273 
04274   va_start(ap, format);
04275   r = control_event_status(EVENT_STATUS_GENERAL, severity, format, ap);
04276   va_end(ap);
04277   return r;
04278 }
04279 
04282 int
04283 control_event_client_status(int severity, const char *format, ...)
04284 {
04285   va_list ap;
04286   int r;
04287   if (!EVENT_IS_INTERESTING(EVENT_STATUS_CLIENT))
04288     return 0;
04289 
04290   va_start(ap, format);
04291   r = control_event_status(EVENT_STATUS_CLIENT, severity, format, ap);
04292   va_end(ap);
04293   return r;
04294 }
04295 
04298 int
04299 control_event_server_status(int severity, const char *format, ...)
04300 {
04301   va_list ap;
04302   int r;
04303   if (!EVENT_IS_INTERESTING(EVENT_STATUS_SERVER))
04304     return 0;
04305 
04306   va_start(ap, format);
04307   r = control_event_status(EVENT_STATUS_SERVER, severity, format, ap);
04308   va_end(ap);
04309   return r;
04310 }
04311 
04315 int
04316 control_event_guard(const char *nickname, const char *digest,
04317                     const char *status)
04318 {
04319   char hbuf[HEX_DIGEST_LEN+1];
04320   base16_encode(hbuf, sizeof(hbuf), digest, DIGEST_LEN);
04321   if (!EVENT_IS_INTERESTING(EVENT_GUARD))
04322     return 0;
04323 
04324   {
04325     char buf[MAX_VERBOSE_NICKNAME_LEN+1];
04326     const node_t *node = node_get_by_id(digest);
04327     if (node) {
04328       node_get_verbose_nickname(node, buf);
04329     } else {
04330       tor_snprintf(buf, sizeof(buf), "$%s~%s", hbuf, nickname);
04331     }
04332     send_control_event(EVENT_GUARD, ALL_FORMATS,
04333                        "650 GUARD ENTRY %s %s\r\n", buf, status);
04334   }
04335   return 0;
04336 }
04337 
04342 int
04343 control_event_conf_changed(smartlist_t *elements)
04344 {
04345   int i;
04346   char *result;
04347   smartlist_t *lines;
04348   if (!EVENT_IS_INTERESTING(EVENT_CONF_CHANGED) ||
04349       smartlist_len(elements) == 0) {
04350     return 0;
04351   }
04352   lines = smartlist_new();
04353   for (i = 0; i < smartlist_len(elements); i += 2) {
04354     char *k = smartlist_get(elements, i);
04355     char *v = smartlist_get(elements, i+1);
04356     if (v == NULL) {
04357       smartlist_add_asprintf(lines, "650-%s", k);
04358     } else {
04359       smartlist_add_asprintf(lines, "650-%s=%s", k, v);
04360     }
04361   }
04362   result = smartlist_join_strings(lines, "\r\n", 0, NULL);
04363   send_control_event(EVENT_CONF_CHANGED, 0,
04364     "650-CONF_CHANGED\r\n%s\r\n650 OK\r\n", result);
04365   tor_free(result);
04366   SMARTLIST_FOREACH(lines, char *, cp, tor_free(cp));
04367   smartlist_free(lines);
04368   return 0;
04369 }
04370 
04373 static char *
04374 get_cookie_file(void)
04375 {
04376   const or_options_t *options = get_options();
04377   if (options->CookieAuthFile && strlen(options->CookieAuthFile)) {
04378     return tor_strdup(options->CookieAuthFile);
04379   } else {
04380     return get_datadir_fname("control_auth_cookie");
04381   }
04382 }
04383 
04388 int
04389 init_cookie_authentication(int enabled)
04390 {
04391   char *fname;
04392   if (!enabled) {
04393     authentication_cookie_is_set = 0;
04394     return 0;
04395   }
04396 
04397   /* We don't want to generate a new cookie every time we call
04398    * options_act(). One should be enough. */
04399   if (authentication_cookie_is_set)
04400     return 0; /* all set */
04401 
04402   fname = get_cookie_file();
04403   crypto_rand(authentication_cookie, AUTHENTICATION_COOKIE_LEN);
04404   authentication_cookie_is_set = 1;
04405   if (write_bytes_to_file(fname, authentication_cookie,
04406                           AUTHENTICATION_COOKIE_LEN, 1)) {
04407     log_warn(LD_FS,"Error writing authentication cookie to %s.",
04408              escaped(fname));
04409     tor_free(fname);
04410     return -1;
04411   }
04412 #ifndef _WIN32
04413   if (get_options()->CookieAuthFileGroupReadable) {
04414     if (chmod(fname, 0640)) {
04415       log_warn(LD_FS,"Unable to make %s group-readable.", escaped(fname));
04416     }
04417   }
04418 #endif
04419 
04420   tor_free(fname);
04421   return 0;
04422 }
04423 
04426 static char *owning_controller_process_spec = NULL;
04427 
04430 static tor_process_monitor_t *owning_controller_process_monitor = NULL;
04431 
04434 static void
04435 owning_controller_procmon_cb(void *unused)
04436 {
04437   (void)unused;
04438 
04439   lost_owning_controller("process", "vanished");
04440 }
04441 
04444 void
04445 monitor_owning_controller_process(const char *process_spec)
04446 {
04447   const char *msg;
04448 
04449   tor_assert((owning_controller_process_spec == NULL) ==
04450              (owning_controller_process_monitor == NULL));
04451 
04452   if (owning_controller_process_spec != NULL) {
04453     if ((process_spec != NULL) && !strcmp(process_spec,
04454                                           owning_controller_process_spec)) {
04455       /* Same process -- return now, instead of disposing of and
04456        * recreating the process-termination monitor. */
04457       return;
04458     }
04459 
04460     /* We are currently owned by a process, and we should no longer be
04461      * owned by it.  Free the process-termination monitor. */
04462     tor_process_monitor_free(owning_controller_process_monitor);
04463     owning_controller_process_monitor = NULL;
04464 
04465     tor_free(owning_controller_process_spec);
04466     owning_controller_process_spec = NULL;
04467   }
04468 
04469   tor_assert((owning_controller_process_spec == NULL) &&
04470              (owning_controller_process_monitor == NULL));
04471 
04472   if (process_spec == NULL)
04473     return;
04474 
04475   owning_controller_process_spec = tor_strdup(process_spec);
04476   owning_controller_process_monitor =
04477     tor_process_monitor_new(tor_libevent_get_base(),
04478                             owning_controller_process_spec,
04479                             LD_CONTROL,
04480                             owning_controller_procmon_cb, NULL,
04481                             &msg);
04482 
04483   if (owning_controller_process_monitor == NULL) {
04484     log_err(LD_BUG, "Couldn't create process-termination monitor for "
04485             "owning controller: %s.  Exiting.",
04486             msg);
04487     owning_controller_process_spec = NULL;
04488     tor_cleanup();
04489     exit(0);
04490   }
04491 }
04492 
04495 static int
04496 bootstrap_status_to_string(bootstrap_status_t s, const char **tag,
04497                            const char **summary)
04498 {
04499   switch (s) {
04500     case BOOTSTRAP_STATUS_UNDEF:
04501       *tag = "undef";
04502       *summary = "Undefined";
04503       break;
04504     case BOOTSTRAP_STATUS_STARTING:
04505       *tag = "starting";
04506       *summary = "Starting";
04507       break;
04508     case BOOTSTRAP_STATUS_CONN_DIR:
04509       *tag = "conn_dir";
04510       *summary = "Connecting to directory server";
04511       break;
04512     case BOOTSTRAP_STATUS_HANDSHAKE:
04513       *tag = "status_handshake";
04514       *summary = "Finishing handshake";
04515       break;
04516     case BOOTSTRAP_STATUS_HANDSHAKE_DIR:
04517       *tag = "handshake_dir";
04518       *summary = "Finishing handshake with directory server";
04519       break;
04520     case BOOTSTRAP_STATUS_ONEHOP_CREATE:
04521       *tag = "onehop_create";
04522       *summary = "Establishing an encrypted directory connection";
04523       break;
04524     case BOOTSTRAP_STATUS_REQUESTING_STATUS:
04525       *tag = "requesting_status";
04526       *summary = "Asking for networkstatus consensus";
04527       break;
04528     case BOOTSTRAP_STATUS_LOADING_STATUS:
04529       *tag = "loading_status";
04530       *summary = "Loading networkstatus consensus";
04531       break;
04532     case BOOTSTRAP_STATUS_LOADING_KEYS:
04533       *tag = "loading_keys";
04534       *summary = "Loading authority key certs";
04535       break;
04536     case BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS:
04537       *tag = "requesting_descriptors";
04538       *summary = "Asking for relay descriptors";
04539       break;
04540     case BOOTSTRAP_STATUS_LOADING_DESCRIPTORS:
04541       *tag = "loading_descriptors";
04542       *summary = "Loading relay descriptors";
04543       break;
04544     case BOOTSTRAP_STATUS_CONN_OR:
04545       *tag = "conn_or";
04546       *summary = "Connecting to the Tor network";
04547       break;
04548     case BOOTSTRAP_STATUS_HANDSHAKE_OR:
04549       *tag = "handshake_or";
04550       *summary = "Finishing handshake with first hop";
04551       break;
04552     case BOOTSTRAP_STATUS_CIRCUIT_CREATE:
04553       *tag = "circuit_create";
04554       *summary = "Establishing a Tor circuit";
04555       break;
04556     case BOOTSTRAP_STATUS_DONE:
04557       *tag = "done";
04558       *summary = "Done";
04559       break;
04560     default:
04561 //      log_warn(LD_BUG, "Unrecognized bootstrap status code %d", s);
04562       *tag = *summary = "unknown";
04563       return -1;
04564   }
04565   return 0;
04566 }
04567 
04573 static int bootstrap_percent = BOOTSTRAP_STATUS_UNDEF;
04574 
04579 static int bootstrap_problems = 0;
04580 
04581 /* We only tell the controller once we've hit a threshold of problems
04582  * for the current phase. */
04583 #define BOOTSTRAP_PROBLEM_THRESHOLD 10
04584 
04591 void
04592 control_event_bootstrap(bootstrap_status_t status, int progress)
04593 {
04594   const char *tag, *summary;
04595   char buf[BOOTSTRAP_MSG_LEN];
04596 
04597   if (bootstrap_percent == BOOTSTRAP_STATUS_DONE)
04598     return; /* already bootstrapped; nothing to be done here. */
04599 
04600   /* special case for handshaking status, since our TLS handshaking code
04601    * can't distinguish what the connection is going to be for. */
04602   if (status == BOOTSTRAP_STATUS_HANDSHAKE) {
04603     if (bootstrap_percent < BOOTSTRAP_STATUS_CONN_OR) {
04604       status =  BOOTSTRAP_STATUS_HANDSHAKE_DIR;
04605     } else {
04606       status = BOOTSTRAP_STATUS_HANDSHAKE_OR;
04607     }
04608   }
04609 
04610   if (status > bootstrap_percent ||
04611       (progress && progress > bootstrap_percent)) {
04612     bootstrap_status_to_string(status, &tag, &summary);
04613     log(status ? LOG_NOTICE : LOG_INFO, LD_CONTROL,
04614         "Bootstrapped %d%%: %s.", progress ? progress : status, summary);
04615     tor_snprintf(buf, sizeof(buf),
04616         "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\"",
04617         progress ? progress : status, tag, summary);
04618     tor_snprintf(last_sent_bootstrap_message,
04619                  sizeof(last_sent_bootstrap_message),
04620                  "NOTICE %s", buf);
04621     control_event_client_status(LOG_NOTICE, "%s", buf);
04622     if (status > bootstrap_percent) {
04623       bootstrap_percent = status; /* new milestone reached */
04624     }
04625     if (progress > bootstrap_percent) {
04626       /* incremental progress within a milestone */
04627       bootstrap_percent = progress;
04628       bootstrap_problems = 0; /* Progress! Reset our problem counter. */
04629     }
04630   }
04631 }
04632 
04637 void
04638 control_event_bootstrap_problem(const char *warn, int reason)
04639 {
04640   int status = bootstrap_percent;
04641   const char *tag, *summary;
04642   char buf[BOOTSTRAP_MSG_LEN];
04643   const char *recommendation = "ignore";
04644   int severity;
04645 
04646   /* bootstrap_percent must not be in "undefined" state here. */
04647   tor_assert(status >= 0);
04648 
04649   if (bootstrap_percent == 100)
04650     return; /* already bootstrapped; nothing to be done here. */
04651 
04652   bootstrap_problems++;
04653 
04654   if (bootstrap_problems >= BOOTSTRAP_PROBLEM_THRESHOLD)
04655     recommendation = "warn";
04656 
04657   if (reason == END_OR_CONN_REASON_NO_ROUTE)
04658     recommendation = "warn";
04659 
04660   if (get_options()->UseBridges &&
04661       !any_bridge_descriptors_known() &&
04662       !any_pending_bridge_descriptor_fetches())
04663     recommendation = "warn";
04664 
04665   while (status>=0 && bootstrap_status_to_string(status, &tag, &summary) < 0)
04666     status--; /* find a recognized status string based on current progress */
04667   status = bootstrap_percent; /* set status back to the actual number */
04668 
04669   severity = !strcmp(recommendation, "warn") ? LOG_WARN : LOG_INFO;
04670 
04671   log_fn(severity,
04672          LD_CONTROL, "Problem bootstrapping. Stuck at %d%%: %s. (%s; %s; "
04673          "count %d; recommendation %s)",
04674          status, summary, warn,
04675          orconn_end_reason_to_control_string(reason),
04676          bootstrap_problems, recommendation);
04677 
04678   connection_or_report_broken_states(severity, LD_HANDSHAKE);
04679 
04680   tor_snprintf(buf, sizeof(buf),
04681       "BOOTSTRAP PROGRESS=%d TAG=%s SUMMARY=\"%s\" WARNING=\"%s\" REASON=%s "
04682       "COUNT=%d RECOMMENDATION=%s",
04683       bootstrap_percent, tag, summary, warn,
04684       orconn_end_reason_to_control_string(reason), bootstrap_problems,
04685       recommendation);
04686   tor_snprintf(last_sent_bootstrap_message,
04687                sizeof(last_sent_bootstrap_message),
04688                "WARN %s", buf);
04689   control_event_client_status(LOG_WARN, "%s", buf);
04690 }
04691 
04695 void
04696 control_event_clients_seen(const char *controller_str)
04697 {
04698   send_control_event(EVENT_CLIENTS_SEEN, 0,
04699     "650 CLIENTS_SEEN %s\r\n", controller_str);
04700 }
04701