test.c 115 KB

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