aboutsummaryrefslogtreecommitdiff
path: root/src/or/routerlist.c
blob: d37e5542b3d028546c1054e7745bcc1c5eb08ac1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
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
/* Copyright 2001-2003 Roger Dingledine, Matej Pfajfar. */
/* See LICENSE for licensing information */
/* $Id$ */

#define _GNU_SOURCE
/* XXX this is required on rh7 to make strptime not complain. how bad
 * is this for portability?
 */

#include "or.h"

/****************************************************************************/

static routerlist_t *routerlist = NULL; /* router array */
extern or_options_t options; /* command-line and config-file options */

/****************************************************************************/

/* Enumeration of possible token types.  The ones starting with K_ correspond
 * to directory 'keywords'.  _SIGNATURE and _PUBLIC_KEY are self-explanatory.
 * _ERR is an error in the tokenizing process, _EOF is an end-of-file marker,
 * and _NIL is used to encode not-a-token.
 */
typedef enum {
  K_ACCEPT,
  K_DIRECTORY_SIGNATURE,
  K_RECOMMENDED_SOFTWARE,
  K_REJECT,
  K_ROUTER,
  K_SIGNED_DIRECTORY,
  K_SIGNING_KEY,
  K_ONION_KEY,
  K_LINK_KEY,
  K_ROUTER_SIGNATURE,
  K_PUBLISHED,
  K_RUNNING_ROUTERS,
  K_PLATFORM,
  K_OPT,
  K_BANDWIDTH,
  K_PORTS,
  _UNRECOGNIZED,
  _ERR,
  _EOF,
  _NIL
} directory_keyword;

typedef struct directory_token_t {
  directory_keyword tp;        /* Type of the token. */
  int n_args;
  char **args;
  char *object_type;
  int object_size;
  char *object_body;
  crypto_pk_env_t *key;      /* For public keys only. */
  char *error;               /* For _ERR tokens only. */
} directory_token_t;

/* ********************************************************************** */

/* Every keyword takes either... */
typedef enum {
  NO_ARGS,     /*    (1) no arguments, ever */
  ARGS,        /*    (2) a list of arguments separated by spaces */
  CONCAT_ARGS, /* or (3) the rest of the line, treated as a single argument. */
} arg_syntax;

typedef enum {
  NO_OBJ,
  NEED_OBJ,
  NEED_KEY,
  OBJ_OK,
} obj_syntax;

typedef enum {
  ANY = 0,
  DIR_ONLY,
  RTR_ONLY,
} where_syntax;

/* Table mapping keywods to token value and to argument rules. */

