test.c 163 KB

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