test.c 173 KB

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