static struct {
  char *t; int v; arg_syntax s; obj_syntax os; where_syntax ws;
} token_table[] = {
  { "accept", K_ACCEPT, ARGS, NO_OBJ, RTR_ONLY },
  { "directory-signature", K_DIRECTORY_SIGNATURE, NO_ARGS, NEED_OBJ, DIR_ONLY},
  { "reject", K_REJECT, ARGS, NO_OBJ, RTR_ONLY },
  { "router", K_ROUTER, ARGS, NO_OBJ, RTR_ONLY },
  { "recommended-software", K_RECOMMENDED_SOFTWARE, ARGS, NO_OBJ, DIR_ONLY },
  { "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ, DIR_ONLY },
  { "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY, RTR_ONLY },
  { "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY, RTR_ONLY },
  { "link-key", K_LINK_KEY, NO_ARGS, NEED_KEY, RTR_ONLY },
  { "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ, RTR_ONLY },
  { "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ, ANY },
  { "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ, DIR_ONLY },
  { "platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ, RTR_ONLY },
  { "ports", K_PORTS, ARGS, NO_OBJ, RTR_ONLY },
  { "bandwidth", K_BANDWIDTH, ARGS, NO_OBJ, RTR_ONLY },
  { "opt", K_OPT, CONCAT_ARGS, OBJ_OK, ANY },

  { NULL, -1 }
};

/* ********************************************************************** */

/* static function prototypes */
static routerinfo_t *
router_pick_directory_server_impl(void);
static int
router_get_list_from_string_impl(const char **s, routerlist_t **dest,
                                 int n_good_nicknames,
                                 const char **good_nickname_lst);
int /* Exposed for unit tests */
router_get_routerlist_from_directory_impl(const char *s, routerlist_t **dest,
                                          crypto_pk_env_t *pkey);
static int
router_add_exit_policy(routerinfo_t *router, directory_token_t *tok);
static int
router_resolve_routerlist(routerlist_t *dir);

static int router_get_hash_impl(const char *s, char *digest,
                                const char *start_str, const char *end_str);
static void token_free(directory_token_t *tok);
static smartlist_t *find_all_exitpolicy(smartlist_t *s);
static directory_token_t *find_first_by_keyword(smartlist_t *s,
                                                directory_keyword keyword);
static int tokenize_string(const char *start, const char *end,
                           smartlist_t *out, int is_dir);
static directory_token_t *get_next_token(const char **s, where_syntax where);

/****************************************************************************/

extern int has_fetched_directory;

/* try to find a running dirserver. if there are no dirservers
 * in our routerlist, reload the routerlist and try again. */
routerinfo_t *router_pick_directory_server(void) {
  routerinfo_t *choice;

  choice = router_pick_directory_server_impl();
  if(!choice) {
    log_fn(LOG_WARN,"No dirservers known. Reloading and trying again.");
    has_fetched_directory=0; /* reset it */
    if(options.RouterFile) {
      if(router_set_routerlist_from_file(options.RouterFile) < 0)
        return NULL;
    } else {
      if(config_assign_default_dirservers() < 0)
        return NULL;
    }
    /* give it another try */
    choice = router_pick_directory_server_impl();
  }
  return choice;
}

/* pick a random running router with a positive dir_port */
static routerinfo_t *router_pick_directory_server_impl(void) {
  int i;
  routerinfo_t *router, *dirserver=NULL;
  smartlist_t *sl;

  if(!routerlist)
    return NULL;

  sl = smartlist_create();
  for(i=0;i< smartlist_len(routerlist->routers); i++) {
    router = smartlist_get(routerlist->routers, i);
    if(router->dir_port > 0 && router->is_running)
      smartlist_add(sl, router);
  }

  router = smartlist_choose(sl);
  smartlist_free(sl);

  if(router)
    return router;
  log_fn(LOG_INFO,"No dirservers are reachable. Trying them all again.");
  /* no running dir servers found? go through and mark them all as up,
   * and we'll cycle through the list again. */
  for(i=0; i < smartlist_len(routerlist->routers); i++) {
    router = smartlist_get(routerlist->routers, i);
    if(router->dir_port > 0) {
      router->is_running = 1;
      dirserver = router;
    }
  }
  if(!dirserver)
    log_fn(LOG_WARN,"No dirservers in directory! Returning NULL.");
  return dirserver;
}

void add_nickname_list_to_smartlist(smartlist_t *sl, char *list) {
  char *start,*end;
  char nick[MAX_NICKNAME_LEN+1];
  routerinfo_t *router;

  assert(sl);
  assert(list);

  while(isspace((int)*list) || *list==',') list++;

  start = list;
  while(*start) {
    end=start; while(*end && !isspace((int)*end) && *end != ',') end++;
    memcpy(nick,start,end-start);
    nick[end-start] = 0; /* null terminate it */
    router = router_get_by_nickname(nick);
    if (router) {
      if (router->is_running)
        smartlist_add(sl,router);
      else
        log_fn(LOG_INFO,"Nickname list includes '%s' which is known but down.",nick);
    } else
      log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO,
             "Nickname list includes '%s' which isn't a known router.",nick);
    while(isspace((int)*end) || *end==',') end++;
    start = end;
  }
}

void router_add_running_routers_to_smartlist(smartlist_t *sl) {
  routerinfo_t *router;
  int i;

  if(!routerlist)
    return;

  for(i=0;i<smartlist_len(routerlist->routers);i++) {
    router = smartlist_get(routerlist->routers, i);
    if(router->is_running &&
       (!options.ORPort ||
        connection_twin_get_by_addr_port(router->addr, router->or_port) ))
      smartlist_add(sl, router);
  }
}

/* Pick a random node from preferred if possible, else from all of dir.
 * Never pick a node in excluded.
 * If excludedsmartlist is defined, never pick a node in it either.
 */
routerinfo_t *router_choose_random_node(routerlist_t *dir,
                                        char *preferred, char *excluded,
                                        smartlist_t *excludedsmartlist)
{
  smartlist_t *sl, *excludednodes;
  routerinfo_t *choice;

  excludednodes = smartlist_create();
  add_nickname_list_to_smartlist(excludednodes,excluded);

  /* try the nodes in RendNodes first */
  sl = smartlist_create();
  add_nickname_list_to_smartlist(sl,preferred);
  smartlist_subtract(sl,excludednodes);
  if(excludedsmartlist)
    smartlist_subtract(sl,excludedsmartlist);
  choice = smartlist_choose(sl);
  smartlist_free(sl);
  if(!choice) {
    sl = smartlist_create();
    router_add_running_routers_to_smartlist(sl);
    smartlist_subtract(sl,excludednodes);
    if(excludedsmartlist)
      smartlist_subtract(sl,excludedsmartlist);
    choice = smartlist_choose(sl);
    smartlist_free(sl);
  }
  smartlist_free(excludednodes);
  if(!choice)
    log_fn(LOG_WARN,"No available nodes when trying to choose node. Failing.");
  return choice;
}

routerinfo_t *router_get_by_addr_port(uint32_t addr, uint16_t port) {
  int i;
  routerinfo_t *router;

  assert(routerlist);

  for(i=0;i<smartlist_len(routerlist->routers);i++) {
    router = smartlist_get(routerlist->routers, i);
    if ((router->addr == addr) && (router->or_port == port))
      return router;
  }
  return NULL;
}

routerinfo_t *router_get_by_link_pk(crypto_pk_env_t *pk)
{
  int i;
  routerinfo_t *router;

  assert(routerlist);

  for(i=0;i<smartlist_len(routerlist->routers);i++) {
    router = smartlist_get(routerlist->routers, i);
    if (0 == crypto_pk_cmp_keys(router->link_pkey, pk))
      return router;
  }
  return NULL;
}

routerinfo_t *router_get_by_nickname(char *nickname)
{
  int i;
  routerinfo_t *router;

  assert(routerlist);

  for(i=0;i<smartlist_len(routerlist->routers);i++) {
    router = smartlist_get(routerlist->routers, i);
    if (0 == strcasecmp(router->nickname, nickname))
      return router;
  }

  return NULL;
}

/* a way to access routerlist outside this file */
void router_get_routerlist(routerlist_t **prouterlist) {
  *prouterlist = routerlist;
}

/* delete a router from memory */
void routerinfo_free(routerinfo_t *router)
{
  struct exit_policy_t *e;

  if (!router)
    return;

  tor_free(router->address);
  tor_free(router->nickname);
  if (router->onion_pkey)
    crypto_free_pk_env(router->onion_pkey);
  if (router->link_pkey)
    crypto_free_pk_env(router->link_pkey);
  if (router->identity_pkey)
    crypto_free_pk_env(router->identity_pkey);
  while (router->exit_policy) {
    e = router->exit_policy;
    router->exit_policy = e->next;
    tor_free(e->string);
    free(e);
  }
  free(router);
}

static void routerlist_free(routerlist_t *rl)
{
  SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
                    routerinfo_free(r));
  smartlist_free(rl->routers);
  tor_free(rl->routers);
  tor_free(rl->software_versions);
  tor_free(rl);
}

void router_mark_as_down(char *nickname) {
  routerinfo_t *router = router_get_by_nickname(nickname);
  if(!router) /* we don't seem to know about him in the first place */
    return;
  log_fn(LOG_DEBUG,"Marking %s as down.",router->nickname);
  router->is_running = 0;
}

/* ------------------------------------------------------------ */

/* Replace the current router list with the one stored in 'routerfile'. */
int router_set_routerlist_from_file(char *routerfile)
{
  char *string;

  string = read_file_to_str(routerfile);
  if(!string) {
    log_fn(LOG_WARN,"Failed to load routerfile %s.",routerfile);
    return -1;
  }

  if(router_set_routerlist_from_string(string) < 0) {
    log_fn(LOG_WARN,"The routerfile itself was corrupt.");
    free(string);
    return -1;
  }

  free(string);
  return 0;
}

/* Helper function: read routerinfo elements from s, and throw out the
 * ones that don't parse and resolve.  Replace the current
 * routerlist. */
int router_set_routerlist_from_string(const char *s)
{
  if (router_get_list_from_string_impl(&s, &routerlist, -1, NULL)) {
    log(LOG_WARN, "Error parsing router file");
    return -1;
  }
  if (router_resolve_routerlist(routerlist)) {
    log(LOG_WARN, "Error resolving routerlist");
    return -1;
  }
  return 0;
}

/* Set 'digest' to the SHA-1 digest of the hash of the directory in 's'.
 * Return 0 on success, nonzero on failure.
 */
int router_get_dir_hash(const char *s, char *digest)
{
  return router_get_hash_impl(s,digest,
                              "signed-directory","directory-signature");
}
/* Set 'digest' to the SHA-1 digest of the hash of the first router in 's'.
 * Return 0 on success, nonzero on failure.
 */
int router_get_router_hash(const char *s, char *digest)
{
  return router_get_hash_impl(s,digest,
                              "router ","router-signature");
}

/* return 1 if myversion is in versionlist. Else return 0.
 * (versionlist contains a comma-separated list of versions.) */
int is_recommended_version(const char *myversion,
                           const char *versionlist) {
  int len_myversion = strlen(myversion);
  char *comma;
  const char *end = versionlist + strlen(versionlist);

  log_fn(LOG_DEBUG,"checking '%s' in '%s'.", myversion, versionlist);

  for(;;) {
    comma = strchr(versionlist, ',');
    if( ((comma ? comma : end) - versionlist == len_myversion) &&
       !strncmp(versionlist, myversion, len_myversion))
      /* only do strncmp if the length matches */
      return 1; /* success, it's there */
    if(!comma)
      return 0; /* nope */
    versionlist = comma+1;
  }
}

/* Replace the current routerlist with the routers stored in the directory
 * 's'.  If pkey is provided, make sure that 's' is signed with pkey. */
int router_set_routerlist_from_directory(const char *s, crypto_pk_env_t *pkey)
{
  if (router_get_routerlist_from_directory_impl(s, &routerlist, pkey)) {
    log_fn(LOG_WARN, "Couldn't parse directory.");
    return -1;
  }
  if (router_resolve_routerlist(routerlist)) {
    log_fn(LOG_WARN, "Error resolving routerlist");
    return -1;
  }
  if (!is_recommended_version(VERSION, routerlist->software_versions)) {
    log(options.IgnoreVersion ? LOG_WARN : LOG_ERR,
        "You are running Tor version %s, which will not work with this network.\n"
       "Please use %s%s.",
        VERSION, strchr(routerlist->software_versions,',') ? "one of " : "",
        routerlist->software_versions);
    if(options.IgnoreVersion) {
      log(LOG_WARN, "IgnoreVersion is set. If it breaks, we told you so.");
    } else {
      fflush(0);
      exit(0);
    }
  }
  return 0;
}

/* Helper function: resolve the hostname for 'router' */
static int
router_resolve(routerinfo_t *router)
{
  struct hostent *rent;

  rent = (struct hostent *)gethostbyname(router->address);
  if (!rent) {
    log_fn(LOG_WARN,"Could not get address for router %s (%s).",
           router->address, router->nickname);
    return -1;
  }
  assert(rent->h_length == 4);
  memcpy(&router->addr, rent->h_addr,rent->h_length);
  router->addr = ntohl(router->addr); /* get it back into host order */

  return 0;
}

/* Helper function: resolve every router in rl, and ensure that our own
 * routerinfo is at the front.
 */
static int
router_resolve_routerlist(routerlist_t *rl)
{
  int i, remove;
  routerinfo_t *r;
  if (!rl)
    rl = routerlist;

  i = 0;
  if ((r = router_get_my_routerinfo())) {
    smartlist_insert(rl->routers, 0, r);
    ++i;
  }

  for ( ; i < smartlist_len(rl->routers); ++i) {
    remove = 0;
    r = smartlist_get(rl->routers,i);
    if (router_is_me(r)) {
      remove = 1;
    } else if (router_resolve(r)) {
      log_fn(LOG_WARN, "Couldn't resolve router %s; not using", r->address);
      remove = 1;
    }
    if (remove) {
      routerinfo_free(r);
      smartlist_del_keeporder(rl->routers, i--);
    }
  }

  return 0;
}

/* Addr is 0 for "IP unknown".
 *
 * Returns -1 for 'rejected', 0 for accepted, 1 for 'maybe' (since IP is
 * unknown.
 */
int router_compare_addr_to_exit_policy(uint32_t addr, uint16_t port,
                                       struct exit_policy_t *policy)
{
  int maybe_reject = 0;
  int maybe_accept = 0;
  int match = 0;
  int maybe = 0;
  struct in_addr in;
  struct exit_policy_t *tmpe;

  for(tmpe=policy; tmpe; tmpe=tmpe->next) {
//    log_fn(LOG_DEBUG,"Considering exit policy %s", tmpe->string);
    maybe = 0;
    if (!addr) {
      /* Address is unknown. */
      if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
        /* The port definitely matches. */
        if (tmpe->msk == 0) {
          match = 1;
        } else {
          maybe = 1;
        }
      } else if (!port) {
        /* The port maybe matches. */
        maybe = 1;
      }
    } else {
      /* Address is known */
      if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
        if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
          /* Exact match for the policy */
          match = 1;
        } else if (!port) {
          maybe = 1;
        }
      }
    }
    if (maybe) {
      if (tmpe->policy_type == EXIT_POLICY_REJECT)
        maybe_reject = 1;
      else
        maybe_accept = 1;
    }
    if (match) {
      in.s_addr = htonl(addr);
      log_fn(LOG_DEBUG,"Address %s:%d matches exit policy '%s'",
             inet_ntoa(in), port, tmpe->string);
      if(tmpe->policy_type == EXIT_POLICY_ACCEPT) {
        /* If we already hit a clause that might trigger a 'reject', than we
         * can't be sure of this certain 'accept'.*/
        return maybe_reject ? ADDR_POLICY_UNKNOWN : ADDR_POLICY_ACCEPTED;
      } else {
        return maybe_accept ? ADDR_POLICY_UNKNOWN : ADDR_POLICY_REJECTED;
      }
    }
  }
  /* accept all by default. */
  return maybe_reject ? ADDR_POLICY_UNKNOWN : ADDR_POLICY_ACCEPTED;
}

/* return 1 if all running routers will reject addr:port, return 0 if
   any might accept it. */
int router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port) {
  int i;
  routerinfo_t *router;

  for (i=0;i<smartlist_len(routerlist->routers);i++) {
    router = smartlist_get(routerlist->routers, i);
    if (router->is_running && router_compare_addr_to_exit_policy(
             addr, port, router->exit_policy) != ADDR_POLICY_REJECTED)
      return 0; /* this one could be ok. good enough. */
  }
  return 1; /* all will reject. */
}

int router_exit_policy_rejects_all(routerinfo_t *router) {
  return router_compare_addr_to_exit_policy(0, 0, router->exit_policy)
    == ADDR_POLICY_REJECTED;
}

static int parse_time(const char *cp, time_t *t)
{
  struct tm st_tm;
#ifdef HAVE_STRPTIME
  if (!strptime(cp, "%Y-%m-%d %H:%M:%S", &st_tm)) {
    log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  }
#else
  unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  if (sscanf(cp, "%u-%u-%u %u:%u:%u", &year, &month,
                &day, &hour, &minute, &second) < 6) {
        log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  }
  if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
          hour > 23 || minute > 59 || second > 61) {
        log_fn(LOG_WARN, "Published time was nonsensical"); return -1;
  }
  st_tm.tm_year = year;
  st_tm.tm_mon = month-1;
  st_tm.tm_mday = day;
  st_tm.tm_hour = hour;
  st_tm.tm_min = minute;
  st_tm.tm_sec = second;
#endif
  *t = tor_timegm(&st_tm);
  return 0;
}


