routerparse.c 94 KB

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