test.c 122 KB

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