/* Helper function: parse a directory from 's' and, when done, store the
 * resulting routerlist in *dest, freeing the old value if necessary.
 * If pkey is provided, we check the directory signature with pkey.
 */
int /* Should be static; exposed for unit tests */
router_get_routerlist_from_directory_impl(const char *str,
                                          routerlist_t **dest,
                                          crypto_pk_env_t *pkey)
{
  directory_token_t *tok;
  char digest[20];
  char signed_digest[128];
  routerlist_t *new_dir = NULL;
  char *versions = NULL;
  time_t published_on;
  char *good_nickname_lst[1024];
  int n_good_nicknames = 0;
  int i, r;
  const char *end;
  smartlist_t *tokens = NULL;

  if (router_get_dir_hash(str, digest)) {
    log_fn(LOG_WARN, "Unable to compute digest of directory");
    goto err;
  }
  log(LOG_DEBUG,"Received directory hashes to %s",hex_str(digest,4));

  if ((end = strstr(str,"\nrouter "))) {
    ++end;
  } else if ((end = strstr(str, "\ndirectory-signature"))) {
    ++end;
  } else {
    end = str + strlen(str);
  }

  tokens = smartlist_create();
  if (tokenize_string(str,end,tokens,1)) {
    log_fn(LOG_WARN, "Error tokenizing directory"); goto err;
  }
  if (smartlist_len(tokens) < 1) {
    log_fn(LOG_WARN, "Impossibly short directory header"); goto err;
  }
  if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
    log_fn(LOG_WARN, "Unrecognized keyword in \"%s\"; can't parse directory.",
           tok->args[0]);
    goto err;
  }

  tok = smartlist_get(tokens,0);
  if (tok->tp != K_SIGNED_DIRECTORY) {
    log_fn(LOG_WARN, "Directory doesn't start with signed-directory.");
    goto err;
  }

  if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
    log_fn(LOG_WARN, "Missing published time on directory.");
    goto err;
  }
  assert(tok->n_args == 1);

  if (parse_time(tok->args[0], &published_on) < 0) {
     goto err;
  }

  if (!(tok = find_first_by_keyword(tokens, K_RECOMMENDED_SOFTWARE))) {
    log_fn(LOG_WARN, "Missing recommended-software line from directory.");
    goto err;
  }
  if (tok->n_args != 1) {
    log_fn(LOG_WARN, "Invalid recommended-software line"); goto err;
  }
  versions = tor_strdup(tok->args[0]);

  if (!(tok = find_first_by_keyword(tokens, K_RUNNING_ROUTERS))) {
    log_fn(LOG_WARN, "Missing running-routers line from directory.");
    goto err;
  }

  n_good_nicknames = tok->n_args;
  memcpy(good_nickname_lst, tok->args, n_good_nicknames*sizeof(char *));
  tok->n_args = 0; /* Don't free the strings in good_nickname_lst yet. */

  /* Read the router list from s, advancing s up past the end of the last
   * router. */
  str = end;
  if (router_get_list_from_string_impl(&str, &new_dir,
                                       n_good_nicknames,
                                       (const char**)good_nickname_lst)) {
    log_fn(LOG_WARN, "Error reading routers from directory");
    goto err;
  }
  for (i = 0; i < n_good_nicknames; ++i) {
    tor_free(good_nickname_lst[i]); /* now free them */
  }
  new_dir->software_versions = versions; versions = NULL;
  new_dir->published_on = published_on;

  SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
  smartlist_free(tokens);

  tokens = smartlist_create();
  if (tokenize_string(str,str+strlen(str),tokens,1)<0) {
    log_fn(LOG_WARN, "Error tokenizing signature"); goto err;
  }

  if (smartlist_len(tokens) != 1 ||
   ((directory_token_t*)smartlist_get(tokens,0))->tp != K_DIRECTORY_SIGNATURE){
    log_fn(LOG_WARN,"Expected a single directory signature"); goto err;
  }
  tok = smartlist_get(tokens,0);
  if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
    log_fn(LOG_WARN, "Bad object type or length on directory signature");
    goto err;
  }
  if (pkey) {
    if (crypto_pk_public_checksig(pkey, tok->object_body, 128, signed_digest)
        != 20) {
      log_fn(LOG_WARN, "Error reading directory: invalid signature.");
      goto err;
    }
    log(LOG_DEBUG,"Signed directory hash starts %s", hex_str(signed_digest,4));

    if (memcmp(digest, signed_digest, 20)) {
      log_fn(LOG_WARN, "Error reading directory: signature does not match.");
      goto err;
    }
  }

  if (*dest)
    routerlist_free(*dest);
  *dest = new_dir;

  r = 0;
  goto done;
 err:
  r = -1;
  if (new_dir)
    routerlist_free(new_dir);
  tor_free(versions);
  for (i = 0; i < n_good_nicknames; ++i) {
    tor_free(good_nickname_lst[i]);
  }
 done:
  if (tokens) {
    SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
    smartlist_free(tokens);
  }
  return r;
}

