test.c 151 KB

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