test.c 131 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2008, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char test_c_id[] =
  7. "$Id$";
  8. const char tor_svn_revision[] = "";
  9. /**
  10. * \file test.c
  11. * \brief Unit tests for many pieces of the lower level Tor modules.
  12. **/
  13. #include "orconfig.h"
  14. #include <stdio.h>
  15. #ifdef HAVE_FCNTL_H
  16. #include <fcntl.h>
  17. #endif
  18. #ifdef MS_WINDOWS
  19. /* For mkdir() */
  20. #include <direct.h>
  21. #else
  22. #include <dirent.h>
  23. #endif
  24. /* These macros pull in declarations for some functions and structures that
  25. * are typically file-private. */
  26. #define BUFFERS_PRIVATE
  27. #define CONFIG_PRIVATE
  28. #define CONTROL_PRIVATE
  29. #define CRYPTO_PRIVATE
  30. #define DIRSERV_PRIVATE
  31. #define DIRVOTE_PRIVATE
  32. #define GEOIP_PRIVATE
  33. #define MEMPOOL_PRIVATE
  34. #define ROUTER_PRIVATE
  35. #include "or.h"
  36. #include "test.h"
  37. #include "torgzip.h"
  38. #include "mempool.h"
  39. #include "memarea.h"
  40. int have_failed = 0;
  41. static char temp_dir[256];
  42. static void
  43. setup_directory(void)
  44. {
  45. static int is_setup = 0;
  46. int r;
  47. if (is_setup) return;
  48. #ifdef MS_WINDOWS
  49. // XXXX
  50. tor_snprintf(temp_dir, sizeof(temp_dir),
  51. "c:\\windows\\temp\\tor_test_%d", (int)getpid());
  52. r = mkdir(temp_dir);
  53. #else
  54. tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d", (int) getpid());
  55. r = mkdir(temp_dir, 0700);
  56. #endif
  57. if (r) {
  58. fprintf(stderr, "Can't create directory %s:", temp_dir);
  59. perror("");
  60. exit(1);
  61. }
  62. is_setup = 1;
  63. }
  64. static const char *
  65. get_fname(const char *name)
  66. {
  67. static char buf[1024];
  68. setup_directory();
  69. tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
  70. return buf;
  71. }
  72. static void
  73. remove_directory(void)
  74. {
  75. smartlist_t *elements = tor_listdir(temp_dir);
  76. if (elements) {
  77. SMARTLIST_FOREACH(elements, const char *, cp,
  78. {
  79. size_t len = strlen(cp)+strlen(temp_dir)+16;
  80. char *tmp = tor_malloc(len);
  81. tor_snprintf(tmp, len, "%s"PATH_SEPARATOR"%s", temp_dir, cp);
  82. unlink(tmp);
  83. tor_free(tmp);
  84. });
  85. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  86. smartlist_free(elements);
  87. }
  88. rmdir(temp_dir);
  89. }
  90. static crypto_pk_env_t *
  91. pk_generate(int idx)
  92. {
  93. static crypto_pk_env_t *pregen[5] = {NULL, NULL, NULL, NULL, NULL};
  94. tor_assert(idx < (int)(sizeof(pregen)/sizeof(pregen[0])));
  95. if (! pregen[idx]) {
  96. pregen[idx] = crypto_new_pk_env();
  97. tor_assert(!crypto_pk_generate_key(pregen[idx]));
  98. }
  99. return crypto_pk_dup_key(pregen[idx]);
  100. }
  101. static void
  102. test_buffers(void)
  103. {
  104. char str[256];
  105. char str2[256];
  106. buf_t *buf, *buf2;
  107. const char *cp;
  108. int j;
  109. size_t r;
  110. /****
  111. * buf_new
  112. ****/
  113. if (!(buf = buf_new()))
  114. test_fail();
  115. //test_eq(buf_capacity(buf), 4096);
  116. test_eq(buf_datalen(buf), 0);
  117. /****
  118. * General pointer frobbing
  119. */
  120. for (j=0;j<256;++j) {
  121. str[j] = (char)j;
  122. }
  123. write_to_buf(str, 256, buf);
  124. write_to_buf(str, 256, buf);
  125. test_eq(buf_datalen(buf), 512);
  126. fetch_from_buf(str2, 200, buf);
  127. test_memeq(str, str2, 200);
  128. test_eq(buf_datalen(buf), 312);
  129. memset(str2, 0, sizeof(str2));
  130. fetch_from_buf(str2, 256, buf);
  131. test_memeq(str+200, str2, 56);
  132. test_memeq(str, str2+56, 200);
  133. test_eq(buf_datalen(buf), 56);
  134. memset(str2, 0, sizeof(str2));
  135. /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
  136. * another 3584 bytes, we hit the end. */
  137. for (j=0;j<15;++j) {
  138. write_to_buf(str, 256, buf);
  139. }
  140. assert_buf_ok(buf);
  141. test_eq(buf_datalen(buf), 3896);
  142. fetch_from_buf(str2, 56, buf);
  143. test_eq(buf_datalen(buf), 3840);
  144. test_memeq(str+200, str2, 56);
  145. for (j=0;j<15;++j) {
  146. memset(str2, 0, sizeof(str2));
  147. fetch_from_buf(str2, 256, buf);
  148. test_memeq(str, str2, 256);
  149. }
  150. test_eq(buf_datalen(buf), 0);
  151. buf_free(buf);
  152. /* Okay, now make sure growing can work. */
  153. buf = buf_new_with_capacity(16);
  154. //test_eq(buf_capacity(buf), 16);
  155. write_to_buf(str+1, 255, buf);
  156. //test_eq(buf_capacity(buf), 256);
  157. fetch_from_buf(str2, 254, buf);
  158. test_memeq(str+1, str2, 254);
  159. //test_eq(buf_capacity(buf), 256);
  160. assert_buf_ok(buf);
  161. write_to_buf(str, 32, buf);
  162. //test_eq(buf_capacity(buf), 256);
  163. assert_buf_ok(buf);
  164. write_to_buf(str, 256, buf);
  165. assert_buf_ok(buf);
  166. //test_eq(buf_capacity(buf), 512);
  167. test_eq(buf_datalen(buf), 33+256);
  168. fetch_from_buf(str2, 33, buf);
  169. test_eq(*str2, str[255]);
  170. test_memeq(str2+1, str, 32);
  171. //test_eq(buf_capacity(buf), 512);
  172. test_eq(buf_datalen(buf), 256);
  173. fetch_from_buf(str2, 256, buf);
  174. test_memeq(str, str2, 256);
  175. /* now try shrinking: case 1. */
  176. buf_free(buf);
  177. buf = buf_new_with_capacity(33668);
  178. for (j=0;j<67;++j) {
  179. write_to_buf(str,255, buf);
  180. }
  181. //test_eq(buf_capacity(buf), 33668);
  182. test_eq(buf_datalen(buf), 17085);
  183. for (j=0; j < 40; ++j) {
  184. fetch_from_buf(str2, 255,buf);
  185. test_memeq(str2, str, 255);
  186. }
  187. /* now try shrinking: case 2. */
  188. buf_free(buf);
  189. buf = buf_new_with_capacity(33668);
  190. for (j=0;j<67;++j) {
  191. write_to_buf(str,255, buf);
  192. }
  193. for (j=0; j < 20; ++j) {
  194. fetch_from_buf(str2, 255,buf);
  195. test_memeq(str2, str, 255);
  196. }
  197. for (j=0;j<80;++j) {
  198. write_to_buf(str,255, buf);
  199. }
  200. //test_eq(buf_capacity(buf),33668);
  201. for (j=0; j < 120; ++j) {
  202. fetch_from_buf(str2, 255,buf);
  203. test_memeq(str2, str, 255);
  204. }
  205. /* Move from buf to buf. */
  206. buf_free(buf);
  207. buf = buf_new_with_capacity(4096);
  208. buf2 = buf_new_with_capacity(4096);
  209. for (j=0;j<100;++j)
  210. write_to_buf(str, 255, buf);
  211. test_eq(buf_datalen(buf), 25500);
  212. for (j=0;j<100;++j) {
  213. r = 10;
  214. move_buf_to_buf(buf2, buf, &r);
  215. test_eq(r, 0);
  216. }
  217. test_eq(buf_datalen(buf), 24500);
  218. test_eq(buf_datalen(buf2), 1000);
  219. for (j=0;j<3;++j) {
  220. fetch_from_buf(str2, 255, buf2);
  221. test_memeq(str2, str, 255);
  222. }
  223. r = 8192; /*big move*/
  224. move_buf_to_buf(buf2, buf, &r);
  225. test_eq(r, 0);
  226. r = 30000; /* incomplete move */
  227. move_buf_to_buf(buf2, buf, &r);
  228. test_eq(r, 13692);
  229. for (j=0;j<97;++j) {
  230. fetch_from_buf(str2, 255, buf2);
  231. test_memeq(str2, str, 255);
  232. }
  233. buf_free(buf);
  234. buf_free(buf2);
  235. buf = buf_new_with_capacity(5);
  236. cp = "Testing. This is a moderately long Testing string.";
  237. for (j = 0; cp[j]; j++)
  238. write_to_buf(cp+j, 1, buf);
  239. test_eq(0, buf_find_string_offset(buf, "Testing", 7));
  240. test_eq(1, buf_find_string_offset(buf, "esting", 6));
  241. test_eq(1, buf_find_string_offset(buf, "est", 3));
  242. test_eq(39, buf_find_string_offset(buf, "ing str", 7));
  243. test_eq(35, buf_find_string_offset(buf, "Testing str", 11));
  244. test_eq(32, buf_find_string_offset(buf, "ng ", 3));
  245. test_eq(43, buf_find_string_offset(buf, "string.", 7));
  246. test_eq(-1, buf_find_string_offset(buf, "shrdlu", 6));
  247. test_eq(-1, buf_find_string_offset(buf, "Testing thing", 13));
  248. test_eq(-1, buf_find_string_offset(buf, "ngx", 3));
  249. buf_free(buf);
  250. #if 0
  251. {
  252. int s;
  253. int eof;
  254. int i;
  255. buf_t *buf2;
  256. /****
  257. * read_to_buf
  258. ****/
  259. s = open(get_fname("data"), O_WRONLY|O_CREAT|O_TRUNC, 0600);
  260. write(s, str, 256);
  261. close(s);
  262. s = open(get_fname("data"), O_RDONLY, 0);
  263. eof = 0;
  264. errno = 0; /* XXXX */
  265. i = read_to_buf(s, 10, buf, &eof);
  266. printf("%s\n", strerror(errno));
  267. test_eq(i, 10);
  268. test_eq(eof, 0);
  269. //test_eq(buf_capacity(buf), 4096);
  270. test_eq(buf_datalen(buf), 10);
  271. test_memeq(str, (char*)_buf_peek_raw_buffer(buf), 10);
  272. /* Test reading 0 bytes. */
  273. i = read_to_buf(s, 0, buf, &eof);
  274. //test_eq(buf_capacity(buf), 512*1024);
  275. test_eq(buf_datalen(buf), 10);
  276. test_eq(eof, 0);
  277. test_eq(i, 0);
  278. /* Now test when buffer is filled exactly. */
  279. buf2 = buf_new_with_capacity(6);
  280. i = read_to_buf(s, 6, buf2, &eof);
  281. //test_eq(buf_capacity(buf2), 6);
  282. test_eq(buf_datalen(buf2), 6);
  283. test_eq(eof, 0);
  284. test_eq(i, 6);
  285. test_memeq(str+10, (char*)_buf_peek_raw_buffer(buf2), 6);
  286. buf_free(buf2);
  287. /* Now test when buffer is filled with more data to read. */
  288. buf2 = buf_new_with_capacity(32);
  289. i = read_to_buf(s, 128, buf2, &eof);
  290. //test_eq(buf_capacity(buf2), 128);
  291. test_eq(buf_datalen(buf2), 32);
  292. test_eq(eof, 0);
  293. test_eq(i, 32);
  294. buf_free(buf2);
  295. /* Now read to eof. */
  296. test_assert(buf_capacity(buf) > 256);
  297. i = read_to_buf(s, 1024, buf, &eof);
  298. test_eq(i, (256-32-10-6));
  299. test_eq(buf_capacity(buf), MAX_BUF_SIZE);
  300. test_eq(buf_datalen(buf), 256-6-32);
  301. test_memeq(str, (char*)_buf_peek_raw_buffer(buf), 10); /* XXX Check rest. */
  302. test_eq(eof, 0);
  303. i = read_to_buf(s, 1024, buf, &eof);
  304. test_eq(i, 0);
  305. test_eq(buf_capacity(buf), MAX_BUF_SIZE);
  306. test_eq(buf_datalen(buf), 256-6-32);
  307. test_eq(eof, 1);
  308. }
  309. #endif
  310. }
  311. static void
  312. test_crypto_dh(void)
  313. {
  314. crypto_dh_env_t *dh1, *dh2;
  315. char p1[DH_BYTES];
  316. char p2[DH_BYTES];
  317. char s1[DH_BYTES];
  318. char s2[DH_BYTES];
  319. int s1len, s2len;
  320. dh1 = crypto_dh_new();
  321. dh2 = crypto_dh_new();
  322. test_eq(crypto_dh_get_bytes(dh1), DH_BYTES);
  323. test_eq(crypto_dh_get_bytes(dh2), DH_BYTES);
  324. memset(p1, 0, DH_BYTES);
  325. memset(p2, 0, DH_BYTES);
  326. test_memeq(p1, p2, DH_BYTES);
  327. test_assert(! crypto_dh_get_public(dh1, p1, DH_BYTES));
  328. test_memneq(p1, p2, DH_BYTES);
  329. test_assert(! crypto_dh_get_public(dh2, p2, DH_BYTES));
  330. test_memneq(p1, p2, DH_BYTES);
  331. memset(s1, 0, DH_BYTES);
  332. memset(s2, 0xFF, DH_BYTES);
  333. s1len = crypto_dh_compute_secret(dh1, p2, DH_BYTES, s1, 50);
  334. s2len = crypto_dh_compute_secret(dh2, p1, DH_BYTES, s2, 50);
  335. test_assert(s1len > 0);
  336. test_eq(s1len, s2len);
  337. test_memeq(s1, s2, s1len);
  338. {
  339. /* XXXX Now fabricate some bad values and make sure they get caught,
  340. * Check 0, 1, N-1, >= N, etc.
  341. */
  342. }
  343. crypto_dh_free(dh1);
  344. crypto_dh_free(dh2);
  345. }
  346. static void
  347. test_crypto(void)
  348. {
  349. crypto_cipher_env_t *env1, *env2;
  350. crypto_pk_env_t *pk1, *pk2;
  351. char *data1, *data2, *data3, *cp;
  352. int i, j, p, len, idx, allok;
  353. size_t size;
  354. data1 = tor_malloc(1024);
  355. data2 = tor_malloc(1024);
  356. data3 = tor_malloc(1024);
  357. test_assert(data1 && data2 && data3);
  358. /* Try out RNG. */
  359. test_assert(! crypto_seed_rng(0));
  360. crypto_rand(data1, 100);
  361. crypto_rand(data2, 100);
  362. test_memneq(data1,data2,100);
  363. allok = 1;
  364. for (i = 0; i < 100; ++i) {
  365. uint64_t big;
  366. char *host;
  367. j = crypto_rand_int(100);
  368. if (i < 0 || i >= 100)
  369. allok = 0;
  370. big = crypto_rand_uint64(U64_LITERAL(1)<<40);
  371. if (big >= (U64_LITERAL(1)<<40))
  372. allok = 0;
  373. big = crypto_rand_uint64(U64_LITERAL(5));
  374. if (big >= 5)
  375. allok = 0;
  376. host = crypto_random_hostname(3,8,"www.",".onion");
  377. if (strcmpstart(host,"www.") ||
  378. strcmpend(host,".onion") ||
  379. strlen(host) < 13 ||
  380. strlen(host) > 18)
  381. allok = 0;
  382. tor_free(host);
  383. }
  384. test_assert(allok);
  385. /* Now, test encryption and decryption with stream cipher. */
  386. data1[0]='\0';
  387. for (i = 1023; i>0; i -= 35)
  388. strncat(data1, "Now is the time for all good onions", i);
  389. memset(data2, 0, 1024);
  390. memset(data3, 0, 1024);
  391. env1 = crypto_new_cipher_env();
  392. test_neq(env1, 0);
  393. env2 = crypto_new_cipher_env();
  394. test_neq(env2, 0);
  395. j = crypto_cipher_generate_key(env1);
  396. crypto_cipher_set_key(env2, crypto_cipher_get_key(env1));
  397. crypto_cipher_encrypt_init_cipher(env1);
  398. crypto_cipher_decrypt_init_cipher(env2);
  399. /* Try encrypting 512 chars. */
  400. crypto_cipher_encrypt(env1, data2, data1, 512);
  401. crypto_cipher_decrypt(env2, data3, data2, 512);
  402. test_memeq(data1, data3, 512);
  403. test_memneq(data1, data2, 512);
  404. /* Now encrypt 1 at a time, and get 1 at a time. */
  405. for (j = 512; j < 560; ++j) {
  406. crypto_cipher_encrypt(env1, data2+j, data1+j, 1);
  407. }
  408. for (j = 512; j < 560; ++j) {
  409. crypto_cipher_decrypt(env2, data3+j, data2+j, 1);
  410. }
  411. test_memeq(data1, data3, 560);
  412. /* Now encrypt 3 at a time, and get 5 at a time. */
  413. for (j = 560; j < 1024-5; j += 3) {
  414. crypto_cipher_encrypt(env1, data2+j, data1+j, 3);
  415. }
  416. for (j = 560; j < 1024-5; j += 5) {
  417. crypto_cipher_decrypt(env2, data3+j, data2+j, 5);
  418. }
  419. test_memeq(data1, data3, 1024-5);
  420. /* Now make sure that when we encrypt with different chunk sizes, we get
  421. the same results. */
  422. crypto_free_cipher_env(env2);
  423. memset(data3, 0, 1024);
  424. env2 = crypto_new_cipher_env();
  425. test_neq(env2, 0);
  426. crypto_cipher_set_key(env2, crypto_cipher_get_key(env1));
  427. crypto_cipher_encrypt_init_cipher(env2);
  428. for (j = 0; j < 1024-16; j += 17) {
  429. crypto_cipher_encrypt(env2, data3+j, data1+j, 17);
  430. }
  431. for (j= 0; j < 1024-16; ++j) {
  432. if (data2[j] != data3[j]) {
  433. printf("%d: %d\t%d\n", j, (int) data2[j], (int) data3[j]);
  434. }
  435. }
  436. test_memeq(data2, data3, 1024-16);
  437. crypto_free_cipher_env(env1);
  438. crypto_free_cipher_env(env2);
  439. /* NIST test vector for aes. */
  440. env1 = crypto_new_cipher_env(); /* IV starts at 0 */
  441. crypto_cipher_set_key(env1, "\x80\x00\x00\x00\x00\x00\x00\x00"
  442. "\x00\x00\x00\x00\x00\x00\x00\x00");
  443. crypto_cipher_encrypt_init_cipher(env1);
  444. crypto_cipher_encrypt(env1, data1,
  445. "\x00\x00\x00\x00\x00\x00\x00\x00"
  446. "\x00\x00\x00\x00\x00\x00\x00\x00", 16);
  447. test_memeq_hex(data1, "0EDD33D3C621E546455BD8BA1418BEC8");
  448. /* Now test rollover. All these values are originally from a python
  449. * script. */
  450. crypto_cipher_set_iv(env1, "\x00\x00\x00\x00\x00\x00\x00\x00"
  451. "\xff\xff\xff\xff\xff\xff\xff\xff");
  452. memset(data2, 0, 1024);
  453. crypto_cipher_encrypt(env1, data1, data2, 32);
  454. test_memeq_hex(data1, "335fe6da56f843199066c14a00a40231"
  455. "cdd0b917dbc7186908a6bfb5ffd574d3");
  456. crypto_cipher_set_iv(env1, "\x00\x00\x00\x00\xff\xff\xff\xff"
  457. "\xff\xff\xff\xff\xff\xff\xff\xff");
  458. memset(data2, 0, 1024);
  459. crypto_cipher_encrypt(env1, data1, data2, 32);
  460. test_memeq_hex(data1, "e627c6423fa2d77832a02b2794094b73"
  461. "3e63c721df790d2c6469cc1953a3ffac");
  462. crypto_cipher_set_iv(env1, "\xff\xff\xff\xff\xff\xff\xff\xff"
  463. "\xff\xff\xff\xff\xff\xff\xff\xff");
  464. memset(data2, 0, 1024);
  465. crypto_cipher_encrypt(env1, data1, data2, 32);
  466. test_memeq_hex(data1, "2aed2bff0de54f9328efd070bf48f70a"
  467. "0EDD33D3C621E546455BD8BA1418BEC8");
  468. /* Now check rollover on inplace cipher. */
  469. crypto_cipher_set_iv(env1, "\xff\xff\xff\xff\xff\xff\xff\xff"
  470. "\xff\xff\xff\xff\xff\xff\xff\xff");
  471. crypto_cipher_crypt_inplace(env1, data2, 64);
  472. test_memeq_hex(data2, "2aed2bff0de54f9328efd070bf48f70a"
  473. "0EDD33D3C621E546455BD8BA1418BEC8"
  474. "93e2c5243d6839eac58503919192f7ae"
  475. "1908e67cafa08d508816659c2e693191");
  476. crypto_cipher_set_iv(env1, "\xff\xff\xff\xff\xff\xff\xff\xff"
  477. "\xff\xff\xff\xff\xff\xff\xff\xff");
  478. crypto_cipher_crypt_inplace(env1, data2, 64);
  479. test_assert(tor_mem_is_zero(data2, 64));
  480. crypto_free_cipher_env(env1);
  481. /* Test SHA-1 with a test vector from the specification. */
  482. i = crypto_digest(data1, "abc", 3);
  483. test_memeq_hex(data1, "A9993E364706816ABA3E25717850C26C9CD0D89D");
  484. /* Test HMAC-SHA-1 with test cases from RFC2202. */
  485. {
  486. char key[80];
  487. char digest[20];
  488. char data[50];
  489. /* Case 1. */
  490. memset(key, 0x0b, 20);
  491. crypto_hmac_sha1(digest, key, 20, "Hi There", 8);
  492. test_streq(hex_str(digest, 20),
  493. "B617318655057264E28BC0B6FB378C8EF146BE00");
  494. /* Case 2. */
  495. crypto_hmac_sha1(digest, "Jefe", 4, "what do ya want for nothing?", 28);
  496. test_streq(hex_str(digest, 20),
  497. "EFFCDF6AE5EB2FA2D27416D5F184DF9C259A7C79");
  498. /* Case 4. */
  499. base16_decode(key, 25,
  500. "0102030405060708090a0b0c0d0e0f10111213141516171819", 50);
  501. memset(data, 0xcd, 50);
  502. crypto_hmac_sha1(digest, key, 25, data, 50);
  503. test_streq(hex_str(digest, 20),
  504. "4C9007F4026250C6BC8414F9BF50C86C2D7235DA");
  505. /* Case . */
  506. memset(key, 0xaa, 80);
  507. crypto_hmac_sha1(digest, key, 80,
  508. "Test Using Larger Than Block-Size Key - Hash Key First",
  509. 54);
  510. test_streq(hex_str(digest, 20),
  511. "AA4AE5E15272D00E95705637CE8A3B55ED402112");
  512. }
  513. /* Public-key ciphers */
  514. pk1 = pk_generate(0);
  515. pk2 = crypto_new_pk_env();
  516. test_assert(pk1 && pk2);
  517. test_assert(! crypto_pk_write_public_key_to_string(pk1, &cp, &size));
  518. test_assert(! crypto_pk_read_public_key_from_string(pk2, cp, size));
  519. test_eq(0, crypto_pk_cmp_keys(pk1, pk2));
  520. tor_free(cp);
  521. test_eq(128, crypto_pk_keysize(pk1));
  522. test_eq(128, crypto_pk_keysize(pk2));
  523. test_eq(128, crypto_pk_public_encrypt(pk2, data1, "Hello whirled.", 15,
  524. PK_PKCS1_OAEP_PADDING));
  525. test_eq(128, crypto_pk_public_encrypt(pk1, data2, "Hello whirled.", 15,
  526. PK_PKCS1_OAEP_PADDING));
  527. /* oaep padding should make encryption not match */
  528. test_memneq(data1, data2, 128);
  529. test_eq(15, crypto_pk_private_decrypt(pk1, data3, data1, 128,
  530. PK_PKCS1_OAEP_PADDING,1));
  531. test_streq(data3, "Hello whirled.");
  532. memset(data3, 0, 1024);
  533. test_eq(15, crypto_pk_private_decrypt(pk1, data3, data2, 128,
  534. PK_PKCS1_OAEP_PADDING,1));
  535. test_streq(data3, "Hello whirled.");
  536. /* Can't decrypt with public key. */
  537. test_eq(-1, crypto_pk_private_decrypt(pk2, data3, data2, 128,
  538. PK_PKCS1_OAEP_PADDING,1));
  539. /* Try again with bad padding */
  540. memcpy(data2+1, "XYZZY", 5); /* This has fails ~ once-in-2^40 */
  541. test_eq(-1, crypto_pk_private_decrypt(pk1, data3, data2, 128,
  542. PK_PKCS1_OAEP_PADDING,1));
  543. /* File operations: save and load private key */
  544. test_assert(! crypto_pk_write_private_key_to_filename(pk1,
  545. get_fname("pkey1")));
  546. /* failing case for read: can't read. */
  547. test_assert(crypto_pk_read_private_key_from_filename(pk2,
  548. get_fname("xyzzy")) < 0);
  549. write_str_to_file(get_fname("xyzzy"), "foobar", 6);
  550. /* Failing case for read: no key. */
  551. test_assert(crypto_pk_read_private_key_from_filename(pk2,
  552. get_fname("xyzzy")) < 0);
  553. test_assert(! crypto_pk_read_private_key_from_filename(pk2,
  554. get_fname("pkey1")));
  555. test_eq(15, crypto_pk_private_decrypt(pk2, data3, data1, 128,
  556. PK_PKCS1_OAEP_PADDING,1));
  557. /* Now try signing. */
  558. strlcpy(data1, "Ossifrage", 1024);
  559. test_eq(128, crypto_pk_private_sign(pk1, data2, data1, 10));
  560. test_eq(10, crypto_pk_public_checksig(pk1, data3, data2, 128));
  561. test_streq(data3, "Ossifrage");
  562. /* Try signing digests. */
  563. test_eq(128, crypto_pk_private_sign_digest(pk1, data2, data1, 10));
  564. test_eq(20, crypto_pk_public_checksig(pk1, data3, data2, 128));
  565. test_eq(0, crypto_pk_public_checksig_digest(pk1, data1, 10, data2, 128));
  566. test_eq(-1, crypto_pk_public_checksig_digest(pk1, data1, 11, data2, 128));
  567. /*XXXX test failed signing*/
  568. /* Try encoding */
  569. crypto_free_pk_env(pk2);
  570. pk2 = NULL;
  571. i = crypto_pk_asn1_encode(pk1, data1, 1024);
  572. test_assert(i>0);
  573. pk2 = crypto_pk_asn1_decode(data1, i);
  574. test_assert(crypto_pk_cmp_keys(pk1,pk2) == 0);
  575. /* Try with hybrid encryption wrappers. */
  576. crypto_rand(data1, 1024);
  577. for (i = 0; i < 3; ++i) {
  578. for (j = 85; j < 140; ++j) {
  579. memset(data2,0,1024);
  580. memset(data3,0,1024);
  581. if (i == 0 && j < 129)
  582. continue;
  583. p = (i==0)?PK_NO_PADDING:
  584. (i==1)?PK_PKCS1_PADDING:PK_PKCS1_OAEP_PADDING;
  585. len = crypto_pk_public_hybrid_encrypt(pk1,data2,data1,j,p,0);
  586. test_assert(len>=0);
  587. len = crypto_pk_private_hybrid_decrypt(pk1,data3,data2,len,p,1);
  588. test_eq(len,j);
  589. test_memeq(data1,data3,j);
  590. }
  591. }
  592. crypto_free_pk_env(pk1);
  593. crypto_free_pk_env(pk2);
  594. /* Base64 tests */
  595. memset(data1, 6, 1024);
  596. for (idx = 0; idx < 10; ++idx) {
  597. i = base64_encode(data2, 1024, data1, idx);
  598. j = base64_decode(data3, 1024, data2, i);
  599. test_eq(j,idx);
  600. test_memeq(data3, data1, idx);
  601. }
  602. strlcpy(data1, "Test string that contains 35 chars.", 1024);
  603. strlcat(data1, " 2nd string that contains 35 chars.", 1024);
  604. i = base64_encode(data2, 1024, data1, 71);
  605. j = base64_decode(data3, 1024, data2, i);
  606. test_eq(j, 71);
  607. test_streq(data3, data1);
  608. test_assert(data2[i] == '\0');
  609. crypto_rand(data1, DIGEST_LEN);
  610. memset(data2, 100, 1024);
  611. digest_to_base64(data2, data1);
  612. test_eq(BASE64_DIGEST_LEN, strlen(data2));
  613. test_eq(100, data2[BASE64_DIGEST_LEN+2]);
  614. memset(data3, 99, 1024);
  615. test_eq(digest_from_base64(data3, data2), 0);
  616. test_memeq(data1, data3, DIGEST_LEN);
  617. test_eq(99, data3[DIGEST_LEN+1]);
  618. test_assert(digest_from_base64(data3, "###") < 0);
  619. /* Base32 tests */
  620. strlcpy(data1, "5chrs", 1024);
  621. /* bit pattern is: [35 63 68 72 73] ->
  622. * [00110101 01100011 01101000 01110010 01110011]
  623. * By 5s: [00110 10101 10001 10110 10000 11100 10011 10011]
  624. */
  625. base32_encode(data2, 9, data1, 5);
  626. test_streq(data2, "gvrwq4tt");
  627. strlcpy(data1, "\xFF\xF5\x6D\x44\xAE\x0D\x5C\xC9\x62\xC4", 1024);
  628. base32_encode(data2, 30, data1, 10);
  629. test_streq(data2, "772w2rfobvomsywe");
  630. /* Base16 tests */
  631. strlcpy(data1, "6chrs\xff", 1024);
  632. base16_encode(data2, 13, data1, 6);
  633. test_streq(data2, "3663687273FF");
  634. strlcpy(data1, "f0d678affc000100", 1024);
  635. i = base16_decode(data2, 8, data1, 16);
  636. test_eq(i,0);
  637. test_memeq(data2, "\xf0\xd6\x78\xaf\xfc\x00\x01\x00",8);
  638. /* now try some failing base16 decodes */
  639. test_eq(-1, base16_decode(data2, 8, data1, 15)); /* odd input len */
  640. test_eq(-1, base16_decode(data2, 7, data1, 16)); /* dest too short */
  641. strlcpy(data1, "f0dz!8affc000100", 1024);
  642. test_eq(-1, base16_decode(data2, 8, data1, 16));
  643. tor_free(data1);
  644. tor_free(data2);
  645. tor_free(data3);
  646. /* Add spaces to fingerprint */
  647. {
  648. data1 = tor_strdup("ABCD1234ABCD56780000ABCD1234ABCD56780000");
  649. test_eq(strlen(data1), 40);
  650. data2 = tor_malloc(FINGERPRINT_LEN+1);
  651. add_spaces_to_fp(data2, FINGERPRINT_LEN+1, data1);
  652. test_streq(data2, "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000");
  653. tor_free(data1);
  654. tor_free(data2);
  655. }
  656. /* Check fingerprint */
  657. {
  658. test_assert(crypto_pk_check_fingerprint_syntax(
  659. "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000"));
  660. test_assert(!crypto_pk_check_fingerprint_syntax(
  661. "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 000"));
  662. test_assert(!crypto_pk_check_fingerprint_syntax(
  663. "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 00000"));
  664. test_assert(!crypto_pk_check_fingerprint_syntax(
  665. "ABCD 1234 ABCD 5678 0000 ABCD1234 ABCD 5678 0000"));
  666. test_assert(!crypto_pk_check_fingerprint_syntax(
  667. "ABCD 1234 ABCD 5678 0000 ABCD1234 ABCD 5678 00000"));
  668. test_assert(!crypto_pk_check_fingerprint_syntax(
  669. "ACD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 00000"));
  670. }
  671. /* Incremental digest code. */
  672. {
  673. crypto_digest_env_t *d1, *d2;
  674. char d_out1[DIGEST_LEN], d_out2[DIGEST_LEN];
  675. d1 = crypto_new_digest_env();
  676. test_assert(d1);
  677. crypto_digest_add_bytes(d1, "abcdef", 6);
  678. d2 = crypto_digest_dup(d1);
  679. test_assert(d2);
  680. crypto_digest_add_bytes(d2, "ghijkl", 6);
  681. crypto_digest_get_digest(d2, d_out1, sizeof(d_out1));
  682. crypto_digest(d_out2, "abcdefghijkl", 12);
  683. test_memeq(d_out1, d_out2, DIGEST_LEN);
  684. crypto_digest_assign(d2, d1);
  685. crypto_digest_add_bytes(d2, "mno", 3);
  686. crypto_digest_get_digest(d2, d_out1, sizeof(d_out1));
  687. crypto_digest(d_out2, "abcdefmno", 9);
  688. test_memeq(d_out1, d_out2, DIGEST_LEN);
  689. crypto_digest_get_digest(d1, d_out1, sizeof(d_out1));
  690. crypto_digest(d_out2, "abcdef", 6);
  691. test_memeq(d_out1, d_out2, DIGEST_LEN);
  692. }
  693. }
  694. static void
  695. test_crypto_s2k(void)
  696. {
  697. char buf[29];
  698. char buf2[29];
  699. char *buf3;
  700. int i;
  701. memset(buf, 0, sizeof(buf));
  702. memset(buf2, 0, sizeof(buf2));
  703. buf3 = tor_malloc(65536);
  704. memset(buf3, 0, 65536);
  705. secret_to_key(buf+9, 20, "", 0, buf);
  706. crypto_digest(buf2+9, buf3, 1024);
  707. test_memeq(buf, buf2, 29);
  708. memcpy(buf,"vrbacrda",8);
  709. memcpy(buf2,"vrbacrda",8);
  710. buf[8] = 96;
  711. buf2[8] = 96;
  712. secret_to_key(buf+9, 20, "12345678", 8, buf);
  713. for (i = 0; i < 65536; i += 16) {
  714. memcpy(buf3+i, "vrbacrda12345678", 16);
  715. }
  716. crypto_digest(buf2+9, buf3, 65536);
  717. test_memeq(buf, buf2, 29);
  718. tor_free(buf3);
  719. }
  720. static int
  721. _compare_strs(const void **a, const void **b)
  722. {
  723. const char *s1 = *a, *s2 = *b;
  724. return strcmp(s1, s2);
  725. }
  726. static int
  727. _compare_without_first_ch(const void *a, const void **b)
  728. {
  729. const char *s1 = a, *s2 = *b;
  730. return strcasecmp(s1+1, s2);
  731. }
  732. static void
  733. test_util(void)
  734. {
  735. struct timeval start, end;
  736. struct tm a_time;
  737. char timestr[RFC1123_TIME_LEN+1];
  738. char buf[1024];
  739. time_t t_res;
  740. int i;
  741. uint32_t u32;
  742. uint16_t u16;
  743. char *cp, *k, *v;
  744. const char *str;
  745. start.tv_sec = 5;
  746. start.tv_usec = 5000;
  747. end.tv_sec = 5;
  748. end.tv_usec = 5000;
  749. test_eq(0L, tv_udiff(&start, &end));
  750. end.tv_usec = 7000;
  751. test_eq(2000L, tv_udiff(&start, &end));
  752. end.tv_sec = 6;
  753. test_eq(1002000L, tv_udiff(&start, &end));
  754. end.tv_usec = 0;
  755. test_eq(995000L, tv_udiff(&start, &end));
  756. end.tv_sec = 4;
  757. test_eq(-1005000L, tv_udiff(&start, &end));
  758. end.tv_usec = 999990;
  759. start.tv_sec = 1;
  760. start.tv_usec = 500;
  761. /* The test values here are confirmed to be correct on a platform
  762. * with a working timegm. */
  763. a_time.tm_year = 2003-1900;
  764. a_time.tm_mon = 7;
  765. a_time.tm_mday = 30;
  766. a_time.tm_hour = 6;
  767. a_time.tm_min = 14;
  768. a_time.tm_sec = 55;
  769. test_eq((time_t) 1062224095UL, tor_timegm(&a_time));
  770. a_time.tm_year = 2004-1900; /* Try a leap year, after feb. */
  771. test_eq((time_t) 1093846495UL, tor_timegm(&a_time));
  772. a_time.tm_mon = 1; /* Try a leap year, in feb. */
  773. a_time.tm_mday = 10;
  774. test_eq((time_t) 1076393695UL, tor_timegm(&a_time));
  775. format_rfc1123_time(timestr, 0);
  776. test_streq("Thu, 01 Jan 1970 00:00:00 GMT", timestr);
  777. format_rfc1123_time(timestr, (time_t)1091580502UL);
  778. test_streq("Wed, 04 Aug 2004 00:48:22 GMT", timestr);
  779. t_res = 0;
  780. i = parse_rfc1123_time(timestr, &t_res);
  781. test_eq(i,0);
  782. test_eq(t_res, (time_t)1091580502UL);
  783. test_eq(-1, parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res));
  784. tor_gettimeofday(&start);
  785. /* Tests for corner cases of strl operations */
  786. test_eq(5, strlcpy(buf, "Hello", 0));
  787. strlcpy(buf, "Hello", sizeof(buf));
  788. test_eq(10, strlcat(buf, "Hello", 5));
  789. /* Test tor_strstrip() */
  790. strlcpy(buf, "Testing 1 2 3", sizeof(buf));
  791. tor_strstrip(buf, ",!");
  792. test_streq(buf, "Testing 1 2 3");
  793. strlcpy(buf, "!Testing 1 2 3?", sizeof(buf));
  794. tor_strstrip(buf, "!? ");
  795. test_streq(buf, "Testing123");
  796. /* Test parse_addr_port */
  797. cp = NULL; u32 = 3; u16 = 3;
  798. test_assert(!parse_addr_port(LOG_WARN, "1.2.3.4", &cp, &u32, &u16));
  799. test_streq(cp, "1.2.3.4");
  800. test_eq(u32, 0x01020304u);
  801. test_eq(u16, 0);
  802. tor_free(cp);
  803. test_assert(!parse_addr_port(LOG_WARN, "4.3.2.1:99", &cp, &u32, &u16));
  804. test_streq(cp, "4.3.2.1");
  805. test_eq(u32, 0x04030201u);
  806. test_eq(u16, 99);
  807. tor_free(cp);
  808. test_assert(!parse_addr_port(LOG_WARN, "nonexistent.address:4040",
  809. &cp, NULL, &u16));
  810. test_streq(cp, "nonexistent.address");
  811. test_eq(u16, 4040);
  812. tor_free(cp);
  813. test_assert(!parse_addr_port(LOG_WARN, "localhost:9999", &cp, &u32, &u16));
  814. test_streq(cp, "localhost");
  815. test_eq(u32, 0x7f000001u);
  816. test_eq(u16, 9999);
  817. tor_free(cp);
  818. u32 = 3;
  819. test_assert(!parse_addr_port(LOG_WARN, "localhost", NULL, &u32, &u16));
  820. test_eq(cp, NULL);
  821. test_eq(u32, 0x7f000001u);
  822. test_eq(u16, 0);
  823. tor_free(cp);
  824. test_eq(0, addr_mask_get_bits(0x0u));
  825. test_eq(32, addr_mask_get_bits(0xFFFFFFFFu));
  826. test_eq(16, addr_mask_get_bits(0xFFFF0000u));
  827. test_eq(31, addr_mask_get_bits(0xFFFFFFFEu));
  828. test_eq(1, addr_mask_get_bits(0x80000000u));
  829. /* Test tor_parse_long. */
  830. test_eq(10L, tor_parse_long("10",10,0,100,NULL,NULL));
  831. test_eq(0L, tor_parse_long("10",10,50,100,NULL,NULL));
  832. test_eq(-50L, tor_parse_long("-50",10,-100,100,NULL,NULL));
  833. /* Test tor_parse_ulong */
  834. test_eq(10UL, tor_parse_ulong("10",10,0,100,NULL,NULL));
  835. test_eq(0UL, tor_parse_ulong("10",10,50,100,NULL,NULL));
  836. /* Test tor_parse_uint64. */
  837. test_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i, &cp));
  838. test_assert(i == 1);
  839. test_streq(cp, " x");
  840. test_assert(U64_LITERAL(12345678901) ==
  841. tor_parse_uint64("12345678901",10,0,UINT64_MAX, &i, &cp));
  842. test_assert(i == 1);
  843. test_streq(cp, "");
  844. test_assert(U64_LITERAL(0) ==
  845. tor_parse_uint64("12345678901",10,500,INT32_MAX, &i, &cp));
  846. test_assert(i == 0);
  847. /* Test failing snprintf cases */
  848. test_eq(-1, tor_snprintf(buf, 0, "Foo"));
  849. test_eq(-1, tor_snprintf(buf, 2, "Foo"));
  850. /* Test printf with uint64 */
  851. tor_snprintf(buf, sizeof(buf), "x!"U64_FORMAT"!x",
  852. U64_PRINTF_ARG(U64_LITERAL(12345678901)));
  853. test_streq(buf, "x!12345678901!x");
  854. /* Test parse_config_line_from_str */
  855. strlcpy(buf, "k v\n" " key value with spaces \n" "keykey val\n"
  856. "k2\n"
  857. "k3 \n" "\n" " \n" "#comment\n"
  858. "k4#a\n" "k5#abc\n" "k6 val #with comment\n"
  859. "kseven \"a quoted 'string\"\n"
  860. "k8 \"a \\x71uoted\\n\\\"str\\\\ing\\t\\001\\01\\1\\\"\"\n"
  861. , sizeof(buf));
  862. str = buf;
  863. str = parse_config_line_from_str(str, &k, &v);
  864. test_streq(k, "k");
  865. test_streq(v, "v");
  866. tor_free(k); tor_free(v);
  867. test_assert(!strcmpstart(str, "key value with"));
  868. str = parse_config_line_from_str(str, &k, &v);
  869. test_streq(k, "key");
  870. test_streq(v, "value with spaces");
  871. tor_free(k); tor_free(v);
  872. test_assert(!strcmpstart(str, "keykey"));
  873. str = parse_config_line_from_str(str, &k, &v);
  874. test_streq(k, "keykey");
  875. test_streq(v, "val");
  876. tor_free(k); tor_free(v);
  877. test_assert(!strcmpstart(str, "k2\n"));
  878. str = parse_config_line_from_str(str, &k, &v);
  879. test_streq(k, "k2");
  880. test_streq(v, "");
  881. tor_free(k); tor_free(v);
  882. test_assert(!strcmpstart(str, "k3 \n"));
  883. str = parse_config_line_from_str(str, &k, &v);
  884. test_streq(k, "k3");
  885. test_streq(v, "");
  886. tor_free(k); tor_free(v);
  887. test_assert(!strcmpstart(str, "#comment"));
  888. str = parse_config_line_from_str(str, &k, &v);
  889. test_streq(k, "k4");
  890. test_streq(v, "");
  891. tor_free(k); tor_free(v);
  892. test_assert(!strcmpstart(str, "k5#abc"));
  893. str = parse_config_line_from_str(str, &k, &v);
  894. test_streq(k, "k5");
  895. test_streq(v, "");
  896. tor_free(k); tor_free(v);
  897. test_assert(!strcmpstart(str, "k6"));
  898. str = parse_config_line_from_str(str, &k, &v);
  899. test_streq(k, "k6");
  900. test_streq(v, "val");
  901. tor_free(k); tor_free(v);
  902. test_assert(!strcmpstart(str, "kseven"));
  903. str = parse_config_line_from_str(str, &k, &v);
  904. test_streq(k, "kseven");
  905. test_streq(v, "a quoted 'string");
  906. tor_free(k); tor_free(v);
  907. test_assert(!strcmpstart(str, "k8 "));
  908. str = parse_config_line_from_str(str, &k, &v);
  909. test_streq(k, "k8");
  910. test_streq(v, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
  911. tor_free(k); tor_free(v);
  912. test_streq(str, "");
  913. /* Test for strcmpstart and strcmpend. */
  914. test_assert(strcmpstart("abcdef", "abcdef")==0);
  915. test_assert(strcmpstart("abcdef", "abc")==0);
  916. test_assert(strcmpstart("abcdef", "abd")<0);
  917. test_assert(strcmpstart("abcdef", "abb")>0);
  918. test_assert(strcmpstart("ab", "abb")<0);
  919. test_assert(strcmpend("abcdef", "abcdef")==0);
  920. test_assert(strcmpend("abcdef", "def")==0);
  921. test_assert(strcmpend("abcdef", "deg")<0);
  922. test_assert(strcmpend("abcdef", "dee")>0);
  923. test_assert(strcmpend("ab", "abb")<0);
  924. test_assert(strcasecmpend("AbcDEF", "abcdef")==0);
  925. test_assert(strcasecmpend("abcdef", "dEF")==0);
  926. test_assert(strcasecmpend("abcDEf", "deg")<0);
  927. test_assert(strcasecmpend("abcdef", "DEE")>0);
  928. test_assert(strcasecmpend("ab", "abB")<0);
  929. /* Test mem_is_zero */
  930. memset(buf,0,128);
  931. buf[128] = 'x';
  932. test_assert(tor_digest_is_zero(buf));
  933. test_assert(tor_mem_is_zero(buf, 10));
  934. test_assert(tor_mem_is_zero(buf, 20));
  935. test_assert(tor_mem_is_zero(buf, 128));
  936. test_assert(!tor_mem_is_zero(buf, 129));
  937. buf[60] = (char)255;
  938. test_assert(!tor_mem_is_zero(buf, 128));
  939. buf[0] = (char)1;
  940. test_assert(!tor_mem_is_zero(buf, 10));
  941. /* Test inet_ntop */
  942. {
  943. char tmpbuf[TOR_ADDR_BUF_LEN];
  944. const char *ip = "176.192.208.224";
  945. struct in_addr in;
  946. tor_inet_pton(AF_INET, ip, &in);
  947. tor_inet_ntop(AF_INET, &in, tmpbuf, sizeof(tmpbuf));
  948. test_streq(tmpbuf, ip);
  949. }
  950. /* Test 'escaped' */
  951. test_streq("\"\"", escaped(""));
  952. test_streq("\"abcd\"", escaped("abcd"));
  953. test_streq("\"\\\\\\n\\r\\t\\\"\\'\"", escaped("\\\n\r\t\"\'"));
  954. test_streq("\"z\\001abc\\277d\"", escaped("z\001abc\277d"));
  955. test_assert(NULL == escaped(NULL));
  956. /* Test strndup and memdup */
  957. {
  958. const char *s = "abcdefghijklmnopqrstuvwxyz";
  959. cp = tor_strndup(s, 30);
  960. test_streq(cp, s); /* same string, */
  961. test_neq(cp, s); /* but different pointers. */
  962. tor_free(cp);
  963. cp = tor_strndup(s, 5);
  964. test_streq(cp, "abcde");
  965. tor_free(cp);
  966. s = "a\0b\0c\0d\0e\0";
  967. cp = tor_memdup(s,10);
  968. test_memeq(cp, s, 10); /* same ram, */
  969. test_neq(cp, s); /* but different pointers. */
  970. tor_free(cp);
  971. }
  972. /* Test str-foo functions */
  973. cp = tor_strdup("abcdef");
  974. test_assert(tor_strisnonupper(cp));
  975. cp[3] = 'D';
  976. test_assert(!tor_strisnonupper(cp));
  977. tor_strupper(cp);
  978. test_streq(cp, "ABCDEF");
  979. test_assert(tor_strisprint(cp));
  980. cp[3] = 3;
  981. test_assert(!tor_strisprint(cp));
  982. tor_free(cp);
  983. /* Test eat_whitespace. */
  984. {
  985. const char *s = " \n a";
  986. test_eq_ptr(eat_whitespace(s), s+4);
  987. s = "abcd";
  988. test_eq_ptr(eat_whitespace(s), s);
  989. s = "#xyz\nab";
  990. test_eq_ptr(eat_whitespace(s), s+5);
  991. }
  992. /* Test memmem and memstr */
  993. {
  994. const char *haystack = "abcde";
  995. tor_assert(!tor_memmem(haystack, 5, "ef", 2));
  996. test_eq_ptr(tor_memmem(haystack, 5, "cd", 2), haystack + 2);
  997. test_eq_ptr(tor_memmem(haystack, 5, "cde", 3), haystack + 2);
  998. haystack = "ababcad";
  999. test_eq_ptr(tor_memmem(haystack, 7, "abc", 3), haystack + 2);
  1000. test_eq_ptr(tor_memstr(haystack, 7, "abc"), haystack + 2);
  1001. test_assert(!tor_memstr(haystack, 7, "fe"));
  1002. test_assert(!tor_memstr(haystack, 7, "longerthantheoriginal"));
  1003. }
  1004. /* Test wrap_string */
  1005. {
  1006. smartlist_t *sl = smartlist_create();
  1007. wrap_string(sl, "This is a test of string wrapping functionality: woot.",
  1008. 10, "", "");
  1009. cp = smartlist_join_strings(sl, "", 0, NULL);
  1010. test_streq(cp,
  1011. "This is a\ntest of\nstring\nwrapping\nfunctional\nity: woot.\n");
  1012. tor_free(cp);
  1013. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1014. smartlist_clear(sl);
  1015. wrap_string(sl, "This is a test of string wrapping functionality: woot.",
  1016. 16, "### ", "# ");
  1017. cp = smartlist_join_strings(sl, "", 0, NULL);
  1018. test_streq(cp,
  1019. "### This is a\n# test of string\n# wrapping\n# functionality:\n"
  1020. "# woot.\n");
  1021. tor_free(cp);
  1022. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1023. smartlist_free(sl);
  1024. }
  1025. /* now make sure time works. */
  1026. tor_gettimeofday(&end);
  1027. /* We might've timewarped a little. */
  1028. test_assert(tv_udiff(&start, &end) >= -5000);
  1029. /* Test tor_log2(). */
  1030. test_eq(tor_log2(64), 6);
  1031. test_eq(tor_log2(65), 6);
  1032. test_eq(tor_log2(63), 5);
  1033. test_eq(tor_log2(1), 0);
  1034. test_eq(tor_log2(2), 1);
  1035. test_eq(tor_log2(3), 1);
  1036. test_eq(tor_log2(4), 2);
  1037. test_eq(tor_log2(5), 2);
  1038. test_eq(tor_log2(U64_LITERAL(40000000000000000)), 55);
  1039. test_eq(tor_log2(UINT64_MAX), 63);
  1040. /* Test round_to_power_of_2 */
  1041. test_eq(round_to_power_of_2(120), 128);
  1042. test_eq(round_to_power_of_2(128), 128);
  1043. test_eq(round_to_power_of_2(130), 128);
  1044. test_eq(round_to_power_of_2(U64_LITERAL(40000000000000000)),
  1045. U64_LITERAL(1)<<55);
  1046. test_eq(round_to_power_of_2(0), 2);
  1047. }
  1048. /** Helper: assert that IPv6 addresses <b>a</b> and <b>b</b> are the same. On
  1049. * failure, reports an error, describing the addresses as <b>e1</b> and
  1050. * <b>e2</b>, and reporting the line number as <b>line</b>. */
  1051. static void
  1052. _test_eq_ip6(struct in6_addr *a, struct in6_addr *b, const char *e1,
  1053. const char *e2, int line)
  1054. {
  1055. int i;
  1056. int ok = 1;
  1057. for (i = 0; i < 16; ++i) {
  1058. if (a->s6_addr[i] != b->s6_addr[i]) {
  1059. ok = 0;
  1060. break;
  1061. }
  1062. }
  1063. if (ok) {
  1064. printf("."); fflush(stdout);
  1065. } else {
  1066. char buf1[128], *cp1;
  1067. char buf2[128], *cp2;
  1068. have_failed = 1;
  1069. cp1 = buf1; cp2 = buf2;
  1070. for (i=0; i<16; ++i) {
  1071. tor_snprintf(cp1, sizeof(buf1)-(cp1-buf1), "%02x", a->s6_addr[i]);
  1072. tor_snprintf(cp2, sizeof(buf2)-(cp2-buf2), "%02x", b->s6_addr[i]);
  1073. cp1 += 2; cp2 += 2;
  1074. if ((i%2)==1 && i != 15) {
  1075. *cp1++ = ':';
  1076. *cp2++ = ':';
  1077. }
  1078. }
  1079. *cp1 = *cp2 = '\0';
  1080. printf("Line %d: assertion failed: (%s == %s)\n"
  1081. " %s != %s\n", line, e1, e2, buf1, buf2);
  1082. fflush(stdout);
  1083. }
  1084. }
  1085. /** Helper: Assert that two strings both decode as IPv6 addresses with
  1086. * tor_inet_pton(), and both decode to the same address. */
  1087. #define test_pton6_same(a,b) STMT_BEGIN \
  1088. test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
  1089. test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
  1090. _test_eq_ip6(&a1,&a2,#a,#b,__LINE__); \
  1091. STMT_END
  1092. /** Helper: Assert that <b>a</b> is recognized as a bad IPv6 address by
  1093. * tor_inet_pton(). */
  1094. #define test_pton6_bad(a) \
  1095. test_eq(0, tor_inet_pton(AF_INET6, a, &a1))
  1096. /** Helper: assert that <b>a</b>, when parsed by tor_inet_pton() and displayed
  1097. * with tor_inet_ntop(), yields <b>b</b>. Also assert that <b>b</b> parses to
  1098. * the same value as <b>a</b>. */
  1099. #define test_ntop6_reduces(a,b) STMT_BEGIN \
  1100. test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
  1101. test_streq(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)), b); \
  1102. test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
  1103. _test_eq_ip6(&a1, &a2, a, b, __LINE__); \
  1104. STMT_END
  1105. /** Helper: assert that <b>a</a> parses by tor_inet_pton() into a address that
  1106. * passes tor_addr_is_internal() with <b>for_listening</b> */
  1107. #define test_internal_ip(a,for_listening) STMT_BEGIN \
  1108. test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
  1109. t1.family = AF_INET6; \
  1110. if (!tor_addr_is_internal(&t1, for_listening)) \
  1111. test_fail_msg( a "was not internal."); \
  1112. STMT_END
  1113. /** Helper: assert that <b>a</a> parses by tor_inet_pton() into a address that
  1114. * does not pass tor_addr_is_internal() with <b>for_listening</b>. */
  1115. #define test_external_ip(a,for_listening) STMT_BEGIN \
  1116. test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
  1117. t1.family = AF_INET6; \
  1118. if (tor_addr_is_internal(&t1, for_listening)) \
  1119. test_fail_msg(a "was not external."); \
  1120. STMT_END
  1121. /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
  1122. * tor_inet_pton(), give addresses that compare in the order defined by
  1123. * <b>op</b> with tor_addr_compare(). */
  1124. #define test_addr_compare(a, op, b) STMT_BEGIN \
  1125. test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
  1126. test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
  1127. t1.family = t2.family = AF_INET6; \
  1128. r = tor_addr_compare(&t1,&t2); \
  1129. if (!(r op 0)) \
  1130. test_fail_msg("failed: tor_addr_compare("a","b") "#op" 0"); \
  1131. STMT_END
  1132. /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
  1133. * tor_inet_pton(), give addresses that compare in the order defined by
  1134. * <b>op</b> with tor_addr_compare_masked() with <b>m</b> masked. */
  1135. #define test_addr_compare_masked(a, op, b, m) STMT_BEGIN \
  1136. test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
  1137. test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
  1138. t1.family = t2.family = AF_INET6; \
  1139. r = tor_addr_compare_masked(&t1,&t2,m); \
  1140. if (!(r op 0)) \
  1141. test_fail_msg("failed: tor_addr_compare_masked("a","b","#m") "#op" 0"); \
  1142. STMT_END
  1143. /** Helper: assert that <b>xx</b> is parseable as a masked IPv6 address with
  1144. * ports by <b>tor_parse_mask_addr_ports(), with family <b>f</b>, IP address
  1145. * as 4 32-bit words <b>ip1...ip4</b>, mask bits as <b>mm</b>, and port range
  1146. * as <b>pt1..pt2</b>. */
  1147. #define test_addr_mask_ports_parse(xx, f, ip1, ip2, ip3, ip4, mm, pt1, pt2) \
  1148. STMT_BEGIN \
  1149. test_eq(tor_addr_parse_mask_ports(xx, &t1, &mask, &port1, &port2), f); \
  1150. p1=tor_inet_ntop(AF_INET6, &t1.addr.in6_addr, bug, sizeof(bug)); \
  1151. test_eq(htonl(ip1), IN6_ADDRESS32(&t1)[0]); \
  1152. test_eq(htonl(ip2), IN6_ADDRESS32(&t1)[1]); \
  1153. test_eq(htonl(ip3), IN6_ADDRESS32(&t1)[2]); \
  1154. test_eq(htonl(ip4), IN6_ADDRESS32(&t1)[3]); \
  1155. test_eq(mask, mm); \
  1156. test_eq(port1, pt1); \
  1157. test_eq(port2, pt2); \
  1158. STMT_END
  1159. static void
  1160. test_util_ip6_helpers(void)
  1161. {
  1162. char buf[TOR_ADDR_BUF_LEN], bug[TOR_ADDR_BUF_LEN];
  1163. struct in6_addr a1, a2;
  1164. tor_addr_t t1, t2;
  1165. int r, i;
  1166. uint16_t port1, port2;
  1167. maskbits_t mask;
  1168. const char *p1;
  1169. // struct in_addr b1, b2;
  1170. /* Test tor_inet_ntop and tor_inet_pton: IPv6 */
  1171. /* === Test pton: valid af_inet6 */
  1172. /* Simple, valid parsing. */
  1173. r = tor_inet_pton(AF_INET6,
  1174. "0102:0304:0506:0708:090A:0B0C:0D0E:0F10", &a1);
  1175. test_assert(r==1);
  1176. for (i=0;i<16;++i) { test_eq(i+1, (int)a1.s6_addr[i]); }
  1177. /* ipv4 ending. */
  1178. test_pton6_same("0102:0304:0506:0708:090A:0B0C:0D0E:0F10",
  1179. "0102:0304:0506:0708:090A:0B0C:13.14.15.16");
  1180. /* shortened words. */
  1181. test_pton6_same("0001:0099:BEEF:0000:0123:FFFF:0001:0001",
  1182. "1:99:BEEF:0:0123:FFFF:1:1");
  1183. /* zeros at the beginning */
  1184. test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
  1185. "::9:c0a8:1:1");
  1186. test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
  1187. "::9:c0a8:0.1.0.1");
  1188. /* zeros in the middle. */
  1189. test_pton6_same("fe80:0000:0000:0000:0202:1111:0001:0001",
  1190. "fe80::202:1111:1:1");
  1191. /* zeros at the end. */
  1192. test_pton6_same("1000:0001:0000:0007:0000:0000:0000:0000",
  1193. "1000:1:0:7::");
  1194. /* === Test ntop: af_inet6 */
  1195. test_ntop6_reduces("0:0:0:0:0:0:0:0", "::");
  1196. test_ntop6_reduces("0001:0099:BEEF:0006:0123:FFFF:0001:0001",
  1197. "1:99:beef:6:123:ffff:1:1");
  1198. //test_ntop6_reduces("0:0:0:0:0:0:c0a8:0101", "::192.168.1.1");
  1199. test_ntop6_reduces("0:0:0:0:0:ffff:c0a8:0101", "::ffff:192.168.1.1");
  1200. test_ntop6_reduces("002:0:0000:0:3::4", "2::3:0:0:4");
  1201. test_ntop6_reduces("0:0::1:0:3", "::1:0:3");
  1202. test_ntop6_reduces("008:0::0", "8::");
  1203. test_ntop6_reduces("0:0:0:0:0:ffff::1", "::ffff:0.0.0.1");
  1204. test_ntop6_reduces("abcd:0:0:0:0:0:7f00::", "abcd::7f00:0");
  1205. test_ntop6_reduces("0000:0000:0000:0000:0009:C0A8:0001:0001",
  1206. "::9:c0a8:1:1");
  1207. test_ntop6_reduces("fe80:0000:0000:0000:0202:1111:0001:0001",
  1208. "fe80::202:1111:1:1");
  1209. test_ntop6_reduces("1000:0001:0000:0007:0000:0000:0000:0000",
  1210. "1000:1:0:7::");
  1211. /* === Test pton: invalid in6. */
  1212. test_pton6_bad("foobar.");
  1213. test_pton6_bad("55555::");
  1214. test_pton6_bad("9:-60::");
  1215. test_pton6_bad("1:2:33333:4:0002:3::");
  1216. //test_pton6_bad("1:2:3333:4:00002:3::");// BAD, but glibc doesn't say so.
  1217. test_pton6_bad("1:2:3333:4:fish:3::");
  1218. test_pton6_bad("1:2:3:4:5:6:7:8:9");
  1219. test_pton6_bad("1:2:3:4:5:6:7");
  1220. test_pton6_bad("1:2:3:4:5:6:1.2.3.4.5");
  1221. test_pton6_bad("1:2:3:4:5:6:1.2.3");
  1222. test_pton6_bad("::1.2.3");
  1223. test_pton6_bad("::1.2.3.4.5");
  1224. test_pton6_bad("99");
  1225. test_pton6_bad("");
  1226. test_pton6_bad("1::2::3:4");
  1227. test_pton6_bad("a:::b:c");
  1228. test_pton6_bad(":::a:b:c");
  1229. test_pton6_bad("a:b:c:::");
  1230. /* test internal checking */
  1231. test_external_ip("fbff:ffff::2:7", 0);
  1232. test_internal_ip("fc01::2:7", 0);
  1233. test_internal_ip("fdff:ffff::f:f", 0);
  1234. test_external_ip("fe00::3:f", 0);
  1235. test_external_ip("fe7f:ffff::2:7", 0);
  1236. test_internal_ip("fe80::2:7", 0);
  1237. test_internal_ip("febf:ffff::f:f", 0);
  1238. test_internal_ip("fec0::2:7:7", 0);
  1239. test_internal_ip("feff:ffff::e:7:7", 0);
  1240. test_external_ip("ff00::e:7:7", 0);
  1241. test_internal_ip("::", 0);
  1242. test_internal_ip("::1", 0);
  1243. test_internal_ip("::1", 1);
  1244. test_internal_ip("::", 0);
  1245. test_external_ip("::", 1);
  1246. test_external_ip("::2", 0);
  1247. test_external_ip("2001::", 0);
  1248. test_external_ip("ffff::", 0);
  1249. test_external_ip("::ffff:0.0.0.0", 1);
  1250. test_internal_ip("::ffff:0.0.0.0", 0);
  1251. test_internal_ip("::ffff:0.255.255.255", 0);
  1252. test_external_ip("::ffff:1.0.0.0", 0);
  1253. test_external_ip("::ffff:9.255.255.255", 0);
  1254. test_internal_ip("::ffff:10.0.0.0", 0);
  1255. test_internal_ip("::ffff:10.255.255.255", 0);
  1256. test_external_ip("::ffff:11.0.0.0", 0);
  1257. test_external_ip("::ffff:126.255.255.255", 0);
  1258. test_internal_ip("::ffff:127.0.0.0", 0);
  1259. test_internal_ip("::ffff:127.255.255.255", 0);
  1260. test_external_ip("::ffff:128.0.0.0", 0);
  1261. test_external_ip("::ffff:172.15.255.255", 0);
  1262. test_internal_ip("::ffff:172.16.0.0", 0);
  1263. test_internal_ip("::ffff:172.31.255.255", 0);
  1264. test_external_ip("::ffff:172.32.0.0", 0);
  1265. test_external_ip("::ffff:192.167.255.255", 0);
  1266. test_internal_ip("::ffff:192.168.0.0", 0);
  1267. test_internal_ip("::ffff:192.168.255.255", 0);
  1268. test_external_ip("::ffff:192.169.0.0", 0);
  1269. test_external_ip("::ffff:169.253.255.255", 0);
  1270. test_internal_ip("::ffff:169.254.0.0", 0);
  1271. test_internal_ip("::ffff:169.254.255.255", 0);
  1272. test_external_ip("::ffff:169.255.0.0", 0);
  1273. /* tor_addr_compare(tor_addr_t x2) */
  1274. test_addr_compare("ffff::", ==, "ffff::0");
  1275. test_addr_compare("0::3:2:1", >, "0::ffff:0.3.2.1");
  1276. test_addr_compare("0::2:2:1", >, "0::ffff:0.3.2.1");
  1277. test_addr_compare("0::ffff:0.3.2.1", <, "0::0:0:0");
  1278. test_addr_compare("0::ffff:5.2.2.1", <, "::ffff:6.0.0.0"); /* XXXX wrong. */
  1279. tor_addr_parse_mask_ports("[::ffff:2.3.4.5]", &t1, NULL, NULL, NULL);
  1280. tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
  1281. test_assert(tor_addr_compare(&t1, &t2) == 0);
  1282. tor_addr_parse_mask_ports("[::ffff:2.3.4.4]", &t1, NULL, NULL, NULL);
  1283. tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
  1284. test_assert(tor_addr_compare(&t1, &t2) < 0);
  1285. /* test compare_masked */
  1286. test_addr_compare_masked("ffff::", ==, "ffff::0", 128);
  1287. test_addr_compare_masked("ffff::", ==, "ffff::0", 64);
  1288. test_addr_compare_masked("0::2:2:1", <, "0::8000:2:1", 81);
  1289. test_addr_compare_masked("0::2:2:1", ==, "0::8000:2:1", 80);
  1290. /* test tor_addr_parse_mask_ports */
  1291. test_addr_mask_ports_parse("[::f]/17:47-95", AF_INET6,
  1292. 0, 0, 0, 0x0000000f, 17, 47, 95);
  1293. //test_addr_parse("[::fefe:4.1.1.7/120]:999-1000");
  1294. //test_addr_parse_check("::fefe:401:107", 120, 999, 1000);
  1295. test_addr_mask_ports_parse("[::ffff:4.1.1.7]/120:443", AF_INET6,
  1296. 0, 0, 0x0000ffff, 0x04010107, 120, 443, 443);
  1297. test_addr_mask_ports_parse("[abcd:2::44a:0]:2-65000", AF_INET6,
  1298. 0xabcd0002, 0, 0, 0x044a0000, 128, 2, 65000);
  1299. r=tor_addr_parse_mask_ports("[fefef::]/112", &t1, NULL, NULL, NULL);
  1300. test_assert(r == -1);
  1301. r=tor_addr_parse_mask_ports("efef::/112", &t1, NULL, NULL, NULL);
  1302. test_assert(r == -1);
  1303. r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f::]", &t1, NULL, NULL, NULL);
  1304. test_assert(r == -1);
  1305. r=tor_addr_parse_mask_ports("[::f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
  1306. test_assert(r == -1);
  1307. r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
  1308. test_assert(r == -1);
  1309. /* Test for V4-mapped address with mask < 96. (arguably not valid) */
  1310. r=tor_addr_parse_mask_ports("[::ffff:1.1.2.2/33]", &t1, &mask, NULL, NULL);
  1311. test_assert(r == -1);
  1312. r=tor_addr_parse_mask_ports("1.1.2.2/33", &t1, &mask, NULL, NULL);
  1313. test_assert(r == -1);
  1314. r=tor_addr_parse_mask_ports("1.1.2.2/31", &t1, &mask, NULL, NULL);
  1315. test_assert(r == AF_INET);
  1316. r=tor_addr_parse_mask_ports("[efef::]/112", &t1, &mask, &port1, &port2);
  1317. test_assert(r == AF_INET6);
  1318. test_assert(port1 == 1);
  1319. test_assert(port2 == 65535);
  1320. /* make sure inet address lengths >= max */
  1321. test_assert(INET_NTOA_BUF_LEN >= sizeof("255.255.255.255"));
  1322. test_assert(TOR_ADDR_BUF_LEN >=
  1323. sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"));
  1324. test_assert(sizeof(tor_addr_t) >= sizeof(struct in6_addr));
  1325. /* get interface addresses */
  1326. r = get_interface_address6(LOG_DEBUG, AF_INET, &t1);
  1327. i = get_interface_address6(LOG_DEBUG, AF_INET6, &t2);
  1328. #if 0
  1329. tor_inet_ntop(AF_INET, &t1.sa.sin_addr, buf, sizeof(buf));
  1330. printf("\nv4 address: %s (family=%i)", buf, IN_FAMILY(&t1));
  1331. tor_inet_ntop(AF_INET6, &t2.sa6.sin6_addr, buf, sizeof(buf));
  1332. printf("\nv6 address: %s (family=%i)", buf, IN_FAMILY(&t2));
  1333. #endif
  1334. }
  1335. static void
  1336. test_util_smartlist(void)
  1337. {
  1338. smartlist_t *sl;
  1339. char *cp;
  1340. size_t sz;
  1341. /* XXXX test sort_digests, uniq_strings, uniq_digests */
  1342. /* Test smartlist add, del_keeporder, insert, get. */
  1343. sl = smartlist_create();
  1344. smartlist_add(sl, (void*)1);
  1345. smartlist_add(sl, (void*)2);
  1346. smartlist_add(sl, (void*)3);
  1347. smartlist_add(sl, (void*)4);
  1348. smartlist_del_keeporder(sl, 1);
  1349. smartlist_insert(sl, 1, (void*)22);
  1350. smartlist_insert(sl, 0, (void*)0);
  1351. smartlist_insert(sl, 5, (void*)555);
  1352. test_eq_ptr((void*)0, smartlist_get(sl,0));
  1353. test_eq_ptr((void*)1, smartlist_get(sl,1));
  1354. test_eq_ptr((void*)22, smartlist_get(sl,2));
  1355. test_eq_ptr((void*)3, smartlist_get(sl,3));
  1356. test_eq_ptr((void*)4, smartlist_get(sl,4));
  1357. test_eq_ptr((void*)555, smartlist_get(sl,5));
  1358. /* Try deleting in the middle. */
  1359. smartlist_del(sl, 1);
  1360. test_eq_ptr((void*)555, smartlist_get(sl, 1));
  1361. /* Try deleting at the end. */
  1362. smartlist_del(sl, 4);
  1363. test_eq(4, smartlist_len(sl));
  1364. /* test isin. */
  1365. test_assert(smartlist_isin(sl, (void*)3));
  1366. test_assert(!smartlist_isin(sl, (void*)99));
  1367. /* Test split and join */
  1368. smartlist_clear(sl);
  1369. test_eq(0, smartlist_len(sl));
  1370. smartlist_split_string(sl, "abc", ":", 0, 0);
  1371. test_eq(1, smartlist_len(sl));
  1372. test_streq("abc", smartlist_get(sl, 0));
  1373. smartlist_split_string(sl, "a::bc::", "::", 0, 0);
  1374. test_eq(4, smartlist_len(sl));
  1375. test_streq("a", smartlist_get(sl, 1));
  1376. test_streq("bc", smartlist_get(sl, 2));
  1377. test_streq("", smartlist_get(sl, 3));
  1378. cp = smartlist_join_strings(sl, "", 0, NULL);
  1379. test_streq(cp, "abcabc");
  1380. tor_free(cp);
  1381. cp = smartlist_join_strings(sl, "!", 0, NULL);
  1382. test_streq(cp, "abc!a!bc!");
  1383. tor_free(cp);
  1384. cp = smartlist_join_strings(sl, "XY", 0, NULL);
  1385. test_streq(cp, "abcXYaXYbcXY");
  1386. tor_free(cp);
  1387. cp = smartlist_join_strings(sl, "XY", 1, NULL);
  1388. test_streq(cp, "abcXYaXYbcXYXY");
  1389. tor_free(cp);
  1390. cp = smartlist_join_strings(sl, "", 1, NULL);
  1391. test_streq(cp, "abcabc");
  1392. tor_free(cp);
  1393. smartlist_split_string(sl, "/def/ /ghijk", "/", 0, 0);
  1394. test_eq(8, smartlist_len(sl));
  1395. test_streq("", smartlist_get(sl, 4));
  1396. test_streq("def", smartlist_get(sl, 5));
  1397. test_streq(" ", smartlist_get(sl, 6));
  1398. test_streq("ghijk", smartlist_get(sl, 7));
  1399. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1400. smartlist_clear(sl);
  1401. smartlist_split_string(sl, "a,bbd,cdef", ",", SPLIT_SKIP_SPACE, 0);
  1402. test_eq(3, smartlist_len(sl));
  1403. test_streq("a", smartlist_get(sl,0));
  1404. test_streq("bbd", smartlist_get(sl,1));
  1405. test_streq("cdef", smartlist_get(sl,2));
  1406. smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
  1407. SPLIT_SKIP_SPACE, 0);
  1408. test_eq(8, smartlist_len(sl));
  1409. test_streq("z", smartlist_get(sl,3));
  1410. test_streq("zhasd", smartlist_get(sl,4));
  1411. test_streq("", smartlist_get(sl,5));
  1412. test_streq("bnud", smartlist_get(sl,6));
  1413. test_streq("", smartlist_get(sl,7));
  1414. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1415. smartlist_clear(sl);
  1416. smartlist_split_string(sl, " ab\tc \td ef ", NULL,
  1417. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1418. test_eq(4, smartlist_len(sl));
  1419. test_streq("ab", smartlist_get(sl,0));
  1420. test_streq("c", smartlist_get(sl,1));
  1421. test_streq("d", smartlist_get(sl,2));
  1422. test_streq("ef", smartlist_get(sl,3));
  1423. smartlist_split_string(sl, "ghi\tj", NULL,
  1424. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1425. test_eq(6, smartlist_len(sl));
  1426. test_streq("ghi", smartlist_get(sl,4));
  1427. test_streq("j", smartlist_get(sl,5));
  1428. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1429. smartlist_clear(sl);
  1430. cp = smartlist_join_strings(sl, "XY", 0, NULL);
  1431. test_streq(cp, "");
  1432. tor_free(cp);
  1433. cp = smartlist_join_strings(sl, "XY", 1, NULL);
  1434. test_streq(cp, "XY");
  1435. tor_free(cp);
  1436. smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
  1437. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1438. test_eq(3, smartlist_len(sl));
  1439. test_streq("z", smartlist_get(sl, 0));
  1440. test_streq("zhasd", smartlist_get(sl, 1));
  1441. test_streq("bnud", smartlist_get(sl, 2));
  1442. smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
  1443. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  1444. test_eq(5, smartlist_len(sl));
  1445. test_streq("z", smartlist_get(sl, 3));
  1446. test_streq("zhasd <> <> bnud<>", smartlist_get(sl, 4));
  1447. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1448. smartlist_clear(sl);
  1449. smartlist_split_string(sl, "abcd\n", "\n",
  1450. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1451. test_eq(1, smartlist_len(sl));
  1452. test_streq("abcd", smartlist_get(sl, 0));
  1453. smartlist_split_string(sl, "efgh", "\n",
  1454. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1455. test_eq(2, smartlist_len(sl));
  1456. test_streq("efgh", smartlist_get(sl, 1));
  1457. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1458. smartlist_clear(sl);
  1459. /* Test swapping, shuffling, and sorting. */
  1460. smartlist_split_string(sl, "the,onion,router,by,arma,and,nickm", ",", 0, 0);
  1461. test_eq(7, smartlist_len(sl));
  1462. smartlist_sort(sl, _compare_strs);
  1463. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1464. test_streq(cp,"and,arma,by,nickm,onion,router,the");
  1465. tor_free(cp);
  1466. smartlist_swap(sl, 1, 5);
  1467. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1468. test_streq(cp,"and,router,by,nickm,onion,arma,the");
  1469. tor_free(cp);
  1470. smartlist_shuffle(sl);
  1471. test_eq(7, smartlist_len(sl));
  1472. test_assert(smartlist_string_isin(sl, "and"));
  1473. test_assert(smartlist_string_isin(sl, "router"));
  1474. test_assert(smartlist_string_isin(sl, "by"));
  1475. test_assert(smartlist_string_isin(sl, "nickm"));
  1476. test_assert(smartlist_string_isin(sl, "onion"));
  1477. test_assert(smartlist_string_isin(sl, "arma"));
  1478. test_assert(smartlist_string_isin(sl, "the"));
  1479. /* Test bsearch. */
  1480. smartlist_sort(sl, _compare_strs);
  1481. test_streq("nickm", smartlist_bsearch(sl, "zNicKM",
  1482. _compare_without_first_ch));
  1483. test_streq("and", smartlist_bsearch(sl, " AND", _compare_without_first_ch));
  1484. test_eq_ptr(NULL, smartlist_bsearch(sl, " ANz", _compare_without_first_ch));
  1485. /* Test bsearch_idx */
  1486. {
  1487. int f;
  1488. test_eq(0, smartlist_bsearch_idx(sl," aaa",_compare_without_first_ch,&f));
  1489. test_eq(f, 0);
  1490. test_eq(0, smartlist_bsearch_idx(sl," and",_compare_without_first_ch,&f));
  1491. test_eq(f, 1);
  1492. test_eq(1, smartlist_bsearch_idx(sl," arm",_compare_without_first_ch,&f));
  1493. test_eq(f, 0);
  1494. test_eq(1, smartlist_bsearch_idx(sl," arma",_compare_without_first_ch,&f));
  1495. test_eq(f, 1);
  1496. test_eq(2, smartlist_bsearch_idx(sl," armb",_compare_without_first_ch,&f));
  1497. test_eq(f, 0);
  1498. test_eq(7, smartlist_bsearch_idx(sl," zzzz",_compare_without_first_ch,&f));
  1499. test_eq(f, 0);
  1500. }
  1501. /* Test reverse() and pop_last() */
  1502. smartlist_reverse(sl);
  1503. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1504. test_streq(cp,"the,router,onion,nickm,by,arma,and");
  1505. tor_free(cp);
  1506. cp = smartlist_pop_last(sl);
  1507. test_streq(cp, "and");
  1508. tor_free(cp);
  1509. test_eq(smartlist_len(sl), 6);
  1510. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1511. smartlist_clear(sl);
  1512. cp = smartlist_pop_last(sl);
  1513. test_eq(cp, NULL);
  1514. /* Test uniq() */
  1515. smartlist_split_string(sl,
  1516. "50,noon,radar,a,man,a,plan,a,canal,panama,radar,noon,50",
  1517. ",", 0, 0);
  1518. smartlist_sort(sl, _compare_strs);
  1519. smartlist_uniq(sl, _compare_strs, _tor_free);
  1520. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1521. test_streq(cp, "50,a,canal,man,noon,panama,plan,radar");
  1522. tor_free(cp);
  1523. /* Test string_isin and isin_case and num_isin */
  1524. test_assert(smartlist_string_isin(sl, "noon"));
  1525. test_assert(!smartlist_string_isin(sl, "noonoon"));
  1526. test_assert(smartlist_string_isin_case(sl, "nOOn"));
  1527. test_assert(!smartlist_string_isin_case(sl, "nooNooN"));
  1528. test_assert(smartlist_string_num_isin(sl, 50));
  1529. test_assert(!smartlist_string_num_isin(sl, 60));
  1530. /* Test smartlist_choose */
  1531. {
  1532. int i;
  1533. int allsame = 1;
  1534. int allin = 1;
  1535. void *first = smartlist_choose(sl);
  1536. test_assert(smartlist_isin(sl, first));
  1537. for (i = 0; i < 100; ++i) {
  1538. void *second = smartlist_choose(sl);
  1539. if (second != first)
  1540. allsame = 0;
  1541. if (!smartlist_isin(sl, second))
  1542. allin = 0;
  1543. }
  1544. test_assert(!allsame);
  1545. test_assert(allin);
  1546. }
  1547. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1548. smartlist_clear(sl);
  1549. /* Test string_remove and remove and join_strings2 */
  1550. smartlist_split_string(sl,
  1551. "Some say the Earth will end in ice and some in fire",
  1552. " ", 0, 0);
  1553. cp = smartlist_get(sl, 4);
  1554. test_streq(cp, "will");
  1555. smartlist_add(sl, cp);
  1556. smartlist_remove(sl, cp);
  1557. tor_free(cp);
  1558. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1559. test_streq(cp, "Some,say,the,Earth,fire,end,in,ice,and,some,in");
  1560. tor_free(cp);
  1561. smartlist_string_remove(sl, "in");
  1562. cp = smartlist_join_strings2(sl, "+XX", 1, 0, &sz);
  1563. test_streq(cp, "Some+say+the+Earth+fire+end+some+ice+and");
  1564. test_eq((int)sz, 40);
  1565. tor_free(cp);
  1566. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1567. smartlist_clear(sl);
  1568. {
  1569. smartlist_t *ints = smartlist_create();
  1570. smartlist_t *odds = smartlist_create();
  1571. smartlist_t *evens = smartlist_create();
  1572. smartlist_t *primes = smartlist_create();
  1573. int i;
  1574. for (i=1; i < 10; i += 2)
  1575. smartlist_add(odds, (void*)(uintptr_t)i);
  1576. for (i=0; i < 10; i += 2)
  1577. smartlist_add(evens, (void*)(uintptr_t)i);
  1578. /* add_all */
  1579. smartlist_add_all(ints, odds);
  1580. smartlist_add_all(ints, evens);
  1581. test_eq(smartlist_len(ints), 10);
  1582. smartlist_add(primes, (void*)2);
  1583. smartlist_add(primes, (void*)3);
  1584. smartlist_add(primes, (void*)5);
  1585. smartlist_add(primes, (void*)7);
  1586. /* overlap */
  1587. test_assert(smartlist_overlap(ints, odds));
  1588. test_assert(smartlist_overlap(odds, primes));
  1589. test_assert(smartlist_overlap(evens, primes));
  1590. test_assert(!smartlist_overlap(odds, evens));
  1591. /* intersect */
  1592. smartlist_add_all(sl, odds);
  1593. smartlist_intersect(sl, primes);
  1594. test_eq(smartlist_len(sl), 3);
  1595. test_assert(smartlist_isin(sl, (void*)3));
  1596. test_assert(smartlist_isin(sl, (void*)5));
  1597. test_assert(smartlist_isin(sl, (void*)7));
  1598. /* subtract */
  1599. smartlist_add_all(sl, primes);
  1600. smartlist_subtract(sl, odds);
  1601. test_eq(smartlist_len(sl), 1);
  1602. test_assert(smartlist_isin(sl, (void*)2));
  1603. smartlist_free(odds);
  1604. smartlist_free(evens);
  1605. smartlist_free(ints);
  1606. smartlist_free(primes);
  1607. smartlist_clear(sl);
  1608. }
  1609. {
  1610. /* digest_isin. */
  1611. smartlist_add(sl, tor_memdup("AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN));
  1612. smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
  1613. smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
  1614. test_eq(0, smartlist_digest_isin(NULL, "AAAAAAAAAAAAAAAAAAAA"));
  1615. test_assert(smartlist_digest_isin(sl, "AAAAAAAAAAAAAAAAAAAA"));
  1616. test_assert(smartlist_digest_isin(sl, "\00090AAB2AAAAaasdAAAAA"));
  1617. test_eq(0, smartlist_digest_isin(sl, "\00090AAB2AAABaasdAAAAA"));
  1618. /* sort digests */
  1619. smartlist_sort_digests(sl);
  1620. test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
  1621. test_memeq(smartlist_get(sl, 1), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
  1622. test_memeq(smartlist_get(sl, 2), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
  1623. test_eq(3, smartlist_len(sl));
  1624. /* uniq_digests */
  1625. smartlist_uniq_digests(sl);
  1626. test_eq(2, smartlist_len(sl));
  1627. test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
  1628. test_memeq(smartlist_get(sl, 1), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
  1629. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1630. smartlist_clear(sl);
  1631. }
  1632. smartlist_free(sl);
  1633. }
  1634. static void
  1635. test_util_bitarray(void)
  1636. {
  1637. bitarray_t *ba;
  1638. int i, j, ok=1;
  1639. ba = bitarray_init_zero(1);
  1640. test_assert(! bitarray_is_set(ba, 0));
  1641. bitarray_set(ba, 0);
  1642. test_assert(bitarray_is_set(ba, 0));
  1643. bitarray_clear(ba, 0);
  1644. test_assert(! bitarray_is_set(ba, 0));
  1645. bitarray_free(ba);
  1646. ba = bitarray_init_zero(1023);
  1647. for (i = 1; i < 64; ) {
  1648. for (j = 0; j < 1023; ++j) {
  1649. if (j % i)
  1650. bitarray_set(ba, j);
  1651. else
  1652. bitarray_clear(ba, j);
  1653. }
  1654. for (j = 0; j < 1023; ++j) {
  1655. if (!bool_eq(bitarray_is_set(ba, j), j%i))
  1656. ok = 0;
  1657. }
  1658. test_assert(ok);
  1659. if (i < 7)
  1660. ++i;
  1661. else if (i == 28)
  1662. i = 32;
  1663. else
  1664. i += 7;
  1665. }
  1666. bitarray_free(ba);
  1667. }
  1668. /* stop threads running at once. */
  1669. static tor_mutex_t *_thread_test_mutex = NULL;
  1670. /* make sure that threads have to run at the same time. */
  1671. static tor_mutex_t *_thread_test_start1 = NULL;
  1672. static tor_mutex_t *_thread_test_start2 = NULL;
  1673. static strmap_t *_thread_test_strmap = NULL;
  1674. static void _thread_test_func(void* _s) ATTR_NORETURN;
  1675. static int t1_count = 0;
  1676. static int t2_count = 0;
  1677. static void
  1678. _thread_test_func(void* _s)
  1679. {
  1680. char *s = _s;
  1681. int i, *count;
  1682. tor_mutex_t *m;
  1683. char buf[64];
  1684. char *cp;
  1685. if (!strcmp(s, "thread 1")) {
  1686. m = _thread_test_start1;
  1687. count = &t1_count;
  1688. } else {
  1689. m = _thread_test_start2;
  1690. count = &t2_count;
  1691. }
  1692. tor_mutex_acquire(m);
  1693. tor_snprintf(buf, sizeof(buf), "%lu", tor_get_thread_id());
  1694. cp = tor_strdup(buf);
  1695. for (i=0; i<10000; ++i) {
  1696. tor_mutex_acquire(_thread_test_mutex);
  1697. strmap_set(_thread_test_strmap, "last to run", cp);
  1698. ++*count;
  1699. tor_mutex_release(_thread_test_mutex);
  1700. }
  1701. tor_mutex_acquire(_thread_test_mutex);
  1702. strmap_set(_thread_test_strmap, s, tor_strdup(buf));
  1703. tor_mutex_release(_thread_test_mutex);
  1704. tor_mutex_release(m);
  1705. spawn_exit();
  1706. }
  1707. static void
  1708. test_util_threads(void)
  1709. {
  1710. char *s1, *s2;
  1711. int done = 0, timedout = 0;
  1712. time_t started;
  1713. #ifndef TOR_IS_MULTITHREADED
  1714. /* Skip this test if we aren't threading. We should be threading most
  1715. * everywhere by now. */
  1716. if (1)
  1717. return;
  1718. #endif
  1719. _thread_test_mutex = tor_mutex_new();
  1720. _thread_test_start1 = tor_mutex_new();
  1721. _thread_test_start2 = tor_mutex_new();
  1722. _thread_test_strmap = strmap_new();
  1723. s1 = tor_strdup("thread 1");
  1724. s2 = tor_strdup("thread 2");
  1725. tor_mutex_acquire(_thread_test_start1);
  1726. tor_mutex_acquire(_thread_test_start2);
  1727. spawn_func(_thread_test_func, s1);
  1728. spawn_func(_thread_test_func, s2);
  1729. tor_mutex_release(_thread_test_start2);
  1730. tor_mutex_release(_thread_test_start1);
  1731. started = time(NULL);
  1732. while (!done) {
  1733. tor_mutex_acquire(_thread_test_mutex);
  1734. strmap_assert_ok(_thread_test_strmap);
  1735. if (strmap_get(_thread_test_strmap, "thread 1") &&
  1736. strmap_get(_thread_test_strmap, "thread 2")) {
  1737. done = 1;
  1738. } else if (time(NULL) > started + 25) {
  1739. timedout = done = 1;
  1740. }
  1741. tor_mutex_release(_thread_test_mutex);
  1742. }
  1743. tor_mutex_free(_thread_test_mutex);
  1744. if (timedout) {
  1745. printf("\nTimed out: %d %d", t1_count, t2_count);
  1746. test_assert(strmap_get(_thread_test_strmap, "thread 1"));
  1747. test_assert(strmap_get(_thread_test_strmap, "thread 2"));
  1748. test_assert(!timedout);
  1749. }
  1750. /* different thread IDs. */
  1751. test_assert(strcmp(strmap_get(_thread_test_strmap, "thread 1"),
  1752. strmap_get(_thread_test_strmap, "thread 2")));
  1753. test_assert(!strcmp(strmap_get(_thread_test_strmap, "thread 1"),
  1754. strmap_get(_thread_test_strmap, "last to run")) ||
  1755. !strcmp(strmap_get(_thread_test_strmap, "thread 2"),
  1756. strmap_get(_thread_test_strmap, "last to run")));
  1757. strmap_free(_thread_test_strmap, _tor_free);
  1758. tor_free(s1);
  1759. tor_free(s2);
  1760. }
  1761. static int
  1762. _compare_strings_for_pqueue(const void *s1, const void *s2)
  1763. {
  1764. return strcmp((const char*)s1, (const char*)s2);
  1765. }
  1766. static void
  1767. test_util_pqueue(void)
  1768. {
  1769. smartlist_t *sl;
  1770. int (*cmp)(const void *, const void*);
  1771. #define OK() smartlist_pqueue_assert_ok(sl, cmp)
  1772. cmp = _compare_strings_for_pqueue;
  1773. sl = smartlist_create();
  1774. smartlist_pqueue_add(sl, cmp, (char*)"cows");
  1775. smartlist_pqueue_add(sl, cmp, (char*)"zebras");
  1776. smartlist_pqueue_add(sl, cmp, (char*)"fish");
  1777. smartlist_pqueue_add(sl, cmp, (char*)"frogs");
  1778. smartlist_pqueue_add(sl, cmp, (char*)"apples");
  1779. smartlist_pqueue_add(sl, cmp, (char*)"squid");
  1780. smartlist_pqueue_add(sl, cmp, (char*)"daschunds");
  1781. smartlist_pqueue_add(sl, cmp, (char*)"eggplants");
  1782. smartlist_pqueue_add(sl, cmp, (char*)"weissbier");
  1783. smartlist_pqueue_add(sl, cmp, (char*)"lobsters");
  1784. smartlist_pqueue_add(sl, cmp, (char*)"roquefort");
  1785. OK();
  1786. test_eq(smartlist_len(sl), 11);
  1787. test_streq(smartlist_get(sl, 0), "apples");
  1788. test_streq(smartlist_pqueue_pop(sl, cmp), "apples");
  1789. test_eq(smartlist_len(sl), 10);
  1790. OK();
  1791. test_streq(smartlist_pqueue_pop(sl, cmp), "cows");
  1792. test_streq(smartlist_pqueue_pop(sl, cmp), "daschunds");
  1793. smartlist_pqueue_add(sl, cmp, (char*)"chinchillas");
  1794. OK();
  1795. smartlist_pqueue_add(sl, cmp, (char*)"fireflies");
  1796. OK();
  1797. test_streq(smartlist_pqueue_pop(sl, cmp), "chinchillas");
  1798. test_streq(smartlist_pqueue_pop(sl, cmp), "eggplants");
  1799. test_streq(smartlist_pqueue_pop(sl, cmp), "fireflies");
  1800. OK();
  1801. test_streq(smartlist_pqueue_pop(sl, cmp), "fish");
  1802. test_streq(smartlist_pqueue_pop(sl, cmp), "frogs");
  1803. test_streq(smartlist_pqueue_pop(sl, cmp), "lobsters");
  1804. test_streq(smartlist_pqueue_pop(sl, cmp), "roquefort");
  1805. OK();
  1806. test_eq(smartlist_len(sl), 3);
  1807. test_streq(smartlist_pqueue_pop(sl, cmp), "squid");
  1808. test_streq(smartlist_pqueue_pop(sl, cmp), "weissbier");
  1809. test_streq(smartlist_pqueue_pop(sl, cmp), "zebras");
  1810. test_eq(smartlist_len(sl), 0);
  1811. OK();
  1812. #undef OK
  1813. smartlist_free(sl);
  1814. }
  1815. static void
  1816. test_util_gzip(void)
  1817. {
  1818. char *buf1, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
  1819. const char *ccp2;
  1820. size_t len1, len2;
  1821. tor_zlib_state_t *state;
  1822. buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
  1823. test_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
  1824. if (is_gzip_supported()) {
  1825. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1826. GZIP_METHOD));
  1827. test_assert(buf2);
  1828. test_assert(!memcmp(buf2, "\037\213", 2)); /* Gzip magic. */
  1829. test_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
  1830. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  1831. GZIP_METHOD, 1, LOG_INFO));
  1832. test_assert(buf3);
  1833. test_streq(buf1,buf3);
  1834. tor_free(buf2);
  1835. tor_free(buf3);
  1836. }
  1837. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1838. ZLIB_METHOD));
  1839. test_assert(buf2);
  1840. test_assert(!memcmp(buf2, "\x78\xDA", 2)); /* deflate magic. */
  1841. test_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
  1842. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  1843. ZLIB_METHOD, 1, LOG_INFO));
  1844. test_assert(buf3);
  1845. test_streq(buf1,buf3);
  1846. /* Check whether we can uncompress concatenated, compresed strings. */
  1847. tor_free(buf3);
  1848. buf2 = tor_realloc(buf2, len1*2);
  1849. memcpy(buf2+len1, buf2, len1);
  1850. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
  1851. ZLIB_METHOD, 1, LOG_INFO));
  1852. test_eq(len2, (strlen(buf1)+1)*2);
  1853. test_memeq(buf3,
  1854. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
  1855. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
  1856. (strlen(buf1)+1)*2);
  1857. tor_free(buf1);
  1858. tor_free(buf2);
  1859. tor_free(buf3);
  1860. /* Check whether we can uncompress partial strings. */
  1861. buf1 =
  1862. tor_strdup("String with low redundancy that won't be compressed much.");
  1863. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1864. ZLIB_METHOD));
  1865. tor_assert(len1>16);
  1866. /* when we allow an uncomplete string, we should succeed.*/
  1867. tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  1868. ZLIB_METHOD, 0, LOG_INFO));
  1869. buf3[len2]='\0';
  1870. tor_assert(len2 > 5);
  1871. tor_assert(!strcmpstart(buf1, buf3));
  1872. /* when we demand a complete string, this must fail. */
  1873. tor_free(buf3);
  1874. tor_assert(tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  1875. ZLIB_METHOD, 1, LOG_INFO));
  1876. tor_assert(!buf3);
  1877. /* Now, try streaming compression. */
  1878. tor_free(buf1);
  1879. tor_free(buf2);
  1880. tor_free(buf3);
  1881. state = tor_zlib_new(1, ZLIB_METHOD);
  1882. tor_assert(state);
  1883. cp1 = buf1 = tor_malloc(1024);
  1884. len1 = 1024;
  1885. ccp2 = "ABCDEFGHIJABCDEFGHIJ";
  1886. len2 = 21;
  1887. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
  1888. == TOR_ZLIB_OK);
  1889. test_eq(len2, 0); /* Make sure we compressed it all. */
  1890. test_assert(cp1 > buf1);
  1891. len2 = 0;
  1892. cp2 = cp1;
  1893. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
  1894. == TOR_ZLIB_DONE);
  1895. test_eq(len2, 0);
  1896. test_assert(cp1 > cp2); /* Make sure we really added something. */
  1897. tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf1, 1024-len1,
  1898. ZLIB_METHOD, 1, LOG_WARN));
  1899. test_streq(buf3, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
  1900. tor_free(buf3);
  1901. tor_zlib_free(state);
  1902. tor_free(buf2);
  1903. tor_free(buf3);
  1904. tor_free(buf1);
  1905. }
  1906. static void
  1907. test_util_strmap(void)
  1908. {
  1909. strmap_t *map;
  1910. strmap_iter_t *iter;
  1911. const char *k;
  1912. void *v;
  1913. char *visited;
  1914. smartlist_t *found_keys;
  1915. map = strmap_new();
  1916. test_eq(strmap_size(map), 0);
  1917. test_assert(strmap_isempty(map));
  1918. v = strmap_set(map, "K1", (void*)99);
  1919. test_eq(v, NULL);
  1920. test_assert(!strmap_isempty(map));
  1921. v = strmap_set(map, "K2", (void*)101);
  1922. test_eq(v, NULL);
  1923. v = strmap_set(map, "K1", (void*)100);
  1924. test_eq(v, (void*)99);
  1925. test_eq_ptr(strmap_get(map,"K1"), (void*)100);
  1926. test_eq_ptr(strmap_get(map,"K2"), (void*)101);
  1927. test_eq_ptr(strmap_get(map,"K-not-there"), NULL);
  1928. strmap_assert_ok(map);
  1929. v = strmap_remove(map,"K2");
  1930. strmap_assert_ok(map);
  1931. test_eq_ptr(v, (void*)101);
  1932. test_eq_ptr(strmap_get(map,"K2"), NULL);
  1933. test_eq_ptr(strmap_remove(map,"K2"), NULL);
  1934. strmap_set(map, "K2", (void*)101);
  1935. strmap_set(map, "K3", (void*)102);
  1936. strmap_set(map, "K4", (void*)103);
  1937. test_eq(strmap_size(map), 4);
  1938. strmap_assert_ok(map);
  1939. strmap_set(map, "K5", (void*)104);
  1940. strmap_set(map, "K6", (void*)105);
  1941. strmap_assert_ok(map);
  1942. /* Test iterator. */
  1943. iter = strmap_iter_init(map);
  1944. found_keys = smartlist_create();
  1945. while (!strmap_iter_done(iter)) {
  1946. strmap_iter_get(iter,&k,&v);
  1947. smartlist_add(found_keys, tor_strdup(k));
  1948. test_eq_ptr(v, strmap_get(map, k));
  1949. if (!strcmp(k, "K2")) {
  1950. iter = strmap_iter_next_rmv(map,iter);
  1951. } else {
  1952. iter = strmap_iter_next(map,iter);
  1953. }
  1954. }
  1955. /* Make sure we removed K2, but not the others. */
  1956. test_eq_ptr(strmap_get(map, "K2"), NULL);
  1957. test_eq_ptr(strmap_get(map, "K5"), (void*)104);
  1958. /* Make sure we visited everyone once */
  1959. smartlist_sort_strings(found_keys);
  1960. visited = smartlist_join_strings(found_keys, ":", 0, NULL);
  1961. test_streq(visited, "K1:K2:K3:K4:K5:K6");
  1962. tor_free(visited);
  1963. SMARTLIST_FOREACH(found_keys, char *, cp, tor_free(cp));
  1964. smartlist_free(found_keys);
  1965. strmap_assert_ok(map);
  1966. /* Clean up after ourselves. */
  1967. strmap_free(map, NULL);
  1968. /* Now try some lc functions. */
  1969. map = strmap_new();
  1970. strmap_set_lc(map,"Ab.C", (void*)1);
  1971. test_eq_ptr(strmap_get(map,"ab.c"), (void*)1);
  1972. strmap_assert_ok(map);
  1973. test_eq_ptr(strmap_get_lc(map,"AB.C"), (void*)1);
  1974. test_eq_ptr(strmap_get(map,"AB.C"), NULL);
  1975. test_eq_ptr(strmap_remove_lc(map,"aB.C"), (void*)1);
  1976. strmap_assert_ok(map);
  1977. test_eq_ptr(strmap_get_lc(map,"AB.C"), NULL);
  1978. strmap_free(map,NULL);
  1979. }
  1980. static void
  1981. test_util_mmap(void)
  1982. {
  1983. char *fname1 = tor_strdup(get_fname("mapped_1"));
  1984. char *fname2 = tor_strdup(get_fname("mapped_2"));
  1985. char *fname3 = tor_strdup(get_fname("mapped_3"));
  1986. const size_t buflen = 17000;
  1987. char *buf = tor_malloc(17000);
  1988. tor_mmap_t *mapping;
  1989. crypto_rand(buf, buflen);
  1990. mapping = tor_mmap_file(fname1);
  1991. test_assert(! mapping);
  1992. write_str_to_file(fname1, "Short file.", 1);
  1993. write_bytes_to_file(fname2, buf, buflen, 1);
  1994. write_bytes_to_file(fname3, buf, 16384, 1);
  1995. mapping = tor_mmap_file(fname1);
  1996. test_assert(mapping);
  1997. test_eq(mapping->size, strlen("Short file."));
  1998. test_streq(mapping->data, "Short file.");
  1999. #ifdef MS_WINDOWS
  2000. tor_munmap_file(mapping);
  2001. test_assert(unlink(fname1) == 0);
  2002. #else
  2003. /* make sure we can unlink. */
  2004. test_assert(unlink(fname1) == 0);
  2005. test_streq(mapping->data, "Short file.");
  2006. tor_munmap_file(mapping);
  2007. #endif
  2008. /* Now a zero-length file. */
  2009. write_str_to_file(fname1, "", 1);
  2010. mapping = tor_mmap_file(fname1);
  2011. test_eq(mapping, NULL);
  2012. test_eq(ERANGE, errno);
  2013. unlink(fname1);
  2014. /* Make sure that we fail to map a no-longer-existent file. */
  2015. mapping = tor_mmap_file(fname1);
  2016. test_assert(mapping == NULL);
  2017. /* Now try a big file that stretches across a few pages and isn't aligned */
  2018. mapping = tor_mmap_file(fname2);
  2019. test_assert(mapping);
  2020. test_eq(mapping->size, buflen);
  2021. test_memeq(mapping->data, buf, buflen);
  2022. tor_munmap_file(mapping);
  2023. /* Now try a big aligned file. */
  2024. mapping = tor_mmap_file(fname3);
  2025. test_assert(mapping);
  2026. test_eq(mapping->size, 16384);
  2027. test_memeq(mapping->data, buf, 16384);
  2028. tor_munmap_file(mapping);
  2029. /* fname1 got unlinked above */
  2030. unlink(fname2);
  2031. unlink(fname3);
  2032. tor_free(fname1);
  2033. tor_free(fname2);
  2034. tor_free(fname3);
  2035. tor_free(buf);
  2036. }
  2037. static void
  2038. test_util_control_formats(void)
  2039. {
  2040. char *out;
  2041. const char *inp =
  2042. "..This is a test\r\nof the emergency \nbroadcast\r\n..system.\r\nZ.\r\n";
  2043. size_t sz;
  2044. sz = read_escaped_data(inp, strlen(inp), &out);
  2045. test_streq(out,
  2046. ".This is a test\nof the emergency \nbroadcast\n.system.\nZ.\n");
  2047. test_eq(sz, strlen(out));
  2048. tor_free(out);
  2049. }
  2050. static void
  2051. test_onion_handshake(void)
  2052. {
  2053. /* client-side */
  2054. crypto_dh_env_t *c_dh = NULL;
  2055. char c_buf[ONIONSKIN_CHALLENGE_LEN];
  2056. char c_keys[40];
  2057. /* server-side */
  2058. char s_buf[ONIONSKIN_REPLY_LEN];
  2059. char s_keys[40];
  2060. /* shared */
  2061. crypto_pk_env_t *pk = NULL;
  2062. pk = pk_generate(0);
  2063. /* client handshake 1. */
  2064. memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
  2065. test_assert(! onion_skin_create(pk, &c_dh, c_buf));
  2066. /* server handshake */
  2067. memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
  2068. memset(s_keys, 0, 40);
  2069. test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
  2070. s_buf, s_keys, 40));
  2071. /* client handshake 2 */
  2072. memset(c_keys, 0, 40);
  2073. test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
  2074. crypto_dh_free(c_dh);
  2075. if (memcmp(c_keys, s_keys, 40)) {
  2076. puts("Aiiiie");
  2077. exit(1);
  2078. }
  2079. test_memeq(c_keys, s_keys, 40);
  2080. memset(s_buf, 0, 40);
  2081. test_memneq(c_keys, s_buf, 40);
  2082. crypto_free_pk_env(pk);
  2083. }
  2084. extern smartlist_t *fingerprint_list;
  2085. static void
  2086. test_dir_format(void)
  2087. {
  2088. char buf[8192], buf2[8192];
  2089. char platform[256];
  2090. char fingerprint[FINGERPRINT_LEN+1];
  2091. char *pk1_str = NULL, *pk2_str = NULL, *pk3_str = NULL, *cp;
  2092. size_t pk1_str_len, pk2_str_len, pk3_str_len;
  2093. routerinfo_t *r1, *r2;
  2094. crypto_pk_env_t *pk1 = NULL, *pk2 = NULL, *pk3 = NULL;
  2095. routerinfo_t *rp1 = NULL, *rp2 = NULL;
  2096. addr_policy_t *ex1, *ex2;
  2097. routerlist_t *dir1 = NULL, *dir2 = NULL;
  2098. tor_version_t ver1;
  2099. pk1 = pk_generate(0);
  2100. pk2 = pk_generate(1);
  2101. pk3 = pk_generate(2);
  2102. test_assert( is_legal_nickname("a"));
  2103. test_assert(!is_legal_nickname(""));
  2104. test_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
  2105. test_assert(!is_legal_nickname("hyphen-")); /* bad char */
  2106. test_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
  2107. test_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2108. /* valid */
  2109. test_assert( is_legal_nickname_or_hexdigest(
  2110. "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2111. test_assert( is_legal_nickname_or_hexdigest(
  2112. "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
  2113. test_assert( is_legal_nickname_or_hexdigest(
  2114. "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
  2115. /* too short */
  2116. test_assert(!is_legal_nickname_or_hexdigest(
  2117. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2118. /* illegal char */
  2119. test_assert(!is_legal_nickname_or_hexdigest(
  2120. "$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2121. /* hex part too long */
  2122. test_assert(!is_legal_nickname_or_hexdigest(
  2123. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2124. test_assert(!is_legal_nickname_or_hexdigest(
  2125. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
  2126. /* Bad nickname */
  2127. test_assert(!is_legal_nickname_or_hexdigest(
  2128. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
  2129. test_assert(!is_legal_nickname_or_hexdigest(
  2130. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
  2131. test_assert(!is_legal_nickname_or_hexdigest(
  2132. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
  2133. test_assert(!is_legal_nickname_or_hexdigest(
  2134. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
  2135. "abcdefghijklmnoppqrst"));
  2136. /* Bad extra char. */
  2137. test_assert(!is_legal_nickname_or_hexdigest(
  2138. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
  2139. test_assert(is_legal_nickname_or_hexdigest("xyzzy"));
  2140. test_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
  2141. test_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
  2142. get_platform_str(platform, sizeof(platform));
  2143. r1 = tor_malloc_zero(sizeof(routerinfo_t));
  2144. r1->address = tor_strdup("18.244.0.1");
  2145. r1->addr = 0xc0a80001u; /* 192.168.0.1 */
  2146. r1->cache_info.published_on = 0;
  2147. r1->or_port = 9000;
  2148. r1->dir_port = 9003;
  2149. r1->onion_pkey = crypto_pk_dup_key(pk1);
  2150. r1->identity_pkey = crypto_pk_dup_key(pk2);
  2151. r1->bandwidthrate = 1000;
  2152. r1->bandwidthburst = 5000;
  2153. r1->bandwidthcapacity = 10000;
  2154. r1->exit_policy = NULL;
  2155. r1->nickname = tor_strdup("Magri");
  2156. r1->platform = tor_strdup(platform);
  2157. ex1 = tor_malloc_zero(sizeof(addr_policy_t));
  2158. ex2 = tor_malloc_zero(sizeof(addr_policy_t));
  2159. ex1->policy_type = ADDR_POLICY_ACCEPT;
  2160. ex1->addr = 0;
  2161. ex1->maskbits = 0;
  2162. ex1->prt_min = ex1->prt_max = 80;
  2163. ex2->policy_type = ADDR_POLICY_REJECT;
  2164. ex2->addr = 18 << 24;
  2165. ex2->maskbits = 8;
  2166. ex2->prt_min = ex2->prt_max = 24;
  2167. r2 = tor_malloc_zero(sizeof(routerinfo_t));
  2168. r2->address = tor_strdup("1.1.1.1");
  2169. r2->addr = 0x0a030201u; /* 10.3.2.1 */
  2170. r2->platform = tor_strdup(platform);
  2171. r2->cache_info.published_on = 5;
  2172. r2->or_port = 9005;
  2173. r2->dir_port = 0;
  2174. r2->onion_pkey = crypto_pk_dup_key(pk2);
  2175. r2->identity_pkey = crypto_pk_dup_key(pk1);
  2176. r2->bandwidthrate = r2->bandwidthburst = r2->bandwidthcapacity = 3000;
  2177. r2->exit_policy = smartlist_create();
  2178. smartlist_add(r2->exit_policy, ex2);
  2179. smartlist_add(r2->exit_policy, ex1);
  2180. r2->nickname = tor_strdup("Fred");
  2181. test_assert(!crypto_pk_write_public_key_to_string(pk1, &pk1_str,
  2182. &pk1_str_len));
  2183. test_assert(!crypto_pk_write_public_key_to_string(pk2 , &pk2_str,
  2184. &pk2_str_len));
  2185. test_assert(!crypto_pk_write_public_key_to_string(pk3 , &pk3_str,
  2186. &pk3_str_len));
  2187. memset(buf, 0, 2048);
  2188. test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
  2189. strlcpy(buf2, "router Magri 18.244.0.1 9000 0 9003\n"
  2190. "platform Tor "VERSION" on ", sizeof(buf2));
  2191. strlcat(buf2, get_uname(), sizeof(buf2));
  2192. strlcat(buf2, "\n"
  2193. "opt protocols Link 1 Circuit 1\n"
  2194. "published 1970-01-01 00:00:00\n"
  2195. "opt fingerprint ", sizeof(buf2));
  2196. test_assert(!crypto_pk_get_fingerprint(pk2, fingerprint, 1));
  2197. strlcat(buf2, fingerprint, sizeof(buf2));
  2198. strlcat(buf2, "\nuptime 0\n"
  2199. /* XXX the "0" above is hardcoded, but even if we made it reflect
  2200. * uptime, that still wouldn't make it right, because the two
  2201. * descriptors might be made on different seconds... hm. */
  2202. "bandwidth 1000 5000 10000\n"
  2203. "opt extra-info-digest 0000000000000000000000000000000000000000\n"
  2204. "onion-key\n", sizeof(buf2));
  2205. strlcat(buf2, pk1_str, sizeof(buf2));
  2206. strlcat(buf2, "signing-key\n", sizeof(buf2));
  2207. strlcat(buf2, pk2_str, sizeof(buf2));
  2208. strlcat(buf2, "reject *:*\nrouter-signature\n", sizeof(buf2));
  2209. buf[strlen(buf2)] = '\0'; /* Don't compare the sig; it's never the same
  2210. * twice */
  2211. test_streq(buf, buf2);
  2212. test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
  2213. cp = buf;
  2214. rp1 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL);
  2215. test_assert(rp1);
  2216. test_streq(rp1->address, r1->address);
  2217. test_eq(rp1->or_port, r1->or_port);
  2218. //test_eq(rp1->dir_port, r1->dir_port);
  2219. test_eq(rp1->bandwidthrate, r1->bandwidthrate);
  2220. test_eq(rp1->bandwidthburst, r1->bandwidthburst);
  2221. test_eq(rp1->bandwidthcapacity, r1->bandwidthcapacity);
  2222. test_assert(crypto_pk_cmp_keys(rp1->onion_pkey, pk1) == 0);
  2223. test_assert(crypto_pk_cmp_keys(rp1->identity_pkey, pk2) == 0);
  2224. //test_assert(rp1->exit_policy == NULL);
  2225. #if 0
  2226. /* XXX Once we have exit policies, test this again. XXX */
  2227. strlcpy(buf2, "router tor.tor.tor 9005 0 0 3000\n", sizeof(buf2));
  2228. strlcat(buf2, pk2_str, sizeof(buf2));
  2229. strlcat(buf2, "signing-key\n", sizeof(buf2));
  2230. strlcat(buf2, pk1_str, sizeof(buf2));
  2231. strlcat(buf2, "accept *:80\nreject 18.*:24\n\n", sizeof(buf2));
  2232. test_assert(router_dump_router_to_string(buf, 2048, &r2, pk2)>0);
  2233. test_streq(buf, buf2);
  2234. cp = buf;
  2235. rp2 = router_parse_entry_from_string(&cp,1);
  2236. test_assert(rp2);
  2237. test_streq(rp2->address, r2.address);
  2238. test_eq(rp2->or_port, r2.or_port);
  2239. test_eq(rp2->dir_port, r2.dir_port);
  2240. test_eq(rp2->bandwidth, r2.bandwidth);
  2241. test_assert(crypto_pk_cmp_keys(rp2->onion_pkey, pk2) == 0);
  2242. test_assert(crypto_pk_cmp_keys(rp2->identity_pkey, pk1) == 0);
  2243. test_eq(rp2->exit_policy->policy_type, EXIT_POLICY_ACCEPT);
  2244. test_streq(rp2->exit_policy->string, "accept *:80");
  2245. test_streq(rp2->exit_policy->address, "*");
  2246. test_streq(rp2->exit_policy->port, "80");
  2247. test_eq(rp2->exit_policy->next->policy_type, EXIT_POLICY_REJECT);
  2248. test_streq(rp2->exit_policy->next->string, "reject 18.*:24");
  2249. test_streq(rp2->exit_policy->next->address, "18.*");
  2250. test_streq(rp2->exit_policy->next->port, "24");
  2251. test_assert(rp2->exit_policy->next->next == NULL);
  2252. /* Okay, now for the directories. */
  2253. {
  2254. fingerprint_list = smartlist_create();
  2255. crypto_pk_get_fingerprint(pk2, buf, 1);
  2256. add_fingerprint_to_dir("Magri", buf, fingerprint_list);
  2257. crypto_pk_get_fingerprint(pk1, buf, 1);
  2258. add_fingerprint_to_dir("Fred", buf, fingerprint_list);
  2259. }
  2260. {
  2261. char d[DIGEST_LEN];
  2262. const char *m;
  2263. /* XXXX NM re-enable. */
  2264. /* Make sure routers aren't too far in the past any more. */
  2265. r1->cache_info.published_on = time(NULL);
  2266. r2->cache_info.published_on = time(NULL)-3*60*60;
  2267. test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
  2268. test_eq(dirserv_add_descriptor(buf,&m), 2);
  2269. test_assert(router_dump_router_to_string(buf, 2048, r2, pk1)>0);
  2270. test_eq(dirserv_add_descriptor(buf,&m), 2);
  2271. get_options()->Nickname = tor_strdup("DirServer");
  2272. test_assert(!dirserv_dump_directory_to_string(&cp,pk3, 0));
  2273. crypto_pk_get_digest(pk3, d);
  2274. test_assert(!router_parse_directory(cp));
  2275. test_eq(2, smartlist_len(dir1->routers));
  2276. tor_free(cp);
  2277. }
  2278. #endif
  2279. dirserv_free_fingerprint_list();
  2280. tor_free(pk1_str);
  2281. tor_free(pk2_str);
  2282. tor_free(pk3_str);
  2283. if (pk1) crypto_free_pk_env(pk1);
  2284. if (pk2) crypto_free_pk_env(pk2);
  2285. if (pk3) crypto_free_pk_env(pk3);
  2286. if (rp1) routerinfo_free(rp1);
  2287. if (rp2) routerinfo_free(rp2);
  2288. tor_free(dir1); /* XXXX And more !*/
  2289. tor_free(dir2); /* And more !*/
  2290. routerinfo_free(r1);
  2291. routerinfo_free(r2);
  2292. /* Try out version parsing functionality */
  2293. test_eq(0, tor_version_parse("0.3.4pre2-cvs", &ver1));
  2294. test_eq(0, ver1.major);
  2295. test_eq(3, ver1.minor);
  2296. test_eq(4, ver1.micro);
  2297. test_eq(VER_PRE, ver1.status);
  2298. test_eq(2, ver1.patchlevel);
  2299. test_eq(0, tor_version_parse("0.3.4rc1", &ver1));
  2300. test_eq(0, ver1.major);
  2301. test_eq(3, ver1.minor);
  2302. test_eq(4, ver1.micro);
  2303. test_eq(VER_RC, ver1.status);
  2304. test_eq(1, ver1.patchlevel);
  2305. test_eq(0, tor_version_parse("1.3.4", &ver1));
  2306. test_eq(1, ver1.major);
  2307. test_eq(3, ver1.minor);
  2308. test_eq(4, ver1.micro);
  2309. test_eq(VER_RELEASE, ver1.status);
  2310. test_eq(0, ver1.patchlevel);
  2311. test_eq(0, tor_version_parse("1.3.4.999", &ver1));
  2312. test_eq(1, ver1.major);
  2313. test_eq(3, ver1.minor);
  2314. test_eq(4, ver1.micro);
  2315. test_eq(VER_RELEASE, ver1.status);
  2316. test_eq(999, ver1.patchlevel);
  2317. test_eq(0, tor_version_parse("0.1.2.4-alpha", &ver1));
  2318. test_eq(0, ver1.major);
  2319. test_eq(1, ver1.minor);
  2320. test_eq(2, ver1.micro);
  2321. test_eq(4, ver1.patchlevel);
  2322. test_eq(VER_RELEASE, ver1.status);
  2323. test_streq("alpha", ver1.status_tag);
  2324. test_eq(0, tor_version_parse("0.1.2.4", &ver1));
  2325. test_eq(0, ver1.major);
  2326. test_eq(1, ver1.minor);
  2327. test_eq(2, ver1.micro);
  2328. test_eq(4, ver1.patchlevel);
  2329. test_eq(VER_RELEASE, ver1.status);
  2330. test_streq("", ver1.status_tag);
  2331. #define test_eq_vs(vs1, vs2) test_eq_type(version_status_t, "%d", (vs1), (vs2))
  2332. #define test_v_i_o(val, ver, lst) \
  2333. test_eq_vs(val, tor_version_is_obsolete(ver, lst))
  2334. /* make sure tor_version_is_obsolete() works */
  2335. test_v_i_o(VS_OLD, "0.0.1", "Tor 0.0.2");
  2336. test_v_i_o(VS_OLD, "0.0.1", "0.0.2, Tor 0.0.3");
  2337. test_v_i_o(VS_OLD, "0.0.1", "0.0.2,Tor 0.0.3");
  2338. test_v_i_o(VS_OLD, "0.0.1","0.0.3,BetterTor 0.0.1");
  2339. test_v_i_o(VS_RECOMMENDED, "0.0.2", "Tor 0.0.2,Tor 0.0.3");
  2340. test_v_i_o(VS_NEW_IN_SERIES, "0.0.2", "Tor 0.0.2pre1,Tor 0.0.3");
  2341. test_v_i_o(VS_OLD, "0.0.2", "Tor 0.0.2.1,Tor 0.0.3");
  2342. test_v_i_o(VS_NEW, "0.1.0", "Tor 0.0.2,Tor 0.0.3");
  2343. test_v_i_o(VS_RECOMMENDED, "0.0.7rc2", "0.0.7,Tor 0.0.7rc2,Tor 0.0.8");
  2344. test_v_i_o(VS_OLD, "0.0.5.0", "0.0.5.1-cvs");
  2345. test_v_i_o(VS_NEW_IN_SERIES, "0.0.5.1-cvs", "0.0.5, 0.0.6");
  2346. /* Not on list, but newer than any in same series. */
  2347. test_v_i_o(VS_NEW_IN_SERIES, "0.1.0.3",
  2348. "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2349. /* Series newer than any on list. */
  2350. test_v_i_o(VS_NEW, "0.1.2.3", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2351. /* Series older than any on list. */
  2352. test_v_i_o(VS_OLD, "0.0.1.3", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2353. /* Not on list, not newer than any on same series. */
  2354. test_v_i_o(VS_UNRECOMMENDED, "0.1.0.1",
  2355. "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2356. /* On list, not newer than any on same series. */
  2357. test_v_i_o(VS_UNRECOMMENDED,
  2358. "0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2359. test_eq(0, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
  2360. test_eq(1, tor_version_as_new_as(
  2361. "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
  2362. "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
  2363. "0.0.8rc2"));
  2364. test_eq(0, tor_version_as_new_as(
  2365. "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
  2366. "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
  2367. /* Now try svn revisions. */
  2368. test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
  2369. "Tor 0.2.1.0-dev (r99)"));
  2370. test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100) on Banana Jr",
  2371. "Tor 0.2.1.0-dev (r99) on Hal 9000"));
  2372. test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
  2373. "Tor 0.2.1.0-dev on Colossus"));
  2374. test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
  2375. "Tor 0.2.1.0-dev (r100)"));
  2376. test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
  2377. "Tor 0.2.1.0-dev (r100) on AM"));
  2378. test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev",
  2379. "Tor 0.2.1.0-dev (r99)"));
  2380. test_eq(1, tor_version_as_new_as("Tor 0.2.1.1",
  2381. "Tor 0.2.1.0-dev (r99)"));
  2382. }
  2383. extern const char AUTHORITY_CERT_1[];
  2384. extern const char AUTHORITY_SIGNKEY_1[];
  2385. extern const char AUTHORITY_CERT_2[];
  2386. extern const char AUTHORITY_SIGNKEY_2[];
  2387. extern const char AUTHORITY_CERT_3[];
  2388. extern const char AUTHORITY_SIGNKEY_3[];
  2389. static void
  2390. test_same_voter(networkstatus_voter_info_t *v1,
  2391. networkstatus_voter_info_t *v2)
  2392. {
  2393. test_streq(v1->nickname, v2->nickname);
  2394. test_memeq(v1->identity_digest, v2->identity_digest, DIGEST_LEN);
  2395. test_streq(v1->address, v2->address);
  2396. test_eq(v1->addr, v2->addr);
  2397. test_eq(v1->dir_port, v2->dir_port);
  2398. test_eq(v1->or_port, v2->or_port);
  2399. test_streq(v1->contact, v2->contact);
  2400. test_memeq(v1->vote_digest, v2->vote_digest, DIGEST_LEN);
  2401. }
  2402. static void
  2403. test_util_order_functions(void)
  2404. {
  2405. int lst[25], n = 0;
  2406. // int a=12,b=24,c=25,d=60,e=77;
  2407. #define median() median_int(lst, n)
  2408. lst[n++] = 12;
  2409. test_eq(12, median()); /* 12 */
  2410. lst[n++] = 77;
  2411. //smartlist_shuffle(sl);
  2412. test_eq(12, median()); /* 12, 77 */
  2413. lst[n++] = 77;
  2414. //smartlist_shuffle(sl);
  2415. test_eq(77, median()); /* 12, 77, 77 */
  2416. lst[n++] = 24;
  2417. test_eq(24, median()); /* 12,24,77,77 */
  2418. lst[n++] = 60;
  2419. lst[n++] = 12;
  2420. lst[n++] = 25;
  2421. //smartlist_shuffle(sl);
  2422. test_eq(25, median()); /* 12,12,24,25,60,77,77 */
  2423. #undef median
  2424. }
  2425. static void
  2426. test_v3_networkstatus(void)
  2427. {
  2428. authority_cert_t *cert1, *cert2, *cert3;
  2429. crypto_pk_env_t *sign_skey_1, *sign_skey_2, *sign_skey_3;
  2430. time_t now = time(NULL);
  2431. networkstatus_voter_info_t *voter;
  2432. networkstatus_t *vote, *v1, *v2, *v3, *con;
  2433. vote_routerstatus_t *vrs;
  2434. routerstatus_t *rs;
  2435. char *v1_text, *v2_text, *v3_text, *consensus_text, *cp;
  2436. smartlist_t *votes = smartlist_create();
  2437. /* Parse certificates and keys. */
  2438. cert1 = authority_cert_parse_from_string(AUTHORITY_CERT_1, NULL);
  2439. test_assert(cert1);
  2440. cert2 = authority_cert_parse_from_string(AUTHORITY_CERT_2, NULL);
  2441. test_assert(cert2);
  2442. cert3 = authority_cert_parse_from_string(AUTHORITY_CERT_3, NULL);
  2443. test_assert(cert3);
  2444. sign_skey_1 = crypto_new_pk_env();
  2445. sign_skey_2 = crypto_new_pk_env();
  2446. sign_skey_3 = crypto_new_pk_env();
  2447. test_assert(!crypto_pk_read_private_key_from_string(sign_skey_1,
  2448. AUTHORITY_SIGNKEY_1));
  2449. test_assert(!crypto_pk_read_private_key_from_string(sign_skey_2,
  2450. AUTHORITY_SIGNKEY_2));
  2451. test_assert(!crypto_pk_read_private_key_from_string(sign_skey_3,
  2452. AUTHORITY_SIGNKEY_3));
  2453. test_assert(!crypto_pk_cmp_keys(sign_skey_1, cert1->signing_key));
  2454. test_assert(!crypto_pk_cmp_keys(sign_skey_2, cert2->signing_key));
  2455. /*
  2456. * Set up a vote; generate it; try to parse it.
  2457. */
  2458. vote = tor_malloc_zero(sizeof(networkstatus_t));
  2459. vote->is_vote = 1;
  2460. vote->published = now;
  2461. vote->valid_after = now+1000;
  2462. vote->fresh_until = now+2000;
  2463. vote->valid_until = now+3000;
  2464. vote->vote_seconds = 100;
  2465. vote->dist_seconds = 200;
  2466. vote->client_versions = tor_strdup("0.1.2.14,0.1.2.15");
  2467. vote->server_versions = tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
  2468. vote->known_flags = smartlist_create();
  2469. smartlist_split_string(vote->known_flags,
  2470. "Authority Exit Fast Guard Running Stable V2Dir Valid",
  2471. 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2472. vote->voters = smartlist_create();
  2473. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2474. voter->nickname = tor_strdup("Voter1");
  2475. voter->address = tor_strdup("1.2.3.4");
  2476. voter->addr = 0x01020304;
  2477. voter->dir_port = 80;
  2478. voter->or_port = 9000;
  2479. voter->contact = tor_strdup("voter@example.com");
  2480. crypto_pk_get_digest(cert1->identity_key, voter->identity_digest);
  2481. smartlist_add(vote->voters, voter);
  2482. vote->cert = authority_cert_dup(cert1);
  2483. vote->routerstatus_list = smartlist_create();
  2484. /* add the first routerstatus. */
  2485. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2486. rs = &vrs->status;
  2487. vrs->version = tor_strdup("0.1.2.14");
  2488. rs->published_on = now-1500;
  2489. strlcpy(rs->nickname, "router2", sizeof(rs->nickname));
  2490. memset(rs->identity_digest, 3, DIGEST_LEN);
  2491. memset(rs->descriptor_digest, 78, DIGEST_LEN);
  2492. rs->addr = 0x99008801;
  2493. rs->or_port = 443;
  2494. rs->dir_port = 8000;
  2495. /* all flags cleared */
  2496. smartlist_add(vote->routerstatus_list, vrs);
  2497. /* add the second routerstatus. */
  2498. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2499. rs = &vrs->status;
  2500. vrs->version = tor_strdup("0.2.0.5");
  2501. rs->published_on = now-1000;
  2502. strlcpy(rs->nickname, "router1", sizeof(rs->nickname));
  2503. memset(rs->identity_digest, 5, DIGEST_LEN);
  2504. memset(rs->descriptor_digest, 77, DIGEST_LEN);
  2505. rs->addr = 0x99009901;
  2506. rs->or_port = 443;
  2507. rs->dir_port = 0;
  2508. rs->is_exit = rs->is_stable = rs->is_fast = rs->is_running =
  2509. rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
  2510. smartlist_add(vote->routerstatus_list, vrs);
  2511. /* add the third routerstatus. */
  2512. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2513. rs = &vrs->status;
  2514. vrs->version = tor_strdup("0.1.0.3");
  2515. rs->published_on = now-1000;
  2516. strlcpy(rs->nickname, "router3", sizeof(rs->nickname));
  2517. memset(rs->identity_digest, 33, DIGEST_LEN);
  2518. memset(rs->descriptor_digest, 78, DIGEST_LEN);
  2519. rs->addr = 0xAA009901;
  2520. rs->or_port = 400;
  2521. rs->dir_port = 9999;
  2522. rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
  2523. rs->is_running = rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
  2524. smartlist_add(vote->routerstatus_list, vrs);
  2525. /* dump the vote and try to parse it. */
  2526. v1_text = format_networkstatus_vote(sign_skey_1, vote);
  2527. test_assert(v1_text);
  2528. v1 = networkstatus_parse_vote_from_string(v1_text, NULL, 1);
  2529. test_assert(v1);
  2530. /* Make sure the parsed thing was right. */
  2531. test_eq(v1->is_vote, 1);
  2532. test_eq(v1->published, vote->published);
  2533. test_eq(v1->valid_after, vote->valid_after);
  2534. test_eq(v1->fresh_until, vote->fresh_until);
  2535. test_eq(v1->valid_until, vote->valid_until);
  2536. test_eq(v1->vote_seconds, vote->vote_seconds);
  2537. test_eq(v1->dist_seconds, vote->dist_seconds);
  2538. test_streq(v1->client_versions, vote->client_versions);
  2539. test_streq(v1->server_versions, vote->server_versions);
  2540. test_assert(v1->voters && smartlist_len(v1->voters));
  2541. voter = smartlist_get(v1->voters, 0);
  2542. test_streq(voter->nickname, "Voter1");
  2543. test_streq(voter->address, "1.2.3.4");
  2544. test_eq(voter->addr, 0x01020304);
  2545. test_eq(voter->dir_port, 80);
  2546. test_eq(voter->or_port, 9000);
  2547. test_streq(voter->contact, "voter@example.com");
  2548. test_assert(v1->cert);
  2549. test_assert(!crypto_pk_cmp_keys(sign_skey_1, v1->cert->signing_key));
  2550. cp = smartlist_join_strings(v1->known_flags, ":", 0, NULL);
  2551. test_streq(cp, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
  2552. tor_free(cp);
  2553. test_eq(smartlist_len(v1->routerstatus_list), 3);
  2554. /* Check the first routerstatus. */
  2555. vrs = smartlist_get(v1->routerstatus_list, 0);
  2556. rs = &vrs->status;
  2557. test_streq(vrs->version, "0.1.2.14");
  2558. test_eq(rs->published_on, now-1500);
  2559. test_streq(rs->nickname, "router2");
  2560. test_memeq(rs->identity_digest,
  2561. "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
  2562. DIGEST_LEN);
  2563. test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
  2564. test_eq(rs->addr, 0x99008801);
  2565. test_eq(rs->or_port, 443);
  2566. test_eq(rs->dir_port, 8000);
  2567. test_eq(vrs->flags, U64_LITERAL(0));
  2568. /* Check the second routerstatus. */
  2569. vrs = smartlist_get(v1->routerstatus_list, 1);
  2570. rs = &vrs->status;
  2571. test_streq(vrs->version, "0.2.0.5");
  2572. test_eq(rs->published_on, now-1000);
  2573. test_streq(rs->nickname, "router1");
  2574. test_memeq(rs->identity_digest,
  2575. "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
  2576. DIGEST_LEN);
  2577. test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
  2578. test_eq(rs->addr, 0x99009901);
  2579. test_eq(rs->or_port, 443);
  2580. test_eq(rs->dir_port, 0);
  2581. test_eq(vrs->flags, U64_LITERAL(254)); // all flags except "authority."
  2582. /* Generate second vote. It disagrees on some of the times,
  2583. * and doesn't list versions, and knows some crazy flags */
  2584. vote->published = now+1;
  2585. vote->fresh_until = now+3005;
  2586. vote->dist_seconds = 300;
  2587. authority_cert_free(vote->cert);
  2588. vote->cert = authority_cert_dup(cert2);
  2589. tor_free(vote->client_versions);
  2590. tor_free(vote->server_versions);
  2591. voter = smartlist_get(vote->voters, 0);
  2592. tor_free(voter->nickname);
  2593. tor_free(voter->address);
  2594. voter->nickname = tor_strdup("Voter2");
  2595. voter->address = tor_strdup("2.3.4.5");
  2596. voter->addr = 0x02030405;
  2597. crypto_pk_get_digest(cert2->identity_key, voter->identity_digest);
  2598. smartlist_add(vote->known_flags, tor_strdup("MadeOfCheese"));
  2599. smartlist_add(vote->known_flags, tor_strdup("MadeOfTin"));
  2600. smartlist_sort_strings(vote->known_flags);
  2601. vrs = smartlist_get(vote->routerstatus_list, 2);
  2602. smartlist_del_keeporder(vote->routerstatus_list, 2);
  2603. tor_free(vrs->version);
  2604. tor_free(vrs);
  2605. vrs = smartlist_get(vote->routerstatus_list, 0);
  2606. vrs->status.is_fast = 1;
  2607. /* generate and parse. */
  2608. v2_text = format_networkstatus_vote(sign_skey_2, vote);
  2609. test_assert(v2_text);
  2610. v2 = networkstatus_parse_vote_from_string(v2_text, NULL, 1);
  2611. test_assert(v2);
  2612. /* Check that flags come out right.*/
  2613. cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
  2614. test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
  2615. "Running:Stable:V2Dir:Valid");
  2616. tor_free(cp);
  2617. vrs = smartlist_get(v2->routerstatus_list, 1);
  2618. /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
  2619. test_eq(vrs->flags, U64_LITERAL(974));
  2620. /* Generate the third vote. */
  2621. vote->published = now;
  2622. vote->fresh_until = now+2003;
  2623. vote->dist_seconds = 250;
  2624. authority_cert_free(vote->cert);
  2625. vote->cert = authority_cert_dup(cert3);
  2626. vote->client_versions = tor_strdup("0.1.2.14,0.1.2.17");
  2627. vote->server_versions = tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
  2628. voter = smartlist_get(vote->voters, 0);
  2629. tor_free(voter->nickname);
  2630. tor_free(voter->address);
  2631. voter->nickname = tor_strdup("Voter3");
  2632. voter->address = tor_strdup("3.4.5.6");
  2633. voter->addr = 0x03040506;
  2634. crypto_pk_get_digest(cert3->identity_key, voter->identity_digest);
  2635. vrs = smartlist_get(vote->routerstatus_list, 0);
  2636. smartlist_del_keeporder(vote->routerstatus_list, 0);
  2637. tor_free(vrs->version);
  2638. tor_free(vrs);
  2639. vrs = smartlist_get(vote->routerstatus_list, 0);
  2640. memset(vrs->status.descriptor_digest, (int)'Z', DIGEST_LEN);
  2641. v3_text = format_networkstatus_vote(sign_skey_3, vote);
  2642. test_assert(v3_text);
  2643. v3 = networkstatus_parse_vote_from_string(v3_text, NULL, 1);
  2644. test_assert(v3);
  2645. /* Compute a consensus as voter 3. */
  2646. smartlist_add(votes, v3);
  2647. smartlist_add(votes, v1);
  2648. smartlist_add(votes, v2);
  2649. consensus_text = networkstatus_compute_consensus(votes, 3,
  2650. cert3->identity_key,
  2651. sign_skey_3);
  2652. test_assert(consensus_text);
  2653. con = networkstatus_parse_vote_from_string(consensus_text, NULL, 0);
  2654. test_assert(con);
  2655. //log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
  2656. // v1_text, v2_text, v3_text);
  2657. /* Check consensus contents. */
  2658. test_assert(!con->is_vote);
  2659. test_eq(con->published, 0); /* this field only appears in votes. */
  2660. test_eq(con->valid_after, now+1000);
  2661. test_eq(con->fresh_until, now+2003); /* median */
  2662. test_eq(con->valid_until, now+3000);
  2663. test_eq(con->vote_seconds, 100);
  2664. test_eq(con->dist_seconds, 250); /* median */
  2665. test_streq(con->client_versions, "0.1.2.14");
  2666. test_streq(con->server_versions, "0.1.2.15,0.1.2.16");
  2667. cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
  2668. test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
  2669. "Running:Stable:V2Dir:Valid");
  2670. tor_free(cp);
  2671. test_eq(3, smartlist_len(con->voters));
  2672. /* The voter id digests should be in this order. */
  2673. test_assert(memcmp(cert2->cache_info.identity_digest,
  2674. cert3->cache_info.identity_digest,DIGEST_LEN)<0);
  2675. test_assert(memcmp(cert3->cache_info.identity_digest,
  2676. cert1->cache_info.identity_digest,DIGEST_LEN)<0);
  2677. test_same_voter(smartlist_get(con->voters, 0),
  2678. smartlist_get(v2->voters, 0));
  2679. test_same_voter(smartlist_get(con->voters, 1),
  2680. smartlist_get(v3->voters, 0));
  2681. test_same_voter(smartlist_get(con->voters, 2),
  2682. smartlist_get(v1->voters, 0));
  2683. test_assert(!con->cert);
  2684. test_eq(2, smartlist_len(con->routerstatus_list));
  2685. /* There should be two listed routers: one with identity 3, one with
  2686. * identity 5. */
  2687. /* This one showed up in 2 digests. */
  2688. rs = smartlist_get(con->routerstatus_list, 0);
  2689. test_memeq(rs->identity_digest,
  2690. "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
  2691. DIGEST_LEN);
  2692. test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
  2693. test_assert(!rs->is_authority);
  2694. test_assert(!rs->is_exit);
  2695. test_assert(!rs->is_fast);
  2696. test_assert(!rs->is_possible_guard);
  2697. test_assert(!rs->is_stable);
  2698. test_assert(!rs->is_running);
  2699. test_assert(!rs->is_v2_dir);
  2700. test_assert(!rs->is_valid);
  2701. test_assert(!rs->is_named);
  2702. /* XXXX check version */
  2703. rs = smartlist_get(con->routerstatus_list, 1);
  2704. /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
  2705. test_memeq(rs->identity_digest,
  2706. "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
  2707. DIGEST_LEN);
  2708. test_streq(rs->nickname, "router1");
  2709. test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
  2710. test_eq(rs->published_on, now-1000);
  2711. test_eq(rs->addr, 0x99009901);
  2712. test_eq(rs->or_port, 443);
  2713. test_eq(rs->dir_port, 0);
  2714. test_assert(!rs->is_authority);
  2715. test_assert(rs->is_exit);
  2716. test_assert(rs->is_fast);
  2717. test_assert(rs->is_possible_guard);
  2718. test_assert(rs->is_stable);
  2719. test_assert(rs->is_running);
  2720. test_assert(rs->is_v2_dir);
  2721. test_assert(rs->is_valid);
  2722. test_assert(!rs->is_named);
  2723. /* XXXX check version */
  2724. /* Check signatures. the first voter hasn't got one. The second one
  2725. * does: validate it. */
  2726. voter = smartlist_get(con->voters, 0);
  2727. test_assert(!voter->signature);
  2728. test_assert(!voter->good_signature);
  2729. test_assert(!voter->bad_signature);
  2730. voter = smartlist_get(con->voters, 1);
  2731. test_assert(voter->signature);
  2732. test_assert(!voter->good_signature);
  2733. test_assert(!voter->bad_signature);
  2734. test_assert(!networkstatus_check_voter_signature(con,
  2735. smartlist_get(con->voters, 1),
  2736. cert3));
  2737. test_assert(voter->signature);
  2738. test_assert(voter->good_signature);
  2739. test_assert(!voter->bad_signature);
  2740. {
  2741. char *consensus_text2, *consensus_text3;
  2742. networkstatus_t *con2, *con3;
  2743. char *detached_text1, *detached_text2;
  2744. ns_detached_signatures_t *dsig1, *dsig2;
  2745. const char *msg=NULL;
  2746. /* Compute the other two signed consensuses. */
  2747. smartlist_shuffle(votes);
  2748. consensus_text2 = networkstatus_compute_consensus(votes, 3,
  2749. cert2->identity_key,
  2750. sign_skey_2);
  2751. smartlist_shuffle(votes);
  2752. consensus_text3 = networkstatus_compute_consensus(votes, 3,
  2753. cert1->identity_key,
  2754. sign_skey_1);
  2755. test_assert(consensus_text2);
  2756. test_assert(consensus_text3);
  2757. con2 = networkstatus_parse_vote_from_string(consensus_text2, NULL, 0);
  2758. con3 = networkstatus_parse_vote_from_string(consensus_text3, NULL, 0);
  2759. test_assert(con2);
  2760. test_assert(con3);
  2761. /* All three should have the same digest. */
  2762. test_memeq(con->networkstatus_digest, con2->networkstatus_digest,
  2763. DIGEST_LEN);
  2764. test_memeq(con->networkstatus_digest, con3->networkstatus_digest,
  2765. DIGEST_LEN);
  2766. /* Extract a detached signature from con3. */
  2767. detached_text1 = networkstatus_get_detached_signatures(con3);
  2768. tor_assert(detached_text1);
  2769. /* Try to parse it. */
  2770. dsig1 = networkstatus_parse_detached_signatures(detached_text1, NULL);
  2771. tor_assert(dsig1);
  2772. /* Are parsed values as expected? */
  2773. test_eq(dsig1->valid_after, con3->valid_after);
  2774. test_eq(dsig1->fresh_until, con3->fresh_until);
  2775. test_eq(dsig1->valid_until, con3->valid_until);
  2776. test_memeq(dsig1->networkstatus_digest, con3->networkstatus_digest,
  2777. DIGEST_LEN);
  2778. test_eq(1, smartlist_len(dsig1->signatures));
  2779. voter = smartlist_get(dsig1->signatures, 0);
  2780. test_memeq(voter->identity_digest, cert1->cache_info.identity_digest,
  2781. DIGEST_LEN);
  2782. /* Try adding it to con2. */
  2783. detached_text2 = networkstatus_get_detached_signatures(con2);
  2784. test_eq(1, networkstatus_add_detached_signatures(con2, dsig1, &msg));
  2785. tor_free(detached_text2);
  2786. detached_text2 = networkstatus_get_detached_signatures(con2);
  2787. //printf("\n<%s>\n", detached_text2);
  2788. dsig2 = networkstatus_parse_detached_signatures(detached_text2, NULL);
  2789. test_assert(dsig2);
  2790. /*
  2791. printf("\n");
  2792. SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
  2793. char hd[64];
  2794. base16_encode(hd, sizeof(hd), vi->identity_digest, DIGEST_LEN);
  2795. printf("%s\n", hd);
  2796. });
  2797. */
  2798. test_eq(2, smartlist_len(dsig2->signatures));
  2799. /* Try adding to con2 twice; verify that nothing changes. */
  2800. test_eq(0, networkstatus_add_detached_signatures(con2, dsig1, &msg));
  2801. /* Add to con. */
  2802. test_eq(2, networkstatus_add_detached_signatures(con, dsig2, &msg));
  2803. /* Check signatures */
  2804. test_assert(!networkstatus_check_voter_signature(con,
  2805. smartlist_get(con->voters, 0),
  2806. cert2));
  2807. test_assert(!networkstatus_check_voter_signature(con,
  2808. smartlist_get(con->voters, 2),
  2809. cert1));
  2810. networkstatus_vote_free(con2);
  2811. networkstatus_vote_free(con3);
  2812. tor_free(consensus_text2);
  2813. tor_free(consensus_text3);
  2814. tor_free(detached_text1);
  2815. tor_free(detached_text2);
  2816. ns_detached_signatures_free(dsig1);
  2817. ns_detached_signatures_free(dsig2);
  2818. }
  2819. smartlist_free(votes);
  2820. tor_free(v1_text);
  2821. tor_free(v2_text);
  2822. tor_free(v3_text);
  2823. tor_free(consensus_text);
  2824. networkstatus_vote_free(vote);
  2825. networkstatus_vote_free(v1);
  2826. networkstatus_vote_free(v2);
  2827. networkstatus_vote_free(v3);
  2828. networkstatus_vote_free(con);
  2829. crypto_free_pk_env(sign_skey_1);
  2830. crypto_free_pk_env(sign_skey_2);
  2831. crypto_free_pk_env(sign_skey_3);
  2832. authority_cert_free(cert1);
  2833. authority_cert_free(cert2);
  2834. authority_cert_free(cert3);
  2835. }
  2836. static void
  2837. test_policies(void)
  2838. {
  2839. smartlist_t *policy, *policy2;
  2840. addr_policy_t *p;
  2841. tor_addr_t tar;
  2842. config_line_t line;
  2843. policy = smartlist_create();
  2844. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  2845. test_eq(ADDR_POLICY_REJECT, p->policy_type);
  2846. tor_addr_from_ipv4(&tar, 0xc0a80000u);
  2847. test_assert(p->addr == 0xc0a80000u);
  2848. test_eq(16, p->maskbits);
  2849. test_eq(1, p->prt_min);
  2850. test_eq(65535, p->prt_max);
  2851. smartlist_add(policy, p);
  2852. test_assert(ADDR_POLICY_ACCEPTED ==
  2853. compare_addr_to_addr_policy(0x01020304u, 2, policy));
  2854. test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
  2855. compare_addr_to_addr_policy(0, 2, policy));
  2856. test_assert(ADDR_POLICY_REJECTED ==
  2857. compare_addr_to_addr_policy(0xc0a80102, 2, policy));
  2858. policy2 = NULL;
  2859. test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL));
  2860. test_assert(policy2);
  2861. test_assert(!exit_policy_is_general_exit(policy));
  2862. test_assert(exit_policy_is_general_exit(policy2));
  2863. test_assert(!exit_policy_is_general_exit(NULL));
  2864. test_assert(cmp_addr_policies(policy, policy2));
  2865. test_assert(cmp_addr_policies(policy, NULL));
  2866. test_assert(!cmp_addr_policies(policy2, policy2));
  2867. test_assert(!cmp_addr_policies(NULL, NULL));
  2868. test_assert(!policy_is_reject_star(policy2));
  2869. test_assert(policy_is_reject_star(policy));
  2870. test_assert(policy_is_reject_star(NULL));
  2871. addr_policy_list_free(policy);
  2872. addr_policy_list_free(policy2);
  2873. /* make sure compacting logic works. */
  2874. policy = NULL;
  2875. line.key = (char*)"foo";
  2876. line.value = (char*)"accept *:80,reject private:*,reject *:*";
  2877. line.next = NULL;
  2878. test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL));
  2879. test_assert(policy);
  2880. //test_streq(policy->string, "accept *:80");
  2881. //test_streq(policy->next->string, "reject *:*");
  2882. test_eq(smartlist_len(policy), 2);
  2883. addr_policy_list_free(policy);
  2884. }
  2885. static void
  2886. test_rend_fns(void)
  2887. {
  2888. char address1[] = "fooaddress.onion";
  2889. char address2[] = "aaaaaaaaaaaaaaaa.onion";
  2890. char address3[] = "fooaddress.exit";
  2891. char address4[] = "www.torproject.org";
  2892. rend_service_descriptor_t *d1, *d2;
  2893. char *encoded;
  2894. size_t len;
  2895. crypto_pk_env_t *pk1, *pk2;
  2896. time_t now;
  2897. int i;
  2898. pk1 = pk_generate(0);
  2899. pk2 = pk_generate(1);
  2900. /* Test unversioned (v0) descriptor */
  2901. d1 = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  2902. d1->pk = crypto_pk_dup_key(pk1);
  2903. now = time(NULL);
  2904. d1->timestamp = now;
  2905. d1->version = 0;
  2906. d1->intro_nodes = smartlist_create();
  2907. for (i = 0; i < 3; i++) {
  2908. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  2909. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  2910. crypto_rand(intro->extend_info->identity_digest, DIGEST_LEN);
  2911. intro->extend_info->nickname[0] = '$';
  2912. base16_encode(intro->extend_info->nickname+1, HEX_DIGEST_LEN+1,
  2913. intro->extend_info->identity_digest, DIGEST_LEN);
  2914. smartlist_add(d1->intro_nodes, intro);
  2915. }
  2916. test_assert(! rend_encode_service_descriptor(d1, pk1, &encoded, &len));
  2917. d2 = rend_parse_service_descriptor(encoded, len);
  2918. test_assert(d2);
  2919. test_assert(!crypto_pk_cmp_keys(d1->pk, d2->pk));
  2920. test_eq(d2->timestamp, now);
  2921. test_eq(d2->version, 0);
  2922. test_eq(d2->protocols, 1<<2);
  2923. test_eq(smartlist_len(d2->intro_nodes), 3);
  2924. for (i = 0; i < 3; i++) {
  2925. rend_intro_point_t *intro1 = smartlist_get(d1->intro_nodes, i);
  2926. rend_intro_point_t *intro2 = smartlist_get(d2->intro_nodes, i);
  2927. test_streq(intro1->extend_info->nickname,
  2928. intro2->extend_info->nickname);
  2929. }
  2930. rend_service_descriptor_free(d1);
  2931. rend_service_descriptor_free(d2);
  2932. tor_free(encoded);
  2933. test_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
  2934. test_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
  2935. test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
  2936. test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
  2937. crypto_free_pk_env(pk1);
  2938. crypto_free_pk_env(pk2);
  2939. }
  2940. static void
  2941. bench_aes(void)
  2942. {
  2943. int len, i;
  2944. char *b1, *b2;
  2945. crypto_cipher_env_t *c;
  2946. struct timeval start, end;
  2947. const int iters = 100000;
  2948. uint64_t nsec;
  2949. c = crypto_new_cipher_env();
  2950. crypto_cipher_generate_key(c);
  2951. crypto_cipher_encrypt_init_cipher(c);
  2952. for (len = 1; len <= 8192; len *= 2) {
  2953. b1 = tor_malloc_zero(len);
  2954. b2 = tor_malloc_zero(len);
  2955. tor_gettimeofday(&start);
  2956. for (i = 0; i < iters; ++i) {
  2957. crypto_cipher_encrypt(c, b1, b2, len);
  2958. }
  2959. tor_gettimeofday(&end);
  2960. tor_free(b1);
  2961. tor_free(b2);
  2962. nsec = (uint64_t) tv_udiff(&start,&end);
  2963. nsec *= 1000;
  2964. nsec /= (iters*len);
  2965. printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
  2966. U64_PRINTF_ARG(nsec));
  2967. }
  2968. crypto_free_cipher_env(c);
  2969. }
  2970. static void
  2971. test_util_mempool(void)
  2972. {
  2973. mp_pool_t *pool;
  2974. smartlist_t *allocated;
  2975. int i;
  2976. pool = mp_pool_new(1, 100);
  2977. test_assert(pool->new_chunk_capacity >= 100);
  2978. test_assert(pool->item_alloc_size >= sizeof(void*)+1);
  2979. mp_pool_destroy(pool);
  2980. pool = mp_pool_new(241, 2500);
  2981. test_assert(pool->new_chunk_capacity >= 10);
  2982. test_assert(pool->item_alloc_size >= sizeof(void*)+241);
  2983. test_eq(pool->item_alloc_size & 0x03, 0);
  2984. test_assert(pool->new_chunk_capacity < 60);
  2985. allocated = smartlist_create();
  2986. for (i = 0; i < 100000; ++i) {
  2987. if (smartlist_len(allocated) < 20 || crypto_rand_int(2)) {
  2988. void *m = mp_pool_get(pool);
  2989. memset(m, 0x09, 241);
  2990. smartlist_add(allocated, m);
  2991. //printf("%d: %p\n", i, m);
  2992. //mp_pool_assert_ok(pool);
  2993. } else {
  2994. int idx = crypto_rand_int(smartlist_len(allocated));
  2995. void *m = smartlist_get(allocated, idx);
  2996. //printf("%d: free %p\n", i, m);
  2997. smartlist_del(allocated, idx);
  2998. mp_pool_release(m);
  2999. //mp_pool_assert_ok(pool);
  3000. }
  3001. if (crypto_rand_int(777)==0)
  3002. mp_pool_clean(pool, 1, 1);
  3003. if (i % 777)
  3004. mp_pool_assert_ok(pool);
  3005. }
  3006. SMARTLIST_FOREACH(allocated, void *, m, mp_pool_release(m));
  3007. mp_pool_assert_ok(pool);
  3008. mp_pool_clean(pool, 0, 0);
  3009. mp_pool_assert_ok(pool);
  3010. mp_pool_destroy(pool);
  3011. smartlist_free(allocated);
  3012. }
  3013. static void
  3014. test_util_memarea(void)
  3015. {
  3016. memarea_t *area = memarea_new(1024);
  3017. char *p1, *p2, *p3, *p1_orig;
  3018. int i;
  3019. test_assert(area);
  3020. p1_orig = p1 = memarea_alloc(area,64);
  3021. p2 = memarea_alloc_zero(area,52);
  3022. p3 = memarea_alloc(area,11);
  3023. test_assert(memarea_owns_ptr(area, p1));
  3024. test_assert(memarea_owns_ptr(area, p2));
  3025. test_assert(memarea_owns_ptr(area, p3));
  3026. /* Make sure we left enough space. */
  3027. test_assert(p1+64 <= p2);
  3028. test_assert(p2+52 <= p3);
  3029. /* Make sure we aligned. */
  3030. test_eq(((uintptr_t)p1) % sizeof(void*), 0);
  3031. test_eq(((uintptr_t)p2) % sizeof(void*), 0);
  3032. test_eq(((uintptr_t)p3) % sizeof(void*), 0);
  3033. test_assert(!memarea_owns_ptr(area, p3+8192));
  3034. test_assert(!memarea_owns_ptr(area, p3+30));
  3035. test_assert(tor_mem_is_zero(p2, 52));
  3036. /* Make sure we don't overalign. */
  3037. p1 = memarea_alloc(area, 1);
  3038. p2 = memarea_alloc(area, 1);
  3039. test_eq(p1+sizeof(void*), p2);
  3040. {
  3041. void *ptr = tor_malloc(64);
  3042. test_assert(!memarea_owns_ptr(area, ptr));
  3043. tor_free(ptr);
  3044. }
  3045. /* memarea_memdup */
  3046. {
  3047. char *ptr = tor_malloc(64);
  3048. crypto_rand(ptr, 64);
  3049. p1 = memarea_memdup(area, ptr, 64);
  3050. test_assert(p1 != ptr);
  3051. test_memeq(p1, ptr, 64);
  3052. tor_free(ptr);
  3053. }
  3054. /* memarea_strdup. */
  3055. p1 = memarea_strdup(area,"");
  3056. p2 = memarea_strdup(area, "abcd");
  3057. test_assert(p1);
  3058. test_assert(p2);
  3059. test_streq(p1, "");
  3060. test_streq(p2, "abcd");
  3061. /* memarea_strndup. */
  3062. {
  3063. const char *s = "Ad ogni porta batte la morte e grida: il nome!";
  3064. /* (From Turandot, act 3.) */
  3065. size_t len = strlen(s);
  3066. p1 = memarea_strndup(area, s, 1000);
  3067. p2 = memarea_strndup(area, s, 10);
  3068. test_streq(p1, s);
  3069. test_assert(p2 >= p1 + len + 1);
  3070. test_memeq(s, p2, 10);
  3071. test_eq(p2[10], '\0');
  3072. p3 = memarea_strndup(area, s, len);
  3073. test_streq(p3, s);
  3074. p3 = memarea_strndup(area, s, len-1);
  3075. test_memeq(s, p3, len-1);
  3076. test_eq(p3[len-1], '\0');
  3077. }
  3078. memarea_clear(area);
  3079. p1 = memarea_alloc(area, 1);
  3080. test_eq(p1, p1_orig);
  3081. memarea_clear(area);
  3082. /* Check for running over an area's size. */
  3083. for (i = 0; i < 512; ++i) {
  3084. p1 = memarea_alloc(area, crypto_rand_int(5)+1);
  3085. test_assert(memarea_owns_ptr(area, p1));
  3086. }
  3087. memarea_assert_ok(area);
  3088. /* Make sure we can allocate a too-big object. */
  3089. p1 = memarea_alloc_zero(area, 9000);
  3090. p2 = memarea_alloc_zero(area, 16);
  3091. test_assert(memarea_owns_ptr(area, p1));
  3092. test_assert(memarea_owns_ptr(area, p2));
  3093. memarea_drop_all(area);
  3094. }
  3095. static void
  3096. test_util_datadir(void)
  3097. {
  3098. char buf[1024];
  3099. char *f;
  3100. f = get_datadir_fname(NULL);
  3101. test_streq(f, temp_dir);
  3102. tor_free(f);
  3103. f = get_datadir_fname("state");
  3104. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
  3105. test_streq(f, buf);
  3106. tor_free(f);
  3107. f = get_datadir_fname2("cache", "thingy");
  3108. tor_snprintf(buf, sizeof(buf),
  3109. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
  3110. test_streq(f, buf);
  3111. tor_free(f);
  3112. f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
  3113. tor_snprintf(buf, sizeof(buf),
  3114. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
  3115. test_streq(f, buf);
  3116. tor_free(f);
  3117. f = get_datadir_fname_suffix("cache", ".foo");
  3118. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
  3119. temp_dir);
  3120. test_streq(f, buf);
  3121. tor_free(f);
  3122. }
  3123. /* Test AES-CTR encryption and decryption with IV. */
  3124. static void
  3125. test_crypto_aes_iv(void)
  3126. {
  3127. crypto_cipher_env_t *cipher;
  3128. char *plain, *encrypted1, *encrypted2, *decrypted1, *decrypted2;
  3129. char plain_1[1], plain_15[15], plain_16[16], plain_17[17];
  3130. char key1[16], key2[16];
  3131. size_t encrypted_size, decrypted_size;
  3132. plain = tor_malloc(4095);
  3133. encrypted1 = tor_malloc(4095 + 1 + 16);
  3134. encrypted2 = tor_malloc(4095 + 1 + 16);
  3135. decrypted1 = tor_malloc(4095 + 1);
  3136. decrypted2 = tor_malloc(4095 + 1);
  3137. crypto_rand(plain, 4095);
  3138. crypto_rand(key1, 16);
  3139. crypto_rand(key2, 16);
  3140. crypto_rand(plain_1, 1);
  3141. crypto_rand(plain_15, 15);
  3142. crypto_rand(plain_16, 16);
  3143. crypto_rand(plain_17, 17);
  3144. key1[0] = key2[0] + 128; /* Make sure that contents are different. */
  3145. /* Encrypt and decrypt with the same key. */
  3146. cipher = crypto_create_init_cipher(key1, 1);
  3147. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 4095,
  3148. plain, 4095);
  3149. crypto_free_cipher_env(cipher);
  3150. test_eq(encrypted_size, 16 + 4095);
  3151. cipher = crypto_create_init_cipher(key1, 0);
  3152. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
  3153. encrypted1, encrypted_size);
  3154. crypto_free_cipher_env(cipher);
  3155. test_eq(decrypted_size, 4095);
  3156. test_memeq(plain, decrypted1, 4095);
  3157. /* Encrypt a second time (with a new random initialization vector). */
  3158. cipher = crypto_create_init_cipher(key1, 1);
  3159. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted2, 16 + 4095,
  3160. plain, 4095);
  3161. crypto_free_cipher_env(cipher);
  3162. test_eq(encrypted_size, 16 + 4095);
  3163. cipher = crypto_create_init_cipher(key1, 0);
  3164. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
  3165. encrypted2, encrypted_size);
  3166. crypto_free_cipher_env(cipher);
  3167. test_eq(decrypted_size, 4095);
  3168. test_memeq(plain, decrypted2, 4095);
  3169. test_memneq(encrypted1, encrypted2, encrypted_size);
  3170. /* Decrypt with the wrong key. */
  3171. cipher = crypto_create_init_cipher(key2, 0);
  3172. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
  3173. encrypted1, encrypted_size);
  3174. crypto_free_cipher_env(cipher);
  3175. test_memneq(plain, decrypted2, encrypted_size);
  3176. /* Alter the initialization vector. */
  3177. encrypted1[0] += 42;
  3178. cipher = crypto_create_init_cipher(key1, 0);
  3179. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
  3180. encrypted1, encrypted_size);
  3181. crypto_free_cipher_env(cipher);
  3182. test_memneq(plain, decrypted2, 4095);
  3183. /* Special length case: 1. */
  3184. cipher = crypto_create_init_cipher(key1, 1);
  3185. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 1,
  3186. plain_1, 1);
  3187. crypto_free_cipher_env(cipher);
  3188. test_eq(encrypted_size, 16 + 1);
  3189. cipher = crypto_create_init_cipher(key1, 0);
  3190. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 1,
  3191. encrypted1, encrypted_size);
  3192. crypto_free_cipher_env(cipher);
  3193. test_eq(decrypted_size, 1);
  3194. test_memeq(plain_1, decrypted1, 1);
  3195. /* Special length case: 15. */
  3196. cipher = crypto_create_init_cipher(key1, 1);
  3197. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 15,
  3198. plain_15, 15);
  3199. crypto_free_cipher_env(cipher);
  3200. test_eq(encrypted_size, 16 + 15);
  3201. cipher = crypto_create_init_cipher(key1, 0);
  3202. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 15,
  3203. encrypted1, encrypted_size);
  3204. crypto_free_cipher_env(cipher);
  3205. test_eq(decrypted_size, 15);
  3206. test_memeq(plain_15, decrypted1, 15);
  3207. /* Special length case: 16. */
  3208. cipher = crypto_create_init_cipher(key1, 1);
  3209. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 16,
  3210. plain_16, 16);
  3211. crypto_free_cipher_env(cipher);
  3212. test_eq(encrypted_size, 16 + 16);
  3213. cipher = crypto_create_init_cipher(key1, 0);
  3214. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 16,
  3215. encrypted1, encrypted_size);
  3216. crypto_free_cipher_env(cipher);
  3217. test_eq(decrypted_size, 16);
  3218. test_memeq(plain_16, decrypted1, 16);
  3219. /* Special length case: 17. */
  3220. cipher = crypto_create_init_cipher(key1, 1);
  3221. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 17,
  3222. plain_17, 17);
  3223. crypto_free_cipher_env(cipher);
  3224. test_eq(encrypted_size, 16 + 17);
  3225. cipher = crypto_create_init_cipher(key1, 0);
  3226. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 17,
  3227. encrypted1, encrypted_size);
  3228. crypto_free_cipher_env(cipher);
  3229. test_eq(decrypted_size, 17);
  3230. test_memeq(plain_17, decrypted1, 17);
  3231. /* Free memory. */
  3232. tor_free(plain);
  3233. tor_free(encrypted1);
  3234. tor_free(encrypted2);
  3235. tor_free(decrypted1);
  3236. tor_free(decrypted2);
  3237. }
  3238. /* Test base32 decoding. */
  3239. static void
  3240. test_crypto_base32_decode(void)
  3241. {
  3242. char plain[60], encoded[96 + 1], decoded[60];
  3243. int res;
  3244. crypto_rand(plain, 60);
  3245. /* Encode and decode a random string. */
  3246. base32_encode(encoded, 96 + 1, plain, 60);
  3247. res = base32_decode(decoded, 60, encoded, 96);
  3248. test_eq(res, 0);
  3249. test_memeq(plain, decoded, 60);
  3250. /* Encode, uppercase, and decode a random string. */
  3251. base32_encode(encoded, 96 + 1, plain, 60);
  3252. tor_strupper(encoded);
  3253. res = base32_decode(decoded, 60, encoded, 96);
  3254. test_eq(res, 0);
  3255. test_memeq(plain, decoded, 60);
  3256. /* Change encoded string and decode. */
  3257. if (encoded[0] == 'A' || encoded[0] == 'a')
  3258. encoded[0] = 'B';
  3259. else
  3260. encoded[0] = 'A';
  3261. res = base32_decode(decoded, 60, encoded, 96);
  3262. test_eq(res, 0);
  3263. test_memneq(plain, decoded, 60);
  3264. /* Bad encodings. */
  3265. encoded[0] = '!';
  3266. res = base32_decode(decoded, 60, encoded, 96);
  3267. test_assert(res < 0);
  3268. }
  3269. /* Test encoding and parsing of v2 rendezvous service descriptors. */
  3270. static void
  3271. test_rend_fns_v2(void)
  3272. {
  3273. rend_service_descriptor_t *generated, *parsed;
  3274. char service_id[DIGEST_LEN];
  3275. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  3276. const char *next_desc;
  3277. smartlist_t *descs = smartlist_create();
  3278. char computed_desc_id[DIGEST_LEN];
  3279. char parsed_desc_id[DIGEST_LEN];
  3280. crypto_pk_env_t *pk1, *pk2;
  3281. time_t now;
  3282. char *intro_points_encrypted;
  3283. size_t intro_points_size;
  3284. size_t encoded_size;
  3285. int i;
  3286. pk1 = pk_generate(0);
  3287. pk2 = pk_generate(1);
  3288. generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  3289. generated->pk = crypto_pk_dup_key(pk1);
  3290. crypto_pk_get_digest(generated->pk, service_id);
  3291. base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
  3292. service_id, REND_SERVICE_ID_LEN);
  3293. now = time(NULL);
  3294. generated->timestamp = now;
  3295. generated->version = 2;
  3296. generated->protocols = 42;
  3297. generated->intro_nodes = smartlist_create();
  3298. for (i = 0; i < 3; i++) {
  3299. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  3300. crypto_pk_env_t *okey = pk_generate(2 + i);
  3301. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  3302. intro->extend_info->onion_key = crypto_pk_dup_key(okey);
  3303. crypto_pk_get_digest(intro->extend_info->onion_key,
  3304. intro->extend_info->identity_digest);
  3305. //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
  3306. intro->extend_info->nickname[0] = '$';
  3307. base16_encode(intro->extend_info->nickname + 1,
  3308. sizeof(intro->extend_info->nickname) - 1,
  3309. intro->extend_info->identity_digest, DIGEST_LEN);
  3310. intro->extend_info->addr = crypto_rand_int(65536); /* Does not cover all
  3311. * IP addresses. */
  3312. intro->extend_info->port = crypto_rand_int(65536);
  3313. intro->intro_key = crypto_pk_dup_key(pk2);
  3314. smartlist_add(generated->intro_nodes, intro);
  3315. }
  3316. test_assert(rend_encode_v2_descriptors(descs, generated, now,
  3317. NULL, 0) > 0);
  3318. test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
  3319. NULL, now, 0) == 0);
  3320. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  3321. smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
  3322. test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
  3323. &intro_points_encrypted,
  3324. &intro_points_size,
  3325. &encoded_size,
  3326. &next_desc,
  3327. ((rend_encoded_v2_service_descriptor_t *)
  3328. smartlist_get(descs, 0))->desc_str) == 0);
  3329. test_assert(parsed);
  3330. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  3331. smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
  3332. test_assert(rend_decrypt_introduction_points(parsed, NULL,
  3333. intro_points_encrypted,
  3334. intro_points_size) == 3);
  3335. test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
  3336. test_eq(parsed->timestamp, now);
  3337. test_eq(parsed->version, 2);
  3338. test_eq(parsed->protocols, 42);
  3339. test_eq(smartlist_len(parsed->intro_nodes), 3);
  3340. for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
  3341. rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
  3342. *gen_intro = smartlist_get(generated->intro_nodes, i);
  3343. extend_info_t *par_info = par_intro->extend_info;
  3344. extend_info_t *gen_info = gen_intro->extend_info;
  3345. test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
  3346. test_memeq(gen_info->identity_digest, par_info->identity_digest,
  3347. DIGEST_LEN);
  3348. test_streq(gen_info->nickname, par_info->nickname);
  3349. test_eq(gen_info->addr, par_info->addr);
  3350. test_eq(gen_info->port, par_info->port);
  3351. }
  3352. tor_free(intro_points_encrypted);
  3353. for (i = 0; i < smartlist_len(descs); i++)
  3354. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  3355. smartlist_free(descs);
  3356. rend_service_descriptor_free(parsed);
  3357. rend_service_descriptor_free(generated);
  3358. }
  3359. static void
  3360. test_geoip(void)
  3361. {
  3362. int i, j;
  3363. time_t now = time(NULL);
  3364. char *s;
  3365. /* Populate the DB a bit. Add these in order, since we can't do the final
  3366. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  3367. * fine uint32_t values. */
  3368. test_eq(0, geoip_parse_entry("10,50,AB"));
  3369. test_eq(0, geoip_parse_entry("52,90,XY"));
  3370. test_eq(0, geoip_parse_entry("95,100,AB"));
  3371. test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
  3372. test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
  3373. test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
  3374. /* We should have 3 countries: ab, xy, zz. */
  3375. test_eq(3, geoip_get_n_countries());
  3376. /* Make sure that country ID actually works. */
  3377. #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
  3378. test_streq("ab", NAMEFOR(32));
  3379. test_streq("??", NAMEFOR(5));
  3380. test_streq("??", NAMEFOR(51));
  3381. test_streq("xy", NAMEFOR(150));
  3382. test_streq("xy", NAMEFOR(190));
  3383. test_streq("??", NAMEFOR(2000));
  3384. #undef NAMEFOR
  3385. get_options()->BridgeRelay = 1;
  3386. get_options()->BridgeRecordUsageByCountry = 1;
  3387. /* Put 9 observations in AB... */
  3388. for (i=32; i < 40; ++i)
  3389. geoip_note_client_seen(i, now);
  3390. geoip_note_client_seen(225, now);
  3391. /* and 3 observations in XY, several times. */
  3392. for (j=0; j < 10; ++j)
  3393. for (i=52; i < 55; ++i)
  3394. geoip_note_client_seen(i, now-3600);
  3395. /* and 17 observations in ZZ... */
  3396. for (i=110; i < 127; ++i)
  3397. geoip_note_client_seen(i, now-7200);
  3398. s = geoip_get_client_history(now+5*24*60*60);
  3399. test_assert(s);
  3400. test_streq("zz=24,ab=16", s);
  3401. tor_free(s);
  3402. /* Now clear out all the zz observations. */
  3403. geoip_remove_old_clients(now-6000);
  3404. s = geoip_get_client_history(now+5*24*60*60);
  3405. test_assert(! s); /* There are only 12 observations left. Not enough to
  3406. build an answer. Add 4 more in XY... */
  3407. for (i=55; i < 59; ++i)
  3408. geoip_note_client_seen(i, now-3600);
  3409. s = geoip_get_client_history(now+5*24*60*60);
  3410. test_assert(s);
  3411. test_streq("ab=16", s);
  3412. tor_free(s);
  3413. }
  3414. #define ENT(x) { #x, test_ ## x, 0, 0 }
  3415. #define SUBENT(x,y) { #x "/" #y, test_ ## x ## _ ## y, 1, 0 }
  3416. static struct {
  3417. const char *test_name;
  3418. void (*test_fn)(void);
  3419. int is_subent;
  3420. int selected;
  3421. } test_array[] = {
  3422. ENT(buffers),
  3423. ENT(crypto),
  3424. SUBENT(crypto, dh),
  3425. SUBENT(crypto, s2k),
  3426. SUBENT(crypto, aes_iv),
  3427. SUBENT(crypto, base32_decode),
  3428. ENT(util),
  3429. SUBENT(util, ip6_helpers),
  3430. SUBENT(util, gzip),
  3431. SUBENT(util, datadir),
  3432. SUBENT(util, smartlist),
  3433. SUBENT(util, bitarray),
  3434. SUBENT(util, mempool),
  3435. SUBENT(util, memarea),
  3436. SUBENT(util, strmap),
  3437. SUBENT(util, control_formats),
  3438. SUBENT(util, pqueue),
  3439. SUBENT(util, mmap),
  3440. SUBENT(util, threads),
  3441. SUBENT(util, order_functions),
  3442. ENT(onion_handshake),
  3443. ENT(dir_format),
  3444. ENT(v3_networkstatus),
  3445. ENT(policies),
  3446. ENT(rend_fns),
  3447. SUBENT(rend_fns, v2),
  3448. ENT(geoip),
  3449. { NULL, NULL, 0, 0 },
  3450. };
  3451. static void syntax(void) ATTR_NORETURN;
  3452. static void
  3453. syntax(void)
  3454. {
  3455. int i;
  3456. printf("Syntax:\n"
  3457. " test [-v|--verbose] [--warn|--notice|--info|--debug]\n"
  3458. " [testname...]\n"
  3459. "Recognized tests are:\n");
  3460. for (i = 0; test_array[i].test_name; ++i) {
  3461. printf(" %s\n", test_array[i].test_name);
  3462. }
  3463. exit(0);
  3464. }
  3465. int
  3466. main(int c, char**v)
  3467. {
  3468. or_options_t *options = options_new();
  3469. char *errmsg = NULL;
  3470. int i;
  3471. int verbose = 0, any_selected = 0;
  3472. int loglevel = LOG_ERR;
  3473. init_logging();
  3474. for (i = 1; i < c; ++i) {
  3475. if (!strcmp(v[i], "-v") || !strcmp(v[i], "--verbose"))
  3476. verbose++;
  3477. else if (!strcmp(v[i], "--warn"))
  3478. loglevel = LOG_WARN;
  3479. else if (!strcmp(v[i], "--notice"))
  3480. loglevel = LOG_NOTICE;
  3481. else if (!strcmp(v[i], "--info"))
  3482. loglevel = LOG_INFO;
  3483. else if (!strcmp(v[i], "--debug"))
  3484. loglevel = LOG_DEBUG;
  3485. else if (!strcmp(v[i], "--help") || !strcmp(v[i], "-h") || v[i][0] == '-')
  3486. syntax();
  3487. else {
  3488. int j, found=0;
  3489. for (j = 0; test_array[j].test_name; ++j) {
  3490. if (!strcmp(v[i], test_array[j].test_name) ||
  3491. (test_array[j].is_subent &&
  3492. !strcmpstart(test_array[j].test_name, v[i]) &&
  3493. test_array[j].test_name[strlen(v[i])] == '/') ||
  3494. (v[i][0] == '=' && !strcmp(v[i]+1, test_array[j].test_name))) {
  3495. test_array[j].selected = 1;
  3496. any_selected = 1;
  3497. found = 1;
  3498. }
  3499. }
  3500. if (!found) {
  3501. printf("Unknown test: %s\n", v[i]);
  3502. syntax();
  3503. }
  3504. }
  3505. }
  3506. if (!any_selected) {
  3507. for (i = 0; test_array[i].test_name; ++i) {
  3508. test_array[i].selected = 1;
  3509. }
  3510. }
  3511. {
  3512. log_severity_list_t *s = tor_malloc_zero(sizeof(log_severity_list_t));
  3513. set_log_severity_config(loglevel, LOG_ERR, s);
  3514. add_stream_log(s, "", stdout);
  3515. }
  3516. options->command = CMD_RUN_UNITTESTS;
  3517. crypto_global_init(0);
  3518. rep_hist_init();
  3519. network_init();
  3520. setup_directory();
  3521. options_init(options);
  3522. options->DataDirectory = tor_strdup(temp_dir);
  3523. if (set_options(options, &errmsg) < 0) {
  3524. printf("Failed to set initial options: %s\n", errmsg);
  3525. tor_free(errmsg);
  3526. return 1;
  3527. }
  3528. crypto_seed_rng(1);
  3529. if (0) {
  3530. bench_aes();
  3531. return 0;
  3532. }
  3533. atexit(remove_directory);
  3534. printf("Running Tor unit tests on %s\n", get_uname());
  3535. for (i = 0; test_array[i].test_name; ++i) {
  3536. if (!test_array[i].selected)
  3537. continue;
  3538. if (!test_array[i].is_subent) {
  3539. printf("\n============================== %s\n",test_array[i].test_name);
  3540. } else if (test_array[i].is_subent && verbose) {
  3541. printf("\n%s", test_array[i].test_name);
  3542. }
  3543. test_array[i].test_fn();
  3544. }
  3545. puts("");
  3546. crypto_global_cleanup();
  3547. if (have_failed)
  3548. return 1;
  3549. else
  3550. return 0;
  3551. }