/* Helper function: Given a string *s containing a concatenated
 * sequence of router descriptors, parses them and stores the result
 * in *dest.  If good_nickname_lst is provided, then routers whose
 * nicknames are not listed are marked as nonrunning.  Advances *s to
 * a point immediately following the last router entry.  Returns 0 on
 * success and -1 on failure.
 */
static int
router_get_list_from_string_impl(const char **s, routerlist_t **dest,
                                 int n_good_nicknames,
                                 const char **good_nickname_lst)
{
  routerinfo_t *router;
  smartlist_t *routers;
  int rarray_len = 0;
  int i;
  const char *end;

  assert(s && *s);

  routers = smartlist_create();

  while (1) {
    *s = eat_whitespace(*s);
    /* Don't start parsing the rest of *s unless it contains a router. */
    if (strncmp(*s, "router ", 7)!=0)
      break;
    if ((end = strstr(*s+1, "\nrouter "))) {
      end++;
    } else if ((end = strstr(*s+1, "\ndirectory-signature"))) {
      end++;
    } else {
      end = *s+strlen(*s);
    }

    router = router_get_entry_from_string(*s, end);
    *s = end;
    if (!router) {
      log_fn(LOG_WARN, "Error reading router; skipping");
      continue;
    }

    if (n_good_nicknames>=0) {
      router->is_running = 0;
      for (i = 0; i < n_good_nicknames; ++i) {
        if (0==strcasecmp(good_nickname_lst[i], router->nickname)) {
          router->is_running = 1;
          break;
        }
      }
    } else {
      router->is_running = 1; /* start out assuming all dirservers are up */
    }
    smartlist_add(routers, router);
    log_fn(LOG_DEBUG,"just added router #%d.",rarray_len);
  }

  if (*dest)
    routerlist_free(*dest);
  *dest = tor_malloc(sizeof(routerlist_t));
  (*dest)->routers = routers;
  (*dest)->software_versions = NULL;
  return 0;
}


