test.c 119 KB

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