aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNick Mathewson <nickm@torproject.org>2006-10-20 14:57:46 +0000
committerNick Mathewson <nickm@torproject.org>2006-10-20 14:57:46 +0000
commit136ed3307140ff82ade78f21765e43c87902d240 (patch)
tree99b1d79e39d022885b82f52f02b5df05ee0c7015
parent77936aa337b05cfea073bced284d764b1a96e852 (diff)
downloadtor-136ed3307140ff82ade78f21765e43c87902d240.tar.gz
tor-136ed3307140ff82ade78f21765e43c87902d240.zip
r9289@31-35-219: nickm | 2006-10-20 09:43:22 -0400
Fix longstanding bug in connection_exit_begin_conn(): Since connection_edge_end() exits when the connection is unattached, we were never sending RELAY_END cells back for failed RELAY_BEGIN attempts. Fix this. This might make clients that were otherwise timing out either fail faster or retry faster, which is good news for us. svn:r8770
-rw-r--r--ChangeLog4
-rw-r--r--doc/TODO4
-rw-r--r--src/or/connection_edge.c65
-rw-r--r--src/or/or.h3
-rw-r--r--src/or/relay.c83
5 files changed, 107 insertions, 52 deletions
diff --git a/ChangeLog b/ChangeLog
index 6dddeeb5e5..e779146968 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -48,6 +48,10 @@ Changes in version 0.1.2.3-alpha - 2006-10-??
- Detect the size of the routers file correctly even if it is corrupted
(on systems without mmap) or not page-aligned (on systems with mmap).
This bug was harmless.
+ - Implement the protocol correctly by always sending a RELAY_END cell
+ when an attempt to open a stream fails. This should make clients
+ able to find a good exit faster in some cases, since unhandleable
+ requests will now get an error rather than timing out.
Changes in version 0.1.2.2-alpha - 2006-10-07
diff --git a/doc/TODO b/doc/TODO
index 018f7f990a..d38d4da015 100644
--- a/doc/TODO
+++ b/doc/TODO
@@ -57,9 +57,9 @@ N . Have (and document) a BEGIN_DIR relay cell that means "Connect to your
- Use for something, so we can be sure it works.
- Test and debug
-N - Send back RELAY_END cells on malformed RELAY_BEGIN.
+ o Send back RELAY_END cells on malformed RELAY_BEGIN.
-N - Change the circuit end reason display a little for reasons from
+ o Change the circuit end reason display a little for reasons from
destroyed/truncated circuits. We want to indicate both that we're
closing because somebody told us to, and why they told us they wanted to
close.
diff --git a/src/or/connection_edge.c b/src/or/connection_edge.c
index 854e75566e..d3232a2475 100644
--- a/src/or/connection_edge.c
+++ b/src/or/connection_edge.c
@@ -1838,36 +1838,51 @@ connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
relay_header_t rh;
char *address=NULL;
uint16_t port;
+ char end_payload[1];
assert_circuit_ok(circ);
- /* XXX currently we don't send an end cell back if we drop the
- * begin because it's malformed.
- */
+ relay_header_unpack(&rh, cell->payload);
+
+ /* Note: we have to use relay_send_command_from_edge here, not
+ * connection_edge_end or connection_edge_send_command, since those require
+ * that we have a stream connected to a circuit, and we don't connect to a
+ * circuit unitl we have a pending/sucessful resolve. */
if (!server_mode(get_options()) &&
circ->purpose != CIRCUIT_PURPOSE_S_REND_JOINED) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Relay begin cell at non-server. Dropping.");
+ end_payload[0] = END_STREAM_REASON_EXITPOLICY;
+ relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
+ end_payload, 1, NULL);
return 0;
}
- relay_header_unpack(&rh, cell->payload);
if (rh.command == RELAY_COMMAND_BEGIN) {
if (!memchr(cell->payload+RELAY_HEADER_SIZE, 0, rh.length)) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Relay begin cell has no \\0. Dropping.");
+ end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
+ relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
+ end_payload, 1, NULL);
return 0;
}
if (parse_addr_port(LOG_PROTOCOL_WARN, cell->payload+RELAY_HEADER_SIZE,
&address,NULL,&port)<0) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Unable to parse addr:port in relay begin cell. Dropping.");
+ end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
+ relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
+ end_payload, 1, NULL);
return 0;
}
if (port==0) {
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Missing port in relay begin cell. Dropping.");
+ end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
+ relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
+ end_payload, 1, NULL);
tor_free(address);
return 0;
}
@@ -1876,6 +1891,9 @@ connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Non-printing characters in address %s in relay "
"begin cell. Dropping.", escaped(address));
+ end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
+ relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
+ end_payload, 1, NULL);
tor_free(address);
return 0;
}
@@ -1886,15 +1904,27 @@ connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
*/
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Attempt to open a stream on first hop of circuit. Dropping.");
+ end_payload[0] = END_STREAM_REASON_TORPROTOCOL;
+ relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
+ end_payload, 1, NULL);
tor_free(address);
return 0;
}
} else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
or_options_t *options = get_options();
+ port = options->DirPort; /* not actually used to open a connection */
+ if (!port || circ->purpose != CIRCUIT_PURPOSE_OR) {
+ end_payload[0] = END_STREAM_REASON_NOTDIRECTORY;
+ relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
+ end_payload, 1, NULL);
+ return 0;
+ }
address = tor_strdup("127.0.0.1");
- port = options->DirPort; /* not actually used. */
} else {
log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
+ end_payload[0] = END_STREAM_REASON_INTERNAL;
+ relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
+ end_payload, 1, NULL);
return 0;
}
@@ -1908,15 +1938,6 @@ connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
n_stream->package_window = STREAMWINDOW_START;
n_stream->deliver_window = STREAMWINDOW_START;
- if (rh.command == RELAY_COMMAND_BEGIN_DIR &&
- (!get_options()->DirPort || circ->purpose != CIRCUIT_PURPOSE_OR)) {
- connection_edge_end(n_stream, END_STREAM_REASON_NOTDIRECTORY,
- n_stream->cpath_layer);
- connection_free(TO_CONN(n_stream));
- tor_free(address);
- return 0;
- }
-
if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
log_debug(LD_REND,"begin is for rendezvous. configuring stream.");
@@ -1929,8 +1950,9 @@ connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
if (rend_service_set_connection_addr_port(n_stream, origin_circ) < 0) {
log_info(LD_REND,"Didn't find rendezvous service (port %d)",
n_stream->_base.port);
- connection_edge_end(n_stream, END_STREAM_REASON_EXITPOLICY,
- n_stream->cpath_layer);
+ end_payload[0] = END_STREAM_REASON_EXITPOLICY;
+ relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
+ end_payload, 1, NULL);
connection_free(TO_CONN(n_stream));
/* knock the whole thing down, somebody screwed up */
circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
@@ -1957,8 +1979,9 @@ connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
/* default to failed, change in dns_resolve if it turns out not to fail */
if (we_are_hibernating()) {
- connection_edge_end(n_stream, END_STREAM_REASON_HIBERNATING,
- n_stream->cpath_layer);
+ end_payload[0] = END_STREAM_REASON_HIBERNATING;
+ relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
+ end_payload, 1, NULL);
connection_free(TO_CONN(n_stream));
return 0;
}
@@ -1985,7 +2008,9 @@ connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
connection_exit_connect(n_stream);
return 0;
case -1: /* resolve failed */
- /* XXXX send back indication of failure for connect case? -NM*/
+ end_payload[0] = END_STREAM_REASON_RESOLVEFAILED;
+ relay_send_command_from_edge(rh.stream_id, circ, RELAY_COMMAND_END,
+ end_payload, 1, NULL);
/* n_stream got freed. don't touch it. */
break;
case 0: /* resolve added to pending list */
@@ -2157,7 +2182,7 @@ connection_exit_connect_dir(edge_connection_t *exit_conn)
if ((err = tor_socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) < 0) {
log_warn(LD_NET,
- "Couldn't construct socketpair (%s). Network down? Delaying.",
+ "Couldn't construct socketpair (%s). Out of sockets?",
tor_socket_strerror(-err));
connection_edge_end(exit_conn, END_STREAM_REASON_RESOURCELIMIT,
exit_conn->cpath_layer);
diff --git a/src/or/or.h b/src/or/or.h
index 1ca35c46fb..f44f8a2a90 100644
--- a/src/or/or.h
+++ b/src/or/or.h
@@ -2332,6 +2332,9 @@ int circuit_receive_relay_cell(cell_t *cell, circuit_t *circ,
void relay_header_pack(char *dest, const relay_header_t *src);
void relay_header_unpack(relay_header_t *dest, const char *src);
+int relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
+ int relay_command, const char *payload,
+ size_t payload_len, crypt_path_t *cpath_layer);
int connection_edge_send_command(edge_connection_t *fromconn, circuit_t *circ,
int relay_command, const char *payload,
size_t payload_len,
diff --git a/src/or/relay.c b/src/or/relay.c
index bfea129270..f70ed23170 100644
--- a/src/or/relay.c
+++ b/src/or/relay.c
@@ -446,17 +446,17 @@ relay_header_unpack(relay_header_t *dest, const char *src)
dest->length = ntohs(get_uint16(src+9));
}
-/** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
- * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
- * that's sending the relay cell, or NULL if it's a control cell.
- * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
- * for OP->OR cells.
+/** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and send
+ * it onto the open circuit <b>circ</b>. <b>stream_id</b> is the ID on
+ * <b>circ</b> for the stream that's sending the relay cell, or 0 if it's a
+ * control cell. <b>cpath_layer</b> is NULL for OR->OP cells, or the
+ * destination hop for OP->OR cells.
*
- * If you can't send the cell, mark the circuit for close and
- * return -1. Else return 0.
+ * If you can't send the cell, mark the circuit for close and return -1. Else
+ * return 0.
*/
int
-connection_edge_send_command(edge_connection_t *fromconn, circuit_t *circ,
+relay_send_command_from_edge(uint16_t stream_id, circuit_t *circ,
int relay_command, const char *payload,
size_t payload_len, crypt_path_t *cpath_layer)
{
@@ -465,26 +465,7 @@ connection_edge_send_command(edge_connection_t *fromconn, circuit_t *circ,
int cell_direction;
/* XXXX NM Split this function into a separate versions per circuit type? */
- if (fromconn && fromconn->_base.marked_for_close) {
- log_warn(LD_BUG,
- "Bug: called on conn that's already marked for close at %s:%d.",
- fromconn->_base.marked_for_close_file,
- fromconn->_base.marked_for_close);
- return 0;
- }
-
- if (!circ) {
- tor_assert(fromconn);
- if (fromconn->_base.type == CONN_TYPE_AP) {
- log_info(LD_APP,"no circ. Closing conn.");
- connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
- } else {
- log_info(LD_EXIT,"no circ. Closing conn.");
- fromconn->_base.edge_has_sent_end = 1; /* no circ to send to */
- connection_mark_for_close(TO_CONN(fromconn));
- }
- return -1;
- }
+ tor_assert(circ);
memset(&cell, 0, sizeof(cell_t));
cell.command = CELL_RELAY;
@@ -500,8 +481,7 @@ connection_edge_send_command(edge_connection_t *fromconn, circuit_t *circ,
memset(&rh, 0, sizeof(rh));
rh.command = relay_command;
- if (fromconn)
- rh.stream_id = fromconn->stream_id; /* else it's 0 */
+ rh.stream_id = stream_id;
rh.length = payload_len;
relay_header_pack(cell.payload, &rh);
if (payload_len) {
@@ -521,6 +501,48 @@ connection_edge_send_command(edge_connection_t *fromconn, circuit_t *circ,
return 0;
}
+/** Make a relay cell out of <b>relay_command</b> and <b>payload</b>, and
+ * send it onto the open circuit <b>circ</b>. <b>fromconn</b> is the stream
+ * that's sending the relay cell, or NULL if it's a control cell.
+ * <b>cpath_layer</b> is NULL for OR->OP cells, or the destination hop
+ * for OP->OR cells.
+ *
+ * If you can't send the cell, mark the circuit for close and
+ * return -1. Else return 0.
+ */
+int
+connection_edge_send_command(edge_connection_t *fromconn, circuit_t *circ,
+ int relay_command, const char *payload,
+ size_t payload_len, crypt_path_t *cpath_layer)
+{
+ /* XXXX NM Split this function into a separate versions per circuit type? */
+
+ if (fromconn && fromconn->_base.marked_for_close) {
+ log_warn(LD_BUG,
+ "Bug: called on conn that's already marked for close at %s:%d.",
+ fromconn->_base.marked_for_close_file,
+ fromconn->_base.marked_for_close);
+ return 0;
+ }
+
+ if (!circ) {
+ tor_assert(fromconn);
+ if (fromconn->_base.type == CONN_TYPE_AP) {
+ log_info(LD_APP,"no circ. Closing conn.");
+ connection_mark_unattached_ap(fromconn, END_STREAM_REASON_INTERNAL);
+ } else {
+ log_info(LD_EXIT,"no circ. Closing conn.");
+ fromconn->_base.edge_has_sent_end = 1; /* no circ to send to */
+ connection_mark_for_close(TO_CONN(fromconn));
+ }
+ return -1;
+ }
+
+ return relay_send_command_from_edge(fromconn ? fromconn->stream_id : 0,
+ circ, relay_command, payload,
+ payload_len, cpath_layer);
+}
+
/** Translate <b>reason</b>, which came from a relay 'end' cell,
* into a static const string describing why the stream is closing.
* <b>reason</b> is -1 if no reason was provided.
@@ -545,6 +567,7 @@ connection_edge_end_reason_str(int reason)
case END_STREAM_REASON_RESOURCELIMIT: return "server out of resources";
case END_STREAM_REASON_CONNRESET: return "connection reset";
case END_STREAM_REASON_TORPROTOCOL: return "Tor protocol error";
+ case END_STREAM_REASON_NOTDIRECTORY: return "not a directory";
default:
log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
"Reason for ending (%d) not recognized.",reason);
834'>834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
/* Copyright (c) 2015-2017, The Tor Project, Inc. */
/* See LICENSE for licensing information */

#define CONTROL_PRIVATE
#include "or.h"
#include "bridges.h"
#include "control.h"
#include "entrynodes.h"
#include "hs_common.h"
#include "networkstatus.h"
#include "rendservice.h"
#include "routerlist.h"
#include "test.h"
#include "test_helpers.h"

#include "control_connection_st.h"

static void
test_add_onion_helper_keyarg_v3(void *arg)
{
  int ret, hs_version;
  add_onion_secret_key_t pk;
  char *key_new_blob = NULL;
  char *err_msg = NULL;
  const char *key_new_alg = NULL;

  (void) arg;

  memset(&pk, 0, sizeof(pk));

  /* Test explicit ED25519-V3 key generation. */
  ret = add_onion_helper_keyarg("NEW:ED25519-V3", 0, &key_new_alg,
                                &key_new_blob, &pk, &hs_version,
                                &err_msg);
  tt_int_op(ret, OP_EQ, 0);
  tt_int_op(hs_version, OP_EQ, HS_VERSION_THREE);
  tt_assert(pk.v3);
  tt_str_op(key_new_alg, OP_EQ, "ED25519-V3");
  tt_assert(key_new_blob);
  tt_ptr_op(err_msg, OP_EQ, NULL);
  tor_free(pk.v3); pk.v3 = NULL;
  tor_free(key_new_blob);

  /* Test discarding the private key. */
  ret = add_onion_helper_keyarg("NEW:ED25519-V3", 1, &key_new_alg,
                                &key_new_blob, &pk, &hs_version,
                                &err_msg);
  tt_int_op(ret, OP_EQ, 0);
  tt_int_op(hs_version, OP_EQ, HS_VERSION_THREE);
  tt_assert(pk.v3);
  tt_ptr_op(key_new_alg, OP_EQ, NULL);
  tt_ptr_op(key_new_blob, OP_EQ, NULL);
  tt_ptr_op(err_msg, OP_EQ, NULL);
  tor_free(pk.v3); pk.v3 = NULL;
  tor_free(key_new_blob);

  /* Test passing a key blob. */
  {
    /* The base64 key and hex key are the same. Hex key is 64 bytes long. The
     * sk has been generated randomly using python3. */
    const char *base64_sk =
      "a9bT19PqGC9Y+BmOo1IQvCGjjwxMiaaxEXZ+FKMxpEQW"
      "6AmSV5roThUGMRCaqQSCnR2jI1vL2QxHORzI4RxMmw==";
    const char *hex_sk =
      "\x6b\xd6\xd3\xd7\xd3\xea\x18\x2f\x58\xf8\x19\x8e\xa3\x52\x10\xbc"
      "\x21\xa3\x8f\x0c\x4c\x89\xa6\xb1\x11\x76\x7e\x14\xa3\x31\xa4\x44"
      "\x16\xe8\x09\x92\x57\x9a\xe8\x4e\x15\x06\x31\x10\x9a\xa9\x04\x82"
      "\x9d\x1d\xa3\x23\x5b\xcb\xd9\x0c\x47\x39\x1c\xc8\xe1\x1c\x4c\x9b";
    char *key_blob = NULL;

    tor_asprintf(&key_blob, "ED25519-V3:%s", base64_sk);
    tt_assert(key_blob);
    ret = add_onion_helper_keyarg(key_blob, 1, &key_new_alg,
                                  &key_new_blob, &pk, &hs_version,
                                  &err_msg);
    tor_free(key_blob);
    tt_int_op(ret, OP_EQ, 0);
    tt_int_op(hs_version, OP_EQ, HS_VERSION_THREE);
    tt_assert(pk.v3);
    tt_mem_op(pk.v3, OP_EQ, hex_sk, 64);
    tt_ptr_op(key_new_alg, OP_EQ, NULL);
    tt_ptr_op(key_new_blob, OP_EQ, NULL);
    tt_ptr_op(err_msg, OP_EQ, NULL);
    tor_free(pk.v3); pk.v3 = NULL;
    tor_free(key_new_blob);
  }

 done:
  tor_free(pk.v3);
  tor_free(key_new_blob);
  tor_free(err_msg);
}

static void
test_add_onion_helper_keyarg_v2(void *arg)
{
  int ret, hs_version;
  add_onion_secret_key_t pk;
  crypto_pk_t *pk1 = NULL;
  const char *key_new_alg = NULL;
  char *key_new_blob = NULL;
  char *err_msg = NULL;
  char *encoded = NULL;
  char *arg_str = NULL;

  (void) arg;

  memset(&pk, 0, sizeof(pk));

  /* Test explicit RSA1024 key generation. */
  ret = add_onion_helper_keyarg("NEW:RSA1024", 0, &key_new_alg, &key_new_blob,
                                &pk, &hs_version, &err_msg);
  tt_int_op(ret, OP_EQ, 0);
  tt_int_op(hs_version, OP_EQ, HS_VERSION_TWO);
  tt_assert(pk.v2);
  tt_str_op(key_new_alg, OP_EQ, "RSA1024");
  tt_assert(key_new_blob);
  tt_ptr_op(err_msg, OP_EQ, NULL);

  /* Test "BEST" key generation (Assumes BEST = RSA1024). */
  crypto_pk_free(pk.v2); pk.v2 = NULL;
  tor_free(key_new_blob);
  ret = add_onion_helper_keyarg("NEW:BEST", 0, &key_new_alg, &key_new_blob,
                                &pk, &hs_version, &err_msg);
  tt_int_op(ret, OP_EQ, 0);
  tt_int_op(hs_version, OP_EQ, HS_VERSION_TWO);
  tt_assert(pk.v2);
  tt_str_op(key_new_alg, OP_EQ, "RSA1024");
  tt_assert(key_new_blob);
  tt_ptr_op(err_msg, OP_EQ, NULL);

  /* Test discarding the private key. */
  crypto_pk_free(pk.v2); pk.v2 = NULL;
  tor_free(key_new_blob);
  ret = add_onion_helper_keyarg("NEW:BEST", 1, &key_new_alg, &key_new_blob,
                               &pk, &hs_version, &err_msg);
  tt_int_op(ret, OP_EQ, 0);
  tt_int_op(hs_version, OP_EQ, HS_VERSION_TWO);
  tt_assert(pk.v2);
  tt_ptr_op(key_new_alg, OP_EQ, NULL);
  tt_ptr_op(key_new_blob, OP_EQ, NULL);
  tt_ptr_op(err_msg, OP_EQ, NULL);

  /* Test generating a invalid key type. */
  crypto_pk_free(pk.v2); pk.v2 = NULL;
  ret = add_onion_helper_keyarg("NEW:RSA512", 0, &key_new_alg, &key_new_blob,
                               &pk, &hs_version, &err_msg);
  tt_int_op(ret, OP_EQ, -1);
  tt_int_op(hs_version, OP_EQ, HS_VERSION_TWO);
  tt_assert(!pk.v2);
  tt_ptr_op(key_new_alg, OP_EQ, NULL);
  tt_ptr_op(key_new_blob, OP_EQ, NULL);
  tt_assert(err_msg);

  /* Test loading a RSA1024 key. */
  tor_free(err_msg);
  pk1 = pk_generate(0);
  tt_int_op(0, OP_EQ, crypto_pk_base64_encode(pk1, &encoded));
  tor_asprintf(&arg_str, "RSA1024:%s", encoded);
  ret = add_onion_helper_keyarg(arg_str, 0, &key_new_alg, &key_new_blob,
                                &pk, &hs_version, &err_msg);
  tt_int_op(ret, OP_EQ, 0);
  tt_int_op(hs_version, OP_EQ, HS_VERSION_TWO);
  tt_assert(pk.v2);
  tt_ptr_op(key_new_alg, OP_EQ, NULL);
  tt_ptr_op(key_new_blob, OP_EQ, NULL);
  tt_ptr_op(err_msg, OP_EQ, NULL);
  tt_int_op(crypto_pk_cmp_keys(pk1, pk.v2), OP_EQ, 0);

  /* Test loading a invalid key type. */
  tor_free(arg_str);
  crypto_pk_free(pk1); pk1 = NULL;
  crypto_pk_free(pk.v2); pk.v2 = NULL;
  tor_asprintf(&arg_str, "RSA512:%s", encoded);
  ret = add_onion_helper_keyarg(arg_str, 0, &key_new_alg, &key_new_blob,
                                &pk, &hs_version, &err_msg);
  tt_int_op(ret, OP_EQ, -1);
  tt_int_op(hs_version, OP_EQ, HS_VERSION_TWO);
  tt_assert(!pk.v2);
  tt_ptr_op(key_new_alg, OP_EQ, NULL);
  tt_ptr_op(key_new_blob, OP_EQ, NULL);
  tt_assert(err_msg);

  /* Test loading a invalid key. */
  tor_free(arg_str);
  crypto_pk_free(pk.v2); pk.v2 = NULL;
  tor_free(err_msg);
  encoded[strlen(encoded)/2] = '\0';
  tor_asprintf(&arg_str, "RSA1024:%s", encoded);
  ret = add_onion_helper_keyarg(arg_str, 0, &key_new_alg, &key_new_blob,
                               &pk, &hs_version, &err_msg);
  tt_int_op(ret, OP_EQ, -1);
  tt_int_op(hs_version, OP_EQ, HS_VERSION_TWO);
  tt_assert(!pk.v2);
  tt_ptr_op(key_new_alg, OP_EQ, NULL);
  tt_ptr_op(key_new_blob, OP_EQ, NULL);
  tt_assert(err_msg);

 done:
  crypto_pk_free(pk1);
  crypto_pk_free(pk.v2);
  tor_free(key_new_blob);
  tor_free(err_msg);
  tor_free(encoded);
  tor_free(arg_str);
}

static void
test_getinfo_helper_onion(void *arg)
{
  (void)arg;
  control_connection_t dummy;
  /* Get results out */
  char *answer = NULL;
  const char *errmsg = NULL;
  char *service_id = NULL;
  int rt = 0;

  dummy.ephemeral_onion_services = NULL;

  /* successfully get an empty answer */
  rt = getinfo_helper_onions(&dummy, "onions/current", &answer, &errmsg);
  tt_int_op(rt, OP_EQ, 0);
  tt_str_op(answer, OP_EQ, "");
  tor_free(answer);

  /* successfully get an empty answer */
  rt = getinfo_helper_onions(&dummy, "onions/detached", &answer, &errmsg);
  tt_int_op(rt, OP_EQ, 0);
  tt_str_op(answer, OP_EQ, "");
  tor_free(answer);

  /* get an answer for one onion service */
  service_id = tor_strdup("dummy_onion_id");
  dummy.ephemeral_onion_services = smartlist_new();
  smartlist_add(dummy.ephemeral_onion_services, service_id);
  rt = getinfo_helper_onions(&dummy, "onions/current", &answer, &errmsg);
  tt_int_op(rt, OP_EQ, 0);
  tt_str_op(answer, OP_EQ, "dummy_onion_id");

 done:
  tor_free(answer);
  tor_free(service_id);
  smartlist_free(dummy.ephemeral_onion_services);
}

static void
test_rend_service_parse_port_config(void *arg)
{
  const char *sep = ",";
  rend_service_port_config_t *cfg = NULL;
  char *err_msg = NULL;

  (void)arg;

  /* Test "VIRTPORT" only. */
  cfg = rend_service_parse_port_config("80", sep, &err_msg);
  tt_assert(cfg);
  tt_ptr_op(err_msg, OP_EQ, NULL);

  /* Test "VIRTPORT,TARGET" (Target is port). */
  rend_service_port_config_free(cfg);
  cfg = rend_service_parse_port_config("80,8080", sep, &err_msg);
  tt_assert(cfg);
  tt_ptr_op(err_msg, OP_EQ, NULL);

  /* Test "VIRTPORT,TARGET" (Target is IPv4:port). */
  rend_service_port_config_free(cfg);
  cfg = rend_service_parse_port_config("80,192.0.2.1:8080", sep, &err_msg);
  tt_assert(cfg);
  tt_ptr_op(err_msg, OP_EQ, NULL);

  /* Test "VIRTPORT,TARGET" (Target is IPv6:port). */
  rend_service_port_config_free(cfg);
  cfg = rend_service_parse_port_config("80,[2001:db8::1]:8080", sep, &err_msg);
  tt_assert(cfg);
  tt_ptr_op(err_msg, OP_EQ, NULL);
  rend_service_port_config_free(cfg);
  cfg = NULL;

  /* XXX: Someone should add tests for AF_UNIX targets if supported. */

  /* Test empty config. */
  rend_service_port_config_free(cfg);
  cfg = rend_service_parse_port_config("", sep, &err_msg);
  tt_ptr_op(cfg, OP_EQ, NULL);
  tt_assert(err_msg);

  /* Test invalid port. */
  tor_free(err_msg);
  cfg = rend_service_parse_port_config("90001", sep, &err_msg);
  tt_ptr_op(cfg, OP_EQ, NULL);
  tt_assert(err_msg);
  tor_free(err_msg);

  /* unix port */
  cfg = NULL;

  /* quoted unix port */
  tor_free(err_msg);
  cfg = rend_service_parse_port_config("100 unix:\"/tmp/foo bar\"",
                                       " ", &err_msg);
  tt_assert(cfg);
  tt_ptr_op(err_msg, OP_EQ, NULL);
  rend_service_port_config_free(cfg);
  cfg = NULL;

  /* quoted unix port */
  tor_free(err_msg);
  cfg = rend_service_parse_port_config("100 unix:\"/tmp/foo bar\"",
                                       " ", &err_msg);
  tt_assert(cfg);
  tt_ptr_op(err_msg, OP_EQ, NULL);
  rend_service_port_config_free(cfg);
  cfg = NULL;

  /* quoted unix port, missing end quote */
  cfg = rend_service_parse_port_config("100 unix:\"/tmp/foo bar",
                                       " ", &err_msg);
  tt_ptr_op(cfg, OP_EQ, NULL);
  tt_str_op(err_msg, OP_EQ, "Couldn't process address <unix:\"/tmp/foo bar> "
            "from hidden service configuration");
  tor_free(err_msg);

  /* bogus IP address */
  MOCK(tor_addr_lookup, mock_tor_addr_lookup__fail_on_bad_addrs);
  cfg = rend_service_parse_port_config("100 foo!!.example.com:9000",
                                       " ", &err_msg);
  UNMOCK(tor_addr_lookup);
  tt_ptr_op(cfg, OP_EQ, NULL);
  tt_str_op(err_msg, OP_EQ, "Unparseable address in hidden service port "
            "configuration.");
  tor_free(err_msg);

  /* bogus port port */
  cfg = rend_service_parse_port_config("100 99999",
                                       " ", &err_msg);
  tt_ptr_op(cfg, OP_EQ, NULL);
  tt_str_op(err_msg, OP_EQ, "Unparseable or out-of-range port \"99999\" "
            "in hidden service port configuration.");
  tor_free(err_msg);

 done:
  rend_service_port_config_free(cfg);
  tor_free(err_msg);
}

static void
test_add_onion_helper_clientauth(void *arg)
{
  rend_authorized_client_t *client = NULL;
  char *err_msg = NULL;
  int created = 0;

  (void)arg;

  /* Test "ClientName" only. */
  client = add_onion_helper_clientauth("alice", &created, &err_msg);
  tt_assert(client);
  tt_assert(created);
  tt_ptr_op(err_msg, OP_EQ, NULL);
  rend_authorized_client_free(client);

  /* Test "ClientName:Blob" */
  client = add_onion_helper_clientauth("alice:475hGBHPlq7Mc0cRZitK/B",
                                       &created, &err_msg);
  tt_assert(client);
  tt_assert(!created);
  tt_ptr_op(err_msg, OP_EQ, NULL);
  rend_authorized_client_free(client);

  /* Test invalid client names */
  client = add_onion_helper_clientauth("no*asterisks*allowed", &created,
                                       &err_msg);
  tt_ptr_op(client, OP_EQ, NULL);
  tt_assert(err_msg);
  tor_free(err_msg);

  /* Test invalid auth cookie */
  client = add_onion_helper_clientauth("alice:12345", &created, &err_msg);
  tt_ptr_op(client, OP_EQ, NULL);
  tt_assert(err_msg);
  tor_free(err_msg);

  /* Test invalid syntax */
  client = add_onion_helper_clientauth(":475hGBHPlq7Mc0cRZitK/B", &created,
                                       &err_msg);
  tt_ptr_op(client, OP_EQ, NULL);
  tt_assert(err_msg);
  tor_free(err_msg);

 done:
  rend_authorized_client_free(client);
  tor_free(err_msg);
}

/* Mocks and data/variables used for GETINFO download status tests */

static const download_status_t dl_status_default =
  { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
    DL_SCHED_INCREMENT_FAILURE, 0, 0 };
static download_status_t ns_dl_status[N_CONSENSUS_FLAVORS];
static download_status_t ns_dl_status_bootstrap[N_CONSENSUS_FLAVORS];
static download_status_t ns_dl_status_running[N_CONSENSUS_FLAVORS];

/*
 * These should explore all the possible cases of download_status_to_string()
 * in control.c
 */
static const download_status_t dls_sample_1 =
  { 1467163900, 0, 0, DL_SCHED_GENERIC, DL_WANT_ANY_DIRSERVER,
    DL_SCHED_INCREMENT_FAILURE, 0, 0 };
static const char * dls_sample_1_str =
    "next-attempt-at 2016-06-29 01:31:40\n"
    "n-download-failures 0\n"
    "n-download-attempts 0\n"
    "schedule DL_SCHED_GENERIC\n"
    "want-authority DL_WANT_ANY_DIRSERVER\n"
    "increment-on DL_SCHED_INCREMENT_FAILURE\n"
    "backoff DL_SCHED_RANDOM_EXPONENTIAL\n"
    "last-backoff-position 0\n"
    "last-delay-used 0\n";
static const download_status_t dls_sample_2 =
  { 1467164400, 1, 2, DL_SCHED_CONSENSUS, DL_WANT_AUTHORITY,
    DL_SCHED_INCREMENT_FAILURE, 0, 0 };
static const char * dls_sample_2_str =
    "next-attempt-at 2016-06-29 01:40:00\n"
    "n-download-failures 1\n"
    "n-download-attempts 2\n"
    "schedule DL_SCHED_CONSENSUS\n"
    "want-authority DL_WANT_AUTHORITY\n"
    "increment-on DL_SCHED_INCREMENT_FAILURE\n"
    "backoff DL_SCHED_RANDOM_EXPONENTIAL\n"
    "last-backoff-position 0\n"
    "last-delay-used 0\n";
static const download_status_t dls_sample_3 =
  { 1467154400, 12, 25, DL_SCHED_BRIDGE, DL_WANT_ANY_DIRSERVER,
    DL_SCHED_INCREMENT_ATTEMPT, 0, 0 };
static const char * dls_sample_3_str =
    "next-attempt-at 2016-06-28 22:53:20\n"
    "n-download-failures 12\n"
    "n-download-attempts 25\n"
    "schedule DL_SCHED_BRIDGE\n"
    "want-authority DL_WANT_ANY_DIRSERVER\n"
    "increment-on DL_SCHED_INCREMENT_ATTEMPT\n"
    "backoff DL_SCHED_RANDOM_EXPONENTIAL\n"
    "last-backoff-position 0\n"
    "last-delay-used 0\n";
static const download_status_t dls_sample_4 =
  { 1467166600, 3, 0, DL_SCHED_GENERIC, DL_WANT_ANY_DIRSERVER,
    DL_SCHED_INCREMENT_FAILURE, 0, 0 };
static const char * dls_sample_4_str =
    "next-attempt-at 2016-06-29 02:16:40\n"
    "n-download-failures 3\n"
    "n-download-attempts 0\n"
    "schedule DL_SCHED_GENERIC\n"
    "want-authority DL_WANT_ANY_DIRSERVER\n"
    "increment-on DL_SCHED_INCREMENT_FAILURE\n"
    "backoff DL_SCHED_RANDOM_EXPONENTIAL\n"
    "last-backoff-position 0\n"
    "last-delay-used 0\n";
static const download_status_t dls_sample_5 =
  { 1467164600, 3, 7, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
    DL_SCHED_INCREMENT_FAILURE, 1, 2112, };
static const char * dls_sample_5_str =
    "next-attempt-at 2016-06-29 01:43:20\n"
    "n-download-failures 3\n"
    "n-download-attempts 7\n"
    "schedule DL_SCHED_CONSENSUS\n"
    "want-authority DL_WANT_ANY_DIRSERVER\n"
    "increment-on DL_SCHED_INCREMENT_FAILURE\n"
    "backoff DL_SCHED_RANDOM_EXPONENTIAL\n"
    "last-backoff-position 1\n"
    "last-delay-used 2112\n";
static const download_status_t dls_sample_6 =
  { 1467164200, 4, 9, DL_SCHED_CONSENSUS, DL_WANT_AUTHORITY,
    DL_SCHED_INCREMENT_ATTEMPT, 3, 432 };
static const char * dls_sample_6_str =
    "next-attempt-at 2016-06-29 01:36:40\n"
    "n-download-failures 4\n"
    "n-download-attempts 9\n"
    "schedule DL_SCHED_CONSENSUS\n"
    "want-authority DL_WANT_AUTHORITY\n"
    "increment-on DL_SCHED_INCREMENT_ATTEMPT\n"
    "backoff DL_SCHED_RANDOM_EXPONENTIAL\n"
    "last-backoff-position 3\n"
    "last-delay-used 432\n";

/* Simulated auth certs */
static const char *auth_id_digest_1_str =
    "63CDD326DFEF0CA020BDD3FEB45A3286FE13A061";
static download_status_t auth_def_cert_download_status_1;
static const char *auth_id_digest_2_str =
    "2C209FCDD8D48DC049777B8DC2C0F94A0408BE99";
static download_status_t auth_def_cert_download_status_2;
/* Expected form of digest list returned for GETINFO downloads/cert/fps */
static const char *auth_id_digest_expected_list =
    "63CDD326DFEF0CA020BDD3FEB45A3286FE13A061\n"
    "2C209FCDD8D48DC049777B8DC2C0F94A0408BE99\n";

/* Signing keys for simulated auth 1 */
static const char *auth_1_sk_1_str =
    "AA69566029B1F023BA09451B8F1B10952384EB58";
static download_status_t auth_1_sk_1_dls;
static const char *auth_1_sk_2_str =
    "710865C7F06B73C5292695A8C34F1C94F769FF72";
static download_status_t auth_1_sk_2_dls;
/*
 * Expected form of sk digest list for
 * GETINFO downloads/cert/<auth_id_digest_1_str>/sks
 */
static const char *auth_1_sk_digest_expected_list =
    "AA69566029B1F023BA09451B8F1B10952384EB58\n"
    "710865C7F06B73C5292695A8C34F1C94F769FF72\n";

/* Signing keys for simulated auth 2 */
static const char *auth_2_sk_1_str =
    "4299047E00D070AD6703FE00BE7AA756DB061E62";
static download_status_t auth_2_sk_1_dls;
static const char *auth_2_sk_2_str =
    "9451B8F1B10952384EB58B5F230C0BB701626C9B";
static download_status_t auth_2_sk_2_dls;
/*
 * Expected form of sk digest list for
 * GETINFO downloads/cert/<auth_id_digest_2_str>/sks
 */
static const char *auth_2_sk_digest_expected_list =
    "4299047E00D070AD6703FE00BE7AA756DB061E62\n"
    "9451B8F1B10952384EB58B5F230C0BB701626C9B\n";

/* Simulated router descriptor digests or bridge identity digests */
static const char *descbr_digest_1_str =
    "616408544C7345822696074A1A3DFA16AB381CBD";
static download_status_t descbr_digest_1_dl;
static const char *descbr_digest_2_str =
    "06E8067246967265DBCB6641631B530EFEC12DC3";
static download_status_t descbr_digest_2_dl;
/* Expected form of digest list returned for GETINFO downloads/desc/descs */
static const char *descbr_expected_list =
    "616408544C7345822696074A1A3DFA16AB381CBD\n"
    "06E8067246967265DBCB6641631B530EFEC12DC3\n";
/*
 * Flag to make all descbr queries fail, to simulate not being
 * configured such that such queries make sense.
 */
static int disable_descbr = 0;

static void
reset_mocked_dl_statuses(void)
{
  int i;

  for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
    memcpy(&(ns_dl_status[i]), &dl_status_default,
           sizeof(download_status_t));
    memcpy(&(ns_dl_status_bootstrap[i]), &dl_status_default,
           sizeof(download_status_t));
    memcpy(&(ns_dl_status_running[i]), &dl_status_default,
           sizeof(download_status_t));
  }

  memcpy(&auth_def_cert_download_status_1, &dl_status_default,
         sizeof(download_status_t));
  memcpy(&auth_def_cert_download_status_2, &dl_status_default,
         sizeof(download_status_t));
  memcpy(&auth_1_sk_1_dls, &dl_status_default,
         sizeof(download_status_t));
  memcpy(&auth_1_sk_2_dls, &dl_status_default,
         sizeof(download_status_t));
  memcpy(&auth_2_sk_1_dls, &dl_status_default,
         sizeof(download_status_t));
  memcpy(&auth_2_sk_2_dls, &dl_status_default,
         sizeof(download_status_t));

  memcpy(&descbr_digest_1_dl, &dl_status_default,
         sizeof(download_status_t));
  memcpy(&descbr_digest_2_dl, &dl_status_default,
         sizeof(download_status_t));
}

static download_status_t *
ns_dl_status_mock(consensus_flavor_t flavor)
{
  return &(ns_dl_status[flavor]);
}

static download_status_t *
ns_dl_status_bootstrap_mock(consensus_flavor_t flavor)
{
  return &(ns_dl_status_bootstrap[flavor]);
}

static download_status_t *
ns_dl_status_running_mock(consensus_flavor_t flavor)
{
  return &(ns_dl_status_running[flavor]);
}

static void
setup_ns_mocks(void)
{
  MOCK(networkstatus_get_dl_status_by_flavor, ns_dl_status_mock);
  MOCK(networkstatus_get_dl_status_by_flavor_bootstrap,
       ns_dl_status_bootstrap_mock);
  MOCK(networkstatus_get_dl_status_by_flavor_running,
       ns_dl_status_running_mock);
  reset_mocked_dl_statuses();
}

static void
clear_ns_mocks(void)
{
  UNMOCK(networkstatus_get_dl_status_by_flavor);
  UNMOCK(networkstatus_get_dl_status_by_flavor_bootstrap);
  UNMOCK(networkstatus_get_dl_status_by_flavor_running);
}

static smartlist_t *
cert_dl_status_auth_ids_mock(void)
{
  char digest[DIGEST_LEN], *tmp;
  int len;
  smartlist_t *list = NULL;

  /* Just pretend we have only the two hard-coded digests listed above */
  list = smartlist_new();
  len = base16_decode(digest, DIGEST_LEN,
                      auth_id_digest_1_str, strlen(auth_id_digest_1_str));
  tt_int_op(len, OP_EQ, DIGEST_LEN);
  tmp = tor_malloc(DIGEST_LEN);
  memcpy(tmp, digest, DIGEST_LEN);
  smartlist_add(list, tmp);
  len = base16_decode(digest, DIGEST_LEN,
                      auth_id_digest_2_str, strlen(auth_id_digest_2_str));
  tt_int_op(len, OP_EQ, DIGEST_LEN);
  tmp = tor_malloc(DIGEST_LEN);
  memcpy(tmp, digest, DIGEST_LEN);
  smartlist_add(list, tmp);

 done:
  return list;
}

static download_status_t *
cert_dl_status_def_for_auth_mock(const char *digest)
{
  download_status_t *dl = NULL;
  char digest_str[HEX_DIGEST_LEN+1];

  tt_ptr_op(digest, OP_NE, NULL);
  base16_encode(digest_str, HEX_DIGEST_LEN + 1,
                digest, DIGEST_LEN);
  digest_str[HEX_DIGEST_LEN] = '\0';

  if (strcmp(digest_str, auth_id_digest_1_str) == 0) {
    dl = &auth_def_cert_download_status_1;
  } else if (strcmp(digest_str, auth_id_digest_2_str) == 0) {
    dl = &auth_def_cert_download_status_2;
  }

 done:
  return dl;
}

static smartlist_t *
cert_dl_status_sks_for_auth_id_mock(const char *digest)
{
  smartlist_t *list = NULL;
  char sk[DIGEST_LEN];
  char digest_str[HEX_DIGEST_LEN+1];
  char *tmp;
  int len;

  tt_ptr_op(digest, OP_NE, NULL);
  base16_encode(digest_str, HEX_DIGEST_LEN + 1,
                digest, DIGEST_LEN);
  digest_str[HEX_DIGEST_LEN] = '\0';

  /*
   * Build a list of two hard-coded digests, depending on what we
   * were just passed.
   */
  if (strcmp(digest_str, auth_id_digest_1_str) == 0) {
    list = smartlist_new();
    len = base16_decode(sk, DIGEST_LEN,
                        auth_1_sk_1_str, strlen(auth_1_sk_1_str));
    tt_int_op(len, OP_EQ, DIGEST_LEN);
    tmp = tor_malloc(DIGEST_LEN);
    memcpy(tmp, sk, DIGEST_LEN);
    smartlist_add(list, tmp);
    len = base16_decode(sk, DIGEST_LEN,
                        auth_1_sk_2_str, strlen(auth_1_sk_2_str));
    tt_int_op(len, OP_EQ, DIGEST_LEN);
    tmp = tor_malloc(DIGEST_LEN);
    memcpy(tmp, sk, DIGEST_LEN);
    smartlist_add(list, tmp);
  } else if (strcmp(digest_str, auth_id_digest_2_str) == 0) {
    list = smartlist_new();
    len = base16_decode(sk, DIGEST_LEN,
                        auth_2_sk_1_str, strlen(auth_2_sk_1_str));
    tt_int_op(len, OP_EQ, DIGEST_LEN);
    tmp = tor_malloc(DIGEST_LEN);
    memcpy(tmp, sk, DIGEST_LEN);
    smartlist_add(list, tmp);
    len = base16_decode(sk, DIGEST_LEN,
                        auth_2_sk_2_str, strlen(auth_2_sk_2_str));
    tt_int_op(len, OP_EQ, DIGEST_LEN);
    tmp = tor_malloc(DIGEST_LEN);
    memcpy(tmp, sk, DIGEST_LEN);
    smartlist_add(list, tmp);
  }

 done:
  return list;
}

static download_status_t *
cert_dl_status_fp_sk_mock(const char *fp_digest, const char *sk_digest)
{
  download_status_t *dl = NULL;
  char fp_digest_str[HEX_DIGEST_LEN+1], sk_digest_str[HEX_DIGEST_LEN+1];

  /*
   * Unpack the digests so we can compare them and figure out which
   * dl status we want.
   */

  tt_ptr_op(fp_digest, OP_NE, NULL);
  base16_encode(fp_digest_str, HEX_DIGEST_LEN + 1,
                fp_digest, DIGEST_LEN);
  fp_digest_str[HEX_DIGEST_LEN] = '\0';
  tt_ptr_op(sk_digest, OP_NE, NULL);
  base16_encode(sk_digest_str, HEX_DIGEST_LEN + 1,
                sk_digest, DIGEST_LEN);
  sk_digest_str[HEX_DIGEST_LEN] = '\0';

  if (strcmp(fp_digest_str, auth_id_digest_1_str) == 0) {
    if (strcmp(sk_digest_str, auth_1_sk_1_str) == 0) {
      dl = &auth_1_sk_1_dls;
    } else if (strcmp(sk_digest_str, auth_1_sk_2_str) == 0) {
      dl = &auth_1_sk_2_dls;
    }
  } else if (strcmp(fp_digest_str, auth_id_digest_2_str) == 0) {
    if (strcmp(sk_digest_str, auth_2_sk_1_str) == 0) {
      dl = &auth_2_sk_1_dls;
    } else if (strcmp(sk_digest_str, auth_2_sk_2_str) == 0) {
      dl = &auth_2_sk_2_dls;
    }
  }

 done:
  return dl;
}

static void
setup_cert_mocks(void)
{
  MOCK(list_authority_ids_with_downloads, cert_dl_status_auth_ids_mock);
  MOCK(id_only_download_status_for_authority_id,
       cert_dl_status_def_for_auth_mock);
  MOCK(list_sk_digests_for_authority_id,
       cert_dl_status_sks_for_auth_id_mock);
  MOCK(download_status_for_authority_id_and_sk,
       cert_dl_status_fp_sk_mock);
  reset_mocked_dl_statuses();
}

static void
clear_cert_mocks(void)
{
  UNMOCK(list_authority_ids_with_downloads);
  UNMOCK(id_only_download_status_for_authority_id);
  UNMOCK(list_sk_digests_for_authority_id);
  UNMOCK(download_status_for_authority_id_and_sk);
}

static smartlist_t *
descbr_get_digests_mock(void)
{
  char digest[DIGEST_LEN], *tmp;
  int len;
  smartlist_t *list = NULL;

  if (!disable_descbr) {
    /* Just pretend we have only the two hard-coded digests listed above */
    list = smartlist_new();
    len = base16_decode(digest, DIGEST_LEN,
                        descbr_digest_1_str, strlen(descbr_digest_1_str));
    tt_int_op(len, OP_EQ, DIGEST_LEN);
    tmp = tor_malloc(DIGEST_LEN);
    memcpy(tmp, digest, DIGEST_LEN);
    smartlist_add(list, tmp);
    len = base16_decode(digest, DIGEST_LEN,
                        descbr_digest_2_str, strlen(descbr_digest_2_str));
    tt_int_op(len, OP_EQ, DIGEST_LEN);
    tmp = tor_malloc(DIGEST_LEN);
    memcpy(tmp, digest, DIGEST_LEN);
    smartlist_add(list, tmp);
  }

 done:
  return list;
}

static download_status_t *
descbr_get_dl_by_digest_mock(const char *digest)
{
  download_status_t *dl = NULL;
  char digest_str[HEX_DIGEST_LEN+1];

  if (!disable_descbr) {
    tt_ptr_op(digest, OP_NE, NULL);
    base16_encode(digest_str, HEX_DIGEST_LEN + 1,
                  digest, DIGEST_LEN);
    digest_str[HEX_DIGEST_LEN] = '\0';

    if (strcmp(digest_str, descbr_digest_1_str) == 0) {
      dl = &descbr_digest_1_dl;
    } else if (strcmp(digest_str, descbr_digest_2_str) == 0) {
      dl = &descbr_digest_2_dl;
    }
  }

 done:
  return dl;
}

static void
setup_desc_mocks(void)
{
  MOCK(router_get_descriptor_digests,
       descbr_get_digests_mock);
  MOCK(router_get_dl_status_by_descriptor_digest,
       descbr_get_dl_by_digest_mock);
  reset_mocked_dl_statuses();
}

static void
clear_desc_mocks(void)
{
  UNMOCK(router_get_descriptor_digests);
  UNMOCK(router_get_dl_status_by_descriptor_digest);
}

static void
setup_bridge_mocks(void)
{
  disable_descbr = 0;

  MOCK(list_bridge_identities,
       descbr_get_digests_mock);
  MOCK(get_bridge_dl_status_by_id,
       descbr_get_dl_by_digest_mock);
  reset_mocked_dl_statuses();
}

static void
clear_bridge_mocks(void)
{
  UNMOCK(list_bridge_identities);
  UNMOCK(get_bridge_dl_status_by_id);

  disable_descbr = 0;
}

static void
test_download_status_consensus(void *arg)
{
  /* We just need one of these to pass, it doesn't matter what's in it */
  control_connection_t dummy;
  /* Get results out */
  char *answer = NULL;
  const char *errmsg = NULL;

  (void)arg;

  /* Check that the unknown prefix case works; no mocks needed yet */
  getinfo_helper_downloads(&dummy, "downloads/foo", &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_str_op(errmsg, OP_EQ, "Unknown download status query");

  setup_ns_mocks();

  /*
   * Check returning serialized dlstatuses, and implicitly also test
   * download_status_to_string().
   */

  /* Case 1 default/FLAV_NS*/
  memcpy(&(ns_dl_status[FLAV_NS]), &dls_sample_1,
         sizeof(download_status_t));
  getinfo_helper_downloads(&dummy, "downloads/networkstatus/ns",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_1_str);
  tor_free(answer);
  errmsg = NULL;

  /* Case 2 default/FLAV_MICRODESC */
  memcpy(&(ns_dl_status[FLAV_MICRODESC]), &dls_sample_2,
         sizeof(download_status_t));
  getinfo_helper_downloads(&dummy, "downloads/networkstatus/microdesc",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_2_str);
  tor_free(answer);
  errmsg = NULL;

  /* Case 3 bootstrap/FLAV_NS */
  memcpy(&(ns_dl_status_bootstrap[FLAV_NS]), &dls_sample_3,
         sizeof(download_status_t));
  getinfo_helper_downloads(&dummy, "downloads/networkstatus/ns/bootstrap",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_3_str);
  tor_free(answer);
  errmsg = NULL;

  /* Case 4 bootstrap/FLAV_MICRODESC */
  memcpy(&(ns_dl_status_bootstrap[FLAV_MICRODESC]), &dls_sample_4,
         sizeof(download_status_t));
  getinfo_helper_downloads(&dummy,
                           "downloads/networkstatus/microdesc/bootstrap",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_4_str);
  tor_free(answer);
  errmsg = NULL;

  /* Case 5 running/FLAV_NS */
  memcpy(&(ns_dl_status_running[FLAV_NS]), &dls_sample_5,
         sizeof(download_status_t));
  getinfo_helper_downloads(&dummy,
                           "downloads/networkstatus/ns/running",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_5_str);
  tor_free(answer);
  errmsg = NULL;

  /* Case 6 running/FLAV_MICRODESC */
  memcpy(&(ns_dl_status_running[FLAV_MICRODESC]), &dls_sample_6,
         sizeof(download_status_t));
  getinfo_helper_downloads(&dummy,
                           "downloads/networkstatus/microdesc/running",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_6_str);
  tor_free(answer);
  errmsg = NULL;

  /* Now check the error case */
  getinfo_helper_downloads(&dummy, "downloads/networkstatus/foo",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "Unknown flavor");
  errmsg = NULL;

 done:
  clear_ns_mocks();
  tor_free(answer);

  return;
}

static void
test_download_status_cert(void *arg)
{
  /* We just need one of these to pass, it doesn't matter what's in it */
  control_connection_t dummy;
  /* Get results out */
  char *question = NULL;
  char *answer = NULL;
  const char *errmsg = NULL;

  (void)arg;

  setup_cert_mocks();

  /*
   * Check returning serialized dlstatuses and digest lists, and implicitly
   * also test download_status_to_string() and digest_list_to_string().
   */

  /* Case 1 - list of authority identity fingerprints */
  getinfo_helper_downloads(&dummy,
                           "downloads/cert/fps",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, auth_id_digest_expected_list);
  tor_free(answer);
  errmsg = NULL;

  /* Case 2 - download status for default cert for 1st auth id */
  memcpy(&auth_def_cert_download_status_1, &dls_sample_1,
         sizeof(download_status_t));
  tor_asprintf(&question, "downloads/cert/fp/%s", auth_id_digest_1_str);
  tt_ptr_op(question, OP_NE, NULL);
  getinfo_helper_downloads(&dummy, question, &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_1_str);
  tor_free(question);
  tor_free(answer);
  errmsg = NULL;

  /* Case 3 - download status for default cert for 2nd auth id */
  memcpy(&auth_def_cert_download_status_2, &dls_sample_2,
         sizeof(download_status_t));
  tor_asprintf(&question, "downloads/cert/fp/%s", auth_id_digest_2_str);
  tt_ptr_op(question, OP_NE, NULL);
  getinfo_helper_downloads(&dummy, question, &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_2_str);
  tor_free(question);
  tor_free(answer);
  errmsg = NULL;

  /* Case 4 - list of signing key digests for 1st auth id */
  tor_asprintf(&question, "downloads/cert/fp/%s/sks", auth_id_digest_1_str);
  tt_ptr_op(question, OP_NE, NULL);
  getinfo_helper_downloads(&dummy, question, &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, auth_1_sk_digest_expected_list);
  tor_free(question);
  tor_free(answer);
  errmsg = NULL;

  /* Case 5 - list of signing key digests for 2nd auth id */
  tor_asprintf(&question, "downloads/cert/fp/%s/sks", auth_id_digest_2_str);
  tt_ptr_op(question, OP_NE, NULL);
  getinfo_helper_downloads(&dummy, question, &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, auth_2_sk_digest_expected_list);
  tor_free(question);
  tor_free(answer);
  errmsg = NULL;

  /* Case 6 - download status for 1st auth id, 1st sk */
  memcpy(&auth_1_sk_1_dls, &dls_sample_3,
         sizeof(download_status_t));
  tor_asprintf(&question, "downloads/cert/fp/%s/%s",
               auth_id_digest_1_str, auth_1_sk_1_str);
  tt_ptr_op(question, OP_NE, NULL);
  getinfo_helper_downloads(&dummy, question, &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_3_str);
  tor_free(question);
  tor_free(answer);
  errmsg = NULL;

  /* Case 7 - download status for 1st auth id, 2nd sk */
  memcpy(&auth_1_sk_2_dls, &dls_sample_4,
         sizeof(download_status_t));
  tor_asprintf(&question, "downloads/cert/fp/%s/%s",
               auth_id_digest_1_str, auth_1_sk_2_str);
  tt_ptr_op(question, OP_NE, NULL);
  getinfo_helper_downloads(&dummy, question, &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_4_str);
  tor_free(question);
  tor_free(answer);
  errmsg = NULL;

  /* Case 8 - download status for 2nd auth id, 1st sk */
  memcpy(&auth_2_sk_1_dls, &dls_sample_5,
         sizeof(download_status_t));
  tor_asprintf(&question, "downloads/cert/fp/%s/%s",
               auth_id_digest_2_str, auth_2_sk_1_str);
  tt_ptr_op(question, OP_NE, NULL);
  getinfo_helper_downloads(&dummy, question, &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_5_str);
  tor_free(question);
  tor_free(answer);
  errmsg = NULL;

  /* Case 9 - download status for 2nd auth id, 2nd sk */
  memcpy(&auth_2_sk_2_dls, &dls_sample_6,
         sizeof(download_status_t));
  tor_asprintf(&question, "downloads/cert/fp/%s/%s",
               auth_id_digest_2_str, auth_2_sk_2_str);
  tt_ptr_op(question, OP_NE, NULL);
  getinfo_helper_downloads(&dummy, question, &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_6_str);
  tor_free(question);
  tor_free(answer);
  errmsg = NULL;

  /* Now check the error cases */

  /* Case 1 - query is garbage after downloads/cert/ part */
  getinfo_helper_downloads(&dummy, "downloads/cert/blahdeblah",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "Unknown certificate download status query");
  errmsg = NULL;

  /*
   * Case 2 - looks like downloads/cert/fp/<fp>, but <fp> isn't even
   * the right length for a digest.
   */
  getinfo_helper_downloads(&dummy, "downloads/cert/fp/2B1D36D32B2942406",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "That didn't look like a digest");
  errmsg = NULL;

  /*
   * Case 3 - looks like downloads/cert/fp/<fp>, and <fp> is digest-sized,
   * but not parseable as one.
   */
  getinfo_helper_downloads(&dummy,
      "downloads/cert/fp/82F52AF55D250115FE44D3GC81D49643241D56A1",
      &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "That didn't look like a digest");
  errmsg = NULL;

  /*
   * Case 4 - downloads/cert/fp/<fp>, and <fp> is not a known authority
   * identity digest
   */
  getinfo_helper_downloads(&dummy,
      "downloads/cert/fp/AC4F23B5745BDD2A77997B85B1FD85D05C2E0F61",
      &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ,
      "Failed to get download status for this authority identity digest");
  errmsg = NULL;

  /*
   * Case 5 - looks like downloads/cert/fp/<fp>/<anything>, but <fp> doesn't
   * parse as a sensible digest.
   */
  getinfo_helper_downloads(&dummy,
      "downloads/cert/fp/82F52AF55D250115FE44D3GC81D49643241D56A1/blah",
      &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "That didn't look like an identity digest");
  errmsg = NULL;

  /*
   * Case 6 - looks like downloads/cert/fp/<fp>/<anything>, but <fp> doesn't
   * parse as a sensible digest.
   */
  getinfo_helper_downloads(&dummy,
      "downloads/cert/fp/82F52AF55D25/blah",
      &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "That didn't look like an identity digest");
  errmsg = NULL;

  /*
   * Case 7 - downloads/cert/fp/<fp>/sks, and <fp> is not a known authority
   * digest.
   */
  getinfo_helper_downloads(&dummy,
      "downloads/cert/fp/AC4F23B5745BDD2A77997B85B1FD85D05C2E0F61/sks",
      &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ,
      "Failed to get list of signing key digests for this authority "
      "identity digest");
  errmsg = NULL;

  /*
   * Case 8 - looks like downloads/cert/fp/<fp>/<sk>, but <sk> doesn't
   * parse as a signing key digest.
   */
  getinfo_helper_downloads(&dummy,
      "downloads/cert/fp/AC4F23B5745BDD2A77997B85B1FD85D05C2E0F61/"
      "82F52AF55D250115FE44D3GC81D49643241D56A1",
      &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "That didn't look like a signing key digest");
  errmsg = NULL;

  /*
   * Case 9 - looks like downloads/cert/fp/<fp>/<sk>, but <sk> doesn't
   * parse as a signing key digest.
   */
  getinfo_helper_downloads(&dummy,
      "downloads/cert/fp/AC4F23B5745BDD2A77997B85B1FD85D05C2E0F61/"
      "82F52AF55D250115FE44D",
      &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "That didn't look like a signing key digest");
  errmsg = NULL;

  /*
   * Case 10 - downloads/cert/fp/<fp>/<sk>, but <fp> isn't a known
   * authority identity digest.
   */
  getinfo_helper_downloads(&dummy,
      "downloads/cert/fp/C6B05DF332F74DB9A13498EE3BBC7AA2F69FCB45/"
      "3A214FC21AE25B012C2ECCB5F4EC8A3602D0545D",
      &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ,
      "Failed to get download status for this identity/"
      "signing key digest pair");
  errmsg = NULL;

  /*
   * Case 11 - downloads/cert/fp/<fp>/<sk>, but <sk> isn't a known
   * signing key digest.
   */
  getinfo_helper_downloads(&dummy,
      "downloads/cert/fp/63CDD326DFEF0CA020BDD3FEB45A3286FE13A061/"
      "3A214FC21AE25B012C2ECCB5F4EC8A3602D0545D",
      &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ,
      "Failed to get download status for this identity/"
      "signing key digest pair");
  errmsg = NULL;

  /*
   * Case 12 - downloads/cert/fp/<fp>/<sk>, but <sk> is on the list for
   * a different authority identity digest.
   */
  getinfo_helper_downloads(&dummy,
      "downloads/cert/fp/63CDD326DFEF0CA020BDD3FEB45A3286FE13A061/"
      "9451B8F1B10952384EB58B5F230C0BB701626C9B",
      &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ,
      "Failed to get download status for this identity/"
      "signing key digest pair");
  errmsg = NULL;

 done:
  clear_cert_mocks();
  tor_free(answer);

  return;
}

static void
test_download_status_desc(void *arg)
{
  /* We just need one of these to pass, it doesn't matter what's in it */
  control_connection_t dummy;
  /* Get results out */
  char *question = NULL;
  char *answer = NULL;
  const char *errmsg = NULL;

  (void)arg;

  setup_desc_mocks();

  /*
   * Check returning serialized dlstatuses and digest lists, and implicitly
   * also test download_status_to_string() and digest_list_to_string().
   */

  /* Case 1 - list of router descriptor digests */
  getinfo_helper_downloads(&dummy,
                           "downloads/desc/descs",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, descbr_expected_list);
  tor_free(answer);
  errmsg = NULL;

  /* Case 2 - get download status for router descriptor 1 */
  memcpy(&descbr_digest_1_dl, &dls_sample_1,
         sizeof(download_status_t));
  tor_asprintf(&question, "downloads/desc/%s", descbr_digest_1_str);
  tt_ptr_op(question, OP_NE, NULL);
  getinfo_helper_downloads(&dummy, question, &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_1_str);
  tor_free(question);
  tor_free(answer);
  errmsg = NULL;

  /* Case 3 - get download status for router descriptor 1 */
  memcpy(&descbr_digest_2_dl, &dls_sample_2,
         sizeof(download_status_t));
  tor_asprintf(&question, "downloads/desc/%s", descbr_digest_2_str);
  tt_ptr_op(question, OP_NE, NULL);
  getinfo_helper_downloads(&dummy, question, &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_2_str);
  tor_free(question);
  tor_free(answer);
  errmsg = NULL;

  /* Now check the error cases */

  /* Case 1 - non-digest-length garbage after downloads/desc */
  getinfo_helper_downloads(&dummy, "downloads/desc/blahdeblah",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "Unknown router descriptor download status query");
  errmsg = NULL;

  /* Case 2 - nonparseable digest-shaped thing */
  getinfo_helper_downloads(
    &dummy,
    "downloads/desc/774EC52FD9A5B80A6FACZE536616E8022E3470AG",
    &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "That didn't look like a digest");
  errmsg = NULL;

  /* Case 3 - digest we have no descriptor for */
  getinfo_helper_downloads(
    &dummy,
    "downloads/desc/B05B46135B0B2C04EBE1DD6A6AE4B12D7CD2226A",
    &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "No such descriptor digest found");
  errmsg = NULL;

  /* Case 4 - microdescs only */
  disable_descbr = 1;
  getinfo_helper_downloads(&dummy,
                           "downloads/desc/descs",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ,
            "We don't seem to have a networkstatus-flavored consensus");
  errmsg = NULL;
  disable_descbr = 0;

 done:
  clear_desc_mocks();
  tor_free(answer);

  return;
}

static void
test_download_status_bridge(void *arg)
{
  /* We just need one of these to pass, it doesn't matter what's in it */
  control_connection_t dummy;
  /* Get results out */
  char *question = NULL;
  char *answer = NULL;
  const char *errmsg = NULL;

  (void)arg;

  setup_bridge_mocks();

  /*
   * Check returning serialized dlstatuses and digest lists, and implicitly
   * also test download_status_to_string() and digest_list_to_string().
   */

  /* Case 1 - list of bridge identity digests */
  getinfo_helper_downloads(&dummy,
                           "downloads/bridge/bridges",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, descbr_expected_list);
  tor_free(answer);
  errmsg = NULL;

  /* Case 2 - get download status for bridge descriptor 1 */
  memcpy(&descbr_digest_1_dl, &dls_sample_3,
         sizeof(download_status_t));
  tor_asprintf(&question, "downloads/bridge/%s", descbr_digest_1_str);
  tt_ptr_op(question, OP_NE, NULL);
  getinfo_helper_downloads(&dummy, question, &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_3_str);
  tor_free(question);
  tor_free(answer);
  errmsg = NULL;

  /* Case 3 - get download status for router descriptor 1 */
  memcpy(&descbr_digest_2_dl, &dls_sample_4,
         sizeof(download_status_t));
  tor_asprintf(&question, "downloads/bridge/%s", descbr_digest_2_str);
  tt_ptr_op(question, OP_NE, NULL);
  getinfo_helper_downloads(&dummy, question, &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, dls_sample_4_str);
  tor_free(question);
  tor_free(answer);
  errmsg = NULL;

  /* Now check the error cases */

  /* Case 1 - non-digest-length garbage after downloads/bridge */
  getinfo_helper_downloads(&dummy, "downloads/bridge/blahdeblah",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "Unknown bridge descriptor download status query");
  errmsg = NULL;

  /* Case 2 - nonparseable digest-shaped thing */
  getinfo_helper_downloads(
    &dummy,
    "downloads/bridge/774EC52FD9A5B80A6FACZE536616E8022E3470AG",
    &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "That didn't look like a digest");
  errmsg = NULL;

  /* Case 3 - digest we have no descriptor for */
  getinfo_helper_downloads(
    &dummy,
    "downloads/bridge/B05B46135B0B2C04EBE1DD6A6AE4B12D7CD2226A",
    &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "No such bridge identity digest found");
  errmsg = NULL;

  /* Case 4 - bridges disabled */
  disable_descbr = 1;
  getinfo_helper_downloads(&dummy,
                           "downloads/bridge/bridges",
                           &answer, &errmsg);
  tt_ptr_op(answer, OP_EQ, NULL);
  tt_ptr_op(errmsg, OP_NE, NULL);
  tt_str_op(errmsg, OP_EQ, "We don't seem to be using bridges");
  errmsg = NULL;
  disable_descbr = 0;

 done:
  clear_bridge_mocks();
  tor_free(answer);

  return;
}

/** Set timeval to a mock date and time. This is necessary
 * to make tor_gettimeofday() mockable. */
static void
mock_tor_gettimeofday(struct timeval *timeval)
{
  timeval->tv_sec = 1523405073;
  timeval->tv_usec = 271645;
}

static void
test_current_time(void *arg)
{
  /* We just need one of these to pass, it doesn't matter what's in it */
  control_connection_t dummy;
  /* Get results out */
  char *answer = NULL;
  const char *errmsg = NULL;

  (void)arg;

  /* We need these for storing the (mock) time. */
  MOCK(tor_gettimeofday, mock_tor_gettimeofday);
  struct timeval now;
  tor_gettimeofday(&now);
  char timebuf[ISO_TIME_LEN+1];

  /* Case 1 - local time */
  format_local_iso_time_nospace(timebuf, (time_t)now.tv_sec);
  getinfo_helper_current_time(&dummy,
                              "current-time/local",
                              &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, timebuf);
  tor_free(answer);
  errmsg = NULL;

  /* Case 2 - UTC time */
  format_iso_time_nospace(timebuf, (time_t)now.tv_sec);
  getinfo_helper_current_time(&dummy,
                              "current-time/utc",
                              &answer, &errmsg);
  tt_ptr_op(answer, OP_NE, NULL);
  tt_ptr_op(errmsg, OP_EQ, NULL);
  tt_str_op(answer, OP_EQ, timebuf);
  tor_free(answer);
  errmsg = NULL;

 done:
  UNMOCK(tor_gettimeofday);
  tor_free(answer);

  return;
}

struct testcase_t controller_tests[] = {
  { "add_onion_helper_keyarg_v2", test_add_onion_helper_keyarg_v2, 0,
    NULL, NULL },
  { "add_onion_helper_keyarg_v3", test_add_onion_helper_keyarg_v3, 0,
    NULL, NULL },
  { "getinfo_helper_onion", test_getinfo_helper_onion, 0, NULL, NULL },
  { "rend_service_parse_port_config", test_rend_service_parse_port_config, 0,
    NULL, NULL },
  { "add_onion_helper_clientauth", test_add_onion_helper_clientauth, 0, NULL,
    NULL },
  { "download_status_consensus", test_download_status_consensus, 0, NULL,
    NULL },
  { "download_status_cert", test_download_status_cert, 0, NULL,
    NULL },
  { "download_status_desc", test_download_status_desc, 0, NULL, NULL },
  { "download_status_bridge", test_download_status_bridge, 0, NULL, NULL },
  { "current_time", test_current_time, 0, NULL, NULL },
  END_OF_TESTCASES
};