/* Helper function: reads a single router entry from *s, and advances
 * *s so it points to just after the router it just read.
 * mallocs a new router and returns it if all goes well, else returns
 * NULL.
 *
 * DOCDOC
 */
routerinfo_t *router_get_entry_from_string(const char *s,
                                           const char *end) {
  routerinfo_t *router = NULL;
  char signed_digest[128];
  char digest[128];
  smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  directory_token_t *tok;
  int t;
  int ports_set, bw_set;

  if (!end) {
    end = s + strlen(s);
  }

  if (router_get_router_hash(s, digest) < 0) {
    log_fn(LOG_WARN, "Couldn't compute router hash.");
    return NULL;
  }
  tokens = smartlist_create();
  if (tokenize_string(s,end,tokens,0)) {
    log_fn(LOG_WARN, "Error tokeninzing router descriptor."); goto err;
  }

  if (smartlist_len(tokens) < 2) {
    log_fn(LOG_WARN, "Impossibly short router descriptor.");
    goto err;
  }
  if ((tok = find_first_by_keyword(tokens, _UNRECOGNIZED))) {
    log_fn(LOG_WARN, "Unrecognized keyword in \"%s\"; skipping descriptor.",
           tok->args[0]);
    goto err;
  }

  tok = smartlist_get(tokens,0);
  if (tok->tp != K_ROUTER) {
    log_fn(LOG_WARN,"Entry does not start with \"router\"");
    goto err;
  }

  router = tor_malloc_zero(sizeof(routerinfo_t));
  router->onion_pkey = router->identity_pkey = router->link_pkey = NULL;
  ports_set = bw_set = 0;

  if (tok->n_args == 2 || tok->n_args == 6) {
    router->nickname = tor_strdup(tok->args[0]);
    if (strlen(router->nickname) > MAX_NICKNAME_LEN) {
      log_fn(LOG_WARN,"Router nickname too long.");
      goto err;
    }
    if (strspn(router->nickname, LEGAL_NICKNAME_CHARACTERS) !=
        strlen(router->nickname)) {
      log_fn(LOG_WARN, "Router nickname contains illegal characters.");
      goto err;
    }
    router->address = tor_strdup(tok->args[1]);
    router->addr = 0;

    if (tok->n_args == 6) {
      router->or_port = atoi(tok->args[2]);
      router->socks_port = atoi(tok->args[3]);
      router->dir_port = atoi(tok->args[4]);
      router->bandwidthrate = atoi(tok->args[5]);
      ports_set = bw_set = 1;
    }
  } else {
    log_fn(LOG_WARN,"Wrong # of arguments to \"router\"");
    goto err;
  }

  tok = find_first_by_keyword(tokens, K_PORTS);
  if (tok && ports_set) {
    log_fn(LOG_WARN,"Redundant ports line");
    goto err;
  } else if (tok) {
    if (tok->n_args != 3) {
      log_fn(LOG_WARN,"Wrong # of arguments to \"ports\"");
      goto err;
    }
    router->or_port = atoi(tok->args[0]);
    router->socks_port = atoi(tok->args[1]);
    router->dir_port = atoi(tok->args[2]);
    ports_set = 1;
  }

  tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  if (tok && bw_set) {
    log_fn(LOG_WARN,"Redundant bandwidth line");
    goto err;
  } else if (tok) {
    if (tok->n_args < 1) {
      log_fn(LOG_WARN,"Not enough arguments to \"bandwidth\"");
      goto err;
    }
    router->bandwidthrate = atoi(tok->args[0]);
    bw_set = 1;
  }

  if (!(tok = find_first_by_keyword(tokens, K_PUBLISHED))) {
    log_fn(LOG_WARN, "Missing published time"); goto err;
  }
  assert(tok->n_args == 1);
  if (parse_time(tok->args[0], &router->published_on) < 0)
          goto err;

  if (!(tok = find_first_by_keyword(tokens, K_ONION_KEY))) {
    log_fn(LOG_WARN, "Missing onion key"); goto err;
  }
  /* XXX Check key length */
  router->onion_pkey = tok->key;
  tok->key = NULL; /* Prevent free */

  if (!(tok = find_first_by_keyword(tokens, K_LINK_KEY))) {
    log_fn(LOG_WARN, "Missing onion key"); goto err;
  }
  /* XXX Check key length */
  router->link_pkey = tok->key;
  tok->key = NULL; /* Prevent free */

  if (!(tok = find_first_by_keyword(tokens, K_SIGNING_KEY))) {
    log_fn(LOG_WARN, "Missing onion key"); goto err;
  }
  /* XXX Check key length */
  router->identity_pkey = tok->key;
  tok->key = NULL; /* Prevent free */

  exit_policy_tokens = find_all_exitpolicy(tokens);
  SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
                    if (router_add_exit_policy(router,t)<0) {
                      log_fn(LOG_WARN,"Error in exit policy"); goto err;}
                    );

  if (!(tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE))) {
    log_fn(LOG_WARN, "Missing router signature"); goto err;
  }
  if (strcmp(tok->object_type, "SIGNATURE") || tok->object_size != 128) {
    log_fn(LOG_WARN, "Bad object type or length on router signature");
    goto err;
  }
  if ((t=crypto_pk_public_checksig(router->identity_pkey, tok->object_body,
                                   128, signed_digest)) != 20) {
    log_fn(LOG_WARN, "Invalid signature %d",t); goto err;
  }
  if (memcmp(digest, signed_digest, 20)) {
    log_fn(LOG_WARN, "Mismatched signature"); goto err;
  }

  if (!ports_set) {
    log_fn(LOG_WARN,"No ports declared; failing."); goto err;
  }
  if (!bw_set) {
    log_fn(LOG_WARN,"No bandwidth declared; failing."); goto err;
  }
  if(!router->or_port) {
    log_fn(LOG_WARN,"or_port unreadable or 0. Failing.");
    goto err;
  }
  if (!router->bandwidthrate) {
    log_fn(LOG_WARN,"bandwidthrate unreadable or 0. Failing.");
    goto err;
  }

