test.c 139 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170
  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,CMP_SEMANTIC); \
  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,CMP_SEMANTIC); \
  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), tor_addr_to_in6_addr32(&t1)[0]); \
  1152. test_eq(htonl(ip2), tor_addr_to_in6_addr32(&t1)[1]); \
  1153. test_eq(htonl(ip3), tor_addr_to_in6_addr32(&t1)[2]); \
  1154. test_eq(htonl(ip4), tor_addr_to_in6_addr32(&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 sockaddr_storage sa_storage;
  1170. struct sockaddr_in *sin;
  1171. struct sockaddr_in6 *sin6;
  1172. // struct in_addr b1, b2;
  1173. /* Test tor_inet_ntop and tor_inet_pton: IPv6 */
  1174. /* ==== Converting to and from sockaddr_t. */
  1175. sin = (struct sockaddr_in *)&sa_storage;
  1176. sin->sin_family = AF_INET;
  1177. sin->sin_port = 9090;
  1178. sin->sin_addr.s_addr = htonl(0x7f7f0102); /*127.127.1.2*/
  1179. tor_addr_from_sockaddr(&t1, (struct sockaddr *)sin);
  1180. test_eq(tor_addr_family(&t1), AF_INET);
  1181. test_eq(tor_addr_to_ipv4h(&t1), 0x7f7f0102);
  1182. memset(&sa_storage, 0, sizeof(sa_storage));
  1183. test_eq(sizeof(struct sockaddr_in),
  1184. tor_addr_to_sockaddr(&t1, 1234, (struct sockaddr *)&sa_storage,
  1185. sizeof(sa_storage)));
  1186. test_eq(1234, sin->sin_port);
  1187. test_eq(0x7f7f0102, ntohl(sin->sin_addr.s_addr));
  1188. memset(&sa_storage, 0, sizeof(sa_storage));
  1189. sin6 = (struct sockaddr_in6 *)&sa_storage;
  1190. sin6->sin6_family = AF_INET6;
  1191. sin6->sin6_port = 7070;
  1192. sin6->sin6_addr.s6_addr[0] = 128;
  1193. tor_addr_from_sockaddr(&t1, (struct sockaddr *)sin6);
  1194. test_eq(tor_addr_family(&t1), AF_INET6);
  1195. p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 0);
  1196. test_streq(p1, "8000::");
  1197. memset(&sa_storage, 0, sizeof(sa_storage));
  1198. test_eq(sizeof(struct sockaddr_in6),
  1199. tor_addr_to_sockaddr(&t1, 9999, (struct sockaddr *)&sa_storage,
  1200. sizeof(sa_storage)));
  1201. test_eq(AF_INET6, sin6->sin6_family);
  1202. test_eq(9999, sin6->sin6_port);
  1203. test_eq(0x80000000, ntohl(S6_ADDR32(sin6->sin6_addr)[0]));
  1204. /* ==== tor_addr_lookup: static cases. (Can't test dns without knowing we
  1205. * have a good resolver. */
  1206. test_eq(0, tor_addr_lookup("127.128.129.130", AF_UNSPEC, &t1));
  1207. test_eq(AF_INET, tor_addr_family(&t1));
  1208. test_eq(tor_addr_to_ipv4h(&t1), 0x7f808182);
  1209. test_eq(0, tor_addr_lookup("9000::5", AF_UNSPEC, &t1));
  1210. test_eq(AF_INET6, tor_addr_family(&t1));
  1211. test_eq(0x90, tor_addr_to_in6_addr8(&t1)[0]);
  1212. test_assert(tor_mem_is_zero((char*)tor_addr_to_in6_addr8(&t1)+1, 14));
  1213. test_eq(0x05, tor_addr_to_in6_addr8(&t1)[15]);
  1214. /* === Test pton: valid af_inet6 */
  1215. /* Simple, valid parsing. */
  1216. r = tor_inet_pton(AF_INET6,
  1217. "0102:0304:0506:0708:090A:0B0C:0D0E:0F10", &a1);
  1218. test_assert(r==1);
  1219. for (i=0;i<16;++i) { test_eq(i+1, (int)a1.s6_addr[i]); }
  1220. /* ipv4 ending. */
  1221. test_pton6_same("0102:0304:0506:0708:090A:0B0C:0D0E:0F10",
  1222. "0102:0304:0506:0708:090A:0B0C:13.14.15.16");
  1223. /* shortened words. */
  1224. test_pton6_same("0001:0099:BEEF:0000:0123:FFFF:0001:0001",
  1225. "1:99:BEEF:0:0123:FFFF:1:1");
  1226. /* zeros at the beginning */
  1227. test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
  1228. "::9:c0a8:1:1");
  1229. test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
  1230. "::9:c0a8:0.1.0.1");
  1231. /* zeros in the middle. */
  1232. test_pton6_same("fe80:0000:0000:0000:0202:1111:0001:0001",
  1233. "fe80::202:1111:1:1");
  1234. /* zeros at the end. */
  1235. test_pton6_same("1000:0001:0000:0007:0000:0000:0000:0000",
  1236. "1000:1:0:7::");
  1237. /* === Test ntop: af_inet6 */
  1238. test_ntop6_reduces("0:0:0:0:0:0:0:0", "::");
  1239. test_ntop6_reduces("0001:0099:BEEF:0006:0123:FFFF:0001:0001",
  1240. "1:99:beef:6:123:ffff:1:1");
  1241. //test_ntop6_reduces("0:0:0:0:0:0:c0a8:0101", "::192.168.1.1");
  1242. test_ntop6_reduces("0:0:0:0:0:ffff:c0a8:0101", "::ffff:192.168.1.1");
  1243. test_ntop6_reduces("002:0:0000:0:3::4", "2::3:0:0:4");
  1244. test_ntop6_reduces("0:0::1:0:3", "::1:0:3");
  1245. test_ntop6_reduces("008:0::0", "8::");
  1246. test_ntop6_reduces("0:0:0:0:0:ffff::1", "::ffff:0.0.0.1");
  1247. test_ntop6_reduces("abcd:0:0:0:0:0:7f00::", "abcd::7f00:0");
  1248. test_ntop6_reduces("0000:0000:0000:0000:0009:C0A8:0001:0001",
  1249. "::9:c0a8:1:1");
  1250. test_ntop6_reduces("fe80:0000:0000:0000:0202:1111:0001:0001",
  1251. "fe80::202:1111:1:1");
  1252. test_ntop6_reduces("1000:0001:0000:0007:0000:0000:0000:0000",
  1253. "1000:1:0:7::");
  1254. /* === Test pton: invalid in6. */
  1255. test_pton6_bad("foobar.");
  1256. test_pton6_bad("55555::");
  1257. test_pton6_bad("9:-60::");
  1258. test_pton6_bad("1:2:33333:4:0002:3::");
  1259. //test_pton6_bad("1:2:3333:4:00002:3::");// BAD, but glibc doesn't say so.
  1260. test_pton6_bad("1:2:3333:4:fish:3::");
  1261. test_pton6_bad("1:2:3:4:5:6:7:8:9");
  1262. test_pton6_bad("1:2:3:4:5:6:7");
  1263. test_pton6_bad("1:2:3:4:5:6:1.2.3.4.5");
  1264. test_pton6_bad("1:2:3:4:5:6:1.2.3");
  1265. test_pton6_bad("::1.2.3");
  1266. test_pton6_bad("::1.2.3.4.5");
  1267. test_pton6_bad("99");
  1268. test_pton6_bad("");
  1269. test_pton6_bad("1::2::3:4");
  1270. test_pton6_bad("a:::b:c");
  1271. test_pton6_bad(":::a:b:c");
  1272. test_pton6_bad("a:b:c:::");
  1273. /* test internal checking */
  1274. test_external_ip("fbff:ffff::2:7", 0);
  1275. test_internal_ip("fc01::2:7", 0);
  1276. test_internal_ip("fdff:ffff::f:f", 0);
  1277. test_external_ip("fe00::3:f", 0);
  1278. test_external_ip("fe7f:ffff::2:7", 0);
  1279. test_internal_ip("fe80::2:7", 0);
  1280. test_internal_ip("febf:ffff::f:f", 0);
  1281. test_internal_ip("fec0::2:7:7", 0);
  1282. test_internal_ip("feff:ffff::e:7:7", 0);
  1283. test_external_ip("ff00::e:7:7", 0);
  1284. test_internal_ip("::", 0);
  1285. test_internal_ip("::1", 0);
  1286. test_internal_ip("::1", 1);
  1287. test_internal_ip("::", 0);
  1288. test_external_ip("::", 1);
  1289. test_external_ip("::2", 0);
  1290. test_external_ip("2001::", 0);
  1291. test_external_ip("ffff::", 0);
  1292. test_external_ip("::ffff:0.0.0.0", 1);
  1293. test_internal_ip("::ffff:0.0.0.0", 0);
  1294. test_internal_ip("::ffff:0.255.255.255", 0);
  1295. test_external_ip("::ffff:1.0.0.0", 0);
  1296. test_external_ip("::ffff:9.255.255.255", 0);
  1297. test_internal_ip("::ffff:10.0.0.0", 0);
  1298. test_internal_ip("::ffff:10.255.255.255", 0);
  1299. test_external_ip("::ffff:11.0.0.0", 0);
  1300. test_external_ip("::ffff:126.255.255.255", 0);
  1301. test_internal_ip("::ffff:127.0.0.0", 0);
  1302. test_internal_ip("::ffff:127.255.255.255", 0);
  1303. test_external_ip("::ffff:128.0.0.0", 0);
  1304. test_external_ip("::ffff:172.15.255.255", 0);
  1305. test_internal_ip("::ffff:172.16.0.0", 0);
  1306. test_internal_ip("::ffff:172.31.255.255", 0);
  1307. test_external_ip("::ffff:172.32.0.0", 0);
  1308. test_external_ip("::ffff:192.167.255.255", 0);
  1309. test_internal_ip("::ffff:192.168.0.0", 0);
  1310. test_internal_ip("::ffff:192.168.255.255", 0);
  1311. test_external_ip("::ffff:192.169.0.0", 0);
  1312. test_external_ip("::ffff:169.253.255.255", 0);
  1313. test_internal_ip("::ffff:169.254.0.0", 0);
  1314. test_internal_ip("::ffff:169.254.255.255", 0);
  1315. test_external_ip("::ffff:169.255.0.0", 0);
  1316. test_assert(is_internal_IP(0x7f000001, 0));
  1317. /* tor_addr_compare(tor_addr_t x2) */
  1318. test_addr_compare("ffff::", ==, "ffff::0");
  1319. test_addr_compare("0::3:2:1", >, "0::ffff:0.3.2.1");
  1320. test_addr_compare("0::2:2:1", >, "0::ffff:0.3.2.1");
  1321. test_addr_compare("0::ffff:0.3.2.1", <, "0::0:0:0");
  1322. test_addr_compare("0::ffff:5.2.2.1", <, "::ffff:6.0.0.0"); /* XXXX wrong. */
  1323. tor_addr_parse_mask_ports("[::ffff:2.3.4.5]", &t1, NULL, NULL, NULL);
  1324. tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
  1325. test_assert(tor_addr_compare(&t1, &t2, CMP_SEMANTIC) == 0);
  1326. tor_addr_parse_mask_ports("[::ffff:2.3.4.4]", &t1, NULL, NULL, NULL);
  1327. tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
  1328. test_assert(tor_addr_compare(&t1, &t2, CMP_SEMANTIC) < 0);
  1329. /* test compare_masked */
  1330. test_addr_compare_masked("ffff::", ==, "ffff::0", 128);
  1331. test_addr_compare_masked("ffff::", ==, "ffff::0", 64);
  1332. test_addr_compare_masked("0::2:2:1", <, "0::8000:2:1", 81);
  1333. test_addr_compare_masked("0::2:2:1", ==, "0::8000:2:1", 80);
  1334. /* Test decorated addr_to_string. */
  1335. test_eq(AF_INET6, tor_addr_from_str(&t1, "[123:45:6789::5005:11]"));
  1336. p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
  1337. test_streq(p1, "[123:45:6789::5005:11]");
  1338. test_eq(AF_INET, tor_addr_from_str(&t1, "18.0.0.1"));
  1339. p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
  1340. test_streq(p1, "18.0.0.1");
  1341. /* test tor_addr_parse_mask_ports */
  1342. test_addr_mask_ports_parse("[::f]/17:47-95", AF_INET6,
  1343. 0, 0, 0, 0x0000000f, 17, 47, 95);
  1344. //test_addr_parse("[::fefe:4.1.1.7/120]:999-1000");
  1345. //test_addr_parse_check("::fefe:401:107", 120, 999, 1000);
  1346. test_addr_mask_ports_parse("[::ffff:4.1.1.7]/120:443", AF_INET6,
  1347. 0, 0, 0x0000ffff, 0x04010107, 120, 443, 443);
  1348. test_addr_mask_ports_parse("[abcd:2::44a:0]:2-65000", AF_INET6,
  1349. 0xabcd0002, 0, 0, 0x044a0000, 128, 2, 65000);
  1350. r=tor_addr_parse_mask_ports("[fefef::]/112", &t1, NULL, NULL, NULL);
  1351. test_assert(r == -1);
  1352. r=tor_addr_parse_mask_ports("efef::/112", &t1, NULL, NULL, NULL);
  1353. test_assert(r == -1);
  1354. r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f::]", &t1, NULL, NULL, NULL);
  1355. test_assert(r == -1);
  1356. r=tor_addr_parse_mask_ports("[::f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
  1357. test_assert(r == -1);
  1358. r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
  1359. test_assert(r == -1);
  1360. /* Test for V4-mapped address with mask < 96. (arguably not valid) */
  1361. r=tor_addr_parse_mask_ports("[::ffff:1.1.2.2/33]", &t1, &mask, NULL, NULL);
  1362. test_assert(r == -1);
  1363. r=tor_addr_parse_mask_ports("1.1.2.2/33", &t1, &mask, NULL, NULL);
  1364. test_assert(r == -1);
  1365. r=tor_addr_parse_mask_ports("1.1.2.2/31", &t1, &mask, NULL, NULL);
  1366. test_assert(r == AF_INET);
  1367. r=tor_addr_parse_mask_ports("[efef::]/112", &t1, &mask, &port1, &port2);
  1368. test_assert(r == AF_INET6);
  1369. test_assert(port1 == 1);
  1370. test_assert(port2 == 65535);
  1371. /* make sure inet address lengths >= max */
  1372. test_assert(INET_NTOA_BUF_LEN >= sizeof("255.255.255.255"));
  1373. test_assert(TOR_ADDR_BUF_LEN >=
  1374. sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"));
  1375. test_assert(sizeof(tor_addr_t) >= sizeof(struct in6_addr));
  1376. /* get interface addresses */
  1377. r = get_interface_address6(LOG_DEBUG, AF_INET, &t1);
  1378. i = get_interface_address6(LOG_DEBUG, AF_INET6, &t2);
  1379. #if 0
  1380. tor_inet_ntop(AF_INET, &t1.sa.sin_addr, buf, sizeof(buf));
  1381. printf("\nv4 address: %s (family=%i)", buf, IN_FAMILY(&t1));
  1382. tor_inet_ntop(AF_INET6, &t2.sa6.sin6_addr, buf, sizeof(buf));
  1383. printf("\nv6 address: %s (family=%i)", buf, IN_FAMILY(&t2));
  1384. #endif
  1385. }
  1386. static void
  1387. test_util_smartlist(void)
  1388. {
  1389. smartlist_t *sl;
  1390. char *cp;
  1391. size_t sz;
  1392. /* XXXX test sort_digests, uniq_strings, uniq_digests */
  1393. /* Test smartlist add, del_keeporder, insert, get. */
  1394. sl = smartlist_create();
  1395. smartlist_add(sl, (void*)1);
  1396. smartlist_add(sl, (void*)2);
  1397. smartlist_add(sl, (void*)3);
  1398. smartlist_add(sl, (void*)4);
  1399. smartlist_del_keeporder(sl, 1);
  1400. smartlist_insert(sl, 1, (void*)22);
  1401. smartlist_insert(sl, 0, (void*)0);
  1402. smartlist_insert(sl, 5, (void*)555);
  1403. test_eq_ptr((void*)0, smartlist_get(sl,0));
  1404. test_eq_ptr((void*)1, smartlist_get(sl,1));
  1405. test_eq_ptr((void*)22, smartlist_get(sl,2));
  1406. test_eq_ptr((void*)3, smartlist_get(sl,3));
  1407. test_eq_ptr((void*)4, smartlist_get(sl,4));
  1408. test_eq_ptr((void*)555, smartlist_get(sl,5));
  1409. /* Try deleting in the middle. */
  1410. smartlist_del(sl, 1);
  1411. test_eq_ptr((void*)555, smartlist_get(sl, 1));
  1412. /* Try deleting at the end. */
  1413. smartlist_del(sl, 4);
  1414. test_eq(4, smartlist_len(sl));
  1415. /* test isin. */
  1416. test_assert(smartlist_isin(sl, (void*)3));
  1417. test_assert(!smartlist_isin(sl, (void*)99));
  1418. /* Test split and join */
  1419. smartlist_clear(sl);
  1420. test_eq(0, smartlist_len(sl));
  1421. smartlist_split_string(sl, "abc", ":", 0, 0);
  1422. test_eq(1, smartlist_len(sl));
  1423. test_streq("abc", smartlist_get(sl, 0));
  1424. smartlist_split_string(sl, "a::bc::", "::", 0, 0);
  1425. test_eq(4, smartlist_len(sl));
  1426. test_streq("a", smartlist_get(sl, 1));
  1427. test_streq("bc", smartlist_get(sl, 2));
  1428. test_streq("", smartlist_get(sl, 3));
  1429. cp = smartlist_join_strings(sl, "", 0, NULL);
  1430. test_streq(cp, "abcabc");
  1431. tor_free(cp);
  1432. cp = smartlist_join_strings(sl, "!", 0, NULL);
  1433. test_streq(cp, "abc!a!bc!");
  1434. tor_free(cp);
  1435. cp = smartlist_join_strings(sl, "XY", 0, NULL);
  1436. test_streq(cp, "abcXYaXYbcXY");
  1437. tor_free(cp);
  1438. cp = smartlist_join_strings(sl, "XY", 1, NULL);
  1439. test_streq(cp, "abcXYaXYbcXYXY");
  1440. tor_free(cp);
  1441. cp = smartlist_join_strings(sl, "", 1, NULL);
  1442. test_streq(cp, "abcabc");
  1443. tor_free(cp);
  1444. smartlist_split_string(sl, "/def/ /ghijk", "/", 0, 0);
  1445. test_eq(8, smartlist_len(sl));
  1446. test_streq("", smartlist_get(sl, 4));
  1447. test_streq("def", smartlist_get(sl, 5));
  1448. test_streq(" ", smartlist_get(sl, 6));
  1449. test_streq("ghijk", smartlist_get(sl, 7));
  1450. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1451. smartlist_clear(sl);
  1452. smartlist_split_string(sl, "a,bbd,cdef", ",", SPLIT_SKIP_SPACE, 0);
  1453. test_eq(3, smartlist_len(sl));
  1454. test_streq("a", smartlist_get(sl,0));
  1455. test_streq("bbd", smartlist_get(sl,1));
  1456. test_streq("cdef", smartlist_get(sl,2));
  1457. smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
  1458. SPLIT_SKIP_SPACE, 0);
  1459. test_eq(8, smartlist_len(sl));
  1460. test_streq("z", smartlist_get(sl,3));
  1461. test_streq("zhasd", smartlist_get(sl,4));
  1462. test_streq("", smartlist_get(sl,5));
  1463. test_streq("bnud", smartlist_get(sl,6));
  1464. test_streq("", smartlist_get(sl,7));
  1465. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1466. smartlist_clear(sl);
  1467. smartlist_split_string(sl, " ab\tc \td ef ", NULL,
  1468. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1469. test_eq(4, smartlist_len(sl));
  1470. test_streq("ab", smartlist_get(sl,0));
  1471. test_streq("c", smartlist_get(sl,1));
  1472. test_streq("d", smartlist_get(sl,2));
  1473. test_streq("ef", smartlist_get(sl,3));
  1474. smartlist_split_string(sl, "ghi\tj", NULL,
  1475. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1476. test_eq(6, smartlist_len(sl));
  1477. test_streq("ghi", smartlist_get(sl,4));
  1478. test_streq("j", smartlist_get(sl,5));
  1479. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1480. smartlist_clear(sl);
  1481. cp = smartlist_join_strings(sl, "XY", 0, NULL);
  1482. test_streq(cp, "");
  1483. tor_free(cp);
  1484. cp = smartlist_join_strings(sl, "XY", 1, NULL);
  1485. test_streq(cp, "XY");
  1486. tor_free(cp);
  1487. smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
  1488. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1489. test_eq(3, smartlist_len(sl));
  1490. test_streq("z", smartlist_get(sl, 0));
  1491. test_streq("zhasd", smartlist_get(sl, 1));
  1492. test_streq("bnud", smartlist_get(sl, 2));
  1493. smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
  1494. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  1495. test_eq(5, smartlist_len(sl));
  1496. test_streq("z", smartlist_get(sl, 3));
  1497. test_streq("zhasd <> <> bnud<>", smartlist_get(sl, 4));
  1498. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1499. smartlist_clear(sl);
  1500. smartlist_split_string(sl, "abcd\n", "\n",
  1501. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1502. test_eq(1, smartlist_len(sl));
  1503. test_streq("abcd", smartlist_get(sl, 0));
  1504. smartlist_split_string(sl, "efgh", "\n",
  1505. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1506. test_eq(2, smartlist_len(sl));
  1507. test_streq("efgh", smartlist_get(sl, 1));
  1508. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1509. smartlist_clear(sl);
  1510. /* Test swapping, shuffling, and sorting. */
  1511. smartlist_split_string(sl, "the,onion,router,by,arma,and,nickm", ",", 0, 0);
  1512. test_eq(7, smartlist_len(sl));
  1513. smartlist_sort(sl, _compare_strs);
  1514. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1515. test_streq(cp,"and,arma,by,nickm,onion,router,the");
  1516. tor_free(cp);
  1517. smartlist_swap(sl, 1, 5);
  1518. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1519. test_streq(cp,"and,router,by,nickm,onion,arma,the");
  1520. tor_free(cp);
  1521. smartlist_shuffle(sl);
  1522. test_eq(7, smartlist_len(sl));
  1523. test_assert(smartlist_string_isin(sl, "and"));
  1524. test_assert(smartlist_string_isin(sl, "router"));
  1525. test_assert(smartlist_string_isin(sl, "by"));
  1526. test_assert(smartlist_string_isin(sl, "nickm"));
  1527. test_assert(smartlist_string_isin(sl, "onion"));
  1528. test_assert(smartlist_string_isin(sl, "arma"));
  1529. test_assert(smartlist_string_isin(sl, "the"));
  1530. /* Test bsearch. */
  1531. smartlist_sort(sl, _compare_strs);
  1532. test_streq("nickm", smartlist_bsearch(sl, "zNicKM",
  1533. _compare_without_first_ch));
  1534. test_streq("and", smartlist_bsearch(sl, " AND", _compare_without_first_ch));
  1535. test_eq_ptr(NULL, smartlist_bsearch(sl, " ANz", _compare_without_first_ch));
  1536. /* Test bsearch_idx */
  1537. {
  1538. int f;
  1539. test_eq(0, smartlist_bsearch_idx(sl," aaa",_compare_without_first_ch,&f));
  1540. test_eq(f, 0);
  1541. test_eq(0, smartlist_bsearch_idx(sl," and",_compare_without_first_ch,&f));
  1542. test_eq(f, 1);
  1543. test_eq(1, smartlist_bsearch_idx(sl," arm",_compare_without_first_ch,&f));
  1544. test_eq(f, 0);
  1545. test_eq(1, smartlist_bsearch_idx(sl," arma",_compare_without_first_ch,&f));
  1546. test_eq(f, 1);
  1547. test_eq(2, smartlist_bsearch_idx(sl," armb",_compare_without_first_ch,&f));
  1548. test_eq(f, 0);
  1549. test_eq(7, smartlist_bsearch_idx(sl," zzzz",_compare_without_first_ch,&f));
  1550. test_eq(f, 0);
  1551. }
  1552. /* Test reverse() and pop_last() */
  1553. smartlist_reverse(sl);
  1554. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1555. test_streq(cp,"the,router,onion,nickm,by,arma,and");
  1556. tor_free(cp);
  1557. cp = smartlist_pop_last(sl);
  1558. test_streq(cp, "and");
  1559. tor_free(cp);
  1560. test_eq(smartlist_len(sl), 6);
  1561. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1562. smartlist_clear(sl);
  1563. cp = smartlist_pop_last(sl);
  1564. test_eq(cp, NULL);
  1565. /* Test uniq() */
  1566. smartlist_split_string(sl,
  1567. "50,noon,radar,a,man,a,plan,a,canal,panama,radar,noon,50",
  1568. ",", 0, 0);
  1569. smartlist_sort(sl, _compare_strs);
  1570. smartlist_uniq(sl, _compare_strs, _tor_free);
  1571. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1572. test_streq(cp, "50,a,canal,man,noon,panama,plan,radar");
  1573. tor_free(cp);
  1574. /* Test string_isin and isin_case and num_isin */
  1575. test_assert(smartlist_string_isin(sl, "noon"));
  1576. test_assert(!smartlist_string_isin(sl, "noonoon"));
  1577. test_assert(smartlist_string_isin_case(sl, "nOOn"));
  1578. test_assert(!smartlist_string_isin_case(sl, "nooNooN"));
  1579. test_assert(smartlist_string_num_isin(sl, 50));
  1580. test_assert(!smartlist_string_num_isin(sl, 60));
  1581. /* Test smartlist_choose */
  1582. {
  1583. int i;
  1584. int allsame = 1;
  1585. int allin = 1;
  1586. void *first = smartlist_choose(sl);
  1587. test_assert(smartlist_isin(sl, first));
  1588. for (i = 0; i < 100; ++i) {
  1589. void *second = smartlist_choose(sl);
  1590. if (second != first)
  1591. allsame = 0;
  1592. if (!smartlist_isin(sl, second))
  1593. allin = 0;
  1594. }
  1595. test_assert(!allsame);
  1596. test_assert(allin);
  1597. }
  1598. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1599. smartlist_clear(sl);
  1600. /* Test string_remove and remove and join_strings2 */
  1601. smartlist_split_string(sl,
  1602. "Some say the Earth will end in ice and some in fire",
  1603. " ", 0, 0);
  1604. cp = smartlist_get(sl, 4);
  1605. test_streq(cp, "will");
  1606. smartlist_add(sl, cp);
  1607. smartlist_remove(sl, cp);
  1608. tor_free(cp);
  1609. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1610. test_streq(cp, "Some,say,the,Earth,fire,end,in,ice,and,some,in");
  1611. tor_free(cp);
  1612. smartlist_string_remove(sl, "in");
  1613. cp = smartlist_join_strings2(sl, "+XX", 1, 0, &sz);
  1614. test_streq(cp, "Some+say+the+Earth+fire+end+some+ice+and");
  1615. test_eq((int)sz, 40);
  1616. tor_free(cp);
  1617. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1618. smartlist_clear(sl);
  1619. {
  1620. smartlist_t *ints = smartlist_create();
  1621. smartlist_t *odds = smartlist_create();
  1622. smartlist_t *evens = smartlist_create();
  1623. smartlist_t *primes = smartlist_create();
  1624. int i;
  1625. for (i=1; i < 10; i += 2)
  1626. smartlist_add(odds, (void*)(uintptr_t)i);
  1627. for (i=0; i < 10; i += 2)
  1628. smartlist_add(evens, (void*)(uintptr_t)i);
  1629. /* add_all */
  1630. smartlist_add_all(ints, odds);
  1631. smartlist_add_all(ints, evens);
  1632. test_eq(smartlist_len(ints), 10);
  1633. smartlist_add(primes, (void*)2);
  1634. smartlist_add(primes, (void*)3);
  1635. smartlist_add(primes, (void*)5);
  1636. smartlist_add(primes, (void*)7);
  1637. /* overlap */
  1638. test_assert(smartlist_overlap(ints, odds));
  1639. test_assert(smartlist_overlap(odds, primes));
  1640. test_assert(smartlist_overlap(evens, primes));
  1641. test_assert(!smartlist_overlap(odds, evens));
  1642. /* intersect */
  1643. smartlist_add_all(sl, odds);
  1644. smartlist_intersect(sl, primes);
  1645. test_eq(smartlist_len(sl), 3);
  1646. test_assert(smartlist_isin(sl, (void*)3));
  1647. test_assert(smartlist_isin(sl, (void*)5));
  1648. test_assert(smartlist_isin(sl, (void*)7));
  1649. /* subtract */
  1650. smartlist_add_all(sl, primes);
  1651. smartlist_subtract(sl, odds);
  1652. test_eq(smartlist_len(sl), 1);
  1653. test_assert(smartlist_isin(sl, (void*)2));
  1654. smartlist_free(odds);
  1655. smartlist_free(evens);
  1656. smartlist_free(ints);
  1657. smartlist_free(primes);
  1658. smartlist_clear(sl);
  1659. }
  1660. {
  1661. /* digest_isin. */
  1662. smartlist_add(sl, tor_memdup("AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN));
  1663. smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
  1664. smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
  1665. test_eq(0, smartlist_digest_isin(NULL, "AAAAAAAAAAAAAAAAAAAA"));
  1666. test_assert(smartlist_digest_isin(sl, "AAAAAAAAAAAAAAAAAAAA"));
  1667. test_assert(smartlist_digest_isin(sl, "\00090AAB2AAAAaasdAAAAA"));
  1668. test_eq(0, smartlist_digest_isin(sl, "\00090AAB2AAABaasdAAAAA"));
  1669. /* sort digests */
  1670. smartlist_sort_digests(sl);
  1671. test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
  1672. test_memeq(smartlist_get(sl, 1), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
  1673. test_memeq(smartlist_get(sl, 2), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
  1674. test_eq(3, smartlist_len(sl));
  1675. /* uniq_digests */
  1676. smartlist_uniq_digests(sl);
  1677. test_eq(2, smartlist_len(sl));
  1678. test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
  1679. test_memeq(smartlist_get(sl, 1), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
  1680. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1681. smartlist_clear(sl);
  1682. }
  1683. {
  1684. smartlist_t *sl2 = smartlist_create(), *sl3 = smartlist_create(),
  1685. *sl4 = smartlist_create();
  1686. /* unique, sorted. */
  1687. smartlist_split_string(sl,
  1688. "Abashments Ambush Anchorman Bacon Banks Borscht "
  1689. "Bunks Inhumane Insurance Knish Know Manners "
  1690. "Maraschinos Stamina Sunbonnets Unicorns Wombats",
  1691. " ", 0, 0);
  1692. /* non-unique, sorted. */
  1693. smartlist_split_string(sl2,
  1694. "Ambush Anchorman Anchorman Anemias Anemias Bacon "
  1695. "Crossbowmen Inhumane Insurance Knish Know Manners "
  1696. "Manners Maraschinos Wombats Wombats Work",
  1697. " ", 0, 0);
  1698. SMARTLIST_FOREACH_JOIN(sl, char *, cp1,
  1699. sl2, char *, cp2,
  1700. strcmp(cp1,cp2),
  1701. smartlist_add(sl3, cp2)) {
  1702. test_streq(cp1, cp2);
  1703. smartlist_add(sl4, cp1);
  1704. } SMARTLIST_FOREACH_JOIN_END(cp1, cp2);
  1705. SMARTLIST_FOREACH(sl3, const char *, cp,
  1706. test_assert(smartlist_isin(sl2, cp) &&
  1707. !smartlist_string_isin(sl, cp)));
  1708. SMARTLIST_FOREACH(sl4, const char *, cp,
  1709. test_assert(smartlist_isin(sl, cp) &&
  1710. smartlist_string_isin(sl2, cp)));
  1711. cp = smartlist_join_strings(sl3, ",", 0, NULL);
  1712. test_streq(cp, "Anemias,Anemias,Crossbowmen,Work");
  1713. tor_free(cp);
  1714. cp = smartlist_join_strings(sl4, ",", 0, NULL);
  1715. test_streq(cp, "Ambush,Anchorman,Anchorman,Bacon,Inhumane,Insurance,"
  1716. "Knish,Know,Manners,Manners,Maraschinos,Wombats,Wombats");
  1717. tor_free(cp);
  1718. smartlist_free(sl4);
  1719. smartlist_free(sl3);
  1720. SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
  1721. smartlist_free(sl2);
  1722. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1723. smartlist_clear(sl);
  1724. }
  1725. smartlist_free(sl);
  1726. }
  1727. static void
  1728. test_util_bitarray(void)
  1729. {
  1730. bitarray_t *ba;
  1731. int i, j, ok=1;
  1732. ba = bitarray_init_zero(1);
  1733. test_assert(! bitarray_is_set(ba, 0));
  1734. bitarray_set(ba, 0);
  1735. test_assert(bitarray_is_set(ba, 0));
  1736. bitarray_clear(ba, 0);
  1737. test_assert(! bitarray_is_set(ba, 0));
  1738. bitarray_free(ba);
  1739. ba = bitarray_init_zero(1023);
  1740. for (i = 1; i < 64; ) {
  1741. for (j = 0; j < 1023; ++j) {
  1742. if (j % i)
  1743. bitarray_set(ba, j);
  1744. else
  1745. bitarray_clear(ba, j);
  1746. }
  1747. for (j = 0; j < 1023; ++j) {
  1748. if (!bool_eq(bitarray_is_set(ba, j), j%i))
  1749. ok = 0;
  1750. }
  1751. test_assert(ok);
  1752. if (i < 7)
  1753. ++i;
  1754. else if (i == 28)
  1755. i = 32;
  1756. else
  1757. i += 7;
  1758. }
  1759. bitarray_free(ba);
  1760. }
  1761. static void
  1762. test_util_digestset(void)
  1763. {
  1764. smartlist_t *included = smartlist_create();
  1765. char d[DIGEST_LEN];
  1766. int i;
  1767. int ok = 1;
  1768. int false_positives = 0;
  1769. digestset_t *set;
  1770. for (i = 0; i < 1000; ++i) {
  1771. crypto_rand(d, DIGEST_LEN);
  1772. smartlist_add(included, tor_memdup(d, DIGEST_LEN));
  1773. }
  1774. set = digestset_new(1000);
  1775. SMARTLIST_FOREACH(included, const char *, cp,
  1776. if (digestset_isin(set, cp))
  1777. ok = 0);
  1778. test_assert(ok);
  1779. SMARTLIST_FOREACH(included, const char *, cp,
  1780. digestset_add(set, cp));
  1781. SMARTLIST_FOREACH(included, const char *, cp,
  1782. if (!digestset_isin(set, cp))
  1783. ok = 0);
  1784. test_assert(ok);
  1785. for (i = 0; i < 1000; ++i) {
  1786. crypto_rand(d, DIGEST_LEN);
  1787. if (digestset_isin(set, d))
  1788. ++false_positives;
  1789. }
  1790. test_assert(false_positives < 50); /* Should be far lower. */
  1791. digestset_free(set);
  1792. }
  1793. /* stop threads running at once. */
  1794. static tor_mutex_t *_thread_test_mutex = NULL;
  1795. /* make sure that threads have to run at the same time. */
  1796. static tor_mutex_t *_thread_test_start1 = NULL;
  1797. static tor_mutex_t *_thread_test_start2 = NULL;
  1798. static strmap_t *_thread_test_strmap = NULL;
  1799. static void _thread_test_func(void* _s) ATTR_NORETURN;
  1800. static int t1_count = 0;
  1801. static int t2_count = 0;
  1802. static void
  1803. _thread_test_func(void* _s)
  1804. {
  1805. char *s = _s;
  1806. int i, *count;
  1807. tor_mutex_t *m;
  1808. char buf[64];
  1809. char *cp;
  1810. if (!strcmp(s, "thread 1")) {
  1811. m = _thread_test_start1;
  1812. count = &t1_count;
  1813. } else {
  1814. m = _thread_test_start2;
  1815. count = &t2_count;
  1816. }
  1817. tor_mutex_acquire(m);
  1818. tor_snprintf(buf, sizeof(buf), "%lu", tor_get_thread_id());
  1819. cp = tor_strdup(buf);
  1820. for (i=0; i<10000; ++i) {
  1821. tor_mutex_acquire(_thread_test_mutex);
  1822. strmap_set(_thread_test_strmap, "last to run", cp);
  1823. ++*count;
  1824. tor_mutex_release(_thread_test_mutex);
  1825. }
  1826. tor_mutex_acquire(_thread_test_mutex);
  1827. strmap_set(_thread_test_strmap, s, tor_strdup(buf));
  1828. tor_mutex_release(_thread_test_mutex);
  1829. tor_mutex_release(m);
  1830. spawn_exit();
  1831. }
  1832. static void
  1833. test_util_threads(void)
  1834. {
  1835. char *s1, *s2;
  1836. int done = 0, timedout = 0;
  1837. time_t started;
  1838. #ifndef TOR_IS_MULTITHREADED
  1839. /* Skip this test if we aren't threading. We should be threading most
  1840. * everywhere by now. */
  1841. if (1)
  1842. return;
  1843. #endif
  1844. _thread_test_mutex = tor_mutex_new();
  1845. _thread_test_start1 = tor_mutex_new();
  1846. _thread_test_start2 = tor_mutex_new();
  1847. _thread_test_strmap = strmap_new();
  1848. s1 = tor_strdup("thread 1");
  1849. s2 = tor_strdup("thread 2");
  1850. tor_mutex_acquire(_thread_test_start1);
  1851. tor_mutex_acquire(_thread_test_start2);
  1852. spawn_func(_thread_test_func, s1);
  1853. spawn_func(_thread_test_func, s2);
  1854. tor_mutex_release(_thread_test_start2);
  1855. tor_mutex_release(_thread_test_start1);
  1856. started = time(NULL);
  1857. while (!done) {
  1858. tor_mutex_acquire(_thread_test_mutex);
  1859. strmap_assert_ok(_thread_test_strmap);
  1860. if (strmap_get(_thread_test_strmap, "thread 1") &&
  1861. strmap_get(_thread_test_strmap, "thread 2")) {
  1862. done = 1;
  1863. } else if (time(NULL) > started + 25) {
  1864. timedout = done = 1;
  1865. }
  1866. tor_mutex_release(_thread_test_mutex);
  1867. }
  1868. tor_mutex_free(_thread_test_mutex);
  1869. if (timedout) {
  1870. printf("\nTimed out: %d %d", t1_count, t2_count);
  1871. test_assert(strmap_get(_thread_test_strmap, "thread 1"));
  1872. test_assert(strmap_get(_thread_test_strmap, "thread 2"));
  1873. test_assert(!timedout);
  1874. }
  1875. /* different thread IDs. */
  1876. test_assert(strcmp(strmap_get(_thread_test_strmap, "thread 1"),
  1877. strmap_get(_thread_test_strmap, "thread 2")));
  1878. test_assert(!strcmp(strmap_get(_thread_test_strmap, "thread 1"),
  1879. strmap_get(_thread_test_strmap, "last to run")) ||
  1880. !strcmp(strmap_get(_thread_test_strmap, "thread 2"),
  1881. strmap_get(_thread_test_strmap, "last to run")));
  1882. strmap_free(_thread_test_strmap, _tor_free);
  1883. tor_free(s1);
  1884. tor_free(s2);
  1885. }
  1886. static int
  1887. _compare_strings_for_pqueue(const void *s1, const void *s2)
  1888. {
  1889. return strcmp((const char*)s1, (const char*)s2);
  1890. }
  1891. static void
  1892. test_util_pqueue(void)
  1893. {
  1894. smartlist_t *sl;
  1895. int (*cmp)(const void *, const void*);
  1896. #define OK() smartlist_pqueue_assert_ok(sl, cmp)
  1897. cmp = _compare_strings_for_pqueue;
  1898. sl = smartlist_create();
  1899. smartlist_pqueue_add(sl, cmp, (char*)"cows");
  1900. smartlist_pqueue_add(sl, cmp, (char*)"zebras");
  1901. smartlist_pqueue_add(sl, cmp, (char*)"fish");
  1902. smartlist_pqueue_add(sl, cmp, (char*)"frogs");
  1903. smartlist_pqueue_add(sl, cmp, (char*)"apples");
  1904. smartlist_pqueue_add(sl, cmp, (char*)"squid");
  1905. smartlist_pqueue_add(sl, cmp, (char*)"daschunds");
  1906. smartlist_pqueue_add(sl, cmp, (char*)"eggplants");
  1907. smartlist_pqueue_add(sl, cmp, (char*)"weissbier");
  1908. smartlist_pqueue_add(sl, cmp, (char*)"lobsters");
  1909. smartlist_pqueue_add(sl, cmp, (char*)"roquefort");
  1910. OK();
  1911. test_eq(smartlist_len(sl), 11);
  1912. test_streq(smartlist_get(sl, 0), "apples");
  1913. test_streq(smartlist_pqueue_pop(sl, cmp), "apples");
  1914. test_eq(smartlist_len(sl), 10);
  1915. OK();
  1916. test_streq(smartlist_pqueue_pop(sl, cmp), "cows");
  1917. test_streq(smartlist_pqueue_pop(sl, cmp), "daschunds");
  1918. smartlist_pqueue_add(sl, cmp, (char*)"chinchillas");
  1919. OK();
  1920. smartlist_pqueue_add(sl, cmp, (char*)"fireflies");
  1921. OK();
  1922. test_streq(smartlist_pqueue_pop(sl, cmp), "chinchillas");
  1923. test_streq(smartlist_pqueue_pop(sl, cmp), "eggplants");
  1924. test_streq(smartlist_pqueue_pop(sl, cmp), "fireflies");
  1925. OK();
  1926. test_streq(smartlist_pqueue_pop(sl, cmp), "fish");
  1927. test_streq(smartlist_pqueue_pop(sl, cmp), "frogs");
  1928. test_streq(smartlist_pqueue_pop(sl, cmp), "lobsters");
  1929. test_streq(smartlist_pqueue_pop(sl, cmp), "roquefort");
  1930. OK();
  1931. test_eq(smartlist_len(sl), 3);
  1932. test_streq(smartlist_pqueue_pop(sl, cmp), "squid");
  1933. test_streq(smartlist_pqueue_pop(sl, cmp), "weissbier");
  1934. test_streq(smartlist_pqueue_pop(sl, cmp), "zebras");
  1935. test_eq(smartlist_len(sl), 0);
  1936. OK();
  1937. #undef OK
  1938. smartlist_free(sl);
  1939. }
  1940. static void
  1941. test_util_gzip(void)
  1942. {
  1943. char *buf1, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
  1944. const char *ccp2;
  1945. size_t len1, len2;
  1946. tor_zlib_state_t *state;
  1947. buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
  1948. test_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
  1949. if (is_gzip_supported()) {
  1950. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1951. GZIP_METHOD));
  1952. test_assert(buf2);
  1953. test_assert(!memcmp(buf2, "\037\213", 2)); /* Gzip magic. */
  1954. test_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
  1955. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  1956. GZIP_METHOD, 1, LOG_INFO));
  1957. test_assert(buf3);
  1958. test_streq(buf1,buf3);
  1959. tor_free(buf2);
  1960. tor_free(buf3);
  1961. }
  1962. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1963. ZLIB_METHOD));
  1964. test_assert(buf2);
  1965. test_assert(!memcmp(buf2, "\x78\xDA", 2)); /* deflate magic. */
  1966. test_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
  1967. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  1968. ZLIB_METHOD, 1, LOG_INFO));
  1969. test_assert(buf3);
  1970. test_streq(buf1,buf3);
  1971. /* Check whether we can uncompress concatenated, compresed strings. */
  1972. tor_free(buf3);
  1973. buf2 = tor_realloc(buf2, len1*2);
  1974. memcpy(buf2+len1, buf2, len1);
  1975. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
  1976. ZLIB_METHOD, 1, LOG_INFO));
  1977. test_eq(len2, (strlen(buf1)+1)*2);
  1978. test_memeq(buf3,
  1979. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
  1980. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
  1981. (strlen(buf1)+1)*2);
  1982. tor_free(buf1);
  1983. tor_free(buf2);
  1984. tor_free(buf3);
  1985. /* Check whether we can uncompress partial strings. */
  1986. buf1 =
  1987. tor_strdup("String with low redundancy that won't be compressed much.");
  1988. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1989. ZLIB_METHOD));
  1990. tor_assert(len1>16);
  1991. /* when we allow an uncomplete string, we should succeed.*/
  1992. tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  1993. ZLIB_METHOD, 0, LOG_INFO));
  1994. buf3[len2]='\0';
  1995. tor_assert(len2 > 5);
  1996. tor_assert(!strcmpstart(buf1, buf3));
  1997. /* when we demand a complete string, this must fail. */
  1998. tor_free(buf3);
  1999. tor_assert(tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  2000. ZLIB_METHOD, 1, LOG_INFO));
  2001. tor_assert(!buf3);
  2002. /* Now, try streaming compression. */
  2003. tor_free(buf1);
  2004. tor_free(buf2);
  2005. tor_free(buf3);
  2006. state = tor_zlib_new(1, ZLIB_METHOD);
  2007. tor_assert(state);
  2008. cp1 = buf1 = tor_malloc(1024);
  2009. len1 = 1024;
  2010. ccp2 = "ABCDEFGHIJABCDEFGHIJ";
  2011. len2 = 21;
  2012. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
  2013. == TOR_ZLIB_OK);
  2014. test_eq(len2, 0); /* Make sure we compressed it all. */
  2015. test_assert(cp1 > buf1);
  2016. len2 = 0;
  2017. cp2 = cp1;
  2018. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
  2019. == TOR_ZLIB_DONE);
  2020. test_eq(len2, 0);
  2021. test_assert(cp1 > cp2); /* Make sure we really added something. */
  2022. tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf1, 1024-len1,
  2023. ZLIB_METHOD, 1, LOG_WARN));
  2024. test_streq(buf3, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
  2025. tor_free(buf3);
  2026. tor_zlib_free(state);
  2027. tor_free(buf2);
  2028. tor_free(buf3);
  2029. tor_free(buf1);
  2030. }
  2031. static void
  2032. test_util_strmap(void)
  2033. {
  2034. strmap_t *map;
  2035. strmap_iter_t *iter;
  2036. const char *k;
  2037. void *v;
  2038. char *visited;
  2039. smartlist_t *found_keys;
  2040. map = strmap_new();
  2041. test_eq(strmap_size(map), 0);
  2042. test_assert(strmap_isempty(map));
  2043. v = strmap_set(map, "K1", (void*)99);
  2044. test_eq(v, NULL);
  2045. test_assert(!strmap_isempty(map));
  2046. v = strmap_set(map, "K2", (void*)101);
  2047. test_eq(v, NULL);
  2048. v = strmap_set(map, "K1", (void*)100);
  2049. test_eq(v, (void*)99);
  2050. test_eq_ptr(strmap_get(map,"K1"), (void*)100);
  2051. test_eq_ptr(strmap_get(map,"K2"), (void*)101);
  2052. test_eq_ptr(strmap_get(map,"K-not-there"), NULL);
  2053. strmap_assert_ok(map);
  2054. v = strmap_remove(map,"K2");
  2055. strmap_assert_ok(map);
  2056. test_eq_ptr(v, (void*)101);
  2057. test_eq_ptr(strmap_get(map,"K2"), NULL);
  2058. test_eq_ptr(strmap_remove(map,"K2"), NULL);
  2059. strmap_set(map, "K2", (void*)101);
  2060. strmap_set(map, "K3", (void*)102);
  2061. strmap_set(map, "K4", (void*)103);
  2062. test_eq(strmap_size(map), 4);
  2063. strmap_assert_ok(map);
  2064. strmap_set(map, "K5", (void*)104);
  2065. strmap_set(map, "K6", (void*)105);
  2066. strmap_assert_ok(map);
  2067. /* Test iterator. */
  2068. iter = strmap_iter_init(map);
  2069. found_keys = smartlist_create();
  2070. while (!strmap_iter_done(iter)) {
  2071. strmap_iter_get(iter,&k,&v);
  2072. smartlist_add(found_keys, tor_strdup(k));
  2073. test_eq_ptr(v, strmap_get(map, k));
  2074. if (!strcmp(k, "K2")) {
  2075. iter = strmap_iter_next_rmv(map,iter);
  2076. } else {
  2077. iter = strmap_iter_next(map,iter);
  2078. }
  2079. }
  2080. /* Make sure we removed K2, but not the others. */
  2081. test_eq_ptr(strmap_get(map, "K2"), NULL);
  2082. test_eq_ptr(strmap_get(map, "K5"), (void*)104);
  2083. /* Make sure we visited everyone once */
  2084. smartlist_sort_strings(found_keys);
  2085. visited = smartlist_join_strings(found_keys, ":", 0, NULL);
  2086. test_streq(visited, "K1:K2:K3:K4:K5:K6");
  2087. tor_free(visited);
  2088. SMARTLIST_FOREACH(found_keys, char *, cp, tor_free(cp));
  2089. smartlist_free(found_keys);
  2090. strmap_assert_ok(map);
  2091. /* Clean up after ourselves. */
  2092. strmap_free(map, NULL);
  2093. /* Now try some lc functions. */
  2094. map = strmap_new();
  2095. strmap_set_lc(map,"Ab.C", (void*)1);
  2096. test_eq_ptr(strmap_get(map,"ab.c"), (void*)1);
  2097. strmap_assert_ok(map);
  2098. test_eq_ptr(strmap_get_lc(map,"AB.C"), (void*)1);
  2099. test_eq_ptr(strmap_get(map,"AB.C"), NULL);
  2100. test_eq_ptr(strmap_remove_lc(map,"aB.C"), (void*)1);
  2101. strmap_assert_ok(map);
  2102. test_eq_ptr(strmap_get_lc(map,"AB.C"), NULL);
  2103. strmap_free(map,NULL);
  2104. }
  2105. static void
  2106. test_util_mmap(void)
  2107. {
  2108. char *fname1 = tor_strdup(get_fname("mapped_1"));
  2109. char *fname2 = tor_strdup(get_fname("mapped_2"));
  2110. char *fname3 = tor_strdup(get_fname("mapped_3"));
  2111. const size_t buflen = 17000;
  2112. char *buf = tor_malloc(17000);
  2113. tor_mmap_t *mapping;
  2114. crypto_rand(buf, buflen);
  2115. mapping = tor_mmap_file(fname1);
  2116. test_assert(! mapping);
  2117. write_str_to_file(fname1, "Short file.", 1);
  2118. write_bytes_to_file(fname2, buf, buflen, 1);
  2119. write_bytes_to_file(fname3, buf, 16384, 1);
  2120. mapping = tor_mmap_file(fname1);
  2121. test_assert(mapping);
  2122. test_eq(mapping->size, strlen("Short file."));
  2123. test_streq(mapping->data, "Short file.");
  2124. #ifdef MS_WINDOWS
  2125. tor_munmap_file(mapping);
  2126. test_assert(unlink(fname1) == 0);
  2127. #else
  2128. /* make sure we can unlink. */
  2129. test_assert(unlink(fname1) == 0);
  2130. test_streq(mapping->data, "Short file.");
  2131. tor_munmap_file(mapping);
  2132. #endif
  2133. /* Now a zero-length file. */
  2134. write_str_to_file(fname1, "", 1);
  2135. mapping = tor_mmap_file(fname1);
  2136. test_eq(mapping, NULL);
  2137. test_eq(ERANGE, errno);
  2138. unlink(fname1);
  2139. /* Make sure that we fail to map a no-longer-existent file. */
  2140. mapping = tor_mmap_file(fname1);
  2141. test_assert(mapping == NULL);
  2142. /* Now try a big file that stretches across a few pages and isn't aligned */
  2143. mapping = tor_mmap_file(fname2);
  2144. test_assert(mapping);
  2145. test_eq(mapping->size, buflen);
  2146. test_memeq(mapping->data, buf, buflen);
  2147. tor_munmap_file(mapping);
  2148. /* Now try a big aligned file. */
  2149. mapping = tor_mmap_file(fname3);
  2150. test_assert(mapping);
  2151. test_eq(mapping->size, 16384);
  2152. test_memeq(mapping->data, buf, 16384);
  2153. tor_munmap_file(mapping);
  2154. /* fname1 got unlinked above */
  2155. unlink(fname2);
  2156. unlink(fname3);
  2157. tor_free(fname1);
  2158. tor_free(fname2);
  2159. tor_free(fname3);
  2160. tor_free(buf);
  2161. }
  2162. static void
  2163. test_util_control_formats(void)
  2164. {
  2165. char *out;
  2166. const char *inp =
  2167. "..This is a test\r\nof the emergency \nbroadcast\r\n..system.\r\nZ.\r\n";
  2168. size_t sz;
  2169. sz = read_escaped_data(inp, strlen(inp), &out);
  2170. test_streq(out,
  2171. ".This is a test\nof the emergency \nbroadcast\n.system.\nZ.\n");
  2172. test_eq(sz, strlen(out));
  2173. tor_free(out);
  2174. }
  2175. static void
  2176. test_onion_handshake(void)
  2177. {
  2178. /* client-side */
  2179. crypto_dh_env_t *c_dh = NULL;
  2180. char c_buf[ONIONSKIN_CHALLENGE_LEN];
  2181. char c_keys[40];
  2182. /* server-side */
  2183. char s_buf[ONIONSKIN_REPLY_LEN];
  2184. char s_keys[40];
  2185. /* shared */
  2186. crypto_pk_env_t *pk = NULL;
  2187. pk = pk_generate(0);
  2188. /* client handshake 1. */
  2189. memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
  2190. test_assert(! onion_skin_create(pk, &c_dh, c_buf));
  2191. /* server handshake */
  2192. memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
  2193. memset(s_keys, 0, 40);
  2194. test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
  2195. s_buf, s_keys, 40));
  2196. /* client handshake 2 */
  2197. memset(c_keys, 0, 40);
  2198. test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
  2199. crypto_dh_free(c_dh);
  2200. if (memcmp(c_keys, s_keys, 40)) {
  2201. puts("Aiiiie");
  2202. exit(1);
  2203. }
  2204. test_memeq(c_keys, s_keys, 40);
  2205. memset(s_buf, 0, 40);
  2206. test_memneq(c_keys, s_buf, 40);
  2207. crypto_free_pk_env(pk);
  2208. }
  2209. extern smartlist_t *fingerprint_list;
  2210. static void
  2211. test_dir_format(void)
  2212. {
  2213. char buf[8192], buf2[8192];
  2214. char platform[256];
  2215. char fingerprint[FINGERPRINT_LEN+1];
  2216. char *pk1_str = NULL, *pk2_str = NULL, *pk3_str = NULL, *cp;
  2217. size_t pk1_str_len, pk2_str_len, pk3_str_len;
  2218. routerinfo_t *r1, *r2;
  2219. crypto_pk_env_t *pk1 = NULL, *pk2 = NULL, *pk3 = NULL;
  2220. routerinfo_t *rp1 = NULL, *rp2 = NULL;
  2221. addr_policy_t *ex1, *ex2;
  2222. routerlist_t *dir1 = NULL, *dir2 = NULL;
  2223. tor_version_t ver1;
  2224. pk1 = pk_generate(0);
  2225. pk2 = pk_generate(1);
  2226. pk3 = pk_generate(2);
  2227. test_assert( is_legal_nickname("a"));
  2228. test_assert(!is_legal_nickname(""));
  2229. test_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
  2230. test_assert(!is_legal_nickname("hyphen-")); /* bad char */
  2231. test_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
  2232. test_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2233. /* valid */
  2234. test_assert( is_legal_nickname_or_hexdigest(
  2235. "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2236. test_assert( is_legal_nickname_or_hexdigest(
  2237. "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
  2238. test_assert( is_legal_nickname_or_hexdigest(
  2239. "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
  2240. /* too short */
  2241. test_assert(!is_legal_nickname_or_hexdigest(
  2242. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2243. /* illegal char */
  2244. test_assert(!is_legal_nickname_or_hexdigest(
  2245. "$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2246. /* hex part too long */
  2247. test_assert(!is_legal_nickname_or_hexdigest(
  2248. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2249. test_assert(!is_legal_nickname_or_hexdigest(
  2250. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
  2251. /* Bad nickname */
  2252. test_assert(!is_legal_nickname_or_hexdigest(
  2253. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
  2254. test_assert(!is_legal_nickname_or_hexdigest(
  2255. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
  2256. test_assert(!is_legal_nickname_or_hexdigest(
  2257. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
  2258. test_assert(!is_legal_nickname_or_hexdigest(
  2259. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
  2260. "abcdefghijklmnoppqrst"));
  2261. /* Bad extra char. */
  2262. test_assert(!is_legal_nickname_or_hexdigest(
  2263. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
  2264. test_assert(is_legal_nickname_or_hexdigest("xyzzy"));
  2265. test_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
  2266. test_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
  2267. get_platform_str(platform, sizeof(platform));
  2268. r1 = tor_malloc_zero(sizeof(routerinfo_t));
  2269. r1->address = tor_strdup("18.244.0.1");
  2270. r1->addr = 0xc0a80001u; /* 192.168.0.1 */
  2271. r1->cache_info.published_on = 0;
  2272. r1->or_port = 9000;
  2273. r1->dir_port = 9003;
  2274. r1->onion_pkey = crypto_pk_dup_key(pk1);
  2275. r1->identity_pkey = crypto_pk_dup_key(pk2);
  2276. r1->bandwidthrate = 1000;
  2277. r1->bandwidthburst = 5000;
  2278. r1->bandwidthcapacity = 10000;
  2279. r1->exit_policy = NULL;
  2280. r1->nickname = tor_strdup("Magri");
  2281. r1->platform = tor_strdup(platform);
  2282. ex1 = tor_malloc_zero(sizeof(addr_policy_t));
  2283. ex2 = tor_malloc_zero(sizeof(addr_policy_t));
  2284. ex1->policy_type = ADDR_POLICY_ACCEPT;
  2285. tor_addr_from_ipv4h(&ex1->addr, 0);
  2286. ex1->maskbits = 0;
  2287. ex1->prt_min = ex1->prt_max = 80;
  2288. ex2->policy_type = ADDR_POLICY_REJECT;
  2289. tor_addr_from_ipv4h(&ex2->addr, 18<<24);
  2290. ex2->maskbits = 8;
  2291. ex2->prt_min = ex2->prt_max = 24;
  2292. r2 = tor_malloc_zero(sizeof(routerinfo_t));
  2293. r2->address = tor_strdup("1.1.1.1");
  2294. r2->addr = 0x0a030201u; /* 10.3.2.1 */
  2295. r2->platform = tor_strdup(platform);
  2296. r2->cache_info.published_on = 5;
  2297. r2->or_port = 9005;
  2298. r2->dir_port = 0;
  2299. r2->onion_pkey = crypto_pk_dup_key(pk2);
  2300. r2->identity_pkey = crypto_pk_dup_key(pk1);
  2301. r2->bandwidthrate = r2->bandwidthburst = r2->bandwidthcapacity = 3000;
  2302. r2->exit_policy = smartlist_create();
  2303. smartlist_add(r2->exit_policy, ex2);
  2304. smartlist_add(r2->exit_policy, ex1);
  2305. r2->nickname = tor_strdup("Fred");
  2306. test_assert(!crypto_pk_write_public_key_to_string(pk1, &pk1_str,
  2307. &pk1_str_len));
  2308. test_assert(!crypto_pk_write_public_key_to_string(pk2 , &pk2_str,
  2309. &pk2_str_len));
  2310. test_assert(!crypto_pk_write_public_key_to_string(pk3 , &pk3_str,
  2311. &pk3_str_len));
  2312. memset(buf, 0, 2048);
  2313. test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
  2314. strlcpy(buf2, "router Magri 18.244.0.1 9000 0 9003\n"
  2315. "platform Tor "VERSION" on ", sizeof(buf2));
  2316. strlcat(buf2, get_uname(), sizeof(buf2));
  2317. strlcat(buf2, "\n"
  2318. "opt protocols Link 1 2 Circuit 1\n"
  2319. "published 1970-01-01 00:00:00\n"
  2320. "opt fingerprint ", sizeof(buf2));
  2321. test_assert(!crypto_pk_get_fingerprint(pk2, fingerprint, 1));
  2322. strlcat(buf2, fingerprint, sizeof(buf2));
  2323. strlcat(buf2, "\nuptime 0\n"
  2324. /* XXX the "0" above is hardcoded, but even if we made it reflect
  2325. * uptime, that still wouldn't make it right, because the two
  2326. * descriptors might be made on different seconds... hm. */
  2327. "bandwidth 1000 5000 10000\n"
  2328. "opt extra-info-digest 0000000000000000000000000000000000000000\n"
  2329. "onion-key\n", sizeof(buf2));
  2330. strlcat(buf2, pk1_str, sizeof(buf2));
  2331. strlcat(buf2, "signing-key\n", sizeof(buf2));
  2332. strlcat(buf2, pk2_str, sizeof(buf2));
  2333. strlcat(buf2, "reject *:*\nrouter-signature\n", sizeof(buf2));
  2334. buf[strlen(buf2)] = '\0'; /* Don't compare the sig; it's never the same
  2335. * twice */
  2336. test_streq(buf, buf2);
  2337. test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
  2338. cp = buf;
  2339. rp1 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL);
  2340. test_assert(rp1);
  2341. test_streq(rp1->address, r1->address);
  2342. test_eq(rp1->or_port, r1->or_port);
  2343. //test_eq(rp1->dir_port, r1->dir_port);
  2344. test_eq(rp1->bandwidthrate, r1->bandwidthrate);
  2345. test_eq(rp1->bandwidthburst, r1->bandwidthburst);
  2346. test_eq(rp1->bandwidthcapacity, r1->bandwidthcapacity);
  2347. test_assert(crypto_pk_cmp_keys(rp1->onion_pkey, pk1) == 0);
  2348. test_assert(crypto_pk_cmp_keys(rp1->identity_pkey, pk2) == 0);
  2349. //test_assert(rp1->exit_policy == NULL);
  2350. #if 0
  2351. /* XXX Once we have exit policies, test this again. XXX */
  2352. strlcpy(buf2, "router tor.tor.tor 9005 0 0 3000\n", sizeof(buf2));
  2353. strlcat(buf2, pk2_str, sizeof(buf2));
  2354. strlcat(buf2, "signing-key\n", sizeof(buf2));
  2355. strlcat(buf2, pk1_str, sizeof(buf2));
  2356. strlcat(buf2, "accept *:80\nreject 18.*:24\n\n", sizeof(buf2));
  2357. test_assert(router_dump_router_to_string(buf, 2048, &r2, pk2)>0);
  2358. test_streq(buf, buf2);
  2359. cp = buf;
  2360. rp2 = router_parse_entry_from_string(&cp,1);
  2361. test_assert(rp2);
  2362. test_streq(rp2->address, r2.address);
  2363. test_eq(rp2->or_port, r2.or_port);
  2364. test_eq(rp2->dir_port, r2.dir_port);
  2365. test_eq(rp2->bandwidth, r2.bandwidth);
  2366. test_assert(crypto_pk_cmp_keys(rp2->onion_pkey, pk2) == 0);
  2367. test_assert(crypto_pk_cmp_keys(rp2->identity_pkey, pk1) == 0);
  2368. test_eq(rp2->exit_policy->policy_type, EXIT_POLICY_ACCEPT);
  2369. test_streq(rp2->exit_policy->string, "accept *:80");
  2370. test_streq(rp2->exit_policy->address, "*");
  2371. test_streq(rp2->exit_policy->port, "80");
  2372. test_eq(rp2->exit_policy->next->policy_type, EXIT_POLICY_REJECT);
  2373. test_streq(rp2->exit_policy->next->string, "reject 18.*:24");
  2374. test_streq(rp2->exit_policy->next->address, "18.*");
  2375. test_streq(rp2->exit_policy->next->port, "24");
  2376. test_assert(rp2->exit_policy->next->next == NULL);
  2377. /* Okay, now for the directories. */
  2378. {
  2379. fingerprint_list = smartlist_create();
  2380. crypto_pk_get_fingerprint(pk2, buf, 1);
  2381. add_fingerprint_to_dir("Magri", buf, fingerprint_list);
  2382. crypto_pk_get_fingerprint(pk1, buf, 1);
  2383. add_fingerprint_to_dir("Fred", buf, fingerprint_list);
  2384. }
  2385. {
  2386. char d[DIGEST_LEN];
  2387. const char *m;
  2388. /* XXXX NM re-enable. */
  2389. /* Make sure routers aren't too far in the past any more. */
  2390. r1->cache_info.published_on = time(NULL);
  2391. r2->cache_info.published_on = time(NULL)-3*60*60;
  2392. test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
  2393. test_eq(dirserv_add_descriptor(buf,&m), 2);
  2394. test_assert(router_dump_router_to_string(buf, 2048, r2, pk1)>0);
  2395. test_eq(dirserv_add_descriptor(buf,&m), 2);
  2396. get_options()->Nickname = tor_strdup("DirServer");
  2397. test_assert(!dirserv_dump_directory_to_string(&cp,pk3, 0));
  2398. crypto_pk_get_digest(pk3, d);
  2399. test_assert(!router_parse_directory(cp));
  2400. test_eq(2, smartlist_len(dir1->routers));
  2401. tor_free(cp);
  2402. }
  2403. #endif
  2404. dirserv_free_fingerprint_list();
  2405. tor_free(pk1_str);
  2406. tor_free(pk2_str);
  2407. tor_free(pk3_str);
  2408. if (pk1) crypto_free_pk_env(pk1);
  2409. if (pk2) crypto_free_pk_env(pk2);
  2410. if (pk3) crypto_free_pk_env(pk3);
  2411. if (rp1) routerinfo_free(rp1);
  2412. if (rp2) routerinfo_free(rp2);
  2413. tor_free(dir1); /* XXXX And more !*/
  2414. tor_free(dir2); /* And more !*/
  2415. routerinfo_free(r1);
  2416. routerinfo_free(r2);
  2417. /* Try out version parsing functionality */
  2418. test_eq(0, tor_version_parse("0.3.4pre2-cvs", &ver1));
  2419. test_eq(0, ver1.major);
  2420. test_eq(3, ver1.minor);
  2421. test_eq(4, ver1.micro);
  2422. test_eq(VER_PRE, ver1.status);
  2423. test_eq(2, ver1.patchlevel);
  2424. test_eq(0, tor_version_parse("0.3.4rc1", &ver1));
  2425. test_eq(0, ver1.major);
  2426. test_eq(3, ver1.minor);
  2427. test_eq(4, ver1.micro);
  2428. test_eq(VER_RC, ver1.status);
  2429. test_eq(1, ver1.patchlevel);
  2430. test_eq(0, tor_version_parse("1.3.4", &ver1));
  2431. test_eq(1, ver1.major);
  2432. test_eq(3, ver1.minor);
  2433. test_eq(4, ver1.micro);
  2434. test_eq(VER_RELEASE, ver1.status);
  2435. test_eq(0, ver1.patchlevel);
  2436. test_eq(0, tor_version_parse("1.3.4.999", &ver1));
  2437. test_eq(1, ver1.major);
  2438. test_eq(3, ver1.minor);
  2439. test_eq(4, ver1.micro);
  2440. test_eq(VER_RELEASE, ver1.status);
  2441. test_eq(999, ver1.patchlevel);
  2442. test_eq(0, tor_version_parse("0.1.2.4-alpha", &ver1));
  2443. test_eq(0, ver1.major);
  2444. test_eq(1, ver1.minor);
  2445. test_eq(2, ver1.micro);
  2446. test_eq(4, ver1.patchlevel);
  2447. test_eq(VER_RELEASE, ver1.status);
  2448. test_streq("alpha", ver1.status_tag);
  2449. test_eq(0, tor_version_parse("0.1.2.4", &ver1));
  2450. test_eq(0, ver1.major);
  2451. test_eq(1, ver1.minor);
  2452. test_eq(2, ver1.micro);
  2453. test_eq(4, ver1.patchlevel);
  2454. test_eq(VER_RELEASE, ver1.status);
  2455. test_streq("", ver1.status_tag);
  2456. #define test_eq_vs(vs1, vs2) test_eq_type(version_status_t, "%d", (vs1), (vs2))
  2457. #define test_v_i_o(val, ver, lst) \
  2458. test_eq_vs(val, tor_version_is_obsolete(ver, lst))
  2459. /* make sure tor_version_is_obsolete() works */
  2460. test_v_i_o(VS_OLD, "0.0.1", "Tor 0.0.2");
  2461. test_v_i_o(VS_OLD, "0.0.1", "0.0.2, Tor 0.0.3");
  2462. test_v_i_o(VS_OLD, "0.0.1", "0.0.2,Tor 0.0.3");
  2463. test_v_i_o(VS_OLD, "0.0.1","0.0.3,BetterTor 0.0.1");
  2464. test_v_i_o(VS_RECOMMENDED, "0.0.2", "Tor 0.0.2,Tor 0.0.3");
  2465. test_v_i_o(VS_NEW_IN_SERIES, "0.0.2", "Tor 0.0.2pre1,Tor 0.0.3");
  2466. test_v_i_o(VS_OLD, "0.0.2", "Tor 0.0.2.1,Tor 0.0.3");
  2467. test_v_i_o(VS_NEW, "0.1.0", "Tor 0.0.2,Tor 0.0.3");
  2468. test_v_i_o(VS_RECOMMENDED, "0.0.7rc2", "0.0.7,Tor 0.0.7rc2,Tor 0.0.8");
  2469. test_v_i_o(VS_OLD, "0.0.5.0", "0.0.5.1-cvs");
  2470. test_v_i_o(VS_NEW_IN_SERIES, "0.0.5.1-cvs", "0.0.5, 0.0.6");
  2471. /* Not on list, but newer than any in same series. */
  2472. test_v_i_o(VS_NEW_IN_SERIES, "0.1.0.3",
  2473. "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2474. /* Series newer than any on list. */
  2475. 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");
  2476. /* Series older than any on list. */
  2477. 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");
  2478. /* Not on list, not newer than any on same series. */
  2479. test_v_i_o(VS_UNRECOMMENDED, "0.1.0.1",
  2480. "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2481. /* On list, not newer than any on same series. */
  2482. test_v_i_o(VS_UNRECOMMENDED,
  2483. "0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2484. test_eq(0, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
  2485. test_eq(1, tor_version_as_new_as(
  2486. "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
  2487. "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
  2488. "0.0.8rc2"));
  2489. test_eq(0, tor_version_as_new_as(
  2490. "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
  2491. "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
  2492. /* Now try svn revisions. */
  2493. test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
  2494. "Tor 0.2.1.0-dev (r99)"));
  2495. test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100) on Banana Jr",
  2496. "Tor 0.2.1.0-dev (r99) on Hal 9000"));
  2497. test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
  2498. "Tor 0.2.1.0-dev on Colossus"));
  2499. test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
  2500. "Tor 0.2.1.0-dev (r100)"));
  2501. test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
  2502. "Tor 0.2.1.0-dev (r100) on AM"));
  2503. test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev",
  2504. "Tor 0.2.1.0-dev (r99)"));
  2505. test_eq(1, tor_version_as_new_as("Tor 0.2.1.1",
  2506. "Tor 0.2.1.0-dev (r99)"));
  2507. }
  2508. extern const char AUTHORITY_CERT_1[];
  2509. extern const char AUTHORITY_SIGNKEY_1[];
  2510. extern const char AUTHORITY_CERT_2[];
  2511. extern const char AUTHORITY_SIGNKEY_2[];
  2512. extern const char AUTHORITY_CERT_3[];
  2513. extern const char AUTHORITY_SIGNKEY_3[];
  2514. static void
  2515. test_same_voter(networkstatus_voter_info_t *v1,
  2516. networkstatus_voter_info_t *v2)
  2517. {
  2518. test_streq(v1->nickname, v2->nickname);
  2519. test_memeq(v1->identity_digest, v2->identity_digest, DIGEST_LEN);
  2520. test_streq(v1->address, v2->address);
  2521. test_eq(v1->addr, v2->addr);
  2522. test_eq(v1->dir_port, v2->dir_port);
  2523. test_eq(v1->or_port, v2->or_port);
  2524. test_streq(v1->contact, v2->contact);
  2525. test_memeq(v1->vote_digest, v2->vote_digest, DIGEST_LEN);
  2526. }
  2527. static void
  2528. test_util_order_functions(void)
  2529. {
  2530. int lst[25], n = 0;
  2531. // int a=12,b=24,c=25,d=60,e=77;
  2532. #define median() median_int(lst, n)
  2533. lst[n++] = 12;
  2534. test_eq(12, median()); /* 12 */
  2535. lst[n++] = 77;
  2536. //smartlist_shuffle(sl);
  2537. test_eq(12, median()); /* 12, 77 */
  2538. lst[n++] = 77;
  2539. //smartlist_shuffle(sl);
  2540. test_eq(77, median()); /* 12, 77, 77 */
  2541. lst[n++] = 24;
  2542. test_eq(24, median()); /* 12,24,77,77 */
  2543. lst[n++] = 60;
  2544. lst[n++] = 12;
  2545. lst[n++] = 25;
  2546. //smartlist_shuffle(sl);
  2547. test_eq(25, median()); /* 12,12,24,25,60,77,77 */
  2548. #undef median
  2549. }
  2550. static void
  2551. test_v3_networkstatus(void)
  2552. {
  2553. authority_cert_t *cert1, *cert2, *cert3;
  2554. crypto_pk_env_t *sign_skey_1, *sign_skey_2, *sign_skey_3;
  2555. crypto_pk_env_t *sign_skey_leg1;
  2556. time_t now = time(NULL);
  2557. networkstatus_voter_info_t *voter;
  2558. networkstatus_t *vote, *v1, *v2, *v3, *con;
  2559. vote_routerstatus_t *vrs;
  2560. routerstatus_t *rs;
  2561. char *v1_text, *v2_text, *v3_text, *consensus_text, *cp;
  2562. smartlist_t *votes = smartlist_create();
  2563. /* Parse certificates and keys. */
  2564. cert1 = authority_cert_parse_from_string(AUTHORITY_CERT_1, NULL);
  2565. test_assert(cert1);
  2566. cert2 = authority_cert_parse_from_string(AUTHORITY_CERT_2, NULL);
  2567. test_assert(cert2);
  2568. cert3 = authority_cert_parse_from_string(AUTHORITY_CERT_3, NULL);
  2569. test_assert(cert3);
  2570. sign_skey_1 = crypto_new_pk_env();
  2571. sign_skey_2 = crypto_new_pk_env();
  2572. sign_skey_3 = crypto_new_pk_env();
  2573. sign_skey_leg1 = pk_generate(4);
  2574. test_assert(!crypto_pk_read_private_key_from_string(sign_skey_1,
  2575. AUTHORITY_SIGNKEY_1));
  2576. test_assert(!crypto_pk_read_private_key_from_string(sign_skey_2,
  2577. AUTHORITY_SIGNKEY_2));
  2578. test_assert(!crypto_pk_read_private_key_from_string(sign_skey_3,
  2579. AUTHORITY_SIGNKEY_3));
  2580. test_assert(!crypto_pk_cmp_keys(sign_skey_1, cert1->signing_key));
  2581. test_assert(!crypto_pk_cmp_keys(sign_skey_2, cert2->signing_key));
  2582. /*
  2583. * Set up a vote; generate it; try to parse it.
  2584. */
  2585. vote = tor_malloc_zero(sizeof(networkstatus_t));
  2586. vote->type = NS_TYPE_VOTE;
  2587. vote->published = now;
  2588. vote->valid_after = now+1000;
  2589. vote->fresh_until = now+2000;
  2590. vote->valid_until = now+3000;
  2591. vote->vote_seconds = 100;
  2592. vote->dist_seconds = 200;
  2593. vote->supported_methods = smartlist_create();
  2594. smartlist_split_string(vote->supported_methods, "1 2 3", NULL, 0, -1);
  2595. vote->client_versions = tor_strdup("0.1.2.14,0.1.2.15");
  2596. vote->server_versions = tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
  2597. vote->known_flags = smartlist_create();
  2598. smartlist_split_string(vote->known_flags,
  2599. "Authority Exit Fast Guard Running Stable V2Dir Valid",
  2600. 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2601. vote->voters = smartlist_create();
  2602. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2603. voter->nickname = tor_strdup("Voter1");
  2604. voter->address = tor_strdup("1.2.3.4");
  2605. voter->addr = 0x01020304;
  2606. voter->dir_port = 80;
  2607. voter->or_port = 9000;
  2608. voter->contact = tor_strdup("voter@example.com");
  2609. crypto_pk_get_digest(cert1->identity_key, voter->identity_digest);
  2610. smartlist_add(vote->voters, voter);
  2611. vote->cert = authority_cert_dup(cert1);
  2612. vote->routerstatus_list = smartlist_create();
  2613. /* add the first routerstatus. */
  2614. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2615. rs = &vrs->status;
  2616. vrs->version = tor_strdup("0.1.2.14");
  2617. rs->published_on = now-1500;
  2618. strlcpy(rs->nickname, "router2", sizeof(rs->nickname));
  2619. memset(rs->identity_digest, 3, DIGEST_LEN);
  2620. memset(rs->descriptor_digest, 78, DIGEST_LEN);
  2621. rs->addr = 0x99008801;
  2622. rs->or_port = 443;
  2623. rs->dir_port = 8000;
  2624. /* all flags but running cleared */
  2625. rs->is_running = 1;
  2626. smartlist_add(vote->routerstatus_list, vrs);
  2627. /* add the second routerstatus. */
  2628. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2629. rs = &vrs->status;
  2630. vrs->version = tor_strdup("0.2.0.5");
  2631. rs->published_on = now-1000;
  2632. strlcpy(rs->nickname, "router1", sizeof(rs->nickname));
  2633. memset(rs->identity_digest, 5, DIGEST_LEN);
  2634. memset(rs->descriptor_digest, 77, DIGEST_LEN);
  2635. rs->addr = 0x99009901;
  2636. rs->or_port = 443;
  2637. rs->dir_port = 0;
  2638. rs->is_exit = rs->is_stable = rs->is_fast = rs->is_running =
  2639. rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
  2640. smartlist_add(vote->routerstatus_list, vrs);
  2641. /* add the third routerstatus. */
  2642. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2643. rs = &vrs->status;
  2644. vrs->version = tor_strdup("0.1.0.3");
  2645. rs->published_on = now-1000;
  2646. strlcpy(rs->nickname, "router3", sizeof(rs->nickname));
  2647. memset(rs->identity_digest, 33, DIGEST_LEN);
  2648. memset(rs->descriptor_digest, 78, DIGEST_LEN);
  2649. rs->addr = 0xAA009901;
  2650. rs->or_port = 400;
  2651. rs->dir_port = 9999;
  2652. rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
  2653. rs->is_running = rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
  2654. smartlist_add(vote->routerstatus_list, vrs);
  2655. /* add a fourth routerstatus that is not running. */
  2656. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2657. rs = &vrs->status;
  2658. vrs->version = tor_strdup("0.1.6.3");
  2659. rs->published_on = now-1000;
  2660. strlcpy(rs->nickname, "router4", sizeof(rs->nickname));
  2661. memset(rs->identity_digest, 34, DIGEST_LEN);
  2662. memset(rs->descriptor_digest, 48, DIGEST_LEN);
  2663. rs->addr = 0xC0000203;
  2664. rs->or_port = 500;
  2665. rs->dir_port = 1999;
  2666. /* Running flag (and others) cleared */
  2667. smartlist_add(vote->routerstatus_list, vrs);
  2668. /* dump the vote and try to parse it. */
  2669. v1_text = format_networkstatus_vote(sign_skey_1, vote);
  2670. test_assert(v1_text);
  2671. v1 = networkstatus_parse_vote_from_string(v1_text, NULL, NS_TYPE_VOTE);
  2672. test_assert(v1);
  2673. /* Make sure the parsed thing was right. */
  2674. test_eq(v1->type, NS_TYPE_VOTE);
  2675. test_eq(v1->published, vote->published);
  2676. test_eq(v1->valid_after, vote->valid_after);
  2677. test_eq(v1->fresh_until, vote->fresh_until);
  2678. test_eq(v1->valid_until, vote->valid_until);
  2679. test_eq(v1->vote_seconds, vote->vote_seconds);
  2680. test_eq(v1->dist_seconds, vote->dist_seconds);
  2681. test_streq(v1->client_versions, vote->client_versions);
  2682. test_streq(v1->server_versions, vote->server_versions);
  2683. test_assert(v1->voters && smartlist_len(v1->voters));
  2684. voter = smartlist_get(v1->voters, 0);
  2685. test_streq(voter->nickname, "Voter1");
  2686. test_streq(voter->address, "1.2.3.4");
  2687. test_eq(voter->addr, 0x01020304);
  2688. test_eq(voter->dir_port, 80);
  2689. test_eq(voter->or_port, 9000);
  2690. test_streq(voter->contact, "voter@example.com");
  2691. test_assert(v1->cert);
  2692. test_assert(!crypto_pk_cmp_keys(sign_skey_1, v1->cert->signing_key));
  2693. cp = smartlist_join_strings(v1->known_flags, ":", 0, NULL);
  2694. test_streq(cp, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
  2695. tor_free(cp);
  2696. test_eq(smartlist_len(v1->routerstatus_list), 4);
  2697. /* Check the first routerstatus. */
  2698. vrs = smartlist_get(v1->routerstatus_list, 0);
  2699. rs = &vrs->status;
  2700. test_streq(vrs->version, "0.1.2.14");
  2701. test_eq(rs->published_on, now-1500);
  2702. test_streq(rs->nickname, "router2");
  2703. test_memeq(rs->identity_digest,
  2704. "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
  2705. DIGEST_LEN);
  2706. test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
  2707. test_eq(rs->addr, 0x99008801);
  2708. test_eq(rs->or_port, 443);
  2709. test_eq(rs->dir_port, 8000);
  2710. test_eq(vrs->flags, U64_LITERAL(16)); // no flags except "running"
  2711. /* Check the second routerstatus. */
  2712. vrs = smartlist_get(v1->routerstatus_list, 1);
  2713. rs = &vrs->status;
  2714. test_streq(vrs->version, "0.2.0.5");
  2715. test_eq(rs->published_on, now-1000);
  2716. test_streq(rs->nickname, "router1");
  2717. test_memeq(rs->identity_digest,
  2718. "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
  2719. DIGEST_LEN);
  2720. test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
  2721. test_eq(rs->addr, 0x99009901);
  2722. test_eq(rs->or_port, 443);
  2723. test_eq(rs->dir_port, 0);
  2724. test_eq(vrs->flags, U64_LITERAL(254)); // all flags except "authority."
  2725. /* Generate second vote. It disagrees on some of the times,
  2726. * and doesn't list versions, and knows some crazy flags */
  2727. vote->published = now+1;
  2728. vote->fresh_until = now+3005;
  2729. vote->dist_seconds = 300;
  2730. authority_cert_free(vote->cert);
  2731. vote->cert = authority_cert_dup(cert2);
  2732. tor_free(vote->client_versions);
  2733. tor_free(vote->server_versions);
  2734. voter = smartlist_get(vote->voters, 0);
  2735. tor_free(voter->nickname);
  2736. tor_free(voter->address);
  2737. voter->nickname = tor_strdup("Voter2");
  2738. voter->address = tor_strdup("2.3.4.5");
  2739. voter->addr = 0x02030405;
  2740. crypto_pk_get_digest(cert2->identity_key, voter->identity_digest);
  2741. smartlist_add(vote->known_flags, tor_strdup("MadeOfCheese"));
  2742. smartlist_add(vote->known_flags, tor_strdup("MadeOfTin"));
  2743. smartlist_sort_strings(vote->known_flags);
  2744. vrs = smartlist_get(vote->routerstatus_list, 2);
  2745. smartlist_del_keeporder(vote->routerstatus_list, 2);
  2746. tor_free(vrs->version);
  2747. tor_free(vrs);
  2748. vrs = smartlist_get(vote->routerstatus_list, 0);
  2749. vrs->status.is_fast = 1;
  2750. /* generate and parse. */
  2751. v2_text = format_networkstatus_vote(sign_skey_2, vote);
  2752. test_assert(v2_text);
  2753. v2 = networkstatus_parse_vote_from_string(v2_text, NULL, NS_TYPE_VOTE);
  2754. test_assert(v2);
  2755. /* Check that flags come out right.*/
  2756. cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
  2757. test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
  2758. "Running:Stable:V2Dir:Valid");
  2759. tor_free(cp);
  2760. vrs = smartlist_get(v2->routerstatus_list, 1);
  2761. /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
  2762. test_eq(vrs->flags, U64_LITERAL(974));
  2763. /* Generate the third vote. */
  2764. vote->published = now;
  2765. vote->fresh_until = now+2003;
  2766. vote->dist_seconds = 250;
  2767. authority_cert_free(vote->cert);
  2768. vote->cert = authority_cert_dup(cert3);
  2769. smartlist_add(vote->supported_methods, tor_strdup("4"));
  2770. vote->client_versions = tor_strdup("0.1.2.14,0.1.2.17");
  2771. vote->server_versions = tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
  2772. voter = smartlist_get(vote->voters, 0);
  2773. tor_free(voter->nickname);
  2774. tor_free(voter->address);
  2775. voter->nickname = tor_strdup("Voter3");
  2776. voter->address = tor_strdup("3.4.5.6");
  2777. voter->addr = 0x03040506;
  2778. crypto_pk_get_digest(cert3->identity_key, voter->identity_digest);
  2779. /* This one has a legacy id. */
  2780. memset(voter->legacy_id_digest, (int)'A', DIGEST_LEN);
  2781. vrs = smartlist_get(vote->routerstatus_list, 0);
  2782. smartlist_del_keeporder(vote->routerstatus_list, 0);
  2783. tor_free(vrs->version);
  2784. tor_free(vrs);
  2785. vrs = smartlist_get(vote->routerstatus_list, 0);
  2786. memset(vrs->status.descriptor_digest, (int)'Z', DIGEST_LEN);
  2787. v3_text = format_networkstatus_vote(sign_skey_3, vote);
  2788. test_assert(v3_text);
  2789. v3 = networkstatus_parse_vote_from_string(v3_text, NULL, NS_TYPE_VOTE);
  2790. test_assert(v3);
  2791. /* Compute a consensus as voter 3. */
  2792. smartlist_add(votes, v3);
  2793. smartlist_add(votes, v1);
  2794. smartlist_add(votes, v2);
  2795. consensus_text = networkstatus_compute_consensus(votes, 3,
  2796. cert3->identity_key,
  2797. sign_skey_3,
  2798. "AAAAAAAAAAAAAAAAAAAA",
  2799. sign_skey_leg1);
  2800. test_assert(consensus_text);
  2801. con = networkstatus_parse_vote_from_string(consensus_text, NULL,
  2802. NS_TYPE_CONSENSUS);
  2803. test_assert(con);
  2804. //log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
  2805. // v1_text, v2_text, v3_text);
  2806. /* Check consensus contents. */
  2807. test_assert(con->type == NS_TYPE_CONSENSUS);
  2808. test_eq(con->published, 0); /* this field only appears in votes. */
  2809. test_eq(con->valid_after, now+1000);
  2810. test_eq(con->fresh_until, now+2003); /* median */
  2811. test_eq(con->valid_until, now+3000);
  2812. test_eq(con->vote_seconds, 100);
  2813. test_eq(con->dist_seconds, 250); /* median */
  2814. test_streq(con->client_versions, "0.1.2.14");
  2815. test_streq(con->server_versions, "0.1.2.15,0.1.2.16");
  2816. cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
  2817. test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
  2818. "Running:Stable:V2Dir:Valid");
  2819. tor_free(cp);
  2820. test_eq(4, smartlist_len(con->voters)); /*3 voters, 1 legacy key.*/
  2821. /* The voter id digests should be in this order. */
  2822. test_assert(memcmp(cert2->cache_info.identity_digest,
  2823. cert3->cache_info.identity_digest,DIGEST_LEN)<0);
  2824. test_assert(memcmp(cert3->cache_info.identity_digest,
  2825. cert1->cache_info.identity_digest,DIGEST_LEN)<0);
  2826. test_same_voter(smartlist_get(con->voters, 1),
  2827. smartlist_get(v2->voters, 0));
  2828. test_same_voter(smartlist_get(con->voters, 2),
  2829. smartlist_get(v3->voters, 0));
  2830. test_same_voter(smartlist_get(con->voters, 3),
  2831. smartlist_get(v1->voters, 0));
  2832. test_assert(!con->cert);
  2833. test_eq(2, smartlist_len(con->routerstatus_list));
  2834. /* There should be two listed routers: one with identity 3, one with
  2835. * identity 5. */
  2836. /* This one showed up in 2 digests. */
  2837. rs = smartlist_get(con->routerstatus_list, 0);
  2838. test_memeq(rs->identity_digest,
  2839. "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
  2840. DIGEST_LEN);
  2841. test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
  2842. test_assert(!rs->is_authority);
  2843. test_assert(!rs->is_exit);
  2844. test_assert(!rs->is_fast);
  2845. test_assert(!rs->is_possible_guard);
  2846. test_assert(!rs->is_stable);
  2847. test_assert(rs->is_running); /* If it wasn't running it wouldn't be here */
  2848. test_assert(!rs->is_v2_dir);
  2849. test_assert(!rs->is_valid);
  2850. test_assert(!rs->is_named);
  2851. /* XXXX check version */
  2852. rs = smartlist_get(con->routerstatus_list, 1);
  2853. /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
  2854. test_memeq(rs->identity_digest,
  2855. "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
  2856. DIGEST_LEN);
  2857. test_streq(rs->nickname, "router1");
  2858. test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
  2859. test_eq(rs->published_on, now-1000);
  2860. test_eq(rs->addr, 0x99009901);
  2861. test_eq(rs->or_port, 443);
  2862. test_eq(rs->dir_port, 0);
  2863. test_assert(!rs->is_authority);
  2864. test_assert(rs->is_exit);
  2865. test_assert(rs->is_fast);
  2866. test_assert(rs->is_possible_guard);
  2867. test_assert(rs->is_stable);
  2868. test_assert(rs->is_running);
  2869. test_assert(rs->is_v2_dir);
  2870. test_assert(rs->is_valid);
  2871. test_assert(!rs->is_named);
  2872. /* XXXX check version */
  2873. /* Check signatures. the first voter is pseudo. The second one hasn't
  2874. signed. The third one has signed: validate it. */
  2875. voter = smartlist_get(con->voters, 1);
  2876. test_assert(!voter->signature);
  2877. test_assert(!voter->good_signature);
  2878. test_assert(!voter->bad_signature);
  2879. voter = smartlist_get(con->voters, 2);
  2880. test_assert(voter->signature);
  2881. test_assert(!voter->good_signature);
  2882. test_assert(!voter->bad_signature);
  2883. test_assert(!networkstatus_check_voter_signature(con,
  2884. smartlist_get(con->voters, 2),
  2885. cert3));
  2886. test_assert(voter->signature);
  2887. test_assert(voter->good_signature);
  2888. test_assert(!voter->bad_signature);
  2889. {
  2890. char *consensus_text2, *consensus_text3;
  2891. networkstatus_t *con2, *con3;
  2892. char *detached_text1, *detached_text2;
  2893. ns_detached_signatures_t *dsig1, *dsig2;
  2894. const char *msg=NULL;
  2895. /* Compute the other two signed consensuses. */
  2896. smartlist_shuffle(votes);
  2897. consensus_text2 = networkstatus_compute_consensus(votes, 3,
  2898. cert2->identity_key,
  2899. sign_skey_2, NULL,NULL);
  2900. smartlist_shuffle(votes);
  2901. consensus_text3 = networkstatus_compute_consensus(votes, 3,
  2902. cert1->identity_key,
  2903. sign_skey_1, NULL,NULL);
  2904. test_assert(consensus_text2);
  2905. test_assert(consensus_text3);
  2906. con2 = networkstatus_parse_vote_from_string(consensus_text2, NULL,
  2907. NS_TYPE_CONSENSUS);
  2908. con3 = networkstatus_parse_vote_from_string(consensus_text3, NULL,
  2909. NS_TYPE_CONSENSUS);
  2910. test_assert(con2);
  2911. test_assert(con3);
  2912. /* All three should have the same digest. */
  2913. test_memeq(con->networkstatus_digest, con2->networkstatus_digest,
  2914. DIGEST_LEN);
  2915. test_memeq(con->networkstatus_digest, con3->networkstatus_digest,
  2916. DIGEST_LEN);
  2917. /* Extract a detached signature from con3. */
  2918. detached_text1 = networkstatus_get_detached_signatures(con3);
  2919. tor_assert(detached_text1);
  2920. /* Try to parse it. */
  2921. dsig1 = networkstatus_parse_detached_signatures(detached_text1, NULL);
  2922. tor_assert(dsig1);
  2923. /* Are parsed values as expected? */
  2924. test_eq(dsig1->valid_after, con3->valid_after);
  2925. test_eq(dsig1->fresh_until, con3->fresh_until);
  2926. test_eq(dsig1->valid_until, con3->valid_until);
  2927. test_memeq(dsig1->networkstatus_digest, con3->networkstatus_digest,
  2928. DIGEST_LEN);
  2929. test_eq(1, smartlist_len(dsig1->signatures));
  2930. voter = smartlist_get(dsig1->signatures, 0);
  2931. test_memeq(voter->identity_digest, cert1->cache_info.identity_digest,
  2932. DIGEST_LEN);
  2933. /* Try adding it to con2. */
  2934. detached_text2 = networkstatus_get_detached_signatures(con2);
  2935. test_eq(1, networkstatus_add_detached_signatures(con2, dsig1, &msg));
  2936. tor_free(detached_text2);
  2937. detached_text2 = networkstatus_get_detached_signatures(con2);
  2938. //printf("\n<%s>\n", detached_text2);
  2939. dsig2 = networkstatus_parse_detached_signatures(detached_text2, NULL);
  2940. test_assert(dsig2);
  2941. /*
  2942. printf("\n");
  2943. SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
  2944. char hd[64];
  2945. base16_encode(hd, sizeof(hd), vi->identity_digest, DIGEST_LEN);
  2946. printf("%s\n", hd);
  2947. });
  2948. */
  2949. test_eq(2, smartlist_len(dsig2->signatures));
  2950. /* Try adding to con2 twice; verify that nothing changes. */
  2951. test_eq(0, networkstatus_add_detached_signatures(con2, dsig1, &msg));
  2952. /* Add to con. */
  2953. test_eq(2, networkstatus_add_detached_signatures(con, dsig2, &msg));
  2954. /* Check signatures */
  2955. test_assert(!networkstatus_check_voter_signature(con,
  2956. smartlist_get(con->voters, 1),
  2957. cert2));
  2958. test_assert(!networkstatus_check_voter_signature(con,
  2959. smartlist_get(con->voters, 3),
  2960. cert1));
  2961. networkstatus_vote_free(con2);
  2962. networkstatus_vote_free(con3);
  2963. tor_free(consensus_text2);
  2964. tor_free(consensus_text3);
  2965. tor_free(detached_text1);
  2966. tor_free(detached_text2);
  2967. ns_detached_signatures_free(dsig1);
  2968. ns_detached_signatures_free(dsig2);
  2969. }
  2970. smartlist_free(votes);
  2971. tor_free(v1_text);
  2972. tor_free(v2_text);
  2973. tor_free(v3_text);
  2974. tor_free(consensus_text);
  2975. networkstatus_vote_free(vote);
  2976. networkstatus_vote_free(v1);
  2977. networkstatus_vote_free(v2);
  2978. networkstatus_vote_free(v3);
  2979. networkstatus_vote_free(con);
  2980. crypto_free_pk_env(sign_skey_1);
  2981. crypto_free_pk_env(sign_skey_2);
  2982. crypto_free_pk_env(sign_skey_3);
  2983. authority_cert_free(cert1);
  2984. authority_cert_free(cert2);
  2985. authority_cert_free(cert3);
  2986. }
  2987. static void
  2988. test_policies(void)
  2989. {
  2990. smartlist_t *policy, *policy2;
  2991. addr_policy_t *p;
  2992. tor_addr_t tar;
  2993. config_line_t line;
  2994. policy = smartlist_create();
  2995. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  2996. test_assert(p != NULL);
  2997. test_eq(ADDR_POLICY_REJECT, p->policy_type);
  2998. tor_addr_from_ipv4h(&tar, 0xc0a80000u);
  2999. test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
  3000. test_eq(16, p->maskbits);
  3001. test_eq(1, p->prt_min);
  3002. test_eq(65535, p->prt_max);
  3003. smartlist_add(policy, p);
  3004. test_assert(ADDR_POLICY_ACCEPTED ==
  3005. compare_addr_to_addr_policy(0x01020304u, 2, policy));
  3006. test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
  3007. compare_addr_to_addr_policy(0, 2, policy));
  3008. test_assert(ADDR_POLICY_REJECTED ==
  3009. compare_addr_to_addr_policy(0xc0a80102, 2, policy));
  3010. policy2 = NULL;
  3011. test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL));
  3012. test_assert(policy2);
  3013. test_assert(!exit_policy_is_general_exit(policy));
  3014. test_assert(exit_policy_is_general_exit(policy2));
  3015. test_assert(!exit_policy_is_general_exit(NULL));
  3016. test_assert(cmp_addr_policies(policy, policy2));
  3017. test_assert(cmp_addr_policies(policy, NULL));
  3018. test_assert(!cmp_addr_policies(policy2, policy2));
  3019. test_assert(!cmp_addr_policies(NULL, NULL));
  3020. test_assert(!policy_is_reject_star(policy2));
  3021. test_assert(policy_is_reject_star(policy));
  3022. test_assert(policy_is_reject_star(NULL));
  3023. addr_policy_list_free(policy);
  3024. addr_policy_list_free(policy2);
  3025. /* make sure compacting logic works. */
  3026. policy = NULL;
  3027. line.key = (char*)"foo";
  3028. line.value = (char*)"accept *:80,reject private:*,reject *:*";
  3029. line.next = NULL;
  3030. test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL));
  3031. test_assert(policy);
  3032. //test_streq(policy->string, "accept *:80");
  3033. //test_streq(policy->next->string, "reject *:*");
  3034. test_eq(smartlist_len(policy), 2);
  3035. addr_policy_list_free(policy);
  3036. }
  3037. static void
  3038. test_rend_fns(void)
  3039. {
  3040. char address1[] = "fooaddress.onion";
  3041. char address2[] = "aaaaaaaaaaaaaaaa.onion";
  3042. char address3[] = "fooaddress.exit";
  3043. char address4[] = "www.torproject.org";
  3044. rend_service_descriptor_t *d1, *d2;
  3045. char *encoded;
  3046. size_t len;
  3047. crypto_pk_env_t *pk1, *pk2;
  3048. time_t now;
  3049. int i;
  3050. pk1 = pk_generate(0);
  3051. pk2 = pk_generate(1);
  3052. /* Test unversioned (v0) descriptor */
  3053. d1 = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  3054. d1->pk = crypto_pk_dup_key(pk1);
  3055. now = time(NULL);
  3056. d1->timestamp = now;
  3057. d1->version = 0;
  3058. d1->intro_nodes = smartlist_create();
  3059. for (i = 0; i < 3; i++) {
  3060. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  3061. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  3062. crypto_rand(intro->extend_info->identity_digest, DIGEST_LEN);
  3063. intro->extend_info->nickname[0] = '$';
  3064. base16_encode(intro->extend_info->nickname+1, HEX_DIGEST_LEN+1,
  3065. intro->extend_info->identity_digest, DIGEST_LEN);
  3066. smartlist_add(d1->intro_nodes, intro);
  3067. }
  3068. test_assert(! rend_encode_service_descriptor(d1, pk1, &encoded, &len));
  3069. d2 = rend_parse_service_descriptor(encoded, len);
  3070. test_assert(d2);
  3071. test_assert(!crypto_pk_cmp_keys(d1->pk, d2->pk));
  3072. test_eq(d2->timestamp, now);
  3073. test_eq(d2->version, 0);
  3074. test_eq(d2->protocols, 1<<2);
  3075. test_eq(smartlist_len(d2->intro_nodes), 3);
  3076. for (i = 0; i < 3; i++) {
  3077. rend_intro_point_t *intro1 = smartlist_get(d1->intro_nodes, i);
  3078. rend_intro_point_t *intro2 = smartlist_get(d2->intro_nodes, i);
  3079. test_streq(intro1->extend_info->nickname,
  3080. intro2->extend_info->nickname);
  3081. }
  3082. rend_service_descriptor_free(d1);
  3083. rend_service_descriptor_free(d2);
  3084. tor_free(encoded);
  3085. test_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
  3086. test_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
  3087. test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
  3088. test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
  3089. crypto_free_pk_env(pk1);
  3090. crypto_free_pk_env(pk2);
  3091. }
  3092. static void
  3093. bench_aes(void)
  3094. {
  3095. int len, i;
  3096. char *b1, *b2;
  3097. crypto_cipher_env_t *c;
  3098. struct timeval start, end;
  3099. const int iters = 100000;
  3100. uint64_t nsec;
  3101. c = crypto_new_cipher_env();
  3102. crypto_cipher_generate_key(c);
  3103. crypto_cipher_encrypt_init_cipher(c);
  3104. for (len = 1; len <= 8192; len *= 2) {
  3105. b1 = tor_malloc_zero(len);
  3106. b2 = tor_malloc_zero(len);
  3107. tor_gettimeofday(&start);
  3108. for (i = 0; i < iters; ++i) {
  3109. crypto_cipher_encrypt(c, b1, b2, len);
  3110. }
  3111. tor_gettimeofday(&end);
  3112. tor_free(b1);
  3113. tor_free(b2);
  3114. nsec = (uint64_t) tv_udiff(&start,&end);
  3115. nsec *= 1000;
  3116. nsec /= (iters*len);
  3117. printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
  3118. U64_PRINTF_ARG(nsec));
  3119. }
  3120. crypto_free_cipher_env(c);
  3121. }
  3122. static void
  3123. bench_dmap(void)
  3124. {
  3125. smartlist_t *sl = smartlist_create();
  3126. smartlist_t *sl2 = smartlist_create();
  3127. struct timeval start, end, pt2, pt3, pt4;
  3128. const int iters = 10000;
  3129. const int elts = 4000;
  3130. const int fpostests = 1000000;
  3131. char d[20];
  3132. int i,n=0, fp = 0;
  3133. digestmap_t *dm = digestmap_new();
  3134. digestset_t *ds = digestset_new(elts);
  3135. for (i = 0; i < elts; ++i) {
  3136. crypto_rand(d, 20);
  3137. smartlist_add(sl, tor_memdup(d, 20));
  3138. }
  3139. for (i = 0; i < elts; ++i) {
  3140. crypto_rand(d, 20);
  3141. smartlist_add(sl2, tor_memdup(d, 20));
  3142. }
  3143. printf("nbits=%d\n", ds->mask+1);
  3144. tor_gettimeofday(&start);
  3145. for (i = 0; i < iters; ++i) {
  3146. SMARTLIST_FOREACH(sl, const char *, cp, digestmap_set(dm, cp, (void*)1));
  3147. }
  3148. tor_gettimeofday(&pt2);
  3149. for (i = 0; i < iters; ++i) {
  3150. SMARTLIST_FOREACH(sl, const char *, cp, digestmap_get(dm, cp));
  3151. SMARTLIST_FOREACH(sl2, const char *, cp, digestmap_get(dm, cp));
  3152. }
  3153. tor_gettimeofday(&pt3);
  3154. for (i = 0; i < iters; ++i) {
  3155. SMARTLIST_FOREACH(sl, const char *, cp, digestset_add(ds, cp));
  3156. }
  3157. tor_gettimeofday(&pt4);
  3158. for (i = 0; i < iters; ++i) {
  3159. SMARTLIST_FOREACH(sl, const char *, cp, n += digestset_isin(ds, cp));
  3160. SMARTLIST_FOREACH(sl2, const char *, cp, n += digestset_isin(ds, cp));
  3161. }
  3162. tor_gettimeofday(&end);
  3163. for (i = 0; i < fpostests; ++i) {
  3164. crypto_rand(d, 20);
  3165. if (digestset_isin(ds, d)) ++fp;
  3166. }
  3167. printf("%ld\n",(unsigned long)tv_udiff(&start, &pt2));
  3168. printf("%ld\n",(unsigned long)tv_udiff(&pt2, &pt3));
  3169. printf("%ld\n",(unsigned long)tv_udiff(&pt3, &pt4));
  3170. printf("%ld\n",(unsigned long)tv_udiff(&pt4, &end));
  3171. printf("-- %d\n", n);
  3172. printf("++ %f\n", fp/(double)fpostests);
  3173. digestmap_free(dm, NULL);
  3174. digestset_free(ds);
  3175. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  3176. SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
  3177. smartlist_free(sl);
  3178. smartlist_free(sl2);
  3179. }
  3180. static void
  3181. test_util_mempool(void)
  3182. {
  3183. mp_pool_t *pool;
  3184. smartlist_t *allocated;
  3185. int i;
  3186. pool = mp_pool_new(1, 100);
  3187. test_assert(pool->new_chunk_capacity >= 100);
  3188. test_assert(pool->item_alloc_size >= sizeof(void*)+1);
  3189. mp_pool_destroy(pool);
  3190. pool = mp_pool_new(241, 2500);
  3191. test_assert(pool->new_chunk_capacity >= 10);
  3192. test_assert(pool->item_alloc_size >= sizeof(void*)+241);
  3193. test_eq(pool->item_alloc_size & 0x03, 0);
  3194. test_assert(pool->new_chunk_capacity < 60);
  3195. allocated = smartlist_create();
  3196. for (i = 0; i < 100000; ++i) {
  3197. if (smartlist_len(allocated) < 20 || crypto_rand_int(2)) {
  3198. void *m = mp_pool_get(pool);
  3199. memset(m, 0x09, 241);
  3200. smartlist_add(allocated, m);
  3201. //printf("%d: %p\n", i, m);
  3202. //mp_pool_assert_ok(pool);
  3203. } else {
  3204. int idx = crypto_rand_int(smartlist_len(allocated));
  3205. void *m = smartlist_get(allocated, idx);
  3206. //printf("%d: free %p\n", i, m);
  3207. smartlist_del(allocated, idx);
  3208. mp_pool_release(m);
  3209. //mp_pool_assert_ok(pool);
  3210. }
  3211. if (crypto_rand_int(777)==0)
  3212. mp_pool_clean(pool, 1, 1);
  3213. if (i % 777)
  3214. mp_pool_assert_ok(pool);
  3215. }
  3216. SMARTLIST_FOREACH(allocated, void *, m, mp_pool_release(m));
  3217. mp_pool_assert_ok(pool);
  3218. mp_pool_clean(pool, 0, 0);
  3219. mp_pool_assert_ok(pool);
  3220. mp_pool_destroy(pool);
  3221. smartlist_free(allocated);
  3222. }
  3223. static void
  3224. test_util_memarea(void)
  3225. {
  3226. memarea_t *area = memarea_new(1024);
  3227. char *p1, *p2, *p3, *p1_orig;
  3228. int i;
  3229. test_assert(area);
  3230. p1_orig = p1 = memarea_alloc(area,64);
  3231. p2 = memarea_alloc_zero(area,52);
  3232. p3 = memarea_alloc(area,11);
  3233. test_assert(memarea_owns_ptr(area, p1));
  3234. test_assert(memarea_owns_ptr(area, p2));
  3235. test_assert(memarea_owns_ptr(area, p3));
  3236. /* Make sure we left enough space. */
  3237. test_assert(p1+64 <= p2);
  3238. test_assert(p2+52 <= p3);
  3239. /* Make sure we aligned. */
  3240. test_eq(((uintptr_t)p1) % sizeof(void*), 0);
  3241. test_eq(((uintptr_t)p2) % sizeof(void*), 0);
  3242. test_eq(((uintptr_t)p3) % sizeof(void*), 0);
  3243. test_assert(!memarea_owns_ptr(area, p3+8192));
  3244. test_assert(!memarea_owns_ptr(area, p3+30));
  3245. test_assert(tor_mem_is_zero(p2, 52));
  3246. /* Make sure we don't overalign. */
  3247. p1 = memarea_alloc(area, 1);
  3248. p2 = memarea_alloc(area, 1);
  3249. test_eq(p1+sizeof(void*), p2);
  3250. {
  3251. void *ptr = tor_malloc(64);
  3252. test_assert(!memarea_owns_ptr(area, ptr));
  3253. tor_free(ptr);
  3254. }
  3255. /* memarea_memdup */
  3256. {
  3257. char *ptr = tor_malloc(64);
  3258. crypto_rand(ptr, 64);
  3259. p1 = memarea_memdup(area, ptr, 64);
  3260. test_assert(p1 != ptr);
  3261. test_memeq(p1, ptr, 64);
  3262. tor_free(ptr);
  3263. }
  3264. /* memarea_strdup. */
  3265. p1 = memarea_strdup(area,"");
  3266. p2 = memarea_strdup(area, "abcd");
  3267. test_assert(p1);
  3268. test_assert(p2);
  3269. test_streq(p1, "");
  3270. test_streq(p2, "abcd");
  3271. /* memarea_strndup. */
  3272. {
  3273. const char *s = "Ad ogni porta batte la morte e grida: il nome!";
  3274. /* (From Turandot, act 3.) */
  3275. size_t len = strlen(s);
  3276. p1 = memarea_strndup(area, s, 1000);
  3277. p2 = memarea_strndup(area, s, 10);
  3278. test_streq(p1, s);
  3279. test_assert(p2 >= p1 + len + 1);
  3280. test_memeq(s, p2, 10);
  3281. test_eq(p2[10], '\0');
  3282. p3 = memarea_strndup(area, s, len);
  3283. test_streq(p3, s);
  3284. p3 = memarea_strndup(area, s, len-1);
  3285. test_memeq(s, p3, len-1);
  3286. test_eq(p3[len-1], '\0');
  3287. }
  3288. memarea_clear(area);
  3289. p1 = memarea_alloc(area, 1);
  3290. test_eq(p1, p1_orig);
  3291. memarea_clear(area);
  3292. /* Check for running over an area's size. */
  3293. for (i = 0; i < 512; ++i) {
  3294. p1 = memarea_alloc(area, crypto_rand_int(5)+1);
  3295. test_assert(memarea_owns_ptr(area, p1));
  3296. }
  3297. memarea_assert_ok(area);
  3298. /* Make sure we can allocate a too-big object. */
  3299. p1 = memarea_alloc_zero(area, 9000);
  3300. p2 = memarea_alloc_zero(area, 16);
  3301. test_assert(memarea_owns_ptr(area, p1));
  3302. test_assert(memarea_owns_ptr(area, p2));
  3303. memarea_drop_all(area);
  3304. }
  3305. static void
  3306. test_util_datadir(void)
  3307. {
  3308. char buf[1024];
  3309. char *f;
  3310. f = get_datadir_fname(NULL);
  3311. test_streq(f, temp_dir);
  3312. tor_free(f);
  3313. f = get_datadir_fname("state");
  3314. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
  3315. test_streq(f, buf);
  3316. tor_free(f);
  3317. f = get_datadir_fname2("cache", "thingy");
  3318. tor_snprintf(buf, sizeof(buf),
  3319. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
  3320. test_streq(f, buf);
  3321. tor_free(f);
  3322. f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
  3323. tor_snprintf(buf, sizeof(buf),
  3324. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
  3325. test_streq(f, buf);
  3326. tor_free(f);
  3327. f = get_datadir_fname_suffix("cache", ".foo");
  3328. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
  3329. temp_dir);
  3330. test_streq(f, buf);
  3331. tor_free(f);
  3332. }
  3333. /* Test AES-CTR encryption and decryption with IV. */
  3334. static void
  3335. test_crypto_aes_iv(void)
  3336. {
  3337. crypto_cipher_env_t *cipher;
  3338. char *plain, *encrypted1, *encrypted2, *decrypted1, *decrypted2;
  3339. char plain_1[1], plain_15[15], plain_16[16], plain_17[17];
  3340. char key1[16], key2[16];
  3341. size_t encrypted_size, decrypted_size;
  3342. plain = tor_malloc(4095);
  3343. encrypted1 = tor_malloc(4095 + 1 + 16);
  3344. encrypted2 = tor_malloc(4095 + 1 + 16);
  3345. decrypted1 = tor_malloc(4095 + 1);
  3346. decrypted2 = tor_malloc(4095 + 1);
  3347. crypto_rand(plain, 4095);
  3348. crypto_rand(key1, 16);
  3349. crypto_rand(key2, 16);
  3350. crypto_rand(plain_1, 1);
  3351. crypto_rand(plain_15, 15);
  3352. crypto_rand(plain_16, 16);
  3353. crypto_rand(plain_17, 17);
  3354. key1[0] = key2[0] + 128; /* Make sure that contents are different. */
  3355. /* Encrypt and decrypt with the same key. */
  3356. cipher = crypto_create_init_cipher(key1, 1);
  3357. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 4095,
  3358. plain, 4095);
  3359. crypto_free_cipher_env(cipher);
  3360. test_eq(encrypted_size, 16 + 4095);
  3361. cipher = crypto_create_init_cipher(key1, 0);
  3362. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
  3363. encrypted1, encrypted_size);
  3364. crypto_free_cipher_env(cipher);
  3365. test_eq(decrypted_size, 4095);
  3366. test_memeq(plain, decrypted1, 4095);
  3367. /* Encrypt a second time (with a new random initialization vector). */
  3368. cipher = crypto_create_init_cipher(key1, 1);
  3369. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted2, 16 + 4095,
  3370. plain, 4095);
  3371. crypto_free_cipher_env(cipher);
  3372. test_eq(encrypted_size, 16 + 4095);
  3373. cipher = crypto_create_init_cipher(key1, 0);
  3374. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
  3375. encrypted2, encrypted_size);
  3376. crypto_free_cipher_env(cipher);
  3377. test_eq(decrypted_size, 4095);
  3378. test_memeq(plain, decrypted2, 4095);
  3379. test_memneq(encrypted1, encrypted2, encrypted_size);
  3380. /* Decrypt with the wrong key. */
  3381. cipher = crypto_create_init_cipher(key2, 0);
  3382. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
  3383. encrypted1, encrypted_size);
  3384. crypto_free_cipher_env(cipher);
  3385. test_memneq(plain, decrypted2, encrypted_size);
  3386. /* Alter the initialization vector. */
  3387. encrypted1[0] += 42;
  3388. cipher = crypto_create_init_cipher(key1, 0);
  3389. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
  3390. encrypted1, encrypted_size);
  3391. crypto_free_cipher_env(cipher);
  3392. test_memneq(plain, decrypted2, 4095);
  3393. /* Special length case: 1. */
  3394. cipher = crypto_create_init_cipher(key1, 1);
  3395. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 1,
  3396. plain_1, 1);
  3397. crypto_free_cipher_env(cipher);
  3398. test_eq(encrypted_size, 16 + 1);
  3399. cipher = crypto_create_init_cipher(key1, 0);
  3400. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 1,
  3401. encrypted1, encrypted_size);
  3402. crypto_free_cipher_env(cipher);
  3403. test_eq(decrypted_size, 1);
  3404. test_memeq(plain_1, decrypted1, 1);
  3405. /* Special length case: 15. */
  3406. cipher = crypto_create_init_cipher(key1, 1);
  3407. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 15,
  3408. plain_15, 15);
  3409. crypto_free_cipher_env(cipher);
  3410. test_eq(encrypted_size, 16 + 15);
  3411. cipher = crypto_create_init_cipher(key1, 0);
  3412. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 15,
  3413. encrypted1, encrypted_size);
  3414. crypto_free_cipher_env(cipher);
  3415. test_eq(decrypted_size, 15);
  3416. test_memeq(plain_15, decrypted1, 15);
  3417. /* Special length case: 16. */
  3418. cipher = crypto_create_init_cipher(key1, 1);
  3419. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 16,
  3420. plain_16, 16);
  3421. crypto_free_cipher_env(cipher);
  3422. test_eq(encrypted_size, 16 + 16);
  3423. cipher = crypto_create_init_cipher(key1, 0);
  3424. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 16,
  3425. encrypted1, encrypted_size);
  3426. crypto_free_cipher_env(cipher);
  3427. test_eq(decrypted_size, 16);
  3428. test_memeq(plain_16, decrypted1, 16);
  3429. /* Special length case: 17. */
  3430. cipher = crypto_create_init_cipher(key1, 1);
  3431. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 17,
  3432. plain_17, 17);
  3433. crypto_free_cipher_env(cipher);
  3434. test_eq(encrypted_size, 16 + 17);
  3435. cipher = crypto_create_init_cipher(key1, 0);
  3436. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 17,
  3437. encrypted1, encrypted_size);
  3438. crypto_free_cipher_env(cipher);
  3439. test_eq(decrypted_size, 17);
  3440. test_memeq(plain_17, decrypted1, 17);
  3441. /* Free memory. */
  3442. tor_free(plain);
  3443. tor_free(encrypted1);
  3444. tor_free(encrypted2);
  3445. tor_free(decrypted1);
  3446. tor_free(decrypted2);
  3447. }
  3448. /* Test base32 decoding. */
  3449. static void
  3450. test_crypto_base32_decode(void)
  3451. {
  3452. char plain[60], encoded[96 + 1], decoded[60];
  3453. int res;
  3454. crypto_rand(plain, 60);
  3455. /* Encode and decode a random string. */
  3456. base32_encode(encoded, 96 + 1, plain, 60);
  3457. res = base32_decode(decoded, 60, encoded, 96);
  3458. test_eq(res, 0);
  3459. test_memeq(plain, decoded, 60);
  3460. /* Encode, uppercase, and decode a random string. */
  3461. base32_encode(encoded, 96 + 1, plain, 60);
  3462. tor_strupper(encoded);
  3463. res = base32_decode(decoded, 60, encoded, 96);
  3464. test_eq(res, 0);
  3465. test_memeq(plain, decoded, 60);
  3466. /* Change encoded string and decode. */
  3467. if (encoded[0] == 'A' || encoded[0] == 'a')
  3468. encoded[0] = 'B';
  3469. else
  3470. encoded[0] = 'A';
  3471. res = base32_decode(decoded, 60, encoded, 96);
  3472. test_eq(res, 0);
  3473. test_memneq(plain, decoded, 60);
  3474. /* Bad encodings. */
  3475. encoded[0] = '!';
  3476. res = base32_decode(decoded, 60, encoded, 96);
  3477. test_assert(res < 0);
  3478. }
  3479. /* Test encoding and parsing of v2 rendezvous service descriptors. */
  3480. static void
  3481. test_rend_fns_v2(void)
  3482. {
  3483. rend_service_descriptor_t *generated, *parsed;
  3484. char service_id[DIGEST_LEN];
  3485. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  3486. const char *next_desc;
  3487. smartlist_t *descs = smartlist_create();
  3488. char computed_desc_id[DIGEST_LEN];
  3489. char parsed_desc_id[DIGEST_LEN];
  3490. crypto_pk_env_t *pk1, *pk2;
  3491. time_t now;
  3492. char *intro_points_encrypted;
  3493. size_t intro_points_size;
  3494. size_t encoded_size;
  3495. int i;
  3496. pk1 = pk_generate(0);
  3497. pk2 = pk_generate(1);
  3498. generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  3499. generated->pk = crypto_pk_dup_key(pk1);
  3500. crypto_pk_get_digest(generated->pk, service_id);
  3501. base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
  3502. service_id, REND_SERVICE_ID_LEN);
  3503. now = time(NULL);
  3504. generated->timestamp = now;
  3505. generated->version = 2;
  3506. generated->protocols = 42;
  3507. generated->intro_nodes = smartlist_create();
  3508. for (i = 0; i < 3; i++) {
  3509. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  3510. crypto_pk_env_t *okey = pk_generate(2 + i);
  3511. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  3512. intro->extend_info->onion_key = crypto_pk_dup_key(okey);
  3513. crypto_pk_get_digest(intro->extend_info->onion_key,
  3514. intro->extend_info->identity_digest);
  3515. //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
  3516. intro->extend_info->nickname[0] = '$';
  3517. base16_encode(intro->extend_info->nickname + 1,
  3518. sizeof(intro->extend_info->nickname) - 1,
  3519. intro->extend_info->identity_digest, DIGEST_LEN);
  3520. intro->extend_info->addr = crypto_rand_int(65536); /* Does not cover all
  3521. * IP addresses. */
  3522. intro->extend_info->port = crypto_rand_int(65536);
  3523. intro->intro_key = crypto_pk_dup_key(pk2);
  3524. smartlist_add(generated->intro_nodes, intro);
  3525. }
  3526. test_assert(rend_encode_v2_descriptors(descs, generated, now,
  3527. NULL, 0) > 0);
  3528. test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
  3529. NULL, now, 0) == 0);
  3530. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  3531. smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
  3532. test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
  3533. &intro_points_encrypted,
  3534. &intro_points_size,
  3535. &encoded_size,
  3536. &next_desc,
  3537. ((rend_encoded_v2_service_descriptor_t *)
  3538. smartlist_get(descs, 0))->desc_str) == 0);
  3539. test_assert(parsed);
  3540. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  3541. smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
  3542. test_assert(rend_decrypt_introduction_points(parsed, NULL,
  3543. intro_points_encrypted,
  3544. intro_points_size) == 3);
  3545. test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
  3546. test_eq(parsed->timestamp, now);
  3547. test_eq(parsed->version, 2);
  3548. test_eq(parsed->protocols, 42);
  3549. test_eq(smartlist_len(parsed->intro_nodes), 3);
  3550. for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
  3551. rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
  3552. *gen_intro = smartlist_get(generated->intro_nodes, i);
  3553. extend_info_t *par_info = par_intro->extend_info;
  3554. extend_info_t *gen_info = gen_intro->extend_info;
  3555. test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
  3556. test_memeq(gen_info->identity_digest, par_info->identity_digest,
  3557. DIGEST_LEN);
  3558. test_streq(gen_info->nickname, par_info->nickname);
  3559. test_eq(gen_info->addr, par_info->addr);
  3560. test_eq(gen_info->port, par_info->port);
  3561. }
  3562. tor_free(intro_points_encrypted);
  3563. for (i = 0; i < smartlist_len(descs); i++)
  3564. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  3565. smartlist_free(descs);
  3566. rend_service_descriptor_free(parsed);
  3567. rend_service_descriptor_free(generated);
  3568. }
  3569. static void
  3570. test_geoip(void)
  3571. {
  3572. int i, j;
  3573. time_t now = time(NULL);
  3574. char *s;
  3575. /* Populate the DB a bit. Add these in order, since we can't do the final
  3576. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  3577. * fine uint32_t values. */
  3578. test_eq(0, geoip_parse_entry("10,50,AB"));
  3579. test_eq(0, geoip_parse_entry("52,90,XY"));
  3580. test_eq(0, geoip_parse_entry("95,100,AB"));
  3581. test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
  3582. test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
  3583. test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
  3584. /* We should have 3 countries: ab, xy, zz. */
  3585. test_eq(3, geoip_get_n_countries());
  3586. /* Make sure that country ID actually works. */
  3587. #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
  3588. test_streq("ab", NAMEFOR(32));
  3589. test_streq("??", NAMEFOR(5));
  3590. test_streq("??", NAMEFOR(51));
  3591. test_streq("xy", NAMEFOR(150));
  3592. test_streq("xy", NAMEFOR(190));
  3593. test_streq("??", NAMEFOR(2000));
  3594. #undef NAMEFOR
  3595. get_options()->BridgeRelay = 1;
  3596. get_options()->BridgeRecordUsageByCountry = 1;
  3597. /* Put 9 observations in AB... */
  3598. for (i=32; i < 40; ++i)
  3599. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now);
  3600. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 225, now);
  3601. /* and 3 observations in XY, several times. */
  3602. for (j=0; j < 10; ++j)
  3603. for (i=52; i < 55; ++i)
  3604. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-3600);
  3605. /* and 17 observations in ZZ... */
  3606. for (i=110; i < 127; ++i)
  3607. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-7200);
  3608. s = geoip_get_client_history(now+5*24*60*60, GEOIP_CLIENT_CONNECT);
  3609. test_assert(s);
  3610. test_streq("zz=24,ab=16,xy=8", s);
  3611. tor_free(s);
  3612. /* Now clear out all the zz observations. */
  3613. geoip_remove_old_clients(now-6000);
  3614. s = geoip_get_client_history(now+5*24*60*60, GEOIP_CLIENT_CONNECT);
  3615. test_assert(s);
  3616. test_streq("ab=16,xy=8", s);
  3617. tor_free(s);
  3618. }
  3619. #define ENT(x) { #x, test_ ## x, 0, 0 }
  3620. #define SUBENT(x,y) { #x "/" #y, test_ ## x ## _ ## y, 1, 0 }
  3621. static struct {
  3622. const char *test_name;
  3623. void (*test_fn)(void);
  3624. int is_subent;
  3625. int selected;
  3626. } test_array[] = {
  3627. ENT(buffers),
  3628. ENT(crypto),
  3629. SUBENT(crypto, dh),
  3630. SUBENT(crypto, s2k),
  3631. SUBENT(crypto, aes_iv),
  3632. SUBENT(crypto, base32_decode),
  3633. ENT(util),
  3634. SUBENT(util, ip6_helpers),
  3635. SUBENT(util, gzip),
  3636. SUBENT(util, datadir),
  3637. SUBENT(util, smartlist),
  3638. SUBENT(util, bitarray),
  3639. SUBENT(util, digestset),
  3640. SUBENT(util, mempool),
  3641. SUBENT(util, memarea),
  3642. SUBENT(util, strmap),
  3643. SUBENT(util, control_formats),
  3644. SUBENT(util, pqueue),
  3645. SUBENT(util, mmap),
  3646. SUBENT(util, threads),
  3647. SUBENT(util, order_functions),
  3648. ENT(onion_handshake),
  3649. ENT(dir_format),
  3650. ENT(v3_networkstatus),
  3651. ENT(policies),
  3652. ENT(rend_fns),
  3653. SUBENT(rend_fns, v2),
  3654. ENT(geoip),
  3655. { NULL, NULL, 0, 0 },
  3656. };
  3657. static void syntax(void) ATTR_NORETURN;
  3658. static void
  3659. syntax(void)
  3660. {
  3661. int i;
  3662. printf("Syntax:\n"
  3663. " test [-v|--verbose] [--warn|--notice|--info|--debug]\n"
  3664. " [testname...]\n"
  3665. "Recognized tests are:\n");
  3666. for (i = 0; test_array[i].test_name; ++i) {
  3667. printf(" %s\n", test_array[i].test_name);
  3668. }
  3669. exit(0);
  3670. }
  3671. int
  3672. main(int c, char**v)
  3673. {
  3674. or_options_t *options = options_new();
  3675. char *errmsg = NULL;
  3676. int i;
  3677. int verbose = 0, any_selected = 0;
  3678. int loglevel = LOG_ERR;
  3679. tor_threads_init();
  3680. init_logging();
  3681. for (i = 1; i < c; ++i) {
  3682. if (!strcmp(v[i], "-v") || !strcmp(v[i], "--verbose"))
  3683. verbose++;
  3684. else if (!strcmp(v[i], "--warn"))
  3685. loglevel = LOG_WARN;
  3686. else if (!strcmp(v[i], "--notice"))
  3687. loglevel = LOG_NOTICE;
  3688. else if (!strcmp(v[i], "--info"))
  3689. loglevel = LOG_INFO;
  3690. else if (!strcmp(v[i], "--debug"))
  3691. loglevel = LOG_DEBUG;
  3692. else if (!strcmp(v[i], "--help") || !strcmp(v[i], "-h") || v[i][0] == '-')
  3693. syntax();
  3694. else {
  3695. int j, found=0;
  3696. for (j = 0; test_array[j].test_name; ++j) {
  3697. if (!strcmp(v[i], test_array[j].test_name) ||
  3698. (test_array[j].is_subent &&
  3699. !strcmpstart(test_array[j].test_name, v[i]) &&
  3700. test_array[j].test_name[strlen(v[i])] == '/') ||
  3701. (v[i][0] == '=' && !strcmp(v[i]+1, test_array[j].test_name))) {
  3702. test_array[j].selected = 1;
  3703. any_selected = 1;
  3704. found = 1;
  3705. }
  3706. }
  3707. if (!found) {
  3708. printf("Unknown test: %s\n", v[i]);
  3709. syntax();
  3710. }
  3711. }
  3712. }
  3713. if (!any_selected) {
  3714. for (i = 0; test_array[i].test_name; ++i) {
  3715. test_array[i].selected = 1;
  3716. }
  3717. }
  3718. {
  3719. log_severity_list_t *s = tor_malloc_zero(sizeof(log_severity_list_t));
  3720. set_log_severity_config(loglevel, LOG_ERR, s);
  3721. add_stream_log(s, "", stdout);
  3722. }
  3723. options->command = CMD_RUN_UNITTESTS;
  3724. crypto_global_init(0);
  3725. rep_hist_init();
  3726. network_init();
  3727. setup_directory();
  3728. options_init(options);
  3729. options->DataDirectory = tor_strdup(temp_dir);
  3730. if (set_options(options, &errmsg) < 0) {
  3731. printf("Failed to set initial options: %s\n", errmsg);
  3732. tor_free(errmsg);
  3733. return 1;
  3734. }
  3735. crypto_seed_rng(1);
  3736. if (0) {
  3737. bench_aes();
  3738. return 0;
  3739. }
  3740. if (0) {
  3741. bench_dmap();
  3742. return 0;
  3743. }
  3744. atexit(remove_directory);
  3745. printf("Running Tor unit tests on %s\n", get_uname());
  3746. for (i = 0; test_array[i].test_name; ++i) {
  3747. if (!test_array[i].selected)
  3748. continue;
  3749. if (!test_array[i].is_subent) {
  3750. printf("\n============================== %s\n",test_array[i].test_name);
  3751. } else if (test_array[i].is_subent && verbose) {
  3752. printf("\n%s", test_array[i].test_name);
  3753. }
  3754. test_array[i].test_fn();
  3755. }
  3756. puts("");
  3757. crypto_global_cleanup();
  3758. if (have_failed)
  3759. return 1;
  3760. else
  3761. return 0;
  3762. }