routerparse.c 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802
  1. /* oCpyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char routerparse_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file routerparse.c
  10. * \brief Code to parse and validate router descriptors and directories.
  11. **/
  12. #include "or.h"
  13. /****************************************************************************/
  14. /** Enumeration of possible token types. The ones starting with K_
  15. * correspond to directory 'keywords'. _UNRECOGNIZED is for an
  16. * unrecognized keyword; _ERR is an error in the tokenizing process,
  17. * _EOF is an end-of-file marker, and _NIL is used to encode
  18. * not-a-token.
  19. */
  20. typedef enum {
  21. K_ACCEPT = 0,
  22. K_DIRECTORY_SIGNATURE,
  23. K_RECOMMENDED_SOFTWARE,
  24. K_REJECT,
  25. K_ROUTER,
  26. K_SIGNED_DIRECTORY,
  27. K_SIGNING_KEY,
  28. K_ONION_KEY,
  29. K_ROUTER_SIGNATURE,
  30. K_PUBLISHED,
  31. K_RUNNING_ROUTERS,
  32. K_ROUTER_STATUS,
  33. K_PLATFORM,
  34. K_OPT,
  35. K_BANDWIDTH,
  36. K_PORTS,
  37. K_CONTACT,
  38. K_NETWORK_STATUS,
  39. K_UPTIME,
  40. K_DIR_SIGNING_KEY,
  41. K_FAMILY,
  42. K_FINGERPRINT,
  43. K_HIBERNATING,
  44. K_READ_HISTORY,
  45. K_WRITE_HISTORY,
  46. K_NETWORK_STATUS_VERSION,
  47. K_DIR_SOURCE,
  48. K_DIR_OPTIONS,
  49. K_CLIENT_VERSIONS,
  50. K_SERVER_VERSIONS,
  51. K_R,
  52. K_S,
  53. K_V,
  54. K_EVENTDNS,
  55. K_EXTRA_INFO,
  56. K_EXTRA_INFO_DIGEST,
  57. K_CACHES_EXTRA_INFO,
  58. K_DIR_KEY_CERTIFICATE_VERSION,
  59. K_DIR_IDENTITY_KEY,
  60. K_DIR_KEY_PUBLISHED,
  61. K_DIR_KEY_EXPIRES,
  62. K_DIR_KEY_CERTIFICATION,
  63. K_VOTE_STATUS,
  64. K_VALID_AFTER,
  65. K_FRESH_UNTIL,
  66. K_VALID_UNTIL,
  67. K_VOTING_DELAY,
  68. K_KNOWN_FLAGS,
  69. K_VOTE_DIGEST,
  70. K_CONSENSUS_DIGEST,
  71. _UNRECOGNIZED,
  72. _ERR,
  73. _EOF,
  74. _NIL
  75. } directory_keyword;
  76. /** Structure to hold a single directory token.
  77. *
  78. * We parse a directory by breaking it into "tokens", each consisting
  79. * of a keyword, a line full of arguments, and a binary object. The
  80. * arguments and object are both optional, depending on the keyword
  81. * type.
  82. */
  83. typedef struct directory_token_t {
  84. directory_keyword tp; /**< Type of the token. */
  85. int n_args; /**< Number of elements in args */
  86. char **args; /**< Array of arguments from keyword line. */
  87. char *object_type; /**< -----BEGIN [object_type]-----*/
  88. size_t object_size; /**< Bytes in object_body */
  89. char *object_body; /**< Contents of object, base64-decoded. */
  90. crypto_pk_env_t *key; /**< For public keys only. */
  91. char *error; /**< For _ERR tokens only. */
  92. } directory_token_t;
  93. /* ********************************************************************** */
  94. /** We use a table of rules to decide how to parse each token type. */
  95. /** Rules for whether the keyword needs an object. */
  96. typedef enum {
  97. NO_OBJ, /**< No object, ever. */
  98. NEED_OBJ, /**< Object is required. */
  99. NEED_KEY_1024, /**< Object is required, and must be a 1024 bit public key */
  100. NEED_KEY, /**< Object is required, and must be a public key. */
  101. OBJ_OK, /**< Object is optional. */
  102. } obj_syntax;
  103. #define AT_START 1
  104. #define AT_END 2
  105. /** Determines the parsing rules for a single token type. */
  106. typedef struct token_rule_t {
  107. /** The string value of the keyword identifying the type of item. */
  108. const char *t;
  109. /** The corresponding directory_keyword enum. */
  110. directory_keyword v;
  111. /** Minimum number of arguments for this item */
  112. int min_args;
  113. /** Maximum number of arguments for this item */
  114. int max_args;
  115. /** If true, we concatenate all arguments for this item into a single
  116. * string. */
  117. int concat_args;
  118. /** Requirments on object syntax for this item. */
  119. obj_syntax os;
  120. /** Lowest number of times this item may appear in a document. */
  121. int min_cnt;
  122. /** Highest number of times this item may appear in a document. */
  123. int max_cnt;
  124. /** One or more of AT_START/AT_END to limit where the item may appear in a
  125. * document. */
  126. int pos;
  127. } token_rule_t;
  128. /*
  129. * Helper macros to define token tables. 's' is a string, 't' is a
  130. * directory_keyword, 'a' is a trio of argument multiplicities, and 'o' is an
  131. * object syntax.
  132. *
  133. */
  134. /** Appears to indicate the end of a table. */
  135. #define END_OF_TABLE { NULL, _NIL, 0,0,0, NO_OBJ, 0, INT_MAX, 0 }
  136. /** An item with no restrictions: used for obsolete document types */
  137. #define T(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0 }
  138. /** An item with no restrictions on multiplicity or location. */
  139. #define T0N(s,t,a,o) { s, t, a, o, 0, INT_MAX, 0 }
  140. /** An item that must appear exactly once */
  141. #define T1(s,t,a,o) { s, t, a, o, 1, 1, 0 }
  142. /** An item that must appear exactly once, at the start of the document */
  143. #define T1_START(s,t,a,o) { s, t, a, o, 1, 1, AT_START }
  144. /** An item that must appear exactly once, at the end of the document */
  145. #define T1_END(s,t,a,o) { s, t, a, o, 1, 1, AT_END }
  146. /** An item that must appear one or more times */
  147. #define T1N(s,t,a,o) { s, t, a, o, 1, INT_MAX, 0 }
  148. /** An item that must appear no more than once */
  149. #define T01(s,t,a,o) { s, t, a, o, 0, 1, 0 }
  150. /* Argument multiplicity: any number of arguments. */
  151. #define ARGS 0,INT_MAX,0
  152. /* Argument multiplicity: no arguments. */
  153. #define NO_ARGS 0,0,0
  154. /* Argument multiplicity: concatenate all arguments. */
  155. #define CONCAT_ARGS 1,1,1
  156. /* Argument multiplicity: at least <b>n</b> arguments. */
  157. #define GE(n) n,INT_MAX,0
  158. /* Argument multiplicity: exactly <b>n</b> arguments. */
  159. #define EQ(n) n,n,0
  160. /** List of tokens allowable in router derscriptors */
  161. static token_rule_t routerdesc_token_table[] = {
  162. T0N("reject", K_REJECT, ARGS, NO_OBJ ),
  163. T0N("accept", K_ACCEPT, ARGS, NO_OBJ ),
  164. T1_START( "router", K_ROUTER, GE(5), NO_OBJ ),
  165. T1( "signing-key", K_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
  166. T1( "onion-key", K_ONION_KEY, NO_ARGS, NEED_KEY_1024 ),
  167. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  168. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  169. T01("uptime", K_UPTIME, GE(1), NO_OBJ ),
  170. T01("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  171. T01("hibernating", K_HIBERNATING, GE(1), NO_OBJ ),
  172. T01("platform", K_PLATFORM, CONCAT_ARGS, NO_OBJ ),
  173. T01("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  174. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  175. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  176. T01("extra-info-digest", K_EXTRA_INFO_DIGEST, GE(1), NO_OBJ ),
  177. T01("family", K_FAMILY, ARGS, NO_OBJ ),
  178. T01("caches-extra-info", K_CACHES_EXTRA_INFO, NO_ARGS, NO_OBJ ),
  179. T01("eventdns", K_EVENTDNS, ARGS, NO_OBJ ),
  180. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  181. T1( "bandwidth", K_BANDWIDTH, GE(3), NO_OBJ ),
  182. END_OF_TABLE
  183. };
  184. /** List of tokens allowable in extra-info documents. */
  185. static token_rule_t extrainfo_token_table[] = {
  186. T1_END( "router-signature", K_ROUTER_SIGNATURE, NO_ARGS, NEED_OBJ ),
  187. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  188. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  189. T01("read-history", K_READ_HISTORY, ARGS, NO_OBJ ),
  190. T01("write-history", K_WRITE_HISTORY, ARGS, NO_OBJ ),
  191. T1_START( "extra-info", K_EXTRA_INFO, GE(2), NO_OBJ ),
  192. END_OF_TABLE
  193. };
  194. /** List of tokens allowable in the body part of v2 and v3 networkstatus
  195. * documents. */
  196. static token_rule_t rtrstatus_token_table[] = {
  197. T1( "r", K_R, GE(8), NO_OBJ ),
  198. T1( "s", K_S, ARGS, NO_OBJ ),
  199. T01("v", K_V, CONCAT_ARGS, NO_OBJ ),
  200. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  201. END_OF_TABLE
  202. };
  203. /** List of tokens allowable in the header part of v2 networkstatus documents.
  204. */
  205. static token_rule_t netstatus_token_table[] = {
  206. T1( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  207. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  208. T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  209. T1( "dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY_1024 ),
  210. T1( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  211. T1_START("network-status-version", K_NETWORK_STATUS_VERSION,
  212. GE(1), NO_OBJ ),
  213. T1( "dir-source", K_DIR_SOURCE, GE(3), NO_OBJ ),
  214. T01("dir-options", K_DIR_OPTIONS, ARGS, NO_OBJ ),
  215. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  216. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  217. END_OF_TABLE
  218. };
  219. /** List of tokens allowable in the footer of v1/v2 directory/networkstatus
  220. * footers. */
  221. static token_rule_t dir_footer_token_table[] = {
  222. T1("directory-signature", K_DIRECTORY_SIGNATURE, EQ(1), NEED_OBJ ),
  223. END_OF_TABLE
  224. };
  225. /** List of tokens allowable in v1 diectory headers/footers. */
  226. static token_rule_t dir_token_table[] = {
  227. /* don't enforce counts; this is obsolete. */
  228. T( "network-status", K_NETWORK_STATUS, NO_ARGS, NO_OBJ ),
  229. T( "directory-signature", K_DIRECTORY_SIGNATURE, ARGS, NEED_OBJ ),
  230. T( "recommended-software",K_RECOMMENDED_SOFTWARE,CONCAT_ARGS, NO_OBJ ),
  231. T( "signed-directory", K_SIGNED_DIRECTORY, NO_ARGS, NO_OBJ ),
  232. T( "running-routers", K_RUNNING_ROUTERS, ARGS, NO_OBJ ),
  233. T( "router-status", K_ROUTER_STATUS, ARGS, NO_OBJ ),
  234. T( "published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  235. T( "opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  236. T( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  237. T( "dir-signing-key", K_DIR_SIGNING_KEY, ARGS, OBJ_OK ),
  238. T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  239. END_OF_TABLE
  240. };
  241. /** List of tokens allowable in the footer of v1/v2 directory/networkstatus
  242. * footers. */
  243. #define CERTIFICATE_MEMBERS \
  244. T1("dir-key-certificate-version", K_DIR_KEY_CERTIFICATE_VERSION, \
  245. GE(1), NO_OBJ ), \
  246. T1("dir-identity-key", K_DIR_IDENTITY_KEY, NO_ARGS, NEED_KEY ),\
  247. T1("dir-key-published",K_DIR_KEY_PUBLISHED, CONCAT_ARGS, NO_OBJ), \
  248. T1("dir-key-expires", K_DIR_KEY_EXPIRES, CONCAT_ARGS, NO_OBJ), \
  249. T1("dir-signing-key", K_DIR_SIGNING_KEY, NO_ARGS, NEED_KEY ),\
  250. T1("dir-key-certification", K_DIR_KEY_CERTIFICATION, \
  251. NO_ARGS, NEED_OBJ),
  252. static token_rule_t dir_key_certificate_table[] = {
  253. CERTIFICATE_MEMBERS
  254. T1("fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  255. END_OF_TABLE
  256. };
  257. static token_rule_t networkstatus_vote_token_table[] = {
  258. T1("network-status-version", K_NETWORK_STATUS_VERSION,
  259. GE(1), NO_OBJ ),
  260. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  261. T1("published", K_PUBLISHED, CONCAT_ARGS, NO_OBJ ),
  262. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  263. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  264. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  265. T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
  266. T1("known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  267. T( "fingerprint", K_FINGERPRINT, CONCAT_ARGS, NO_OBJ ),
  268. CERTIFICATE_MEMBERS
  269. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  270. T1( "contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  271. T1( "dir-source", K_DIR_SOURCE, GE(6), NO_OBJ ),
  272. T1( "dir-options", K_DIR_OPTIONS, ARGS, NO_OBJ ),
  273. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  274. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  275. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  276. END_OF_TABLE
  277. };
  278. static token_rule_t networkstatus_consensus_token_table[] = {
  279. T1("network-status-version", K_NETWORK_STATUS_VERSION,
  280. GE(1), NO_OBJ ),
  281. T1("vote-status", K_VOTE_STATUS, GE(1), NO_OBJ ),
  282. T1("valid-after", K_VALID_AFTER, CONCAT_ARGS, NO_OBJ ),
  283. T1("fresh-until", K_FRESH_UNTIL, CONCAT_ARGS, NO_OBJ ),
  284. T1("valid-until", K_VALID_UNTIL, CONCAT_ARGS, NO_OBJ ),
  285. T1("voting-delay", K_VOTING_DELAY, GE(2), NO_OBJ ),
  286. T0N("opt", K_OPT, CONCAT_ARGS, OBJ_OK ),
  287. T1N("dir-source", K_DIR_SOURCE, GE(3), NO_OBJ ),
  288. T1N("contact", K_CONTACT, CONCAT_ARGS, NO_OBJ ),
  289. T1N("vote-digest", K_VOTE_DIGEST, GE(1), NO_OBJ ),
  290. T1( "known-flags", K_KNOWN_FLAGS, CONCAT_ARGS, NO_OBJ ),
  291. T01("client-versions", K_CLIENT_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  292. T01("server-versions", K_SERVER_VERSIONS, CONCAT_ARGS, NO_OBJ ),
  293. END_OF_TABLE
  294. };
  295. static token_rule_t networkstatus_vote_footer_token_table[] = {
  296. T( "directory-signature", K_DIRECTORY_SIGNATURE, GE(2), NEED_OBJ ),
  297. END_OF_TABLE
  298. };
  299. #undef T
  300. /* static function prototypes */
  301. static int router_add_exit_policy(routerinfo_t *router,directory_token_t *tok);
  302. static addr_policy_t *router_parse_addr_policy(directory_token_t *tok);
  303. static addr_policy_t *router_parse_addr_policy_private(directory_token_t *tok);
  304. static int router_get_hash_impl(const char *s, char *digest,
  305. const char *start_str, const char *end_str,
  306. char end_char);
  307. static void token_free(directory_token_t *tok);
  308. static smartlist_t *find_all_exitpolicy(smartlist_t *s);
  309. static directory_token_t *find_first_by_keyword(smartlist_t *s,
  310. directory_keyword keyword);
  311. static int tokenize_string(const char *start, const char *end,
  312. smartlist_t *out,
  313. token_rule_t *table);
  314. static directory_token_t *get_next_token(const char **s,
  315. token_rule_t *table);
  316. static int check_signature_token(const char *digest,
  317. directory_token_t *tok,
  318. crypto_pk_env_t *pkey,
  319. int check_authority,
  320. const char *doctype);
  321. static crypto_pk_env_t *find_dir_signing_key(const char *str);
  322. static int tor_version_same_series(tor_version_t *a, tor_version_t *b);
  323. /** Set <b>digest</b> to the SHA-1 digest of the hash of the directory in
  324. * <b>s</b>. Return 0 on success, -1 on failure.
  325. */
  326. int
  327. router_get_dir_hash(const char *s, char *digest)
  328. {
  329. return router_get_hash_impl(s,digest,
  330. "signed-directory","\ndirectory-signature",'\n');
  331. }
  332. /** Set <b>digest</b> to the SHA-1 digest of the hash of the first router in
  333. * <b>s</b>. Return 0 on success, -1 on failure.
  334. */
  335. int
  336. router_get_router_hash(const char *s, char *digest)
  337. {
  338. return router_get_hash_impl(s,digest,
  339. "router ","\nrouter-signature", '\n');
  340. }
  341. /** Set <b>digest</b> to the SHA-1 digest of the hash of the running-routers
  342. * string in <b>s</b>. Return 0 on success, -1 on failure.
  343. */
  344. int
  345. router_get_runningrouters_hash(const char *s, char *digest)
  346. {
  347. return router_get_hash_impl(s,digest,
  348. "network-status","\ndirectory-signature", '\n');
  349. }
  350. /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
  351. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  352. int
  353. router_get_networkstatus_v2_hash(const char *s, char *digest)
  354. {
  355. return router_get_hash_impl(s,digest,
  356. "network-status-version","\ndirectory-signature",
  357. '\n');
  358. }
  359. /** Set <b>digest</b> to the SHA-1 digest of the hash of the network-status
  360. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  361. int
  362. router_get_networkstatus_v3_hash(const char *s, char *digest)
  363. {
  364. return router_get_hash_impl(s,digest,
  365. "network-status-version","\ndirectory-signature",
  366. ' ');
  367. }
  368. /** Set <b>digest</b> to the SHA-1 digest of the hash of the extrainfo
  369. * string in <b>s</b>. Return 0 on success, -1 on failure. */
  370. int
  371. router_get_extrainfo_hash(const char *s, char *digest)
  372. {
  373. return router_get_hash_impl(s,digest,"extra-info","\nrouter-signature",'\n');
  374. }
  375. /** Helper: used to generate signatures for routers, directories and
  376. * network-status objects. Given a digest in <b>digest</b> and a secret
  377. * <b>private_key</b>, generate an PKCS1-padded signature, BASE64-encode it,
  378. * surround it with -----BEGIN/END----- pairs, and write it to the
  379. * <b>buf_len</b>-byte buffer at <b>buf</b>. Return 0 on success, -1 on
  380. * failure.
  381. */
  382. int
  383. router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest,
  384. crypto_pk_env_t *private_key)
  385. {
  386. char *signature;
  387. int i;
  388. signature = tor_malloc(crypto_pk_keysize(private_key));
  389. if (crypto_pk_private_sign(private_key, signature, digest, DIGEST_LEN) < 0) {
  390. log_warn(LD_BUG,"Couldn't sign digest.");
  391. goto err;
  392. }
  393. if (strlcat(buf, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
  394. goto truncated;
  395. i = strlen(buf);
  396. if (base64_encode(buf+i, buf_len-i, signature, 128) < 0) {
  397. log_warn(LD_BUG,"couldn't base64-encode signature");
  398. tor_free(buf);
  399. goto err;
  400. }
  401. if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
  402. goto truncated;
  403. tor_free(signature);
  404. return 0;
  405. truncated:
  406. log_warn(LD_BUG,"tried to exceed string length.");
  407. err:
  408. tor_free(signature);
  409. return -1;
  410. }
  411. /** Return VS_RECOMMENDED if <b>myversion</b> is contained in
  412. * <b>versionlist</b>. Else, return VS_OLD if every member of
  413. * <b>versionlist</b> is newer than <b>myversion</b>. Else, return
  414. * VS_NEW_IN_SERIES if there is at least one member of <b>versionlist</b> in
  415. * the same series (major.minor.micro) as <b>myversion</b>, but no such member
  416. * is newer than <b>myversion.</b>. Else, return VS_NEW if every memeber of
  417. * <b>versionlist</b> is older than <b>myversion</b>. Else, return
  418. * VS_UNRECOMMENDED.
  419. *
  420. * (versionlist is a comma-separated list of version strings,
  421. * optionally prefixed with "Tor". Versions that can't be parsed are
  422. * ignored.)
  423. */
  424. version_status_t
  425. tor_version_is_obsolete(const char *myversion, const char *versionlist)
  426. {
  427. tor_version_t mine, other;
  428. int found_newer = 0, found_older = 0, found_newer_in_series = 0,
  429. found_any_in_series = 0, r, same;
  430. version_status_t ret = VS_UNRECOMMENDED;
  431. smartlist_t *version_sl;
  432. log_debug(LD_CONFIG,"Checking whether version '%s' is in '%s'",
  433. myversion, versionlist);
  434. if (tor_version_parse(myversion, &mine)) {
  435. log_err(LD_BUG,"I couldn't parse my own version (%s)", myversion);
  436. tor_assert(0);
  437. }
  438. version_sl = smartlist_create();
  439. smartlist_split_string(version_sl, versionlist, ",", SPLIT_SKIP_SPACE, 0);
  440. SMARTLIST_FOREACH(version_sl, const char *, cp, {
  441. if (!strcmpstart(cp, "Tor "))
  442. cp += 4;
  443. if (tor_version_parse(cp, &other)) {
  444. /* Couldn't parse other; it can't be a match. */
  445. } else {
  446. same = tor_version_same_series(&mine, &other);
  447. if (same)
  448. found_any_in_series = 1;
  449. r = tor_version_compare(&mine, &other);
  450. if (r==0) {
  451. ret = VS_RECOMMENDED;
  452. goto done;
  453. } else if (r<0) {
  454. found_newer = 1;
  455. if (same)
  456. found_newer_in_series = 1;
  457. } else if (r>0) {
  458. found_older = 1;
  459. }
  460. }
  461. });
  462. /* We didn't find the listed version. Is it new or old? */
  463. if (found_any_in_series && !found_newer_in_series && found_newer) {
  464. ret = VS_NEW_IN_SERIES;
  465. } else if (found_newer && !found_older) {
  466. ret = VS_OLD;
  467. } else if (found_older && !found_newer) {
  468. ret = VS_NEW;
  469. } else {
  470. ret = VS_UNRECOMMENDED;
  471. }
  472. done:
  473. SMARTLIST_FOREACH(version_sl, char *, version, tor_free(version));
  474. smartlist_free(version_sl);
  475. return ret;
  476. }
  477. /** Return the combined status of the current version, given that we know of
  478. * one set of networkstatuses that give us status <b>a</b>, and another that
  479. * gives us status <b>b</b>.
  480. *
  481. * For example, if one authority thinks that we're NEW, and another thinks
  482. * we're OLD, we're simply UNRECOMMENDED.
  483. *
  484. * This function does not handle calculating whether we're RECOMMENDED; that
  485. * follows a simple majority rule. This function simply calculates *why*
  486. * we're not recommended (if we're not).
  487. */
  488. version_status_t
  489. version_status_join(version_status_t a, version_status_t b)
  490. {
  491. if (a == b)
  492. return a;
  493. else if (a == VS_UNRECOMMENDED || b == VS_UNRECOMMENDED)
  494. return VS_UNRECOMMENDED;
  495. else if (a == VS_RECOMMENDED)
  496. return b;
  497. else if (b == VS_RECOMMENDED)
  498. return a;
  499. /* Okay. Neither is 'recommended' or 'unrecommended', and they differ. */
  500. else if (a == VS_OLD || b == VS_OLD)
  501. return VS_UNRECOMMENDED;
  502. /* One is VS_NEW, the other is VS_NEW_IN_SERIES */
  503. else
  504. return VS_NEW_IN_SERIES;
  505. }
  506. /** Read a signed directory from <b>str</b>. If it's well-formed, return 0.
  507. * Otherwise, return -1. If we're a directory cache, cache it.
  508. */
  509. int
  510. router_parse_directory(const char *str)
  511. {
  512. directory_token_t *tok;
  513. char digest[DIGEST_LEN];
  514. time_t published_on;
  515. int r;
  516. const char *end, *cp;
  517. smartlist_t *tokens = NULL;
  518. crypto_pk_env_t *declared_key = NULL;
  519. /* XXXX This could be simplified a lot, but it will all go away
  520. * once pre-0.1.1.8 is obsolete, and for now it's better not to
  521. * touch it. */
  522. if (router_get_dir_hash(str, digest)) {
  523. log_warn(LD_DIR, "Unable to compute digest of directory");
  524. goto err;
  525. }
  526. log_debug(LD_DIR,"Received directory hashes to %s",hex_str(digest,4));
  527. /* Check signature first, before we try to tokenize. */
  528. cp = str;
  529. while (cp && (end = strstr(cp+1, "\ndirectory-signature")))
  530. cp = end;
  531. if (cp == str || !cp) {
  532. log_warn(LD_DIR, "No signature found on directory."); goto err;
  533. }
  534. ++cp;
  535. tokens = smartlist_create();
  536. if (tokenize_string(cp,strchr(cp,'\0'),tokens,dir_token_table)) {
  537. log_warn(LD_DIR, "Error tokenizing directory signature"); goto err;
  538. }
  539. if (smartlist_len(tokens) != 1) {
  540. log_warn(LD_DIR, "Unexpected number of tokens in signature"); goto err;
  541. }
  542. tok=smartlist_get(tokens,0);
  543. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  544. log_warn(LD_DIR,"Expected a single directory signature"); goto err;
  545. }
  546. declared_key = find_dir_signing_key(str);
  547. note_crypto_pk_op(VERIFY_DIR);
  548. if (check_signature_token(digest, tok, declared_key, 1, "directory")<0)
  549. goto err;
  550. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  551. smartlist_free(tokens);
  552. tokens = NULL;
  553. /* Now try to parse the first part of the directory. */
  554. if ((end = strstr(str,"\nrouter "))) {
  555. ++end;
  556. } else if ((end = strstr(str, "\ndirectory-signature"))) {
  557. ++end;
  558. } else {
  559. end = str + strlen(str);
  560. }
  561. tokens = smartlist_create();
  562. if (tokenize_string(str,end,tokens,dir_token_table)) {
  563. log_warn(LD_DIR, "Error tokenizing directory"); goto err;
  564. }
  565. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  566. tor_assert(tok);
  567. tor_assert(tok->n_args == 1);
  568. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  569. goto err;
  570. }
  571. /* Now that we know the signature is okay, and we have a
  572. * publication time, cache the directory. */
  573. if (get_options()->DirPort && !authdir_mode_v1(get_options()))
  574. dirserv_set_cached_directory(str, published_on, 0);
  575. r = 0;
  576. goto done;
  577. err:
  578. r = -1;
  579. done:
  580. if (declared_key) crypto_free_pk_env(declared_key);
  581. if (tokens) {
  582. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  583. smartlist_free(tokens);
  584. }
  585. return r;
  586. }
  587. /** Read a signed router status statement from <b>str</b>. If it's
  588. * well-formed, return 0. Otherwise, return -1. If we're a directory cache,
  589. * cache it.*/
  590. int
  591. router_parse_runningrouters(const char *str)
  592. {
  593. char digest[DIGEST_LEN];
  594. directory_token_t *tok;
  595. time_t published_on;
  596. int r = -1;
  597. crypto_pk_env_t *declared_key = NULL;
  598. smartlist_t *tokens = NULL;
  599. if (router_get_runningrouters_hash(str, digest)) {
  600. log_warn(LD_DIR, "Unable to compute digest of running-routers");
  601. goto err;
  602. }
  603. tokens = smartlist_create();
  604. if (tokenize_string(str,str+strlen(str),tokens,dir_token_table)) {
  605. log_warn(LD_DIR, "Error tokenizing running-routers"); goto err;
  606. }
  607. tok = smartlist_get(tokens,0);
  608. if (tok->tp != K_NETWORK_STATUS) {
  609. log_warn(LD_DIR, "Network-status starts with wrong token");
  610. goto err;
  611. }
  612. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  613. tor_assert(tok);
  614. tor_assert(tok->n_args == 1);
  615. if (parse_iso_time(tok->args[0], &published_on) < 0) {
  616. goto err;
  617. }
  618. if (!(tok = find_first_by_keyword(tokens, K_DIRECTORY_SIGNATURE))) {
  619. log_warn(LD_DIR, "Missing signature on running-routers");
  620. goto err;
  621. }
  622. declared_key = find_dir_signing_key(str);
  623. note_crypto_pk_op(VERIFY_DIR);
  624. if (check_signature_token(digest, tok, declared_key, 1, "running-routers")
  625. < 0)
  626. goto err;
  627. /* Now that we know the signature is okay, and we have a
  628. * publication time, cache the list. */
  629. if (get_options()->DirPort && !authdir_mode_v1(get_options()))
  630. dirserv_set_cached_directory(str, published_on, 1);
  631. r = 0;
  632. err:
  633. if (declared_key) crypto_free_pk_env(declared_key);
  634. if (tokens) {
  635. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  636. smartlist_free(tokens);
  637. }
  638. return r;
  639. }
  640. /** Given a directory or running-routers string in <b>str</b>, try to
  641. * find the its dir-signing-key token (if any). If this token is
  642. * present, extract and return the key. Return NULL on failure. */
  643. static crypto_pk_env_t *
  644. find_dir_signing_key(const char *str)
  645. {
  646. const char *cp;
  647. directory_token_t *tok;
  648. crypto_pk_env_t *key = NULL;
  649. /* Is there a dir-signing-key in the directory? */
  650. cp = strstr(str, "\nopt dir-signing-key");
  651. if (!cp)
  652. cp = strstr(str, "\ndir-signing-key");
  653. if (!cp)
  654. return NULL;
  655. ++cp; /* Now cp points to the start of the token. */
  656. tok = get_next_token(&cp, dir_token_table);
  657. if (!tok) {
  658. log_warn(LD_DIR, "Unparseable dir-signing-key token");
  659. return NULL;
  660. }
  661. if (tok->tp != K_DIR_SIGNING_KEY) {
  662. log_warn(LD_DIR, "Dir-signing-key token did not parse as expected");
  663. return NULL;
  664. }
  665. if (tok->key) {
  666. key = tok->key;
  667. tok->key = NULL; /* steal reference. */
  668. } else {
  669. log_warn(LD_DIR, "Dir-signing-key token contained no key");
  670. return NULL;
  671. }
  672. token_free(tok);
  673. return key;
  674. }
  675. /** Return true iff <b>key</b> is allowed to sign directories.
  676. */
  677. static int
  678. dir_signing_key_is_trusted(crypto_pk_env_t *key)
  679. {
  680. char digest[DIGEST_LEN];
  681. if (!key) return 0;
  682. if (crypto_pk_get_digest(key, digest) < 0) {
  683. log_warn(LD_DIR, "Error computing dir-signing-key digest");
  684. return 0;
  685. }
  686. if (!router_digest_is_trusted_dir(digest)) {
  687. log_warn(LD_DIR, "Listed dir-signing-key is not trusted");
  688. return 0;
  689. }
  690. return 1;
  691. }
  692. /** Check whether the object body of the token in <b>tok</b> has a good
  693. * signature for <b>digest</b> using key <b>pkey</b>. If
  694. * <b>check_authority</b> is set, make sure that <b>pkey</b> is the key of a
  695. * directory authority. Use <b>doctype</b> as the type of the document when
  696. * generating log messages. Return 0 on success, negative on failure.
  697. */
  698. static int
  699. check_signature_token(const char *digest,
  700. directory_token_t *tok,
  701. crypto_pk_env_t *pkey,
  702. int check_authority,
  703. const char *doctype)
  704. {
  705. char *signed_digest;
  706. tor_assert(pkey);
  707. tor_assert(tok);
  708. tor_assert(digest);
  709. tor_assert(doctype);
  710. if (check_authority && !dir_signing_key_is_trusted(pkey)) {
  711. log_warn(LD_DIR, "Key on %s did not come from an authority; rejecting",
  712. doctype);
  713. return -1;
  714. }
  715. if (strcmp(tok->object_type, "SIGNATURE")) {
  716. log_warn(LD_DIR, "Bad object type on %s signature", doctype);
  717. return -1;
  718. }
  719. signed_digest = tor_malloc(tok->object_size);
  720. if (crypto_pk_public_checksig(pkey, signed_digest, tok->object_body,
  721. tok->object_size)
  722. != DIGEST_LEN) {
  723. log_warn(LD_DIR, "Error reading %s: invalid signature.", doctype);
  724. tor_free(signed_digest);
  725. return -1;
  726. }
  727. log_debug(LD_DIR,"Signed %s hash starts %s", doctype,
  728. hex_str(signed_digest,4));
  729. if (memcmp(digest, signed_digest, DIGEST_LEN)) {
  730. log_warn(LD_DIR, "Error reading %s: signature does not match.", doctype);
  731. tor_free(signed_digest);
  732. return -1;
  733. }
  734. tor_free(signed_digest);
  735. return 0;
  736. }
  737. /** Given a string *<b>s</b> containing a concatenated sequence of router
  738. * descriptors (or extra-info documents if <b>is_extrainfo</b> is set), parses
  739. * them and stores the result in <b>dest</b>. All routers are marked running
  740. * and valid. Advances *s to a point immediately following the last router
  741. * entry. Ignore any trailing router entries that are not complete.
  742. *
  743. * If <b>saved_location</b> isn't SAVED_IN_CACHE, make a local copy of each
  744. * descriptor in the signed_descriptor_body field of each routerinfo_t. If it
  745. * isn't SAVED_NOWHERE, remember the offset of each descriptor.
  746. *
  747. * Returns 0 on success and -1 on failure.
  748. */
  749. int
  750. router_parse_list_from_string(const char **s, const char *eos,
  751. smartlist_t *dest,
  752. saved_location_t saved_location,
  753. int want_extrainfo)
  754. {
  755. routerinfo_t *router;
  756. extrainfo_t *extrainfo;
  757. signed_descriptor_t *signed_desc;
  758. void *elt;
  759. const char *end, *start;
  760. int have_extrainfo;
  761. tor_assert(s);
  762. tor_assert(*s);
  763. tor_assert(dest);
  764. start = *s;
  765. if (!eos)
  766. eos = *s + strlen(*s);
  767. tor_assert(eos >= *s);
  768. while (1) {
  769. *s = eat_whitespace_eos(*s, eos);
  770. if ((eos - *s) < 32) /* make sure it's long enough. */
  771. break;
  772. /* Don't start parsing the rest of *s unless it contains a router. */
  773. if (strcmpstart(*s, "extra-info ")==0) {
  774. have_extrainfo = 1;
  775. } else if (strcmpstart(*s, "router ")==0) {
  776. have_extrainfo = 0;
  777. } else {
  778. /* skip junk. */
  779. const char *ei = tor_memstr(*s, eos-*s, "\nextra-info ");
  780. const char *ri = tor_memstr(*s, eos-*s, "\nrouter ");
  781. if (ri && (!ei || ri < ei)) {
  782. have_extrainfo = 0;
  783. *s = ri + 1;
  784. } else if (ei) {
  785. have_extrainfo = 1;
  786. *s = ei + 1;
  787. } else {
  788. break;
  789. }
  790. }
  791. end = tor_memstr(*s, eos-*s, "\nrouter-signature");
  792. if (end)
  793. end = tor_memstr(end, eos-*s, "\n-----END SIGNATURE-----\n");
  794. if (end)
  795. end += strlen("\n-----END SIGNATURE-----\n");
  796. if (!end)
  797. break;
  798. elt = NULL;
  799. if (have_extrainfo && want_extrainfo) {
  800. routerlist_t *rl = router_get_routerlist();
  801. extrainfo = extrainfo_parse_entry_from_string(*s, end,
  802. saved_location != SAVED_IN_CACHE,
  803. rl->identity_map);
  804. if (extrainfo) {
  805. signed_desc = &extrainfo->cache_info;
  806. elt = extrainfo;
  807. }
  808. } else if (!have_extrainfo && !want_extrainfo) {
  809. router = router_parse_entry_from_string(*s, end,
  810. saved_location != SAVED_IN_CACHE);
  811. if (router) {
  812. signed_desc = &router->cache_info;
  813. elt = router;
  814. }
  815. }
  816. if (!elt) {
  817. *s = end;
  818. continue;
  819. }
  820. if (saved_location != SAVED_NOWHERE) {
  821. signed_desc->saved_location = saved_location;
  822. signed_desc->saved_offset = *s - start;
  823. }
  824. *s = end;
  825. smartlist_add(dest, elt);
  826. }
  827. return 0;
  828. }
  829. /* For debugging: define to count every descriptor digest we've seen so we
  830. * know if we need to try harder to avoid duplicate verifies. */
  831. #undef COUNT_DISTINCT_DIGESTS
  832. #ifdef COUNT_DISTINCT_DIGESTS
  833. static digestmap_t *verified_digests = NULL;
  834. #endif
  835. /** Log the total count of the number of distinct router digests we've ever
  836. * verified. When compared to the number of times we've verified routerdesc
  837. * signatures <i>in toto</i>, this will tell us if we're doing too much
  838. * multiple-verification. */
  839. void
  840. dump_distinct_digest_count(int severity)
  841. {
  842. #ifdef COUNT_DISTINCT_DIGESTS
  843. if (!verified_digests)
  844. verified_digests = digestmap_new();
  845. log(severity, LD_GENERAL, "%d *distinct* router digests verified",
  846. digestmap_size(verified_digests));
  847. #else
  848. (void)severity; /* suppress "unused parameter" warning */
  849. #endif
  850. }
  851. /** Helper function: reads a single router entry from *<b>s</b> ...
  852. * *<b>end</b>. Mallocs a new router and returns it if all goes well, else
  853. * returns NULL. If <b>cache_copy</b> is true, duplicate the contents of
  854. * s through end into the signed_descriptor_body of the resulting
  855. * routerinfo_t.
  856. */
  857. routerinfo_t *
  858. router_parse_entry_from_string(const char *s, const char *end,
  859. int cache_copy)
  860. {
  861. routerinfo_t *router = NULL;
  862. char digest[128];
  863. smartlist_t *tokens = NULL, *exit_policy_tokens = NULL;
  864. directory_token_t *tok;
  865. struct in_addr in;
  866. if (!end) {
  867. end = s + strlen(s);
  868. }
  869. /* point 'end' to a point immediately after the final newline. */
  870. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  871. --end;
  872. if (router_get_router_hash(s, digest) < 0) {
  873. log_warn(LD_DIR, "Couldn't compute router hash.");
  874. return NULL;
  875. }
  876. tokens = smartlist_create();
  877. if (tokenize_string(s,end,tokens,routerdesc_token_table)) {
  878. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  879. goto err;
  880. }
  881. if (smartlist_len(tokens) < 2) {
  882. log_warn(LD_DIR, "Impossibly short router descriptor.");
  883. goto err;
  884. }
  885. tok = smartlist_get(tokens,0);
  886. if (tok->tp != K_ROUTER) {
  887. log_warn(LD_DIR,"Entry does not start with \"router\"");
  888. goto err;
  889. }
  890. tor_assert(tok->n_args >= 5);
  891. router = tor_malloc_zero(sizeof(routerinfo_t));
  892. router->routerlist_index = -1;
  893. if (cache_copy)
  894. router->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  895. router->cache_info.signed_descriptor_len = end-s;
  896. memcpy(router->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  897. router->nickname = tor_strdup(tok->args[0]);
  898. if (!is_legal_nickname(router->nickname)) {
  899. log_warn(LD_DIR,"Router nickname is invalid");
  900. goto err;
  901. }
  902. router->address = tor_strdup(tok->args[1]);
  903. if (!tor_inet_aton(router->address, &in)) {
  904. log_warn(LD_DIR,"Router address is not an IP.");
  905. goto err;
  906. }
  907. router->addr = ntohl(in.s_addr);
  908. router->or_port =
  909. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  910. router->dir_port =
  911. (uint16_t) tor_parse_long(tok->args[4],10,0,65535,NULL,NULL);
  912. tok = find_first_by_keyword(tokens, K_BANDWIDTH);
  913. tor_assert(tok && tok->n_args >= 3);
  914. router->bandwidthrate =
  915. tor_parse_long(tok->args[0],10,0,INT_MAX,NULL,NULL);
  916. if (!router->bandwidthrate) {
  917. log_warn(LD_DIR, "bandwidthrate %s unreadable or 0. Failing.",
  918. escaped(tok->args[0]));
  919. goto err;
  920. }
  921. router->bandwidthburst =
  922. tor_parse_long(tok->args[1],10,0,INT_MAX,NULL,NULL);
  923. router->bandwidthcapacity =
  924. tor_parse_long(tok->args[2],10,0,INT_MAX,NULL,NULL);
  925. /* XXXX020 we don't error-check these values? -RD */
  926. if ((tok = find_first_by_keyword(tokens, K_UPTIME))) {
  927. tor_assert(tok->n_args >= 1);
  928. router->uptime = tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL);
  929. }
  930. if ((tok = find_first_by_keyword(tokens, K_HIBERNATING))) {
  931. tor_assert(tok->n_args >= 1);
  932. router->is_hibernating
  933. = (tor_parse_long(tok->args[0],10,0,LONG_MAX,NULL,NULL) != 0);
  934. }
  935. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  936. tor_assert(tok);
  937. tor_assert(tok->n_args == 1);
  938. if (parse_iso_time(tok->args[0], &router->cache_info.published_on) < 0)
  939. goto err;
  940. tok = find_first_by_keyword(tokens, K_ONION_KEY);
  941. tor_assert(tok);
  942. router->onion_pkey = tok->key;
  943. tok->key = NULL; /* Prevent free */
  944. tok = find_first_by_keyword(tokens, K_SIGNING_KEY);
  945. tor_assert(tok);
  946. router->identity_pkey = tok->key;
  947. tok->key = NULL; /* Prevent free */
  948. if (crypto_pk_get_digest(router->identity_pkey,
  949. router->cache_info.identity_digest)) {
  950. log_warn(LD_DIR, "Couldn't calculate key digest"); goto err;
  951. }
  952. if ((tok = find_first_by_keyword(tokens, K_FINGERPRINT))) {
  953. /* If there's a fingerprint line, it must match the identity digest. */
  954. char d[DIGEST_LEN];
  955. tor_assert(tok->n_args == 1);
  956. tor_strstrip(tok->args[0], " ");
  957. if (base16_decode(d, DIGEST_LEN, tok->args[0], strlen(tok->args[0]))) {
  958. log_warn(LD_DIR, "Couldn't decode router fingerprint %s",
  959. escaped(tok->args[0]));
  960. goto err;
  961. }
  962. if (memcmp(d,router->cache_info.identity_digest, DIGEST_LEN)!=0) {
  963. log_warn(LD_DIR, "Fingerprint '%s' does not match identity digest.",
  964. tok->args[0]);
  965. goto err;
  966. }
  967. }
  968. if ((tok = find_first_by_keyword(tokens, K_PLATFORM))) {
  969. router->platform = tor_strdup(tok->args[0]);
  970. }
  971. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  972. router->contact_info = tor_strdup(tok->args[0]);
  973. }
  974. if ((tok = find_first_by_keyword(tokens, K_EVENTDNS))) {
  975. router->has_old_dnsworkers = tok->n_args && !strcmp(tok->args[0], "0");
  976. } else if (router->platform) {
  977. if (! tor_version_as_new_as(router->platform, "0.1.2.2-alpha"))
  978. router->has_old_dnsworkers = 1;
  979. }
  980. exit_policy_tokens = find_all_exitpolicy(tokens);
  981. SMARTLIST_FOREACH(exit_policy_tokens, directory_token_t *, t,
  982. if (router_add_exit_policy(router,t)<0) {
  983. log_warn(LD_DIR,"Error in exit policy");
  984. goto err;
  985. });
  986. if ((tok = find_first_by_keyword(tokens, K_FAMILY)) && tok->n_args) {
  987. int i;
  988. router->declared_family = smartlist_create();
  989. for (i=0;i<tok->n_args;++i) {
  990. if (!is_legal_nickname_or_hexdigest(tok->args[i])) {
  991. log_warn(LD_DIR, "Illegal nickname %s in family line",
  992. escaped(tok->args[i]));
  993. goto err;
  994. }
  995. smartlist_add(router->declared_family, tor_strdup(tok->args[i]));
  996. }
  997. }
  998. if ((tok = find_first_by_keyword(tokens, K_CACHES_EXTRA_INFO)))
  999. router->caches_extra_info = 1;
  1000. if ((tok = find_first_by_keyword(tokens, K_EXTRA_INFO_DIGEST))) {
  1001. tor_assert(tok->n_args >= 1);
  1002. if (strlen(tok->args[0]) == HEX_DIGEST_LEN) {
  1003. base16_decode(router->cache_info.extra_info_digest,
  1004. DIGEST_LEN, tok->args[0], HEX_DIGEST_LEN);
  1005. } else {
  1006. log_warn(LD_DIR, "Invalid extra info digest %s", escaped(tok->args[0]));
  1007. }
  1008. }
  1009. tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1010. tor_assert(tok);
  1011. note_crypto_pk_op(VERIFY_RTR);
  1012. #ifdef COUNT_DISTINCT_DIGESTS
  1013. if (!verified_digests)
  1014. verified_digests = digestmap_new();
  1015. digestmap_set(verified_digests, signed_digest, (void*)(uintptr_t)1);
  1016. #endif
  1017. if (check_signature_token(digest, tok, router->identity_pkey, 0,
  1018. "router descriptor") < 0)
  1019. goto err;
  1020. if (!router->or_port) {
  1021. log_warn(LD_DIR,"or_port unreadable or 0. Failing.");
  1022. goto err;
  1023. }
  1024. if (!router->platform) {
  1025. router->platform = tor_strdup("<unknown>");
  1026. }
  1027. goto done;
  1028. err:
  1029. routerinfo_free(router);
  1030. router = NULL;
  1031. done:
  1032. if (tokens) {
  1033. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1034. smartlist_free(tokens);
  1035. }
  1036. if (exit_policy_tokens) {
  1037. smartlist_free(exit_policy_tokens);
  1038. }
  1039. return router;
  1040. }
  1041. /** Parse a single extrainfo entry from the string <b>s</b>, ending at
  1042. * <b>end</b>. (If <b>end</b> is NULL, parse up to the end of <b>s</b>.) If
  1043. * <b>cache_copy</b> is true, make a copy of the extra-info document in the
  1044. * cache_info fields of the result. If <b>routermap</b> is provided, use it
  1045. * as a map from router identity to routerinfo_t when looking up signing keys.
  1046. */
  1047. extrainfo_t *
  1048. extrainfo_parse_entry_from_string(const char *s, const char *end,
  1049. int cache_copy, digestmap_t *routermap)
  1050. {
  1051. extrainfo_t *extrainfo = NULL;
  1052. char digest[128];
  1053. smartlist_t *tokens = NULL;
  1054. directory_token_t *tok;
  1055. crypto_pk_env_t *key = NULL;
  1056. routerinfo_t *router;
  1057. if (!end) {
  1058. end = s + strlen(s);
  1059. }
  1060. /* point 'end' to a point immediately after the final newline. */
  1061. while (end > s+2 && *(end-1) == '\n' && *(end-2) == '\n')
  1062. --end;
  1063. if (router_get_extrainfo_hash(s, digest) < 0) {
  1064. log_warn(LD_DIR, "Couldn't compute router hash.");
  1065. return NULL;
  1066. }
  1067. tokens = smartlist_create();
  1068. if (tokenize_string(s,end,tokens,extrainfo_token_table)) {
  1069. log_warn(LD_DIR, "Error tokenizing router descriptor.");
  1070. goto err;
  1071. }
  1072. if (smartlist_len(tokens) < 2) {
  1073. log_warn(LD_DIR, "Impossibly short router descriptor.");
  1074. goto err;
  1075. }
  1076. tok = smartlist_get(tokens,0);
  1077. if (tok->tp != K_EXTRA_INFO) {
  1078. log_warn(LD_DIR,"Entry does not start with \"extra-info\"");
  1079. goto err;
  1080. }
  1081. extrainfo = tor_malloc_zero(sizeof(extrainfo_t));
  1082. extrainfo->cache_info.is_extrainfo = 1;
  1083. if (cache_copy)
  1084. extrainfo->cache_info.signed_descriptor_body = tor_strndup(s, end-s);
  1085. extrainfo->cache_info.signed_descriptor_len = end-s;
  1086. memcpy(extrainfo->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1087. tor_assert(tok->n_args >= 2);
  1088. if (!is_legal_nickname(tok->args[0])) {
  1089. log_warn(LD_DIR,"Bad nickname %s on \"extra-info\"",escaped(tok->args[0]));
  1090. goto err;
  1091. }
  1092. strlcpy(extrainfo->nickname, tok->args[0], sizeof(extrainfo->nickname));
  1093. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1094. base16_decode(extrainfo->cache_info.identity_digest, DIGEST_LEN,
  1095. tok->args[1], HEX_DIGEST_LEN)) {
  1096. log_warn(LD_DIR,"Invalid fingerprint %s on \"extra-info\"",
  1097. escaped(tok->args[1]));
  1098. goto err;
  1099. }
  1100. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1101. tor_assert(tok);
  1102. if (parse_iso_time(tok->args[0], &extrainfo->cache_info.published_on)) {
  1103. log_warn(LD_DIR,"Invalid published time %s on \"extra-info\"",
  1104. escaped(tok->args[0]));
  1105. goto err;
  1106. }
  1107. if (routermap &&
  1108. (router = digestmap_get(routermap,
  1109. extrainfo->cache_info.identity_digest))) {
  1110. key = router->identity_pkey;
  1111. }
  1112. tok = find_first_by_keyword(tokens, K_ROUTER_SIGNATURE);
  1113. tor_assert(tok);
  1114. if (strcmp(tok->object_type, "SIGNATURE") ||
  1115. tok->object_size < 128 || tok->object_size > 512) {
  1116. log_warn(LD_DIR, "Bad object type or length on extra-info signature");
  1117. goto err;
  1118. }
  1119. if (key) {
  1120. note_crypto_pk_op(VERIFY_RTR);
  1121. if (check_signature_token(digest, tok, key, 0, "extra-info") < 0)
  1122. goto err;
  1123. } else {
  1124. extrainfo->pending_sig = tor_memdup(tok->object_body,
  1125. tok->object_size);
  1126. extrainfo->pending_sig_len = tok->object_size;
  1127. }
  1128. goto done;
  1129. err:
  1130. if (extrainfo)
  1131. extrainfo_free(extrainfo);
  1132. extrainfo = NULL;
  1133. done:
  1134. if (tokens) {
  1135. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1136. smartlist_free(tokens);
  1137. }
  1138. return extrainfo;
  1139. }
  1140. /** Free storage held in <b>cert</b>. */
  1141. void
  1142. authority_cert_free(authority_cert_t *cert)
  1143. {
  1144. if (!cert)
  1145. return;
  1146. tor_free(cert->cache_info.signed_descriptor_body);
  1147. if (cert->signing_key)
  1148. crypto_free_pk_env(cert->signing_key);
  1149. if (cert->identity_key)
  1150. crypto_free_pk_env(cert->identity_key);
  1151. tor_free(cert);
  1152. }
  1153. /** Parse a key certificate from <b>s</b>; point <b>end-of-string</b> to
  1154. * the first character after the certificate. */
  1155. authority_cert_t *
  1156. authority_cert_parse_from_string(const char *s, const char **end_of_string)
  1157. {
  1158. authority_cert_t *cert = NULL;
  1159. smartlist_t *tokens = NULL;
  1160. char digest[DIGEST_LEN];
  1161. directory_token_t *tok;
  1162. char fp_declared[DIGEST_LEN];
  1163. char *eos;
  1164. size_t len;
  1165. trusted_dir_server_t *ds;
  1166. s = eat_whitespace(s);
  1167. eos = strstr(s, "\n-----END SIGNATURE-----\n");
  1168. if (! eos) {
  1169. log_warn(LD_DIR, "No end-of-signature found on key certificate");
  1170. return NULL;
  1171. }
  1172. eos = strchr(eos+2, '\n');
  1173. tor_assert(eos);
  1174. ++eos;
  1175. len = eos - s;
  1176. tokens = smartlist_create();
  1177. if (tokenize_string(s, eos, tokens, dir_key_certificate_table) < 0) {
  1178. log_warn(LD_DIR, "Error tokenizing key certificate");
  1179. goto err;
  1180. }
  1181. if (router_get_hash_impl(s, digest, "dir-key-certificate-version",
  1182. "\ndir-key-certification", '\n') < 0)
  1183. goto err;
  1184. tok = smartlist_get(tokens, 0);
  1185. if (tok->tp != K_DIR_KEY_CERTIFICATE_VERSION || strcmp(tok->args[0], "3")) {
  1186. log_warn(LD_DIR,
  1187. "Key certificate does not begin with a recognized version (3).");
  1188. goto err;
  1189. }
  1190. cert = tor_malloc_zero(sizeof(authority_cert_t));
  1191. memcpy(cert->cache_info.signed_descriptor_digest, digest, DIGEST_LEN);
  1192. tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1193. tor_assert(tok && tok->key);
  1194. cert->signing_key = tok->key;
  1195. tok->key = NULL;
  1196. tok = find_first_by_keyword(tokens, K_DIR_IDENTITY_KEY);
  1197. tor_assert(tok && tok->key);
  1198. cert->identity_key = tok->key;
  1199. tok->key = NULL;
  1200. tok = find_first_by_keyword(tokens, K_FINGERPRINT);
  1201. tor_assert(tok && tok->n_args);
  1202. if (base16_decode(fp_declared, DIGEST_LEN, tok->args[0],
  1203. strlen(tok->args[0]))) {
  1204. log_warn(LD_DIR, "Couldn't decode key certificate fingerprint %s",
  1205. escaped(tok->args[0]));
  1206. goto err;
  1207. }
  1208. if (crypto_pk_get_digest(cert->identity_key,
  1209. cert->cache_info.identity_digest))
  1210. goto err;
  1211. if (memcmp(cert->cache_info.identity_digest, fp_declared, DIGEST_LEN)) {
  1212. log_warn(LD_DIR, "Digest of certificate key didn't match declared "
  1213. "fingerprint");
  1214. goto err;
  1215. }
  1216. tok = find_first_by_keyword(tokens, K_DIR_KEY_PUBLISHED);
  1217. tor_assert(tok);
  1218. if (parse_iso_time(tok->args[0], &cert->cache_info.published_on) < 0) {
  1219. goto err;
  1220. }
  1221. tok = find_first_by_keyword(tokens, K_DIR_KEY_EXPIRES);
  1222. tor_assert(tok);
  1223. if (parse_iso_time(tok->args[0], &cert->expires) < 0) {
  1224. goto err;
  1225. }
  1226. tok = smartlist_get(tokens, smartlist_len(tokens)-1);
  1227. if (tok->tp != K_DIR_KEY_CERTIFICATION) {
  1228. log_warn(LD_DIR, "Certificate didn't end with dir-key-certification.");
  1229. goto err;
  1230. }
  1231. /* If we already have this cert, don't bother checking the signature. */
  1232. ds = trusteddirserver_get_by_v3_auth_digest(
  1233. cert->cache_info.identity_digest);
  1234. if (ds && ds->v3_cert &&
  1235. ds->v3_cert->cache_info.signed_descriptor_len == len &&
  1236. ds->v3_cert->cache_info.signed_descriptor_body &&
  1237. ! memcmp(s, ds->v3_cert->cache_info.signed_descriptor_body, len)) {
  1238. log_debug(LD_DIR, "We already checked the signature on this certificate;"
  1239. " no need to do so again.");
  1240. } else {
  1241. if (check_signature_token(digest, tok, cert->identity_key, 0,
  1242. "key certificate")) {
  1243. goto err;
  1244. }
  1245. }
  1246. cert->cache_info.signed_descriptor_len = len;
  1247. cert->cache_info.signed_descriptor_body = tor_malloc(len+1);
  1248. memcpy(cert->cache_info.signed_descriptor_body, s, len);
  1249. cert->cache_info.signed_descriptor_body[len] = 0;
  1250. cert->cache_info.saved_location = SAVED_NOWHERE;
  1251. if (end_of_string) {
  1252. *end_of_string = eat_whitespace(eos);
  1253. }
  1254. return cert;
  1255. err:
  1256. authority_cert_free(cert);
  1257. return NULL;
  1258. }
  1259. /** Helper: given a string <b>s</b>, return the start of the next router-status
  1260. * object (starting with "r " at the start of a line). If none is found,
  1261. * return the start of the next directory signature. If none is found, return
  1262. * the end of the string. */
  1263. static INLINE const char *
  1264. find_start_of_next_routerstatus(const char *s)
  1265. {
  1266. const char *eos = strstr(s, "\nr ");
  1267. if (!eos)
  1268. eos = strstr(s, "\ndirectory-signature");
  1269. if (eos)
  1270. return eos+1;
  1271. else
  1272. return s + strlen(s);
  1273. }
  1274. /** Given a string at *<b>s</b>, containing a routerstatus object, and an
  1275. * empty smartlist at <b>tokens</b>, parse and return the first router status
  1276. * object in the string, and advance *<b>s</b> to just after the end of the
  1277. * router status. Return NULL and advance *<b>s</b> on error. */
  1278. static routerstatus_t *
  1279. routerstatus_parse_entry_from_string(const char **s, smartlist_t *tokens,
  1280. networkstatus_vote_t *vote,
  1281. vote_routerstatus_t *vote_rs)
  1282. {
  1283. const char *eos;
  1284. routerstatus_t *rs = NULL;
  1285. directory_token_t *tok;
  1286. char timebuf[ISO_TIME_LEN+1];
  1287. struct in_addr in;
  1288. tor_assert(tokens);
  1289. tor_assert(bool_eq(vote, vote_rs));
  1290. eos = find_start_of_next_routerstatus(*s);
  1291. if (tokenize_string(*s, eos, tokens, rtrstatus_token_table)) {
  1292. log_warn(LD_DIR, "Error tokenizing router status");
  1293. goto err;
  1294. }
  1295. if (smartlist_len(tokens) < 1) {
  1296. log_warn(LD_DIR, "Impossibly short router status");
  1297. goto err;
  1298. }
  1299. tok = find_first_by_keyword(tokens, K_R);
  1300. tor_assert(tok);
  1301. tor_assert(tok->n_args >= 8);
  1302. if (vote_rs) {
  1303. rs = &vote_rs->status;
  1304. } else {
  1305. rs = tor_malloc_zero(sizeof(routerstatus_t));
  1306. }
  1307. if (!is_legal_nickname(tok->args[0])) {
  1308. log_warn(LD_DIR,
  1309. "Invalid nickname %s in router status; skipping.",
  1310. escaped(tok->args[0]));
  1311. goto err;
  1312. }
  1313. strlcpy(rs->nickname, tok->args[0], sizeof(rs->nickname));
  1314. if (digest_from_base64(rs->identity_digest, tok->args[1])) {
  1315. log_warn(LD_DIR, "Error decoding identity digest %s",
  1316. escaped(tok->args[1]));
  1317. goto err;
  1318. }
  1319. if (digest_from_base64(rs->descriptor_digest, tok->args[2])) {
  1320. log_warn(LD_DIR, "Error decoding descriptor digest %s",
  1321. escaped(tok->args[2]));
  1322. goto err;
  1323. }
  1324. if (tor_snprintf(timebuf, sizeof(timebuf), "%s %s",
  1325. tok->args[3], tok->args[4]) < 0 ||
  1326. parse_iso_time(timebuf, &rs->published_on)<0) {
  1327. log_warn(LD_DIR, "Error parsing time '%s %s'",
  1328. tok->args[3], tok->args[4]);
  1329. goto err;
  1330. }
  1331. if (tor_inet_aton(tok->args[5], &in) == 0) {
  1332. log_warn(LD_DIR, "Error parsing router address in network-status %s",
  1333. escaped(tok->args[5]));
  1334. goto err;
  1335. }
  1336. rs->addr = ntohl(in.s_addr);
  1337. rs->or_port =(uint16_t) tor_parse_long(tok->args[6],10,0,65535,NULL,NULL);
  1338. rs->dir_port = (uint16_t) tor_parse_long(tok->args[7],10,0,65535,NULL,NULL);
  1339. tok = find_first_by_keyword(tokens, K_S);
  1340. if (tok && vote) {
  1341. int i, j;
  1342. vote_rs->flags = 0;
  1343. for (i=0; i < tok->n_args; ++i) {
  1344. for (j=0; vote->known_flags[j]; ++j) {
  1345. if (!strcmp(tok->args[i], vote->known_flags[j])) {
  1346. vote_rs->flags |= (1<<j);
  1347. break;
  1348. }
  1349. }
  1350. }
  1351. } else if (tok) {
  1352. int i;
  1353. for (i=0; i < tok->n_args; ++i) {
  1354. if (!strcmp(tok->args[i], "Exit"))
  1355. rs->is_exit = 1;
  1356. else if (!strcmp(tok->args[i], "Stable"))
  1357. rs->is_stable = 1;
  1358. else if (!strcmp(tok->args[i], "Fast"))
  1359. rs->is_fast = 1;
  1360. else if (!strcmp(tok->args[i], "Running"))
  1361. rs->is_running = 1;
  1362. else if (!strcmp(tok->args[i], "Named"))
  1363. rs->is_named = 1;
  1364. else if (!strcmp(tok->args[i], "Valid"))
  1365. rs->is_valid = 1;
  1366. else if (!strcmp(tok->args[i], "V2Dir"))
  1367. rs->is_v2_dir = 1;
  1368. else if (!strcmp(tok->args[i], "Guard"))
  1369. rs->is_possible_guard = 1;
  1370. else if (!strcmp(tok->args[i], "BadExit"))
  1371. rs->is_bad_exit = 1;
  1372. else if (!strcmp(tok->args[i], "BadDirectory"))
  1373. rs->is_bad_directory = 1;
  1374. }
  1375. }
  1376. if ((tok = find_first_by_keyword(tokens, K_V))) {
  1377. tor_assert(tok->n_args == 1);
  1378. rs->version_known = 1;
  1379. if (strcmpstart(tok->args[0], "Tor ")) {
  1380. rs->version_supports_begindir = 1;
  1381. rs->version_supports_extrainfo_upload = 1;
  1382. } else {
  1383. rs->version_supports_begindir =
  1384. tor_version_as_new_as(tok->args[0], "0.1.2.2-alpha");
  1385. rs->version_supports_begindir =
  1386. tor_version_as_new_as(tok->args[0], "0.2.0.0-alpha-dev (r10070)");
  1387. }
  1388. if (vote_rs) {
  1389. vote_rs->version = tok->args[0];
  1390. tok->args[0] = NULL; /* suppress free() */
  1391. }
  1392. }
  1393. if (!strcasecmp(rs->nickname, UNNAMED_ROUTER_NICKNAME))
  1394. rs->is_named = 0;
  1395. goto done;
  1396. err:
  1397. if (rs && !vote_rs)
  1398. routerstatus_free(rs);
  1399. rs = NULL;
  1400. done:
  1401. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1402. smartlist_clear(tokens);
  1403. *s = eos;
  1404. return rs;
  1405. }
  1406. /** Helper to sort a smartlist of pointers to routerstatus_t */
  1407. static int
  1408. _compare_routerstatus_entries(const void **_a, const void **_b)
  1409. {
  1410. const routerstatus_t *a = *_a, *b = *_b;
  1411. return memcmp(a->identity_digest, b->identity_digest, DIGEST_LEN);
  1412. }
  1413. /** Helper: used in call to _smartlist_uniq to clear out duplicate entries. */
  1414. static void
  1415. _free_duplicate_routerstatus_entry(void *e)
  1416. {
  1417. log_warn(LD_DIR,
  1418. "Network-status has two entries for the same router. "
  1419. "Dropping one.");
  1420. routerstatus_free(e);
  1421. }
  1422. /** Given a v2 network-status object in <b>s</b>, try to
  1423. * parse it and return the result. Return NULL on failure. Check the
  1424. * signature of the network status, but do not (yet) check the signing key for
  1425. * authority.
  1426. */
  1427. networkstatus_t *
  1428. networkstatus_parse_from_string(const char *s)
  1429. {
  1430. const char *eos;
  1431. smartlist_t *tokens = smartlist_create();
  1432. smartlist_t *footer_tokens = smartlist_create();
  1433. networkstatus_t *ns = NULL;
  1434. char ns_digest[DIGEST_LEN];
  1435. char tmp_digest[DIGEST_LEN];
  1436. struct in_addr in;
  1437. directory_token_t *tok;
  1438. int i;
  1439. if (router_get_networkstatus_v2_hash(s, ns_digest)) {
  1440. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1441. goto err;
  1442. }
  1443. eos = find_start_of_next_routerstatus(s);
  1444. if (tokenize_string(s, eos, tokens, netstatus_token_table)) {
  1445. log_warn(LD_DIR, "Error tokenizing network-status header.");
  1446. goto err;
  1447. }
  1448. ns = tor_malloc_zero(sizeof(networkstatus_t));
  1449. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1450. tok = find_first_by_keyword(tokens, K_NETWORK_STATUS_VERSION);
  1451. tor_assert(tok && tok->n_args >= 1);
  1452. if (strcmp(tok->args[0], "2")) {
  1453. log_warn(LD_BUG, "Got a non-v2 networkstatus. Version was "
  1454. "%s", escaped(tok->args[0]));
  1455. goto err;
  1456. }
  1457. tok = find_first_by_keyword(tokens, K_DIR_SOURCE);
  1458. tor_assert(tok);
  1459. tor_assert(tok->n_args >= 3);
  1460. ns->source_address = tok->args[0]; tok->args[0] = NULL;
  1461. if (tor_inet_aton(tok->args[1], &in) == 0) {
  1462. log_warn(LD_DIR, "Error parsing network-status source address %s",
  1463. escaped(tok->args[1]));
  1464. goto err;
  1465. }
  1466. ns->source_addr = ntohl(in.s_addr);
  1467. ns->source_dirport =
  1468. (uint16_t) tor_parse_long(tok->args[2],10,0,65535,NULL,NULL);
  1469. if (ns->source_dirport == 0) {
  1470. log_warn(LD_DIR, "Directory source without dirport; skipping.");
  1471. goto err;
  1472. }
  1473. tok = find_first_by_keyword(tokens, K_FINGERPRINT);
  1474. tor_assert(tok);
  1475. tor_assert(tok->n_args);
  1476. if (base16_decode(ns->identity_digest, DIGEST_LEN, tok->args[0],
  1477. strlen(tok->args[0]))) {
  1478. log_warn(LD_DIR, "Couldn't decode networkstatus fingerprint %s",
  1479. escaped(tok->args[0]));
  1480. goto err;
  1481. }
  1482. if ((tok = find_first_by_keyword(tokens, K_CONTACT))) {
  1483. tor_assert(tok->n_args);
  1484. ns->contact = tok->args[0];
  1485. tok->args[0] = NULL;
  1486. }
  1487. tok = find_first_by_keyword(tokens, K_DIR_SIGNING_KEY);
  1488. tor_assert(tok && tok->key);
  1489. ns->signing_key = tok->key;
  1490. tok->key = NULL;
  1491. if (crypto_pk_get_digest(ns->signing_key, tmp_digest)<0) {
  1492. log_warn(LD_DIR, "Couldn't compute signing key digest");
  1493. goto err;
  1494. }
  1495. if (memcmp(tmp_digest, ns->identity_digest, DIGEST_LEN)) {
  1496. log_warn(LD_DIR,
  1497. "network-status fingerprint did not match dir-signing-key");
  1498. goto err;
  1499. }
  1500. if ((tok = find_first_by_keyword(tokens, K_DIR_OPTIONS))) {
  1501. for (i=0; i < tok->n_args; ++i) {
  1502. if (!strcmp(tok->args[i], "Names"))
  1503. ns->binds_names = 1;
  1504. if (!strcmp(tok->args[i], "Versions"))
  1505. ns->recommends_versions = 1;
  1506. if (!strcmp(tok->args[i], "BadExits"))
  1507. ns->lists_bad_exits = 1;
  1508. if (!strcmp(tok->args[i], "BadDirectories"))
  1509. ns->lists_bad_directories = 1;
  1510. }
  1511. }
  1512. if (ns->recommends_versions) {
  1513. if (!(tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1514. log_warn(LD_DIR, "Missing client-versions");
  1515. }
  1516. ns->client_versions = tok->args[0];
  1517. tok->args[0] = NULL;
  1518. if (!(tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS)) ||
  1519. tok->n_args<1) {
  1520. log_warn(LD_DIR, "Missing server-versions on versioning directory");
  1521. goto err;
  1522. }
  1523. ns->server_versions = tok->args[0];
  1524. tok->args[0] = NULL;
  1525. }
  1526. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1527. tor_assert(tok);
  1528. tor_assert(tok->n_args == 1);
  1529. if (parse_iso_time(tok->args[0], &ns->published_on) < 0) {
  1530. goto err;
  1531. }
  1532. ns->entries = smartlist_create();
  1533. s = eos;
  1534. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1535. smartlist_clear(tokens);
  1536. while (!strcmpstart(s, "r ")) {
  1537. routerstatus_t *rs;
  1538. if ((rs = routerstatus_parse_entry_from_string(&s, tokens, NULL, NULL)))
  1539. smartlist_add(ns->entries, rs);
  1540. }
  1541. smartlist_sort(ns->entries, _compare_routerstatus_entries);
  1542. smartlist_uniq(ns->entries, _compare_routerstatus_entries,
  1543. _free_duplicate_routerstatus_entry);
  1544. if (tokenize_string(s, NULL, footer_tokens, dir_footer_token_table)) {
  1545. log_warn(LD_DIR, "Error tokenizing network-status footer.");
  1546. goto err;
  1547. }
  1548. if (smartlist_len(footer_tokens) < 1) {
  1549. log_warn(LD_DIR, "Too few items in network-status footer.");
  1550. goto err;
  1551. }
  1552. tok = smartlist_get(footer_tokens, smartlist_len(footer_tokens)-1);
  1553. if (tok->tp != K_DIRECTORY_SIGNATURE) {
  1554. log_warn(LD_DIR,
  1555. "Expected network-status footer to end with a signature.");
  1556. goto err;
  1557. }
  1558. note_crypto_pk_op(VERIFY_DIR);
  1559. if (check_signature_token(ns_digest, tok, ns->signing_key, 0,
  1560. "network-status") < 0)
  1561. goto err;
  1562. goto done;
  1563. err:
  1564. if (ns)
  1565. networkstatus_free(ns);
  1566. ns = NULL;
  1567. done:
  1568. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1569. smartlist_free(tokens);
  1570. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  1571. smartlist_free(footer_tokens);
  1572. return ns;
  1573. }
  1574. /** DOCDOC */
  1575. networkstatus_vote_t *
  1576. networkstatus_parse_vote_from_string(const char *s, int is_vote)
  1577. {
  1578. smartlist_t *tokens = smartlist_create();
  1579. smartlist_t *rs_tokens = NULL, *footer_tokens = NULL;
  1580. networkstatus_voter_info_t *voter = NULL;
  1581. networkstatus_vote_t *ns = NULL;
  1582. char ns_digest[DIGEST_LEN];
  1583. const char *cert, *end_of_header, *end_of_footer;
  1584. directory_token_t *tok;
  1585. int ok;
  1586. struct in_addr in;
  1587. int i;
  1588. if (router_get_networkstatus_v3_hash(s, ns_digest)) {
  1589. log_warn(LD_DIR, "Unable to compute digest of network-status");
  1590. goto err;
  1591. }
  1592. end_of_header = find_start_of_next_routerstatus(s);
  1593. if (tokenize_string(s, end_of_header, tokens,
  1594. is_vote ? networkstatus_vote_token_table :
  1595. networkstatus_consensus_token_table)) {
  1596. log_warn(LD_DIR, "Error tokenizing network-status vote header.");
  1597. goto err;
  1598. }
  1599. ns = tor_malloc_zero(sizeof(networkstatus_vote_t));
  1600. memcpy(ns->networkstatus_digest, ns_digest, DIGEST_LEN);
  1601. if (is_vote) {
  1602. const char *end_of_cert = NULL;
  1603. if (!(cert = strstr(s, "\ndir-key-certificate-version")))
  1604. goto err;
  1605. ++cert;
  1606. ns->cert = authority_cert_parse_from_string(cert, &end_of_cert);
  1607. if (!ns->cert || !end_of_cert || end_of_cert > end_of_header)
  1608. goto err;
  1609. }
  1610. tok = find_first_by_keyword(tokens, K_VOTE_STATUS);
  1611. tor_assert(tok);
  1612. tor_assert(tok->n_args);
  1613. if (!strcmp(tok->args[0], "vote")) {
  1614. ns->is_vote = 1;
  1615. } else if (!strcmp(tok->args[0], "consensus")) {
  1616. ns->is_vote = 0;
  1617. } else {
  1618. log_warn(LD_DIR, "Unrecognized vote status %s in network-status",
  1619. escaped(tok->args[0]));
  1620. goto err;
  1621. }
  1622. if (!bool_eq(ns->is_vote, is_vote)) {
  1623. log_warn(LD_DIR, "Got the wrong kind of v3 networkstatus.");
  1624. goto err;
  1625. }
  1626. if (ns->is_vote) {
  1627. tok = find_first_by_keyword(tokens, K_PUBLISHED);
  1628. if (parse_iso_time(tok->args[0], &ns->published))
  1629. goto err;
  1630. }
  1631. tok = find_first_by_keyword(tokens, K_VALID_AFTER);
  1632. if (parse_iso_time(tok->args[0], &ns->valid_after))
  1633. goto err;
  1634. tok = find_first_by_keyword(tokens, K_FRESH_UNTIL);
  1635. if (parse_iso_time(tok->args[0], &ns->fresh_until))
  1636. goto err;
  1637. tok = find_first_by_keyword(tokens, K_VALID_UNTIL);
  1638. if (parse_iso_time(tok->args[0], &ns->valid_until))
  1639. goto err;
  1640. tok = find_first_by_keyword(tokens, K_VOTING_DELAY);
  1641. tor_assert(tok->n_args >= 2);
  1642. ns->vote_seconds =
  1643. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  1644. if (!ok)
  1645. goto err;
  1646. ns->dist_seconds =
  1647. (int) tor_parse_long(tok->args[0], 10, 0, INT_MAX, &ok, NULL);
  1648. if (!ok)
  1649. goto err;
  1650. if ((tok = find_first_by_keyword(tokens, K_CLIENT_VERSIONS))) {
  1651. ns->client_versions = tok->args[0];
  1652. tok->args[0] = NULL;
  1653. }
  1654. if ((tok = find_first_by_keyword(tokens, K_SERVER_VERSIONS))) {
  1655. ns->server_versions = tok->args[0];
  1656. tok->args[0] = NULL;
  1657. }
  1658. tok = find_first_by_keyword(tokens, K_KNOWN_FLAGS);
  1659. ns->known_flags = tor_malloc(sizeof(char*)*(tok->n_args+1));
  1660. memcpy(ns->known_flags, tok->args, sizeof(char*)*(tok->n_args));
  1661. ns->known_flags[tok->n_args] = NULL;
  1662. tok->n_args = 0; /* suppress free of args members, but not of args itself. */
  1663. ns->voters = smartlist_create();
  1664. SMARTLIST_FOREACH(tokens, directory_token_t *, _tok,
  1665. {
  1666. tok = _tok;
  1667. if (tok->tp == K_DIR_SOURCE) {
  1668. tor_assert(tok->n_args >= 6);
  1669. if (voter)
  1670. smartlist_add(ns->voters, voter);
  1671. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  1672. voter->nickname = tor_strdup(tok->args[0]);
  1673. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1674. base16_decode(voter->identity_digest, sizeof(voter->identity_digest),
  1675. tok->args[1], HEX_DIGEST_LEN) < 0) {
  1676. log_warn(LD_DIR, "Error decoding identity digest %s in "
  1677. "network-status vote.", escaped(tok->args[1]));
  1678. goto err;
  1679. }
  1680. voter->address = tor_strdup(tok->args[2]);
  1681. if (!tor_inet_aton(tok->args[3], &in)) {
  1682. log_warn(LD_DIR, "Error decoding IP address %s in network-status.",
  1683. escaped(tok->args[3]));
  1684. goto err;
  1685. }
  1686. voter->dir_port = (uint64_t)
  1687. (int) tor_parse_long(tok->args[4], 10, 0, 65535, &ok, NULL);
  1688. if (!ok)
  1689. goto err;
  1690. voter->or_port = (uint64_t)
  1691. (int) tor_parse_long(tok->args[5], 10, 0, 65535, &ok, NULL);
  1692. if (!ok)
  1693. goto err;
  1694. } else if (tok->tp == K_CONTACT) {
  1695. if (!voter || voter->contact) {
  1696. log_warn(LD_DIR, "contact element is out of place.");
  1697. goto err;
  1698. }
  1699. voter->contact = tor_strdup(tok->args[0]);
  1700. } else if (tok->tp == K_VOTE_DIGEST) {
  1701. tor_assert(!is_vote);
  1702. tor_assert(tok->n_args >= 1);
  1703. if (!voter || ! tor_digest_is_zero(voter->vote_digest)) {
  1704. log_warn(LD_DIR, "vote-digest element is out of place.");
  1705. goto err;
  1706. }
  1707. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  1708. base16_decode(voter->vote_digest, sizeof(voter->vote_digest),
  1709. tok->args[0], HEX_DIGEST_LEN) < 0) {
  1710. log_warn(LD_DIR, "Error decoding vote digest %s in "
  1711. "network-status consensus.", escaped(tok->args[1]));
  1712. goto err;
  1713. }
  1714. }
  1715. });
  1716. if (voter) {
  1717. smartlist_add(ns->voters, voter);
  1718. voter = NULL;
  1719. }
  1720. if (smartlist_len(ns->voters) == 0) {
  1721. log_warn(LD_DIR, "Missing dir-source elements in a vote networkstatus.");
  1722. goto err;
  1723. } else if (is_vote && smartlist_len(ns->voters) != 1) {
  1724. log_warn(LD_DIR, "Too many dir-source elements in a vote networkstatus.");
  1725. goto err;
  1726. }
  1727. /* Parse routerstatus lines. */
  1728. rs_tokens = smartlist_create();
  1729. s = end_of_header;
  1730. ns->routerstatus_list = smartlist_create();
  1731. while (!strcmpstart(s, "r ")) {
  1732. if (is_vote) {
  1733. vote_routerstatus_t *rs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  1734. if (routerstatus_parse_entry_from_string(&s, tokens, ns, rs))
  1735. smartlist_add(ns->routerstatus_list, rs);
  1736. else {
  1737. tor_free(rs->version);
  1738. tor_free(rs);
  1739. }
  1740. } else {
  1741. routerstatus_t *rs;
  1742. if ((rs =routerstatus_parse_entry_from_string(&s, tokens, NULL, NULL)))
  1743. smartlist_add(ns->routerstatus_list, rs);
  1744. }
  1745. }
  1746. for (i = 1; i < smartlist_len(ns->routerstatus_list); ++i) {
  1747. routerstatus_t *rs1, *rs2;
  1748. if (is_vote) {
  1749. vote_routerstatus_t *a = smartlist_get(ns->routerstatus_list, i-1);
  1750. vote_routerstatus_t *b = smartlist_get(ns->routerstatus_list, i);
  1751. rs1 = &a->status; rs2 = &b->status;
  1752. } else {
  1753. rs1 = smartlist_get(ns->routerstatus_list, i-1);
  1754. rs2 = smartlist_get(ns->routerstatus_list, i);
  1755. }
  1756. if (memcmp(rs1->identity_digest, rs2->identity_digest, DIGEST_LEN) >= 0) {
  1757. log_warn(LD_DIR, "Vote networkstatus entries not sorted by identity "
  1758. "digest");
  1759. goto err;
  1760. }
  1761. }
  1762. /* Parse footer; check signature. */
  1763. footer_tokens = smartlist_create();
  1764. end_of_footer = s + strlen(s);
  1765. if (tokenize_string(s, end_of_footer, footer_tokens,
  1766. networkstatus_vote_footer_token_table)) {
  1767. log_warn(LD_DIR, "Error tokenizing network-status vote footer.");
  1768. goto err;
  1769. }
  1770. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, _tok,
  1771. {
  1772. char declared_identity[DIGEST_LEN];
  1773. networkstatus_voter_info_t *v;
  1774. tok = _tok;
  1775. if (tok->tp != K_DIRECTORY_SIGNATURE)
  1776. continue;
  1777. tor_assert(tok->n_args >= 2);
  1778. if (!tok->object_type ||
  1779. strcmp(tok->object_type, "SIGNATURE") ||
  1780. tok->object_size < 128 || tok->object_size > 512) {
  1781. log_warn(LD_DIR, "Bad object type or length on directory-signature");
  1782. goto err;
  1783. }
  1784. if (strlen(tok->args[0]) != HEX_DIGEST_LEN ||
  1785. base16_decode(declared_identity, sizeof(declared_identity),
  1786. tok->args[0], HEX_DIGEST_LEN) < 0) {
  1787. log_warn(LD_DIR, "Error decoding declared identity %s in "
  1788. "network-status vote.", escaped(tok->args[0]));
  1789. goto err;
  1790. }
  1791. if (!(v = networkstatus_get_voter_by_id(ns, declared_identity))) {
  1792. log_warn(LD_DIR, "ID on signature on network-status vote does not match"
  1793. "any declared directory source.");
  1794. goto err;
  1795. }
  1796. if (strlen(tok->args[1]) != HEX_DIGEST_LEN ||
  1797. base16_decode(v->signing_key_digest, sizeof(v->signing_key_digest),
  1798. tok->args[1], HEX_DIGEST_LEN) < 0) {
  1799. log_warn(LD_DIR, "Error decoding declared digest %s in "
  1800. "network-status vote.", escaped(tok->args[1]));
  1801. goto err;
  1802. }
  1803. if (is_vote &&
  1804. memcmp(declared_identity, ns->cert->cache_info.identity_digest,
  1805. DIGEST_LEN)) {
  1806. log_warn(LD_DIR, "Digest mismatch between declared and actual on "
  1807. "network-status vote.");
  1808. goto err;
  1809. /* XXXX020 also check cert against dir-source line. */
  1810. }
  1811. if (is_vote) {
  1812. if (check_signature_token(ns_digest, tok, ns->cert->signing_key, 0,
  1813. "network-status vote"))
  1814. goto err;
  1815. v->good_signature = 1;
  1816. } else {
  1817. v->pending_signature = tor_memdup(tok->object_body,
  1818. tok->object_size);
  1819. v->pending_signature_len = tok->object_size;
  1820. }
  1821. });
  1822. /* XXXX020 check dates for plausibility. ??? */
  1823. goto done;
  1824. err:
  1825. if (ns)
  1826. networkstatus_vote_free(ns);
  1827. ns = NULL;
  1828. done:
  1829. if (tokens) {
  1830. SMARTLIST_FOREACH(tokens, directory_token_t *, t, token_free(t));
  1831. smartlist_free(tokens);
  1832. }
  1833. if (voter) {
  1834. tor_free(voter->nickname);
  1835. tor_free(voter->address);
  1836. tor_free(voter->contact);
  1837. tor_free(voter);
  1838. }
  1839. if (rs_tokens) {
  1840. SMARTLIST_FOREACH(rs_tokens, directory_token_t *, t, token_free(t));
  1841. smartlist_free(rs_tokens);
  1842. }
  1843. if (footer_tokens) {
  1844. SMARTLIST_FOREACH(footer_tokens, directory_token_t *, t, token_free(t));
  1845. smartlist_free(footer_tokens);
  1846. }
  1847. return ns;
  1848. }
  1849. /** Parse the addr policy in the string <b>s</b> and return it. If
  1850. * assume_action is nonnegative, then insert its action (ADDR_POLICY_ACCEPT or
  1851. * ADDR_POLICY_REJECT) for items that specify no action.
  1852. */
  1853. addr_policy_t *
  1854. router_parse_addr_policy_from_string(const char *s, int assume_action)
  1855. {
  1856. directory_token_t *tok = NULL;
  1857. const char *cp;
  1858. char *tmp;
  1859. addr_policy_t *r;
  1860. size_t len, idx;
  1861. /* *s might not end with \n, so we need to extend it with one. */
  1862. len = strlen(s);
  1863. cp = tmp = tor_malloc(len+2);
  1864. for (idx = 0; idx < len; ++idx) {
  1865. tmp[idx] = TOR_TOLOWER(s[idx]);
  1866. }
  1867. tmp[len]='\n';
  1868. tmp[len+1]='\0';
  1869. while (TOR_ISSPACE(*cp))
  1870. ++cp;
  1871. if ((*cp == '*' || TOR_ISDIGIT(*cp)) && assume_action >= 0) {
  1872. char *new_str = tor_malloc(len+10);
  1873. tor_snprintf(new_str, len+10, "%s %s\n",
  1874. assume_action == ADDR_POLICY_ACCEPT?"accept":"reject", cp);
  1875. tor_free(tmp);
  1876. cp = tmp = new_str;
  1877. }
  1878. tok = get_next_token(&cp, routerdesc_token_table);
  1879. if (tok->tp == _ERR) {
  1880. log_warn(LD_DIR, "Error reading address policy: %s", tok->error);
  1881. goto err;
  1882. }
  1883. if (tok->tp != K_ACCEPT && tok->tp != K_REJECT) {
  1884. log_warn(LD_DIR, "Expected 'accept' or 'reject'.");
  1885. goto err;
  1886. }
  1887. /* Now that we've gotten an addr policy, add it to the router. */
  1888. r = router_parse_addr_policy(tok);
  1889. goto done;
  1890. err:
  1891. r = NULL;
  1892. done:
  1893. tor_free(tmp);
  1894. token_free(tok);
  1895. return r;
  1896. }
  1897. /** Add an exit policy stored in the token <b>tok</b> to the router info in
  1898. * <b>router</b>. Return 0 on success, -1 on failure. */
  1899. static int
  1900. router_add_exit_policy(routerinfo_t *router, directory_token_t *tok)
  1901. {
  1902. addr_policy_t *newe, **tmpe;
  1903. newe = router_parse_addr_policy(tok);
  1904. if (!newe)
  1905. return -1;
  1906. for (tmpe = &router->exit_policy; *tmpe; tmpe=&((*tmpe)->next))
  1907. ;
  1908. *tmpe = newe;
  1909. return 0;
  1910. }
  1911. /** Given a K_ACCEPT or K_REJECT token and a router, create and return
  1912. * a new exit_policy_t corresponding to the token. */
  1913. static addr_policy_t *
  1914. router_parse_addr_policy(directory_token_t *tok)
  1915. {
  1916. addr_policy_t *newe;
  1917. char *arg;
  1918. char buf[POLICY_BUF_LEN];
  1919. tor_assert(tok->tp == K_REJECT || tok->tp == K_ACCEPT);
  1920. if (tok->n_args != 1)
  1921. return NULL;
  1922. arg = tok->args[0];
  1923. if (!strcmpstart(arg,"private"))
  1924. return router_parse_addr_policy_private(tok);
  1925. newe = tor_malloc_zero(sizeof(addr_policy_t));
  1926. newe->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1927. : ADDR_POLICY_ACCEPT;
  1928. if (parse_addr_and_port_range(arg, &newe->addr, &newe->msk,
  1929. &newe->prt_min, &newe->prt_max))
  1930. goto policy_read_failed;
  1931. if (policy_write_item(buf, sizeof(buf), newe) < 0)
  1932. goto policy_read_failed;
  1933. newe->string = tor_strdup(buf);
  1934. return newe;
  1935. policy_read_failed:
  1936. log_warn(LD_DIR,"Couldn't parse line %s. Dropping", escaped(arg));
  1937. tor_free(newe);
  1938. return NULL;
  1939. }
  1940. /** Parse an exit policy line of the format "accept/reject private:...".
  1941. * This didn't exist until Tor 0.1.1.15, so nobody should generate it in
  1942. * router descriptors until earlier versions are obsolete.
  1943. */
  1944. static addr_policy_t *
  1945. router_parse_addr_policy_private(directory_token_t *tok)
  1946. {
  1947. static const char *private_nets[] = {
  1948. "0.0.0.0/8", "169.254.0.0/16",
  1949. "127.0.0.0/8", "192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12",NULL };
  1950. char *arg;
  1951. addr_policy_t *result, **nextp;
  1952. int net;
  1953. uint16_t port_min, port_max;
  1954. arg = tok->args[0];
  1955. if (strcmpstart(arg, "private"))
  1956. return NULL;
  1957. arg += strlen("private");
  1958. arg = (char*) eat_whitespace(arg);
  1959. if (!arg || *arg != ':')
  1960. return NULL;
  1961. if (parse_port_range(arg+1, &port_min, &port_max)<0)
  1962. return NULL;
  1963. nextp = &result;
  1964. for (net = 0; private_nets[net]; ++net) {
  1965. size_t len;
  1966. *nextp = tor_malloc_zero(sizeof(addr_policy_t));
  1967. (*nextp)->policy_type = (tok->tp == K_REJECT) ? ADDR_POLICY_REJECT
  1968. : ADDR_POLICY_ACCEPT;
  1969. len = strlen(arg)+strlen(private_nets[net])+16;
  1970. (*nextp)->string = tor_malloc(len+1);
  1971. tor_snprintf((*nextp)->string, len, "%s %s%s",
  1972. tok->tp == K_REJECT ? "reject" : "accept",
  1973. private_nets[net], arg);
  1974. if (parse_addr_and_port_range((*nextp)->string + 7,
  1975. &(*nextp)->addr, &(*nextp)->msk,
  1976. &(*nextp)->prt_min, &(*nextp)->prt_max)) {
  1977. log_warn(LD_BUG, "Couldn't parse an address range we generated!");
  1978. return NULL;
  1979. }
  1980. nextp = &(*nextp)->next;
  1981. }
  1982. return result;
  1983. }
  1984. /** Log and exit if <b>t</b> is malformed */
  1985. void
  1986. assert_addr_policy_ok(addr_policy_t *t)
  1987. {
  1988. addr_policy_t *t2;
  1989. while (t) {
  1990. tor_assert(t->policy_type == ADDR_POLICY_REJECT ||
  1991. t->policy_type == ADDR_POLICY_ACCEPT);
  1992. tor_assert(t->prt_min <= t->prt_max);
  1993. t2 = router_parse_addr_policy_from_string(t->string, -1);
  1994. tor_assert(t2);
  1995. tor_assert(t2->policy_type == t->policy_type);
  1996. tor_assert(t2->addr == t->addr);
  1997. tor_assert(t2->msk == t->msk);
  1998. tor_assert(t2->prt_min == t->prt_min);
  1999. tor_assert(t2->prt_max == t->prt_max);
  2000. tor_assert(!strcmp(t2->string, t->string));
  2001. tor_assert(t2->next == NULL);
  2002. addr_policy_free(t2);
  2003. t = t->next;
  2004. }
  2005. }
  2006. /*
  2007. * Low-level tokenizer for router descriptors and directories.
  2008. */
  2009. /** Free all resources allocated for <b>tok</b> */
  2010. static void
  2011. token_free(directory_token_t *tok)
  2012. {
  2013. int i;
  2014. tor_assert(tok);
  2015. if (tok->args) {
  2016. for (i = 0; i < tok->n_args; ++i) {
  2017. tor_free(tok->args[i]);
  2018. }
  2019. tor_free(tok->args);
  2020. }
  2021. tor_free(tok->object_type);
  2022. tor_free(tok->object_body);
  2023. tor_free(tok->error);
  2024. if (tok->key)
  2025. crypto_free_pk_env(tok->key);
  2026. tor_free(tok);
  2027. }
  2028. #define RET_ERR(msg) \
  2029. do { \
  2030. if (tok) token_free(tok); \
  2031. tok = tor_malloc_zero(sizeof(directory_token_t)); \
  2032. tok->tp = _ERR; \
  2033. tok->error = tor_strdup(msg); \
  2034. goto done_tokenizing; } while (0)
  2035. static INLINE directory_token_t *
  2036. token_check_object(const char *kwd,
  2037. directory_token_t *tok, obj_syntax o_syn)
  2038. {
  2039. char ebuf[128];
  2040. switch (o_syn) {
  2041. case NO_OBJ:
  2042. if (tok->object_body) {
  2043. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected object for %s", kwd);
  2044. RET_ERR(ebuf);
  2045. }
  2046. if (tok->key) {
  2047. tor_snprintf(ebuf, sizeof(ebuf), "Unexpected public key for %s", kwd);
  2048. RET_ERR(ebuf);
  2049. }
  2050. break;
  2051. case NEED_OBJ:
  2052. if (!tok->object_body) {
  2053. tor_snprintf(ebuf, sizeof(ebuf), "Missing object for %s", kwd);
  2054. RET_ERR(ebuf);
  2055. }
  2056. break;
  2057. case NEED_KEY_1024:
  2058. if (tok->key && crypto_pk_keysize(tok->key) != PK_BYTES) {
  2059. tor_snprintf(ebuf, sizeof(ebuf), "Wrong size on key for %s: %d bits",
  2060. kwd, (int)crypto_pk_keysize(tok->key));
  2061. RET_ERR(ebuf);
  2062. }
  2063. /* fall through */
  2064. case NEED_KEY:
  2065. if (!tok->key) {
  2066. tor_snprintf(ebuf, sizeof(ebuf), "Missing public key for %s", kwd);
  2067. }
  2068. break;
  2069. case OBJ_OK:
  2070. break;
  2071. }
  2072. done_tokenizing:
  2073. return tok;
  2074. }
  2075. /** Helper function: read the next token from *s, advance *s to the end of the
  2076. * token, and return the parsed token. Parse *<b>s</b> according to the list
  2077. * of tokens in <b>table</b>.
  2078. */
  2079. static directory_token_t *
  2080. get_next_token(const char **s, token_rule_t *table)
  2081. {
  2082. const char *next, *obstart;
  2083. int i, j, done, allocated;
  2084. directory_token_t *tok;
  2085. obj_syntax o_syn = NO_OBJ;
  2086. char ebuf[128];
  2087. const char *kwd = "";
  2088. #define RET_ERR(msg) \
  2089. do { \
  2090. if (tok) token_free(tok); \
  2091. tok = tor_malloc_zero(sizeof(directory_token_t)); \
  2092. tok->tp = _ERR; \
  2093. tok->error = tor_strdup(msg); \
  2094. goto done_tokenizing; } while (0)
  2095. tok = tor_malloc_zero(sizeof(directory_token_t));
  2096. tok->tp = _ERR;
  2097. *s = eat_whitespace(*s);
  2098. if (!**s) {
  2099. tok->tp = _EOF;
  2100. return tok;
  2101. }
  2102. next = find_whitespace(*s);
  2103. if (!next) {
  2104. tok->error = tor_strdup("Unexpected EOF"); return tok;
  2105. }
  2106. /* It's a keyword... but which one? */
  2107. if (!strncmp("opt", *s, next-*s)) {
  2108. /* Skip past an "opt" at the start of the line. */
  2109. *s = eat_whitespace(next);
  2110. next = NULL;
  2111. if (**s)
  2112. next = find_whitespace(*s);
  2113. if (!**s || !next) {
  2114. RET_ERR("opt without keyword");
  2115. }
  2116. }
  2117. /* Search the table for the appropriate entry. (I tried a binary search
  2118. * instead, but it wasn't any faster.) */
  2119. for (i = 0; table[i].t ; ++i) {
  2120. if (!strncmp(table[i].t, *s, next-*s)) {
  2121. /* We've found the keyword. */
  2122. kwd = table[i].t;
  2123. tok->tp = table[i].v;
  2124. o_syn = table[i].os;
  2125. if (table[i].concat_args) {
  2126. /* The keyword takes the line as a single argument */
  2127. *s = eat_whitespace_no_nl(next);
  2128. next = strchr(*s, '\n');
  2129. if (!next)
  2130. RET_ERR("Unexpected EOF");
  2131. tok->args = tor_malloc(sizeof(char*));
  2132. tok->args[0] = tor_strndup(*s,next-*s);
  2133. tok->n_args = 1;
  2134. *s = eat_whitespace_no_nl(next+1);
  2135. } else {
  2136. /* This keyword takes multiple arguments. */
  2137. j = 0;
  2138. done = (*next == '\n');
  2139. allocated = 32;
  2140. tok->args = tor_malloc(sizeof(char*)*32);
  2141. *s = eat_whitespace_no_nl(next);
  2142. while (**s != '\n' && !done) {
  2143. next = find_whitespace(*s);
  2144. if (*next == '\n')
  2145. done = 1;
  2146. if (j == allocated) {
  2147. allocated *= 2;
  2148. tok->args = tor_realloc(tok->args,sizeof(char*)*allocated);
  2149. }
  2150. tok->args[j++] = tor_strndup(*s,next-*s);
  2151. *s = eat_whitespace_no_nl(next+1);
  2152. }
  2153. tok->n_args = j;
  2154. }
  2155. if (tok->n_args < table[i].min_args) {
  2156. tor_snprintf(ebuf, sizeof(ebuf), "Too few arguments to %s", kwd);
  2157. RET_ERR(ebuf);
  2158. } else if (tok->n_args > table[i].max_args) {
  2159. tor_snprintf(ebuf, sizeof(ebuf), "Too many arguments to %s", kwd);
  2160. RET_ERR(ebuf);
  2161. }
  2162. break;
  2163. }
  2164. }
  2165. if (tok->tp == _ERR) {
  2166. tok->tp = K_OPT;
  2167. *s = eat_whitespace_no_nl(next);
  2168. next = strchr(*s,'\n');
  2169. if (!next)
  2170. RET_ERR("Unexpected EOF");
  2171. tok->args = tor_malloc(sizeof(char*));
  2172. tok->args[0] = tor_strndup(*s,next-*s);
  2173. tok->n_args = 1;
  2174. *s = eat_whitespace_no_nl(next+1);
  2175. o_syn = OBJ_OK;
  2176. }
  2177. *s = eat_whitespace(*s);
  2178. if (strcmpstart(*s, "-----BEGIN ")) {
  2179. goto check_object;
  2180. }
  2181. obstart = *s;
  2182. *s += 11; /* length of "-----BEGIN ". */
  2183. next = strchr(*s, '\n');
  2184. if (next-*s < 6 || strcmpstart(next-5, "-----\n")) {
  2185. RET_ERR("Malformed object: bad begin line");
  2186. }
  2187. tok->object_type = tor_strndup(*s, next-*s-5);
  2188. *s = next+1;
  2189. next = strstr(*s, "-----END ");
  2190. if (!next) {
  2191. RET_ERR("Malformed object: missing end line");
  2192. }
  2193. if (!strcmp(tok->object_type, "RSA PUBLIC KEY")) {
  2194. if (strcmpstart(next, "-----END RSA PUBLIC KEY-----\n"))
  2195. RET_ERR("Malformed object: mismatched end line");
  2196. next = strchr(next,'\n')+1;
  2197. tok->key = crypto_new_pk_env();
  2198. if (crypto_pk_read_public_key_from_string(tok->key, obstart, next-obstart))
  2199. RET_ERR("Couldn't parse public key.");
  2200. *s = next;
  2201. } else {
  2202. tok->object_body = tor_malloc(next-*s); /* really, this is too much RAM. */
  2203. i = base64_decode(tok->object_body, 256, *s, next-*s);
  2204. if (i<0) {
  2205. RET_ERR("Malformed object: bad base64-encoded data");
  2206. }
  2207. tok->object_size = i;
  2208. *s = next + 9; /* length of "-----END ". */
  2209. i = strlen(tok->object_type);
  2210. if (strncmp(*s, tok->object_type, i) || strcmpstart(*s+i, "-----\n")) {
  2211. RET_ERR("Malformed object: mismatched end tag");
  2212. }
  2213. *s += i+6;
  2214. }
  2215. check_object:
  2216. tok = token_check_object(kwd, tok, o_syn);
  2217. done_tokenizing:
  2218. return tok;
  2219. #undef RET_ERR
  2220. }
  2221. /** Read all tokens from a string between <b>start</b> and <b>end</b>, and add
  2222. * them to <b>out</b>. Parse according to the token rules in <b>table</b>.
  2223. */
  2224. static int
  2225. tokenize_string(const char *start, const char *end, smartlist_t *out,
  2226. token_rule_t *table)
  2227. {
  2228. const char **s;
  2229. directory_token_t *tok = NULL;
  2230. int counts[_NIL];
  2231. int i;
  2232. s = &start;
  2233. if (!end)
  2234. end = start+strlen(start);
  2235. for (i = 0; i < _NIL; ++i)
  2236. counts[i] = 0;
  2237. while (*s < end && (!tok || tok->tp != _EOF)) {
  2238. tok = get_next_token(s, table);
  2239. if (tok->tp == _ERR) {
  2240. log_warn(LD_DIR, "parse error: %s", tok->error);
  2241. return -1;
  2242. }
  2243. ++counts[tok->tp];
  2244. smartlist_add(out, tok);
  2245. *s = eat_whitespace(*s);
  2246. }
  2247. for (i = 0; table[i].t; ++i) {
  2248. if (counts[table[i].v] < table[i].min_cnt) {
  2249. log_warn(LD_DIR, "Parse error: missing %s element.", table[i].t);
  2250. return -1;
  2251. }
  2252. if (counts[table[i].v] > table[i].max_cnt) {
  2253. log_warn(LD_DIR, "Parse error: too many %s elements.", table[i].t);
  2254. return -1;
  2255. }
  2256. if (table[i].pos & AT_START) {
  2257. if (smartlist_len(out) < 1 ||
  2258. (tok = smartlist_get(out, 0))->tp != table[i].v) {
  2259. log_warn(LD_DIR, "Parse error: first item is not %s.", table[i].t);
  2260. return -1;
  2261. }
  2262. }
  2263. if (table[i].pos & AT_END) {
  2264. if (smartlist_len(out) < 1 ||
  2265. (tok = smartlist_get(out, smartlist_len(out)-1))->tp != table[i].v) {
  2266. log_warn(LD_DIR, "Parse error: last item is not %s.", table[i].t);
  2267. return -1;
  2268. }
  2269. }
  2270. }
  2271. return 0;
  2272. }
  2273. /** Find the first token in <b>s</b> whose keyword is <b>keyword</b>; return
  2274. * NULL if no such keyword is found.
  2275. */
  2276. static directory_token_t *
  2277. find_first_by_keyword(smartlist_t *s, directory_keyword keyword)
  2278. {
  2279. SMARTLIST_FOREACH(s, directory_token_t *, t, if (t->tp == keyword) return t);
  2280. return NULL;
  2281. }
  2282. /** Return a newly allocated smartlist of all accept or reject tokens in
  2283. * <b>s</b>.
  2284. */
  2285. static smartlist_t *
  2286. find_all_exitpolicy(smartlist_t *s)
  2287. {
  2288. smartlist_t *out = smartlist_create();
  2289. SMARTLIST_FOREACH(s, directory_token_t *, t,
  2290. if (t->tp == K_ACCEPT || t->tp == K_REJECT)
  2291. smartlist_add(out,t));
  2292. return out;
  2293. }
  2294. /** Compute the SHA-1 digest of the substring of <b>s</b> taken from the first
  2295. * occurrence of <b>start_str</b> through the first instance of c after the
  2296. * first subsequent occurrence of <b>end_str</b>; store the 20-byte result in
  2297. * <b>digest</b>; return 0 on success.
  2298. *
  2299. * If no such substring exists, return -1.
  2300. */
  2301. static int
  2302. router_get_hash_impl(const char *s, char *digest,
  2303. const char *start_str,
  2304. const char *end_str, char end_c)
  2305. {
  2306. char *start, *end;
  2307. start = strstr(s, start_str);
  2308. if (!start) {
  2309. log_warn(LD_DIR,"couldn't find start of hashed material \"%s\"",start_str);
  2310. return -1;
  2311. }
  2312. if (start != s && *(start-1) != '\n') {
  2313. log_warn(LD_DIR,
  2314. "first occurrence of \"%s\" is not at the start of a line",
  2315. start_str);
  2316. return -1;
  2317. }
  2318. end = strstr(start+strlen(start_str), end_str);
  2319. if (!end) {
  2320. log_warn(LD_DIR,"couldn't find end of hashed material \"%s\"",end_str);
  2321. return -1;
  2322. }
  2323. end = strchr(end+strlen(end_str), end_c);
  2324. if (!end) {
  2325. log_warn(LD_DIR,"couldn't find EOL");
  2326. return -1;
  2327. }
  2328. ++end;
  2329. if (crypto_digest(digest, start, end-start)) {
  2330. log_warn(LD_BUG,"couldn't compute digest");
  2331. return -1;
  2332. }
  2333. return 0;
  2334. }
  2335. /** Parse the Tor version of the platform string <b>platform</b>,
  2336. * and compare it to the version in <b>cutoff</b>. Return 1 if
  2337. * the router is at least as new as the cutoff, else return 0.
  2338. */
  2339. int
  2340. tor_version_as_new_as(const char *platform, const char *cutoff)
  2341. {
  2342. tor_version_t cutoff_version, router_version;
  2343. char *s, *s2, *start;
  2344. char tmp[128];
  2345. tor_assert(platform);
  2346. if (tor_version_parse(cutoff, &cutoff_version)<0) {
  2347. log_warn(LD_BUG,"cutoff version '%s' unparseable.",cutoff);
  2348. return 0;
  2349. }
  2350. if (strcmpstart(platform,"Tor ")) /* nonstandard Tor; be safe and say yes */
  2351. return 1;
  2352. start = (char *)eat_whitespace(platform+3);
  2353. if (!*start) return 0;
  2354. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  2355. s2 = (char*)eat_whitespace(s);
  2356. if (!strcmpstart(s2, "(r"))
  2357. s = (char*)find_whitespace(s2);
  2358. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  2359. return 0;
  2360. strlcpy(tmp, start, s-start+1);
  2361. if (tor_version_parse(tmp, &router_version)<0) {
  2362. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  2363. return 1; /* be safe and say yes */
  2364. }
  2365. /* Here's why we don't need to do any special handling for svn revisions:
  2366. * - If neither has an svn revision, we're fine.
  2367. * - If the router doesn't have an svn revision, we can't assume that it
  2368. * is "at least" any svn revision, so we need to return 0.
  2369. * - If the target version doesn't have an svn revision, any svn revision
  2370. * (or none at all) is good enough, so return 1.
  2371. * - If both target and router have an svn revision, we compare them.
  2372. */
  2373. return tor_version_compare(&router_version, &cutoff_version) >= 0;
  2374. }
  2375. /** Parse a tor version from <b>s</b>, and store the result in <b>out</b>.
  2376. * Return 0 on success, -1 on failure. */
  2377. int
  2378. tor_version_parse(const char *s, tor_version_t *out)
  2379. {
  2380. char *eos=NULL;
  2381. const char *cp=NULL;
  2382. /* Format is:
  2383. * "Tor " ? NUM dot NUM dot NUM [ ( pre | rc | dot ) NUM [ - tag ] ]
  2384. */
  2385. tor_assert(s);
  2386. tor_assert(out);
  2387. memset(out, 0, sizeof(tor_version_t));
  2388. if (!strcasecmpstart(s, "Tor "))
  2389. s += 4;
  2390. /* Get major. */
  2391. out->major = strtol(s,&eos,10);
  2392. if (!eos || eos==s || *eos != '.') return -1;
  2393. cp = eos+1;
  2394. /* Get minor */
  2395. out->minor = strtol(cp,&eos,10);
  2396. if (!eos || eos==cp || *eos != '.') return -1;
  2397. cp = eos+1;
  2398. /* Get micro */
  2399. out->micro = strtol(cp,&eos,10);
  2400. if (!eos || eos==cp) return -1;
  2401. if (!*eos) {
  2402. out->status = VER_RELEASE;
  2403. out->patchlevel = 0;
  2404. return 0;
  2405. }
  2406. cp = eos;
  2407. /* Get status */
  2408. if (*cp == '.') {
  2409. out->status = VER_RELEASE;
  2410. ++cp;
  2411. } else if (0==strncmp(cp, "pre", 3)) {
  2412. out->status = VER_PRE;
  2413. cp += 3;
  2414. } else if (0==strncmp(cp, "rc", 2)) {
  2415. out->status = VER_RC;
  2416. cp += 2;
  2417. } else {
  2418. return -1;
  2419. }
  2420. /* Get patchlevel */
  2421. out->patchlevel = strtol(cp,&eos,10);
  2422. if (!eos || eos==cp) return -1;
  2423. cp = eos;
  2424. /* Get status tag. */
  2425. if (*cp == '-' || *cp == '.')
  2426. ++cp;
  2427. eos = (char*) find_whitespace(cp);
  2428. if (eos-cp >= (int)sizeof(out->status_tag))
  2429. strlcpy(out->status_tag, cp, sizeof(out->status_tag));
  2430. else {
  2431. memcpy(out->status_tag, cp, eos-cp);
  2432. out->status_tag[eos-cp] = 0;
  2433. }
  2434. cp = eat_whitespace(eos);
  2435. if (!strcmpstart(cp, "(r")) {
  2436. cp += 2;
  2437. out->svn_revision = strtol(cp,&eos,10);
  2438. }
  2439. return 0;
  2440. }
  2441. /** Compare two tor versions; Return <0 if a < b; 0 if a ==b, >0 if a >
  2442. * b. */
  2443. int
  2444. tor_version_compare(tor_version_t *a, tor_version_t *b)
  2445. {
  2446. int i;
  2447. tor_assert(a);
  2448. tor_assert(b);
  2449. if ((i = a->major - b->major))
  2450. return i;
  2451. else if ((i = a->minor - b->minor))
  2452. return i;
  2453. else if ((i = a->micro - b->micro))
  2454. return i;
  2455. else if ((i = a->status - b->status))
  2456. return i;
  2457. else if ((i = a->patchlevel - b->patchlevel))
  2458. return i;
  2459. else if ((i = strcmp(a->status_tag, b->status_tag)))
  2460. return i;
  2461. else
  2462. return a->svn_revision - b->svn_revision;
  2463. }
  2464. /** Return true iff versions <b>a</b> and <b>b</b> belong to the same series.
  2465. */
  2466. static int
  2467. tor_version_same_series(tor_version_t *a, tor_version_t *b)
  2468. {
  2469. tor_assert(a);
  2470. tor_assert(b);
  2471. return ((a->major == b->major) &&
  2472. (a->minor == b->minor) &&
  2473. (a->micro == b->micro));
  2474. }
  2475. /** Helper: Given pointers to two strings describing tor versions, return -1
  2476. * if _a precedes _b, 1 if _b preceeds _a, and 0 if they are equivalent.
  2477. * Used to sort a list of versions. */
  2478. static int
  2479. _compare_tor_version_str_ptr(const void **_a, const void **_b)
  2480. {
  2481. const char *a = *_a, *b = *_b;
  2482. int ca, cb;
  2483. tor_version_t va, vb;
  2484. ca = tor_version_parse(a, &va);
  2485. cb = tor_version_parse(b, &vb);
  2486. /* If they both parse, compare them. */
  2487. if (!ca && !cb)
  2488. return tor_version_compare(&va,&vb);
  2489. /* If one parses, it comes first. */
  2490. if (!ca && cb)
  2491. return -1;
  2492. if (ca && !cb)
  2493. return 1;
  2494. /* If neither parses, compare strings. Also, the directory server admin
  2495. ** needs to be smacked upside the head. But Tor is tolerant and gentle. */
  2496. return strcmp(a,b);
  2497. }
  2498. /** Sort a list of string-representations of versions in ascending order. */
  2499. void
  2500. sort_version_list(smartlist_t *versions, int remove_duplicates)
  2501. {
  2502. smartlist_sort(versions, _compare_tor_version_str_ptr);
  2503. if (remove_duplicates)
  2504. smartlist_uniq(versions, _compare_tor_version_str_ptr, NULL);
  2505. }