#if XXXBC
  router->bandwidthburst = atoi(ARGS[6]);
  if (!router->bandwidthburst) {
    log_fn(LOG_WARN,"bandwidthburst unreadable or 0. Failing.");
    goto err;
  }
#else
  router->bandwidthburst = 10*router->bandwidthrate;
#endif

  log_fn(LOG_DEBUG,"or_port %d, socks_port %d, dir_port %d, bandwidthrate %u, bandwidthburst %u.",
    router->or_port, router->socks_port, router->dir_port,
    (unsigned) router->bandwidthrate, (unsigned) router->bandwidthburst);


  goto done;
  return router;

 err:
  routerinfo_free(router);
  router = NULL;
 done:
  if (tokens) {
    SMARTLIST_FOREACH(tokens, directory_token_t *, tok, token_free(tok));
    smartlist_free(tokens);
  }
  if (exit_policy_tokens) {
    smartlist_free(exit_policy_tokens);
  }
  return router;
}

/* Parse the exit policy in the string 's' and add it to 'router'.
 */
int
router_add_exit_policy_from_string(routerinfo_t *router, const char *s)
{
  directory_token_t *tok = NULL;
  const char *cp;
  char *tmp;
  int r;
  int len, idx;

  /* *s might not end with \n, so we need to extend it with one. */
  len = strlen(s);
  cp = tmp = tor_malloc(len+2);
  for (idx = 0; idx < len; ++idx) {
    tmp[idx] = tolower(s[idx]);
  }
  tmp[len]='\n';
  tmp[len+1]='\0';
  tok = get_next_token(&cp, RTR_ONLY);
  if (tok->tp == _ERR) {
    log_fn(LOG_WARN, "Error reading exit policy: %s", tok->error);
    goto err;
  }
  if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
    log_fn(LOG_WARN, "Expected 'accept' or 'reject'.");
    goto err;
  }

  /* Now that we've gotten an exit policy, add it to the router. */
  r = router_add_exit_policy(router, tok);
  goto done;
 err:
  r = -1;
 done:
  free(tmp);
  token_free(tok);
  return r;
}

/* Given a K_ACCEPT or K_REJECT token and a router, create a new exit_policy_t
 * corresponding to the token, and add it to 'router' */
