test.c 108 KB

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