static int
router_add_exit_policy(routerinfo_t *router, directory_token_t *tok) {

  struct exit_policy_t *tmpe, *newe;
  struct in_addr in;
  char *arg, *address, *mask, *port, *endptr;
  int bits;

  assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);

  if (tok->n_args != 1)
    return -1;
  arg = tok->args[0];

  newe = tor_malloc_zero(sizeof(struct exit_policy_t));

  newe->string = tor_malloc(8+strlen(arg));
  if (tok->tp == K_REJECT) {
    strcpy(newe->string, "reject ");
    newe->policy_type = EXIT_POLICY_REJECT;
  } else {
    strcpy(newe->string, "accept ");
    newe->policy_type = EXIT_POLICY_ACCEPT;
  }
  strcat(newe->string, arg); /* can't overflow */

  address = arg;
  mask = strchr(arg,'/');
  port = strchr(mask?mask:arg,':');
  /* Break 'arg' into separate strings.  'arg' was already strdup'd by
   * _router_get_next_token, so it's safe to modify.
   */
  if (mask)
    *mask++ = 0;
  if (port)
    *port++ = 0;

  if (strcmp(address, "*") == 0) {
    newe->addr = 0;
  } else if (tor_inet_aton(address, &in) != 0) {
    newe->addr = ntohl(in.s_addr);
  } else {
    log_fn(LOG_WARN, "Malformed IP %s in exit policy; rejecting.",
           address);
    goto policy_read_failed;
  }
  if (!mask) {
    if (strcmp(address, "*") == 0)
      newe->msk = 0;
    else
      newe->msk = 0xFFFFFFFFu;
  } else {
    endptr = NULL;
    bits = (int) strtol(mask, &endptr, 10);
    if (!*endptr) {
      /* strtol handled the whole mask. */
      newe->msk = ~((1<<(32-bits))-1);
    } else if (tor_inet_aton(mask, &in) != 0) {
      newe->msk = ntohl(in.s_addr);
    } else {
      log_fn(LOG_WARN, "Malformed mask %s on exit policy; rejecting.",
             mask);
      goto policy_read_failed;
    }
  }
  if (!port || strcmp(port, "*") == 0) {
    newe->prt_min = 0;
    newe->prt_max = 65535;
  } else {
    endptr = NULL;
    newe->prt_min = (uint16_t) strtol(port, &endptr, 10);
    if (*endptr == '-') {
      port = endptr+1;
      endptr = NULL;
      newe->prt_max = (uint16_t) strtol(port, &endptr, 10);
      if (*endptr) {
      log_fn(LOG_WARN, "Malformed port %s on exit policy; rejecting.",
             port);
      }
    } else if (*endptr) {
      log_fn(LOG_WARN, "Malformed port %s on exit policy; rejecting.",
             port);
      goto policy_read_failed;
    } else {
      newe->prt_max = newe->prt_min;
    }
  }

  in.s_addr = htonl(newe->addr);
  address = tor_strdup(inet_ntoa(in));
  in.s_addr = htonl(newe->msk);
  log_fn(LOG_DEBUG,"%s %s/%s:%d-%d",
         newe->policy_type == EXIT_POLICY_REJECT ? "reject" : "accept",
         address, inet_ntoa(in), newe->prt_min, newe->prt_max);
  tor_free(address);

  /* now link newe onto the end of exit_policy */

  if(!router->exit_policy) {
    router->exit_policy = newe;
    return 0;
  }

  for(tmpe=router->exit_policy; tmpe->next; tmpe=tmpe->next) ;
  tmpe->next = newe;

  return 0;

policy_read_failed:
  assert(newe->string);
  log_fn(LOG_WARN,"Couldn't parse line '%s'. Dropping", newe->string);
  tor_free(newe->string);
  free(newe);
  return -1;
}

/* ------------------------------------------------------------ */
/* Tokenizer for router descriptors and directories. */


/* Free any malloced resources allocated for a token.  Does not free
 *  the token itself.
 */
static void
token_free(directory_token_t *tok)
{
  int i;
  assert(tok);
  if (tok->args) {
    for (i = 0; i < tok->n_args; ++i) {
      tor_free(tok->args[i]);
    }
    tor_free(tok->args);
  }
  tor_free(tok->object_type);
  tor_free(tok->object_body);
  if (tok->key)
    crypto_free_pk_env(tok->key);
  tor_free(tok);
}

/* Helper function: read the next token from *s, and stores it into a new
 * directory token *tok.
 */
static directory_token_t *
get_next_token(const char **s, where_syntax where) {
  const char *next, *obstart;
  int i, done, allocated;
  directory_token_t *tok;
  arg_syntax a_syn;
  obj_syntax o_syn = NO_OBJ;

#define RET_ERR(msg)                                    \
  do { if (tok) token_free(tok);                        \
       tok = tor_malloc_zero(sizeof(directory_token_t));\
       tok->tp = _ERR;                                  \
       tok->error = msg;                                \
       goto done_tokenizing; } while (0)

  tok = tor_malloc_zero(sizeof(directory_token_t));
  tok->tp = _ERR;

  *s = eat_whitespace(*s);
  if (!**s) {
    tok->tp = _EOF;
    return tok;
  }
  next = find_whitespace(*s);
  if (!next) {
    tok->error = "Unexpected EOF"; return tok;
  }
  /* It's a keyword... but which one? */
  for (i = 0 ; token_table[i].t ; ++i) {
    if (!strncmp(token_table[i].t, *s, next-*s)) {
      /* We've found the keyword. */
      tok->tp = token_table[i].v;
      a_syn = token_table[i].s;
      o_syn = token_table[i].os;
      if (token_table[i].ws != ANY && token_table[i].ws != where) {
        if (where == DIR_ONLY) {
          RET_ERR("Found a router-only token in a directory section");
        } else {
          RET_ERR("Found a directory-only token in a router descriptor");
        }
      }
      if (a_syn == ARGS) {
        /* This keyword takes multiple arguments. */
        i = 0;
        done = (*next == '\n');
        allocated = 32;
        tok->args = tor_malloc(sizeof(char*)*32);
        *s = eat_whitespace_no_nl(next);
        while (**s != '\n' && !done) {
          next = find_whitespace(*s);
          if (*next == '\n')
            done = 1;
          if (i == allocated) {
            allocated *= 2;
            tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
          }
          tok->args[i++] = tor_strndup(*s,next-*s);
          *s = eat_whitespace_no_nl(next+1);
        }
        tok->n_args = i;
      } else if (a_syn == CONCAT_ARGS) {
        /* The keyword takes the line as a single argument */
        *s = eat_whitespace_no_nl(next);
        next = strchr(*s, '\n');
        if (!next)
          RET_ERR("Unexpected EOF");
        tok->args = tor_malloc(sizeof(char*));
        tok->args[0] = tor_strndup(*s,next-*s);
        tok->n_args = 1;
        *s = eat_whitespace_no_nl(next+1);
      } else {
        /* The keyword takes no arguments. */
        assert(a_syn == NO_ARGS);
        *s = eat_whitespace_no_nl(next);
        if (**s != '\n') {
          RET_ERR("Unexpected arguments");
        }
        tok->n_args = 0;
        *s = eat_whitespace_no_nl(*s+1);
      }
      break;
    }
  }
  if (tok->tp == _ERR) {
    tok->tp = _UNRECOGNIZED;
    next = strchr(*s, '\n');
    if (!next) {
      RET_ERR("Unexpected EOF");
    }
    tok->args = tor_malloc(sizeof(char*));
    tok->args[0] = tor_strndup(*s,next-*s);
    tok->n_args = 1;
    *s = next+1;
    o_syn = OBJ_OK;
  }
  *s = eat_whitespace(*s);
  if (strncmp(*s, "-----BEGIN ", 11)) {
    goto done_tokenizing;
  }
  obstart = *s;
  *s += 11; /* length of "-----BEGIN ". */
  next = strchr(*s, '\n');
  if (next-*s < 6 || strncmp(next-5, "-----\n", 6)) {
    RET_ERR("Malformed object: bad begin line");
  }
  tok->object_type = tor_strndup(*s, next-*s-5);
  *s = next+1;
  next = strstr(*s, "-----END ");
  if (!next) {
    RET_ERR("Malformed object: missing end line");
  }
  if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) {
    if (strncmp(next, "-----END RSA PUBLIC KEY-----\n", 29))
      RET_ERR("Malformed object: mismatched end line");
    next = strchr(next,'\n')+1;
    tok->key = crypto_new_pk_env();
    if (crypto_pk_read_public_key_from_string(tok->key, obstart, next-obstart))
      RET_ERR("Couldn't parse public key.");
    *s = next;
  } else {
    tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
    i = base64_decode(tok->object_body, 256, *s, next-*s);
    if (i<0) {
      RET_ERR("Malformed object: bad base64-encoded data");
    }
    tok->object_size = i;
    *s = next + 9; /* length of "-----END ". */
    i = strlen(tok->object_type);
    if (strncmp(*s, tok->object_type, i) || strncmp(*s+i, "-----\n", 6)) {
      RET_ERR("Malformed object: mismatched end tag");
    }
    *s += i+6;
  }
  switch(o_syn)
    {
    case NO_OBJ:
      if (tok->object_body)
        RET_ERR("Unexpected object for keyword");
      if (tok->key)
        RET_ERR("Unexpected public key for keyword");
      break;
    case NEED_OBJ:
      if (!tok->object_body)
        RET_ERR("Missing object for keyword");
      break;
    case NEED_KEY:
      if (!tok->key)
        RET_ERR("Missing publid key for keyword");
      break;
    case OBJ_OK:
      break;
    }

 done_tokenizing:

#if 0
  for (i = 0; token_table[i].t ; ++i) {
    if (token_table[i].v == tok->tp) {
      fputs(token_table[i].t, stdout);
      break;
      i = -1;
    }
  }
  if (i) {
    if (tok->tp == _UNRECOGNIZED) fputs("UNRECOGNIZED", stdout);
    if (tok->tp == _ERR) fputs("ERR",stdout);
    if (tok->tp == _EOF) fputs("EOF",stdout);
    if (tok->tp == _NIL) fputs("_NIL",stdout);
  }
  for(i = 0; i < tok->n_args; ++i) {
    fprintf(stdout," \"%s\"", tok->args[i]);
  }
  if (tok->error) { fprintf(stdout," *%s*", tok->error); }
  fputs("\n",stdout);
#endif


  return tok;
#undef RET_ERR
}

static int
tokenize_string(const char *start, const char *end, smartlist_t *out,
                int is_dir)
{
  const char **s;
  directory_token_t *tok = NULL;
  where_syntax where = is_dir ? DIR_ONLY : RTR_ONLY;
  s = &start;
  while (*s < end && (!tok || tok->tp != _EOF)) {
    tok = get_next_token(s, where);
    if (tok->tp == _ERR) {
      log_fn(LOG_WARN, "parse error: %s", tok->error);
      return -1;
    }
    smartlist_add(out, tok);
    *s = eat_whitespace(*s);
  }

  return 0;
}

static directory_token_t *
find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
{
  SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  return NULL;
}

static smartlist_t *
find_all_exitpolicy(smartlist_t *s)
{
  smartlist_t *out = smartlist_create();
  SMARTLIST_FOREACH(s, directory_token_t *, t,
                    if (t->tp == K_ACCEPT || t->tp == K_REJECT)
                      smartlist_add(out,t));
  return out;
}


/* Compute the SHA digest of the substring of s taken from the first
 * occurrence of start_str through the first newline after the first
 * subsequent occurrence of end_str; store the 20-byte result in 'digest';
 * return 0 on success.
 *
 * If no such substring exists, return -1.
 */
static int router_get_hash_impl(const char *s, char *digest,
                                const char *start_str,
                                const char *end_str)
{
  char *start, *end;
  start = strstr(s, start_str);
  if (!start) {
    log_fn(LOG_WARN,"couldn't find \"%s\"",start_str);
    return -1;
  }
  end = strstr(start+strlen(start_str), end_str);
  if (!end) {
    log_fn(LOG_WARN,"couldn't find \"%s\"",end_str);
    return -1;
  }
  end = strchr(end, '\n');
  if (!end) {
    log_fn(LOG_WARN,"couldn't find EOL");
    return -1;
  }
  ++end;

  if (crypto_digest(start, end-start, digest)) {
    log_fn(LOG_WARN,"couldn't compute digest");
    return -1;
  }

  return 0;
}

/*
  Local Variables:
  mode:c
  indent-tabs-mode:nil
  c-basic-offset:2
  End:
*/