test_util.c 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2013, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #include "orconfig.h"
  6. #define COMPAT_PRIVATE
  7. #define CONTROL_PRIVATE
  8. #define MEMPOOL_PRIVATE
  9. #define UTIL_PRIVATE
  10. #include "or.h"
  11. #include "config.h"
  12. #include "control.h"
  13. #include "test.h"
  14. #include "mempool.h"
  15. #include "memarea.h"
  16. #ifdef _WIN32
  17. #include <tchar.h>
  18. #endif
  19. #include <math.h>
  20. /* XXXX this is a minimal wrapper to make the unit tests compile with the
  21. * changed tor_timegm interface. */
  22. static time_t
  23. tor_timegm_wrapper(const struct tm *tm)
  24. {
  25. time_t t;
  26. if (tor_timegm(tm, &t) < 0)
  27. return -1;
  28. return t;
  29. }
  30. #define tor_timegm tor_timegm_wrapper
  31. static void
  32. test_util_read_until_eof_impl(const char *fname, size_t file_len,
  33. size_t read_limit)
  34. {
  35. char *fifo_name = NULL;
  36. char *test_str = NULL;
  37. char *str = NULL;
  38. size_t sz = 9999999;
  39. int fd = -1;
  40. int r;
  41. fifo_name = tor_strdup(get_fname(fname));
  42. test_str = tor_malloc(file_len);
  43. crypto_rand(test_str, file_len);
  44. r = write_bytes_to_file(fifo_name, test_str, file_len, 1);
  45. tt_int_op(r, ==, 0);
  46. fd = open(fifo_name, O_RDONLY|O_BINARY);
  47. tt_int_op(fd, >=, 0);
  48. str = read_file_to_str_until_eof(fd, read_limit, &sz);
  49. tt_assert(str != NULL);
  50. if (read_limit < file_len)
  51. tt_int_op(sz, ==, read_limit);
  52. else
  53. tt_int_op(sz, ==, file_len);
  54. test_mem_op(test_str, ==, str, sz);
  55. test_assert(str[sz] == '\0');
  56. done:
  57. unlink(fifo_name);
  58. tor_free(fifo_name);
  59. tor_free(test_str);
  60. tor_free(str);
  61. if (fd >= 0)
  62. close(fd);
  63. }
  64. static void
  65. test_util_read_file_eof_tiny_limit(void *arg)
  66. {
  67. (void)arg;
  68. // purposely set limit shorter than what we wrote to the FIFO to
  69. // test the maximum, and that it puts the NUL in the right spot
  70. test_util_read_until_eof_impl("tor_test_fifo_tiny", 5, 4);
  71. }
  72. static void
  73. test_util_read_file_eof_two_loops(void *arg)
  74. {
  75. (void)arg;
  76. // write more than 1024 bytes to the FIFO to test two passes through
  77. // the loop in the method; if the re-alloc size is changed this
  78. // should be updated as well.
  79. test_util_read_until_eof_impl("tor_test_fifo_2k", 2048, 10000);
  80. }
  81. static void
  82. test_util_read_file_eof_zero_bytes(void *arg)
  83. {
  84. (void)arg;
  85. // zero-byte fifo
  86. test_util_read_until_eof_impl("tor_test_fifo_empty", 0, 10000);
  87. }
  88. /* Test the basic expected behaviour for write_chunks_to_file.
  89. * NOTE: This will need to be updated if we ever change the tempfile location
  90. * or extension */
  91. static void
  92. test_util_write_chunks_to_file(void *arg)
  93. {
  94. char *fname = NULL;
  95. char *tempname = NULL;
  96. char *str = NULL;
  97. int r;
  98. int fd = -1;
  99. struct stat st;
  100. /* These should be two different sizes to ensure the data is different
  101. * between the data file and the temp file's 'known string' */
  102. int temp_str_len = 1024;
  103. int data_str_len = 512;
  104. char *data_str = tor_malloc(data_str_len);
  105. char *temp_str = tor_malloc(temp_str_len);
  106. smartlist_t *chunks = smartlist_new();
  107. sized_chunk_t c = {data_str, data_str_len/2};
  108. sized_chunk_t c2 = {data_str + data_str_len/2, data_str_len/2};
  109. (void)arg;
  110. crypto_rand(temp_str, temp_str_len);
  111. crypto_rand(data_str, data_str_len);
  112. // Ensure it can write multiple chunks
  113. smartlist_add(chunks, &c);
  114. smartlist_add(chunks, &c2);
  115. /*
  116. * Check if it writes using a tempfile
  117. */
  118. fname = tor_strdup(get_fname("write_chunks_with_tempfile"));
  119. tor_asprintf(&tempname, "%s.tmp", fname);
  120. // write a known string to a file where the tempfile will be
  121. r = write_bytes_to_file(tempname, temp_str, temp_str_len, 1);
  122. tt_int_op(r, ==, 0);
  123. // call write_chunks_to_file
  124. r = write_chunks_to_file(fname, chunks, 1, 0);
  125. tt_int_op(r, ==, 0);
  126. // assert the file has been written (expected size)
  127. str = read_file_to_str(fname, RFTS_BIN, &st);
  128. tt_assert(str != NULL);
  129. tt_int_op(st.st_size, ==, data_str_len);
  130. test_mem_op(data_str, ==, str, data_str_len);
  131. tor_free(str);
  132. close(fd);
  133. // assert that the tempfile is removed (should not leave artifacts)
  134. str = read_file_to_str(tempname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  135. tt_assert(str == NULL);
  136. // Remove old testfile for second test
  137. r = unlink(fname);
  138. tt_int_op(r, ==, 0);
  139. tor_free(fname);
  140. tor_free(tempname);
  141. /*
  142. * Check if it skips using a tempfile with flags
  143. */
  144. fname = tor_strdup(get_fname("write_chunks_with_no_tempfile"));
  145. tor_asprintf(&tempname, "%s.tmp", fname);
  146. // write a known string to a file where the tempfile will be
  147. r = write_bytes_to_file(tempname, temp_str, temp_str_len, 1);
  148. tt_int_op(r, ==, 0);
  149. // call write_chunks_to_file with no_tempfile = true
  150. r = write_chunks_to_file(fname, chunks, 1, 1);
  151. tt_int_op(r, ==, 0);
  152. // assert the file has been written (expected size)
  153. str = read_file_to_str(fname, RFTS_BIN, &st);
  154. tt_assert(str != NULL);
  155. tt_int_op(st.st_size, ==, data_str_len);
  156. test_mem_op(data_str, ==, str, data_str_len);
  157. tor_free(str);
  158. close(fd);
  159. // assert the tempfile still contains the known string
  160. str = read_file_to_str(tempname, RFTS_BIN, &st);
  161. tt_assert(str != NULL);
  162. tt_int_op(st.st_size, ==, temp_str_len);
  163. test_mem_op(temp_str, ==, str, temp_str_len);
  164. done:
  165. unlink(fname);
  166. unlink(tempname);
  167. smartlist_free(chunks);
  168. tor_free(fname);
  169. tor_free(tempname);
  170. tor_free(str);
  171. tor_free(data_str);
  172. tor_free(temp_str);
  173. if (fd >= 0)
  174. close(fd);
  175. }
  176. static void
  177. test_util_time(void)
  178. {
  179. struct timeval start, end;
  180. struct tm a_time;
  181. char timestr[128];
  182. time_t t_res;
  183. int i;
  184. struct timeval tv;
  185. /* Test tv_udiff */
  186. start.tv_sec = 5;
  187. start.tv_usec = 5000;
  188. end.tv_sec = 5;
  189. end.tv_usec = 5000;
  190. test_eq(0L, tv_udiff(&start, &end));
  191. end.tv_usec = 7000;
  192. test_eq(2000L, tv_udiff(&start, &end));
  193. end.tv_sec = 6;
  194. test_eq(1002000L, tv_udiff(&start, &end));
  195. end.tv_usec = 0;
  196. test_eq(995000L, tv_udiff(&start, &end));
  197. end.tv_sec = 4;
  198. test_eq(-1005000L, tv_udiff(&start, &end));
  199. /* Test tor_timegm */
  200. /* The test values here are confirmed to be correct on a platform
  201. * with a working timegm. */
  202. a_time.tm_year = 2003-1900;
  203. a_time.tm_mon = 7;
  204. a_time.tm_mday = 30;
  205. a_time.tm_hour = 6;
  206. a_time.tm_min = 14;
  207. a_time.tm_sec = 55;
  208. test_eq((time_t) 1062224095UL, tor_timegm(&a_time));
  209. a_time.tm_year = 2004-1900; /* Try a leap year, after feb. */
  210. test_eq((time_t) 1093846495UL, tor_timegm(&a_time));
  211. a_time.tm_mon = 1; /* Try a leap year, in feb. */
  212. a_time.tm_mday = 10;
  213. test_eq((time_t) 1076393695UL, tor_timegm(&a_time));
  214. a_time.tm_mon = 0;
  215. a_time.tm_mday = 10;
  216. test_eq((time_t) 1073715295UL, tor_timegm(&a_time));
  217. a_time.tm_mon = 12; /* Wrong month, it's 0-based */
  218. a_time.tm_mday = 10;
  219. test_eq((time_t) -1, tor_timegm(&a_time));
  220. a_time.tm_mon = -1; /* Wrong month */
  221. a_time.tm_mday = 10;
  222. test_eq((time_t) -1, tor_timegm(&a_time));
  223. /* Test {format,parse}_rfc1123_time */
  224. format_rfc1123_time(timestr, 0);
  225. test_streq("Thu, 01 Jan 1970 00:00:00 GMT", timestr);
  226. format_rfc1123_time(timestr, (time_t)1091580502UL);
  227. test_streq("Wed, 04 Aug 2004 00:48:22 GMT", timestr);
  228. t_res = 0;
  229. i = parse_rfc1123_time(timestr, &t_res);
  230. test_eq(0,i);
  231. test_eq(t_res, (time_t)1091580502UL);
  232. /* The timezone doesn't matter */
  233. t_res = 0;
  234. test_eq(0, parse_rfc1123_time("Wed, 04 Aug 2004 00:48:22 ZUL", &t_res));
  235. test_eq(t_res, (time_t)1091580502UL);
  236. test_eq(-1, parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res));
  237. test_eq(-1, parse_rfc1123_time("Wed, 32 Mar 2011 00:00:00 GMT", &t_res));
  238. test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 24:00:00 GMT", &t_res));
  239. test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 23:60:00 GMT", &t_res));
  240. test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 23:59:62 GMT", &t_res));
  241. test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 1969 23:59:59 GMT", &t_res));
  242. test_eq(-1, parse_rfc1123_time("Wed, 30 Ene 2011 23:59:59 GMT", &t_res));
  243. test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 23:59:59 GM", &t_res));
  244. #if 0
  245. /* This fails, I imagine it's important and should be fixed? */
  246. test_eq(-1, parse_rfc1123_time("Wed, 29 Feb 2011 16:00:00 GMT", &t_res));
  247. /* Why is this string valid (ie. the test fails because it doesn't
  248. return -1)? */
  249. test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 23:59:61 GMT", &t_res));
  250. #endif
  251. /* Test parse_iso_time */
  252. t_res = 0;
  253. i = parse_iso_time("", &t_res);
  254. test_eq(-1, i);
  255. t_res = 0;
  256. i = parse_iso_time("2004-08-32 00:48:22", &t_res);
  257. test_eq(-1, i);
  258. t_res = 0;
  259. i = parse_iso_time("1969-08-03 00:48:22", &t_res);
  260. test_eq(-1, i);
  261. t_res = 0;
  262. i = parse_iso_time("2004-08-04 00:48:22", &t_res);
  263. test_eq(0,i);
  264. test_eq(t_res, (time_t)1091580502UL);
  265. t_res = 0;
  266. i = parse_iso_time("2004-8-4 0:48:22", &t_res);
  267. test_eq(0, i);
  268. test_eq(t_res, (time_t)1091580502UL);
  269. test_eq(-1, parse_iso_time("2004-08-zz 99-99x99 GMT", &t_res));
  270. test_eq(-1, parse_iso_time("2011-03-32 00:00:00 GMT", &t_res));
  271. test_eq(-1, parse_iso_time("2011-03-30 24:00:00 GMT", &t_res));
  272. test_eq(-1, parse_iso_time("2011-03-30 23:60:00 GMT", &t_res));
  273. test_eq(-1, parse_iso_time("2011-03-30 23:59:62 GMT", &t_res));
  274. test_eq(-1, parse_iso_time("1969-03-30 23:59:59 GMT", &t_res));
  275. test_eq(-1, parse_iso_time("2011-00-30 23:59:59 GMT", &t_res));
  276. test_eq(-1, parse_iso_time("2147483647-08-29 14:00:00", &t_res));
  277. test_eq(-1, parse_iso_time("2011-03-30 23:59", &t_res));
  278. /* Test tor_gettimeofday */
  279. end.tv_sec = 4;
  280. end.tv_usec = 999990;
  281. start.tv_sec = 1;
  282. start.tv_usec = 500;
  283. tor_gettimeofday(&start);
  284. /* now make sure time works. */
  285. tor_gettimeofday(&end);
  286. /* We might've timewarped a little. */
  287. tt_int_op(tv_udiff(&start, &end), >=, -5000);
  288. /* Test format_iso_time */
  289. tv.tv_sec = (time_t)1326296338;
  290. tv.tv_usec = 3060;
  291. format_iso_time(timestr, tv.tv_sec);
  292. test_streq("2012-01-11 15:38:58", timestr);
  293. /* The output of format_local_iso_time will vary by timezone, and setting
  294. our timezone for testing purposes would be a nontrivial flaky pain.
  295. Skip this test for now.
  296. format_local_iso_time(timestr, tv.tv_sec);
  297. test_streq("2012-01-11 10:38:58", timestr);
  298. */
  299. format_iso_time_nospace(timestr, tv.tv_sec);
  300. test_streq("2012-01-11T15:38:58", timestr);
  301. test_eq(strlen(timestr), ISO_TIME_LEN);
  302. format_iso_time_nospace_usec(timestr, &tv);
  303. test_streq("2012-01-11T15:38:58.003060", timestr);
  304. test_eq(strlen(timestr), ISO_TIME_USEC_LEN);
  305. done:
  306. ;
  307. }
  308. static void
  309. test_util_parse_http_time(void *arg)
  310. {
  311. struct tm a_time;
  312. char b[ISO_TIME_LEN+1];
  313. (void)arg;
  314. #define T(s) do { \
  315. format_iso_time(b, tor_timegm(&a_time)); \
  316. tt_str_op(b, ==, (s)); \
  317. b[0]='\0'; \
  318. } while (0)
  319. /* Test parse_http_time */
  320. test_eq(-1, parse_http_time("", &a_time));
  321. test_eq(-1, parse_http_time("Sunday, 32 Aug 2004 00:48:22 GMT", &a_time));
  322. test_eq(-1, parse_http_time("Sunday, 3 Aug 1869 00:48:22 GMT", &a_time));
  323. test_eq(-1, parse_http_time("Sunday, 32-Aug-94 00:48:22 GMT", &a_time));
  324. test_eq(-1, parse_http_time("Sunday, 3-Ago-04 00:48:22", &a_time));
  325. test_eq(-1, parse_http_time("Sunday, August the third", &a_time));
  326. test_eq(-1, parse_http_time("Wednesday,,04 Aug 1994 00:48:22 GMT", &a_time));
  327. test_eq(0, parse_http_time("Wednesday, 04 Aug 1994 00:48:22 GMT", &a_time));
  328. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  329. T("1994-08-04 00:48:22");
  330. test_eq(0, parse_http_time("Wednesday, 4 Aug 1994 0:48:22 GMT", &a_time));
  331. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  332. T("1994-08-04 00:48:22");
  333. test_eq(0, parse_http_time("Miercoles, 4 Aug 1994 0:48:22 GMT", &a_time));
  334. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  335. T("1994-08-04 00:48:22");
  336. test_eq(0, parse_http_time("Wednesday, 04-Aug-94 00:48:22 GMT", &a_time));
  337. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  338. T("1994-08-04 00:48:22");
  339. test_eq(0, parse_http_time("Wednesday, 4-Aug-94 0:48:22 GMT", &a_time));
  340. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  341. T("1994-08-04 00:48:22");
  342. test_eq(0, parse_http_time("Miercoles, 4-Aug-94 0:48:22 GMT", &a_time));
  343. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  344. T("1994-08-04 00:48:22");
  345. test_eq(0, parse_http_time("Wed Aug 04 00:48:22 1994", &a_time));
  346. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  347. T("1994-08-04 00:48:22");
  348. test_eq(0, parse_http_time("Wed Aug 4 0:48:22 1994", &a_time));
  349. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  350. T("1994-08-04 00:48:22");
  351. test_eq(0, parse_http_time("Mie Aug 4 0:48:22 1994", &a_time));
  352. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  353. T("1994-08-04 00:48:22");
  354. test_eq(0, parse_http_time("Sun, 1 Jan 2012 00:00:00 GMT", &a_time));
  355. test_eq((time_t)1325376000UL, tor_timegm(&a_time));
  356. T("2012-01-01 00:00:00");
  357. test_eq(0, parse_http_time("Mon, 31 Dec 2012 00:00:00 GMT", &a_time));
  358. test_eq((time_t)1356912000UL, tor_timegm(&a_time));
  359. T("2012-12-31 00:00:00");
  360. test_eq(-1, parse_http_time("2004-08-zz 99-99x99 GMT", &a_time));
  361. test_eq(-1, parse_http_time("2011-03-32 00:00:00 GMT", &a_time));
  362. test_eq(-1, parse_http_time("2011-03-30 24:00:00 GMT", &a_time));
  363. test_eq(-1, parse_http_time("2011-03-30 23:60:00 GMT", &a_time));
  364. test_eq(-1, parse_http_time("2011-03-30 23:59:62 GMT", &a_time));
  365. test_eq(-1, parse_http_time("1969-03-30 23:59:59 GMT", &a_time));
  366. test_eq(-1, parse_http_time("2011-00-30 23:59:59 GMT", &a_time));
  367. test_eq(-1, parse_http_time("2011-03-30 23:59", &a_time));
  368. #undef T
  369. done:
  370. ;
  371. }
  372. static void
  373. test_util_config_line(void)
  374. {
  375. char buf[1024];
  376. char *k=NULL, *v=NULL;
  377. const char *str;
  378. /* Test parse_config_line_from_str */
  379. strlcpy(buf, "k v\n" " key value with spaces \n" "keykey val\n"
  380. "k2\n"
  381. "k3 \n" "\n" " \n" "#comment\n"
  382. "k4#a\n" "k5#abc\n" "k6 val #with comment\n"
  383. "kseven \"a quoted 'string\"\n"
  384. "k8 \"a \\x71uoted\\n\\\"str\\\\ing\\t\\001\\01\\1\\\"\"\n"
  385. "k9 a line that\\\n spans two lines.\n\n"
  386. "k10 more than\\\n one contin\\\nuation\n"
  387. "k11 \\\ncontinuation at the start\n"
  388. "k12 line with a\\\n#comment\n embedded\n"
  389. "k13\\\ncontinuation at the very start\n"
  390. "k14 a line that has a comment and # ends with a slash \\\n"
  391. "k15 this should be the next new line\n"
  392. "k16 a line that has a comment and # ends without a slash \n"
  393. "k17 this should be the next new line\n"
  394. , sizeof(buf));
  395. str = buf;
  396. str = parse_config_line_from_str(str, &k, &v);
  397. test_streq(k, "k");
  398. test_streq(v, "v");
  399. tor_free(k); tor_free(v);
  400. test_assert(!strcmpstart(str, "key value with"));
  401. str = parse_config_line_from_str(str, &k, &v);
  402. test_streq(k, "key");
  403. test_streq(v, "value with spaces");
  404. tor_free(k); tor_free(v);
  405. test_assert(!strcmpstart(str, "keykey"));
  406. str = parse_config_line_from_str(str, &k, &v);
  407. test_streq(k, "keykey");
  408. test_streq(v, "val");
  409. tor_free(k); tor_free(v);
  410. test_assert(!strcmpstart(str, "k2\n"));
  411. str = parse_config_line_from_str(str, &k, &v);
  412. test_streq(k, "k2");
  413. test_streq(v, "");
  414. tor_free(k); tor_free(v);
  415. test_assert(!strcmpstart(str, "k3 \n"));
  416. str = parse_config_line_from_str(str, &k, &v);
  417. test_streq(k, "k3");
  418. test_streq(v, "");
  419. tor_free(k); tor_free(v);
  420. test_assert(!strcmpstart(str, "#comment"));
  421. str = parse_config_line_from_str(str, &k, &v);
  422. test_streq(k, "k4");
  423. test_streq(v, "");
  424. tor_free(k); tor_free(v);
  425. test_assert(!strcmpstart(str, "k5#abc"));
  426. str = parse_config_line_from_str(str, &k, &v);
  427. test_streq(k, "k5");
  428. test_streq(v, "");
  429. tor_free(k); tor_free(v);
  430. test_assert(!strcmpstart(str, "k6"));
  431. str = parse_config_line_from_str(str, &k, &v);
  432. test_streq(k, "k6");
  433. test_streq(v, "val");
  434. tor_free(k); tor_free(v);
  435. test_assert(!strcmpstart(str, "kseven"));
  436. str = parse_config_line_from_str(str, &k, &v);
  437. test_streq(k, "kseven");
  438. test_streq(v, "a quoted \'string");
  439. tor_free(k); tor_free(v);
  440. test_assert(!strcmpstart(str, "k8 "));
  441. str = parse_config_line_from_str(str, &k, &v);
  442. test_streq(k, "k8");
  443. test_streq(v, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
  444. tor_free(k); tor_free(v);
  445. str = parse_config_line_from_str(str, &k, &v);
  446. test_streq(k, "k9");
  447. test_streq(v, "a line that spans two lines.");
  448. tor_free(k); tor_free(v);
  449. str = parse_config_line_from_str(str, &k, &v);
  450. test_streq(k, "k10");
  451. test_streq(v, "more than one continuation");
  452. tor_free(k); tor_free(v);
  453. str = parse_config_line_from_str(str, &k, &v);
  454. test_streq(k, "k11");
  455. test_streq(v, "continuation at the start");
  456. tor_free(k); tor_free(v);
  457. str = parse_config_line_from_str(str, &k, &v);
  458. test_streq(k, "k12");
  459. test_streq(v, "line with a embedded");
  460. tor_free(k); tor_free(v);
  461. str = parse_config_line_from_str(str, &k, &v);
  462. test_streq(k, "k13");
  463. test_streq(v, "continuation at the very start");
  464. tor_free(k); tor_free(v);
  465. str = parse_config_line_from_str(str, &k, &v);
  466. test_streq(k, "k14");
  467. test_streq(v, "a line that has a comment and" );
  468. tor_free(k); tor_free(v);
  469. str = parse_config_line_from_str(str, &k, &v);
  470. test_streq(k, "k15");
  471. test_streq(v, "this should be the next new line");
  472. tor_free(k); tor_free(v);
  473. str = parse_config_line_from_str(str, &k, &v);
  474. test_streq(k, "k16");
  475. test_streq(v, "a line that has a comment and" );
  476. tor_free(k); tor_free(v);
  477. str = parse_config_line_from_str(str, &k, &v);
  478. test_streq(k, "k17");
  479. test_streq(v, "this should be the next new line");
  480. tor_free(k); tor_free(v);
  481. test_streq(str, "");
  482. done:
  483. tor_free(k);
  484. tor_free(v);
  485. }
  486. static void
  487. test_util_config_line_quotes(void)
  488. {
  489. char buf1[1024];
  490. char buf2[128];
  491. char buf3[128];
  492. char buf4[128];
  493. char *k=NULL, *v=NULL;
  494. const char *str;
  495. /* Test parse_config_line_from_str */
  496. strlcpy(buf1, "kTrailingSpace \"quoted value\" \n"
  497. "kTrailingGarbage \"quoted value\"trailing garbage\n"
  498. , sizeof(buf1));
  499. strlcpy(buf2, "kTrailingSpaceAndGarbage \"quoted value\" trailing space+g\n"
  500. , sizeof(buf2));
  501. strlcpy(buf3, "kMultilineTrailingSpace \"mline\\ \nvalue w/ trailing sp\"\n"
  502. , sizeof(buf3));
  503. strlcpy(buf4, "kMultilineNoTrailingBackslash \"naked multiline\nvalue\"\n"
  504. , sizeof(buf4));
  505. str = buf1;
  506. str = parse_config_line_from_str(str, &k, &v);
  507. test_streq(k, "kTrailingSpace");
  508. test_streq(v, "quoted value");
  509. tor_free(k); tor_free(v);
  510. str = parse_config_line_from_str(str, &k, &v);
  511. test_eq_ptr(str, NULL);
  512. tor_free(k); tor_free(v);
  513. str = buf2;
  514. str = parse_config_line_from_str(str, &k, &v);
  515. test_eq_ptr(str, NULL);
  516. tor_free(k); tor_free(v);
  517. str = buf3;
  518. str = parse_config_line_from_str(str, &k, &v);
  519. test_eq_ptr(str, NULL);
  520. tor_free(k); tor_free(v);
  521. str = buf4;
  522. str = parse_config_line_from_str(str, &k, &v);
  523. test_eq_ptr(str, NULL);
  524. tor_free(k); tor_free(v);
  525. done:
  526. tor_free(k);
  527. tor_free(v);
  528. }
  529. static void
  530. test_util_config_line_comment_character(void)
  531. {
  532. char buf[1024];
  533. char *k=NULL, *v=NULL;
  534. const char *str;
  535. /* Test parse_config_line_from_str */
  536. strlcpy(buf, "k1 \"# in quotes\"\n"
  537. "k2 some value # some comment\n"
  538. "k3 /home/user/myTorNetwork#2\n" /* Testcase for #1323 */
  539. , sizeof(buf));
  540. str = buf;
  541. str = parse_config_line_from_str(str, &k, &v);
  542. test_streq(k, "k1");
  543. test_streq(v, "# in quotes");
  544. tor_free(k); tor_free(v);
  545. str = parse_config_line_from_str(str, &k, &v);
  546. test_streq(k, "k2");
  547. test_streq(v, "some value");
  548. tor_free(k); tor_free(v);
  549. test_streq(str, "k3 /home/user/myTorNetwork#2\n");
  550. #if 0
  551. str = parse_config_line_from_str(str, &k, &v);
  552. test_streq(k, "k3");
  553. test_streq(v, "/home/user/myTorNetwork#2");
  554. tor_free(k); tor_free(v);
  555. test_streq(str, "");
  556. #endif
  557. done:
  558. tor_free(k);
  559. tor_free(v);
  560. }
  561. static void
  562. test_util_config_line_escaped_content(void)
  563. {
  564. char buf1[1024];
  565. char buf2[128];
  566. char buf3[128];
  567. char buf4[128];
  568. char buf5[128];
  569. char buf6[128];
  570. char *k=NULL, *v=NULL;
  571. const char *str;
  572. /* Test parse_config_line_from_str */
  573. strlcpy(buf1, "HexadecimalLower \"\\x2a\"\n"
  574. "HexadecimalUpper \"\\x2A\"\n"
  575. "HexadecimalUpperX \"\\X2A\"\n"
  576. "Octal \"\\52\"\n"
  577. "Newline \"\\n\"\n"
  578. "Tab \"\\t\"\n"
  579. "CarriageReturn \"\\r\"\n"
  580. "DoubleQuote \"\\\"\"\n"
  581. "SimpleQuote \"\\'\"\n"
  582. "Backslash \"\\\\\"\n"
  583. "Mix \"This is a \\\"star\\\":\\t\\'\\x2a\\'\\nAnd second line\"\n"
  584. , sizeof(buf1));
  585. strlcpy(buf2, "BrokenEscapedContent \"\\a\"\n"
  586. , sizeof(buf2));
  587. strlcpy(buf3, "BrokenEscapedContent \"\\x\"\n"
  588. , sizeof(buf3));
  589. strlcpy(buf4, "BrokenOctal \"\\8\"\n"
  590. , sizeof(buf4));
  591. strlcpy(buf5, "BrokenHex \"\\xg4\"\n"
  592. , sizeof(buf5));
  593. strlcpy(buf6, "BrokenEscape \"\\"
  594. , sizeof(buf6));
  595. str = buf1;
  596. str = parse_config_line_from_str(str, &k, &v);
  597. test_streq(k, "HexadecimalLower");
  598. test_streq(v, "*");
  599. tor_free(k); tor_free(v);
  600. str = parse_config_line_from_str(str, &k, &v);
  601. test_streq(k, "HexadecimalUpper");
  602. test_streq(v, "*");
  603. tor_free(k); tor_free(v);
  604. str = parse_config_line_from_str(str, &k, &v);
  605. test_streq(k, "HexadecimalUpperX");
  606. test_streq(v, "*");
  607. tor_free(k); tor_free(v);
  608. str = parse_config_line_from_str(str, &k, &v);
  609. test_streq(k, "Octal");
  610. test_streq(v, "*");
  611. tor_free(k); tor_free(v);
  612. str = parse_config_line_from_str(str, &k, &v);
  613. test_streq(k, "Newline");
  614. test_streq(v, "\n");
  615. tor_free(k); tor_free(v);
  616. str = parse_config_line_from_str(str, &k, &v);
  617. test_streq(k, "Tab");
  618. test_streq(v, "\t");
  619. tor_free(k); tor_free(v);
  620. str = parse_config_line_from_str(str, &k, &v);
  621. test_streq(k, "CarriageReturn");
  622. test_streq(v, "\r");
  623. tor_free(k); tor_free(v);
  624. str = parse_config_line_from_str(str, &k, &v);
  625. test_streq(k, "DoubleQuote");
  626. test_streq(v, "\"");
  627. tor_free(k); tor_free(v);
  628. str = parse_config_line_from_str(str, &k, &v);
  629. test_streq(k, "SimpleQuote");
  630. test_streq(v, "'");
  631. tor_free(k); tor_free(v);
  632. str = parse_config_line_from_str(str, &k, &v);
  633. test_streq(k, "Backslash");
  634. test_streq(v, "\\");
  635. tor_free(k); tor_free(v);
  636. str = parse_config_line_from_str(str, &k, &v);
  637. test_streq(k, "Mix");
  638. test_streq(v, "This is a \"star\":\t'*'\nAnd second line");
  639. tor_free(k); tor_free(v);
  640. test_streq(str, "");
  641. str = buf2;
  642. str = parse_config_line_from_str(str, &k, &v);
  643. test_eq_ptr(str, NULL);
  644. tor_free(k); tor_free(v);
  645. str = buf3;
  646. str = parse_config_line_from_str(str, &k, &v);
  647. test_eq_ptr(str, NULL);
  648. tor_free(k); tor_free(v);
  649. str = buf4;
  650. str = parse_config_line_from_str(str, &k, &v);
  651. test_eq_ptr(str, NULL);
  652. tor_free(k); tor_free(v);
  653. #if 0
  654. str = buf5;
  655. str = parse_config_line_from_str(str, &k, &v);
  656. test_eq_ptr(str, NULL);
  657. tor_free(k); tor_free(v);
  658. #endif
  659. str = buf6;
  660. str = parse_config_line_from_str(str, &k, &v);
  661. test_eq_ptr(str, NULL);
  662. tor_free(k); tor_free(v);
  663. done:
  664. tor_free(k);
  665. tor_free(v);
  666. }
  667. #ifndef _WIN32
  668. static void
  669. test_util_expand_filename(void)
  670. {
  671. char *str;
  672. setenv("HOME", "/home/itv", 1); /* For "internal test value" */
  673. str = expand_filename("");
  674. test_streq("", str);
  675. tor_free(str);
  676. str = expand_filename("/normal/path");
  677. test_streq("/normal/path", str);
  678. tor_free(str);
  679. str = expand_filename("/normal/trailing/path/");
  680. test_streq("/normal/trailing/path/", str);
  681. tor_free(str);
  682. str = expand_filename("~");
  683. test_streq("/home/itv/", str);
  684. tor_free(str);
  685. str = expand_filename("$HOME/nodice");
  686. test_streq("$HOME/nodice", str);
  687. tor_free(str);
  688. str = expand_filename("~/");
  689. test_streq("/home/itv/", str);
  690. tor_free(str);
  691. str = expand_filename("~/foobarqux");
  692. test_streq("/home/itv/foobarqux", str);
  693. tor_free(str);
  694. str = expand_filename("~/../../etc/passwd");
  695. test_streq("/home/itv/../../etc/passwd", str);
  696. tor_free(str);
  697. str = expand_filename("~/trailing/");
  698. test_streq("/home/itv/trailing/", str);
  699. tor_free(str);
  700. /* Ideally we'd test ~anotheruser, but that's shady to test (we'd
  701. have to somehow inject/fake the get_user_homedir call) */
  702. /* $HOME ending in a trailing slash */
  703. setenv("HOME", "/home/itv/", 1);
  704. str = expand_filename("~");
  705. test_streq("/home/itv/", str);
  706. tor_free(str);
  707. str = expand_filename("~/");
  708. test_streq("/home/itv/", str);
  709. tor_free(str);
  710. str = expand_filename("~/foo");
  711. test_streq("/home/itv/foo", str);
  712. tor_free(str);
  713. /* Try with empty $HOME */
  714. setenv("HOME", "", 1);
  715. str = expand_filename("~");
  716. test_streq("/", str);
  717. tor_free(str);
  718. str = expand_filename("~/");
  719. test_streq("/", str);
  720. tor_free(str);
  721. str = expand_filename("~/foobar");
  722. test_streq("/foobar", str);
  723. tor_free(str);
  724. /* Try with $HOME unset */
  725. unsetenv("HOME");
  726. str = expand_filename("~");
  727. test_streq("/", str);
  728. tor_free(str);
  729. str = expand_filename("~/");
  730. test_streq("/", str);
  731. tor_free(str);
  732. str = expand_filename("~/foobar");
  733. test_streq("/foobar", str);
  734. tor_free(str);
  735. done:
  736. tor_free(str);
  737. }
  738. #endif
  739. /** Test tor_escape_str_for_pt_args(). */
  740. static void
  741. test_util_escape_string_socks(void)
  742. {
  743. char *escaped_string = NULL;
  744. /** Simple backslash escape. */
  745. escaped_string = tor_escape_str_for_pt_args("This is a backslash: \\",";\\");
  746. test_assert(escaped_string);
  747. test_streq(escaped_string, "This is a backslash: \\\\");
  748. tor_free(escaped_string);
  749. /** Simple semicolon escape. */
  750. escaped_string = tor_escape_str_for_pt_args("First rule:Do not use ;",";\\");
  751. test_assert(escaped_string);
  752. test_streq(escaped_string, "First rule:Do not use \\;");
  753. tor_free(escaped_string);
  754. /** Empty string. */
  755. escaped_string = tor_escape_str_for_pt_args("", ";\\");
  756. test_assert(escaped_string);
  757. test_streq(escaped_string, "");
  758. tor_free(escaped_string);
  759. /** Escape all characters. */
  760. escaped_string = tor_escape_str_for_pt_args(";\\;\\", ";\\");
  761. test_assert(escaped_string);
  762. test_streq(escaped_string, "\\;\\\\\\;\\\\");
  763. tor_free(escaped_string);
  764. escaped_string = tor_escape_str_for_pt_args(";", ";\\");
  765. test_assert(escaped_string);
  766. test_streq(escaped_string, "\\;");
  767. tor_free(escaped_string);
  768. done:
  769. tor_free(escaped_string);
  770. }
  771. static void
  772. test_util_string_is_key_value(void *ptr)
  773. {
  774. (void)ptr;
  775. test_assert(string_is_key_value(LOG_WARN, "key=value"));
  776. test_assert(string_is_key_value(LOG_WARN, "k=v"));
  777. test_assert(string_is_key_value(LOG_WARN, "key="));
  778. test_assert(string_is_key_value(LOG_WARN, "x="));
  779. test_assert(string_is_key_value(LOG_WARN, "xx="));
  780. test_assert(!string_is_key_value(LOG_WARN, "=value"));
  781. test_assert(!string_is_key_value(LOG_WARN, "=x"));
  782. test_assert(!string_is_key_value(LOG_WARN, "="));
  783. /* ??? */
  784. /* test_assert(!string_is_key_value(LOG_WARN, "===")); */
  785. done:
  786. ;
  787. }
  788. /** Test basic string functionality. */
  789. static void
  790. test_util_strmisc(void)
  791. {
  792. char buf[1024];
  793. int i;
  794. char *cp, *cp_tmp = NULL;
  795. /* Test strl operations */
  796. test_eq(5, strlcpy(buf, "Hello", 0));
  797. test_eq(5, strlcpy(buf, "Hello", 10));
  798. test_streq(buf, "Hello");
  799. test_eq(5, strlcpy(buf, "Hello", 6));
  800. test_streq(buf, "Hello");
  801. test_eq(5, strlcpy(buf, "Hello", 5));
  802. test_streq(buf, "Hell");
  803. strlcpy(buf, "Hello", sizeof(buf));
  804. test_eq(10, strlcat(buf, "Hello", 5));
  805. /* Test strstrip() */
  806. strlcpy(buf, "Testing 1 2 3", sizeof(buf));
  807. tor_strstrip(buf, ",!");
  808. test_streq(buf, "Testing 1 2 3");
  809. strlcpy(buf, "!Testing 1 2 3?", sizeof(buf));
  810. tor_strstrip(buf, "!? ");
  811. test_streq(buf, "Testing123");
  812. strlcpy(buf, "!!!Testing 1 2 3??", sizeof(buf));
  813. tor_strstrip(buf, "!? ");
  814. test_streq(buf, "Testing123");
  815. /* Test parse_long */
  816. /* Empty/zero input */
  817. test_eq(0L, tor_parse_long("",10,0,100,&i,NULL));
  818. test_eq(0, i);
  819. test_eq(0L, tor_parse_long("0",10,0,100,&i,NULL));
  820. test_eq(1, i);
  821. /* Normal cases */
  822. test_eq(10L, tor_parse_long("10",10,0,100,&i,NULL));
  823. test_eq(1, i);
  824. test_eq(10L, tor_parse_long("10",10,0,10,&i,NULL));
  825. test_eq(1, i);
  826. test_eq(10L, tor_parse_long("10",10,10,100,&i,NULL));
  827. test_eq(1, i);
  828. test_eq(-50L, tor_parse_long("-50",10,-100,100,&i,NULL));
  829. test_eq(1, i);
  830. test_eq(-50L, tor_parse_long("-50",10,-100,0,&i,NULL));
  831. test_eq(1, i);
  832. test_eq(-50L, tor_parse_long("-50",10,-50,0,&i,NULL));
  833. test_eq(1, i);
  834. /* Extra garbage */
  835. test_eq(0L, tor_parse_long("10m",10,0,100,&i,NULL));
  836. test_eq(0, i);
  837. test_eq(0L, tor_parse_long("-50 plus garbage",10,-100,100,&i,NULL));
  838. test_eq(0, i);
  839. test_eq(10L, tor_parse_long("10m",10,0,100,&i,&cp));
  840. test_eq(1, i);
  841. test_streq(cp, "m");
  842. test_eq(-50L, tor_parse_long("-50 plus garbage",10,-100,100,&i,&cp));
  843. test_eq(1, i);
  844. test_streq(cp, " plus garbage");
  845. /* Out of bounds */
  846. test_eq(0L, tor_parse_long("10",10,50,100,&i,NULL));
  847. test_eq(0, i);
  848. test_eq(0L, tor_parse_long("-50",10,0,100,&i,NULL));
  849. test_eq(0, i);
  850. /* Base different than 10 */
  851. test_eq(2L, tor_parse_long("10",2,0,100,NULL,NULL));
  852. test_eq(0L, tor_parse_long("2",2,0,100,NULL,NULL));
  853. test_eq(0L, tor_parse_long("10",-2,0,100,NULL,NULL));
  854. test_eq(68284L, tor_parse_long("10abc",16,0,70000,NULL,NULL));
  855. test_eq(68284L, tor_parse_long("10ABC",16,0,70000,NULL,NULL));
  856. /* Test parse_ulong */
  857. test_eq(0UL, tor_parse_ulong("",10,0,100,NULL,NULL));
  858. test_eq(0UL, tor_parse_ulong("0",10,0,100,NULL,NULL));
  859. test_eq(10UL, tor_parse_ulong("10",10,0,100,NULL,NULL));
  860. test_eq(0UL, tor_parse_ulong("10",10,50,100,NULL,NULL));
  861. test_eq(10UL, tor_parse_ulong("10",10,0,10,NULL,NULL));
  862. test_eq(10UL, tor_parse_ulong("10",10,10,100,NULL,NULL));
  863. test_eq(0UL, tor_parse_ulong("8",8,0,100,NULL,NULL));
  864. test_eq(50UL, tor_parse_ulong("50",10,50,100,NULL,NULL));
  865. test_eq(0UL, tor_parse_ulong("-50",10,-100,100,NULL,NULL));
  866. /* Test parse_uint64 */
  867. test_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i, &cp));
  868. test_eq(1, i);
  869. test_streq(cp, " x");
  870. test_assert(U64_LITERAL(12345678901) ==
  871. tor_parse_uint64("12345678901",10,0,UINT64_MAX, &i, &cp));
  872. test_eq(1, i);
  873. test_streq(cp, "");
  874. test_assert(U64_LITERAL(0) ==
  875. tor_parse_uint64("12345678901",10,500,INT32_MAX, &i, &cp));
  876. test_eq(0, i);
  877. {
  878. /* Test parse_double */
  879. double d = tor_parse_double("10", 0, UINT64_MAX,&i,NULL);
  880. test_eq(1, i);
  881. test_assert(DBL_TO_U64(d) == 10);
  882. d = tor_parse_double("0", 0, UINT64_MAX,&i,NULL);
  883. test_eq(1, i);
  884. test_assert(DBL_TO_U64(d) == 0);
  885. d = tor_parse_double(" ", 0, UINT64_MAX,&i,NULL);
  886. test_eq(0, i);
  887. d = tor_parse_double(".0a", 0, UINT64_MAX,&i,NULL);
  888. test_eq(0, i);
  889. d = tor_parse_double(".0a", 0, UINT64_MAX,&i,&cp);
  890. test_eq(1, i);
  891. d = tor_parse_double("-.0", 0, UINT64_MAX,&i,NULL);
  892. test_eq(1, i);
  893. test_assert(DBL_TO_U64(d) == 0);
  894. d = tor_parse_double("-10", -100.0, 100.0,&i,NULL);
  895. test_eq(1, i);
  896. test_eq(-10.0, d);
  897. }
  898. {
  899. /* Test tor_parse_* where we overflow/underflow the underlying type. */
  900. /* This string should overflow 64-bit ints. */
  901. #define TOOBIG "100000000000000000000000000"
  902. test_eq(0L, tor_parse_long(TOOBIG, 10, LONG_MIN, LONG_MAX, &i, NULL));
  903. test_eq(i, 0);
  904. test_eq(0L, tor_parse_long("-"TOOBIG, 10, LONG_MIN, LONG_MAX, &i, NULL));
  905. test_eq(i, 0);
  906. test_eq(0UL, tor_parse_ulong(TOOBIG, 10, 0, ULONG_MAX, &i, NULL));
  907. test_eq(i, 0);
  908. test_eq(U64_LITERAL(0), tor_parse_uint64(TOOBIG, 10,
  909. 0, UINT64_MAX, &i, NULL));
  910. test_eq(i, 0);
  911. }
  912. /* Test snprintf */
  913. /* Returning -1 when there's not enough room in the output buffer */
  914. test_eq(-1, tor_snprintf(buf, 0, "Foo"));
  915. test_eq(-1, tor_snprintf(buf, 2, "Foo"));
  916. test_eq(-1, tor_snprintf(buf, 3, "Foo"));
  917. test_neq(-1, tor_snprintf(buf, 4, "Foo"));
  918. /* Always NUL-terminate the output */
  919. tor_snprintf(buf, 5, "abcdef");
  920. test_eq(0, buf[4]);
  921. tor_snprintf(buf, 10, "abcdef");
  922. test_eq(0, buf[6]);
  923. /* uint64 */
  924. tor_snprintf(buf, sizeof(buf), "x!"U64_FORMAT"!x",
  925. U64_PRINTF_ARG(U64_LITERAL(12345678901)));
  926. test_streq("x!12345678901!x", buf);
  927. /* Test str{,case}cmpstart */
  928. test_assert(strcmpstart("abcdef", "abcdef")==0);
  929. test_assert(strcmpstart("abcdef", "abc")==0);
  930. test_assert(strcmpstart("abcdef", "abd")<0);
  931. test_assert(strcmpstart("abcdef", "abb")>0);
  932. test_assert(strcmpstart("ab", "abb")<0);
  933. test_assert(strcmpstart("ab", "")==0);
  934. test_assert(strcmpstart("ab", "ab ")<0);
  935. test_assert(strcasecmpstart("abcdef", "abCdEF")==0);
  936. test_assert(strcasecmpstart("abcDeF", "abc")==0);
  937. test_assert(strcasecmpstart("abcdef", "Abd")<0);
  938. test_assert(strcasecmpstart("Abcdef", "abb")>0);
  939. test_assert(strcasecmpstart("ab", "Abb")<0);
  940. test_assert(strcasecmpstart("ab", "")==0);
  941. test_assert(strcasecmpstart("ab", "ab ")<0);
  942. /* Test str{,case}cmpend */
  943. test_assert(strcmpend("abcdef", "abcdef")==0);
  944. test_assert(strcmpend("abcdef", "def")==0);
  945. test_assert(strcmpend("abcdef", "deg")<0);
  946. test_assert(strcmpend("abcdef", "dee")>0);
  947. test_assert(strcmpend("ab", "aab")>0);
  948. test_assert(strcasecmpend("AbcDEF", "abcdef")==0);
  949. test_assert(strcasecmpend("abcdef", "dEF")==0);
  950. test_assert(strcasecmpend("abcdef", "Deg")<0);
  951. test_assert(strcasecmpend("abcDef", "dee")>0);
  952. test_assert(strcasecmpend("AB", "abb")<0);
  953. /* Test digest_is_zero */
  954. memset(buf,0,20);
  955. buf[20] = 'x';
  956. test_assert(tor_digest_is_zero(buf));
  957. buf[19] = 'x';
  958. test_assert(!tor_digest_is_zero(buf));
  959. /* Test mem_is_zero */
  960. memset(buf,0,128);
  961. buf[128] = 'x';
  962. test_assert(tor_mem_is_zero(buf, 10));
  963. test_assert(tor_mem_is_zero(buf, 20));
  964. test_assert(tor_mem_is_zero(buf, 128));
  965. test_assert(!tor_mem_is_zero(buf, 129));
  966. buf[60] = (char)255;
  967. test_assert(!tor_mem_is_zero(buf, 128));
  968. buf[0] = (char)1;
  969. test_assert(!tor_mem_is_zero(buf, 10));
  970. /* Test 'escaped' */
  971. test_assert(NULL == escaped(NULL));
  972. test_streq("\"\"", escaped(""));
  973. test_streq("\"abcd\"", escaped("abcd"));
  974. test_streq("\"\\\\ \\n\\r\\t\\\"\\'\"", escaped("\\ \n\r\t\"'"));
  975. test_streq("\"unnecessary \\'backslashes\\'\"",
  976. escaped("unnecessary \'backslashes\'"));
  977. /* Non-printable characters appear as octal */
  978. test_streq("\"z\\001abc\\277d\"", escaped("z\001abc\277d"));
  979. test_streq("\"z\\336\\255 ;foo\"", escaped("z\xde\xad\x20;foo"));
  980. /* Test strndup and memdup */
  981. {
  982. const char *s = "abcdefghijklmnopqrstuvwxyz";
  983. cp_tmp = tor_strndup(s, 30);
  984. test_streq(cp_tmp, s); /* same string, */
  985. test_neq_ptr(cp_tmp, s); /* but different pointers. */
  986. tor_free(cp_tmp);
  987. cp_tmp = tor_strndup(s, 5);
  988. test_streq(cp_tmp, "abcde");
  989. tor_free(cp_tmp);
  990. s = "a\0b\0c\0d\0e\0";
  991. cp_tmp = tor_memdup(s,10);
  992. test_memeq(cp_tmp, s, 10); /* same ram, */
  993. test_neq_ptr(cp_tmp, s); /* but different pointers. */
  994. tor_free(cp_tmp);
  995. }
  996. /* Test str-foo functions */
  997. cp = tor_strdup("abcdef");
  998. test_assert(tor_strisnonupper(cp));
  999. cp[3] = 'D';
  1000. test_assert(!tor_strisnonupper(cp));
  1001. tor_strupper(cp);
  1002. test_streq(cp, "ABCDEF");
  1003. tor_strlower(cp);
  1004. test_streq(cp, "abcdef");
  1005. test_assert(tor_strisnonupper(cp));
  1006. test_assert(tor_strisprint(cp));
  1007. cp[3] = 3;
  1008. test_assert(!tor_strisprint(cp));
  1009. tor_free(cp);
  1010. /* Test memmem and memstr */
  1011. {
  1012. const char *haystack = "abcde";
  1013. test_assert(!tor_memmem(haystack, 5, "ef", 2));
  1014. test_eq_ptr(tor_memmem(haystack, 5, "cd", 2), haystack + 2);
  1015. test_eq_ptr(tor_memmem(haystack, 5, "cde", 3), haystack + 2);
  1016. test_assert(!tor_memmem(haystack, 4, "cde", 3));
  1017. haystack = "ababcad";
  1018. test_eq_ptr(tor_memmem(haystack, 7, "abc", 3), haystack + 2);
  1019. /* memstr */
  1020. test_eq_ptr(tor_memstr(haystack, 7, "abc"), haystack + 2);
  1021. test_eq_ptr(tor_memstr(haystack, 7, "cad"), haystack + 4);
  1022. test_assert(!tor_memstr(haystack, 6, "cad"));
  1023. test_assert(!tor_memstr(haystack, 7, "cadd"));
  1024. test_assert(!tor_memstr(haystack, 7, "fe"));
  1025. test_assert(!tor_memstr(haystack, 7, "ababcade"));
  1026. }
  1027. /* Test hex_str */
  1028. {
  1029. char binary_data[68];
  1030. size_t i;
  1031. for (i = 0; i < sizeof(binary_data); ++i)
  1032. binary_data[i] = i;
  1033. test_streq(hex_str(binary_data, 0), "");
  1034. test_streq(hex_str(binary_data, 1), "00");
  1035. test_streq(hex_str(binary_data, 17), "000102030405060708090A0B0C0D0E0F10");
  1036. test_streq(hex_str(binary_data, 32),
  1037. "000102030405060708090A0B0C0D0E0F"
  1038. "101112131415161718191A1B1C1D1E1F");
  1039. test_streq(hex_str(binary_data, 34),
  1040. "000102030405060708090A0B0C0D0E0F"
  1041. "101112131415161718191A1B1C1D1E1F");
  1042. /* Repeat these tests for shorter strings after longer strings
  1043. have been tried, to make sure we're correctly terminating strings */
  1044. test_streq(hex_str(binary_data, 1), "00");
  1045. test_streq(hex_str(binary_data, 0), "");
  1046. }
  1047. /* Test strcmp_opt */
  1048. tt_int_op(strcmp_opt("", "foo"), <, 0);
  1049. tt_int_op(strcmp_opt("", ""), ==, 0);
  1050. tt_int_op(strcmp_opt("foo", ""), >, 0);
  1051. tt_int_op(strcmp_opt(NULL, ""), <, 0);
  1052. tt_int_op(strcmp_opt(NULL, NULL), ==, 0);
  1053. tt_int_op(strcmp_opt("", NULL), >, 0);
  1054. tt_int_op(strcmp_opt(NULL, "foo"), <, 0);
  1055. tt_int_op(strcmp_opt("foo", NULL), >, 0);
  1056. /* Test strcmp_len */
  1057. tt_int_op(strcmp_len("foo", "bar", 3), >, 0);
  1058. tt_int_op(strcmp_len("foo", "bar", 2), <, 0); /* First len, then lexical */
  1059. tt_int_op(strcmp_len("foo2", "foo1", 4), >, 0);
  1060. tt_int_op(strcmp_len("foo2", "foo1", 3), <, 0); /* Really stop at len */
  1061. tt_int_op(strcmp_len("foo2", "foo", 3), ==, 0); /* Really stop at len */
  1062. tt_int_op(strcmp_len("blah", "", 4), >, 0);
  1063. tt_int_op(strcmp_len("blah", "", 0), ==, 0);
  1064. done:
  1065. tor_free(cp_tmp);
  1066. }
  1067. static void
  1068. test_util_pow2(void)
  1069. {
  1070. /* Test tor_log2(). */
  1071. test_eq(tor_log2(64), 6);
  1072. test_eq(tor_log2(65), 6);
  1073. test_eq(tor_log2(63), 5);
  1074. test_eq(tor_log2(0), 0); /* incorrect mathematically, but as specified */
  1075. test_eq(tor_log2(1), 0);
  1076. test_eq(tor_log2(2), 1);
  1077. test_eq(tor_log2(3), 1);
  1078. test_eq(tor_log2(4), 2);
  1079. test_eq(tor_log2(5), 2);
  1080. test_eq(tor_log2(U64_LITERAL(40000000000000000)), 55);
  1081. test_eq(tor_log2(UINT64_MAX), 63);
  1082. /* Test round_to_power_of_2 */
  1083. test_eq(round_to_power_of_2(120), 128);
  1084. test_eq(round_to_power_of_2(128), 128);
  1085. test_eq(round_to_power_of_2(130), 128);
  1086. test_eq(round_to_power_of_2(U64_LITERAL(40000000000000000)),
  1087. U64_LITERAL(1)<<55);
  1088. test_eq(round_to_power_of_2(U64_LITERAL(0xffffffffffffffff)),
  1089. U64_LITERAL(1)<<63);
  1090. test_eq(round_to_power_of_2(0), 1);
  1091. test_eq(round_to_power_of_2(1), 1);
  1092. test_eq(round_to_power_of_2(2), 2);
  1093. test_eq(round_to_power_of_2(3), 2);
  1094. test_eq(round_to_power_of_2(4), 4);
  1095. test_eq(round_to_power_of_2(5), 4);
  1096. test_eq(round_to_power_of_2(6), 4);
  1097. test_eq(round_to_power_of_2(7), 8);
  1098. done:
  1099. ;
  1100. }
  1101. /** mutex for thread test to stop the threads hitting data at the same time. */
  1102. static tor_mutex_t *thread_test_mutex_ = NULL;
  1103. /** mutexes for the thread test to make sure that the threads have to
  1104. * interleave somewhat. */
  1105. static tor_mutex_t *thread_test_start1_ = NULL,
  1106. *thread_test_start2_ = NULL;
  1107. /** Shared strmap for the thread test. */
  1108. static strmap_t *thread_test_strmap_ = NULL;
  1109. /** The name of thread1 for the thread test */
  1110. static char *thread1_name_ = NULL;
  1111. /** The name of thread2 for the thread test */
  1112. static char *thread2_name_ = NULL;
  1113. static void thread_test_func_(void* _s) ATTR_NORETURN;
  1114. /** How many iterations have the threads in the unit test run? */
  1115. static int t1_count = 0, t2_count = 0;
  1116. /** Helper function for threading unit tests: This function runs in a
  1117. * subthread. It grabs its own mutex (start1 or start2) to make sure that it
  1118. * should start, then it repeatedly alters _test_thread_strmap protected by
  1119. * thread_test_mutex_. */
  1120. static void
  1121. thread_test_func_(void* _s)
  1122. {
  1123. char *s = _s;
  1124. int i, *count;
  1125. tor_mutex_t *m;
  1126. char buf[64];
  1127. char **cp;
  1128. if (!strcmp(s, "thread 1")) {
  1129. m = thread_test_start1_;
  1130. cp = &thread1_name_;
  1131. count = &t1_count;
  1132. } else {
  1133. m = thread_test_start2_;
  1134. cp = &thread2_name_;
  1135. count = &t2_count;
  1136. }
  1137. tor_snprintf(buf, sizeof(buf), "%lu", tor_get_thread_id());
  1138. *cp = tor_strdup(buf);
  1139. tor_mutex_acquire(m);
  1140. for (i=0; i<10000; ++i) {
  1141. tor_mutex_acquire(thread_test_mutex_);
  1142. strmap_set(thread_test_strmap_, "last to run", *cp);
  1143. ++*count;
  1144. tor_mutex_release(thread_test_mutex_);
  1145. }
  1146. tor_mutex_acquire(thread_test_mutex_);
  1147. strmap_set(thread_test_strmap_, s, *cp);
  1148. tor_mutex_release(thread_test_mutex_);
  1149. tor_mutex_release(m);
  1150. spawn_exit();
  1151. }
  1152. /** Run unit tests for threading logic. */
  1153. static void
  1154. test_util_threads(void)
  1155. {
  1156. char *s1 = NULL, *s2 = NULL;
  1157. int done = 0, timedout = 0;
  1158. time_t started;
  1159. #ifndef _WIN32
  1160. struct timeval tv;
  1161. tv.tv_sec=0;
  1162. tv.tv_usec=100*1000;
  1163. #endif
  1164. #ifndef TOR_IS_MULTITHREADED
  1165. /* Skip this test if we aren't threading. We should be threading most
  1166. * everywhere by now. */
  1167. if (1)
  1168. return;
  1169. #endif
  1170. thread_test_mutex_ = tor_mutex_new();
  1171. thread_test_start1_ = tor_mutex_new();
  1172. thread_test_start2_ = tor_mutex_new();
  1173. thread_test_strmap_ = strmap_new();
  1174. s1 = tor_strdup("thread 1");
  1175. s2 = tor_strdup("thread 2");
  1176. tor_mutex_acquire(thread_test_start1_);
  1177. tor_mutex_acquire(thread_test_start2_);
  1178. spawn_func(thread_test_func_, s1);
  1179. spawn_func(thread_test_func_, s2);
  1180. tor_mutex_release(thread_test_start2_);
  1181. tor_mutex_release(thread_test_start1_);
  1182. started = time(NULL);
  1183. while (!done) {
  1184. tor_mutex_acquire(thread_test_mutex_);
  1185. strmap_assert_ok(thread_test_strmap_);
  1186. if (strmap_get(thread_test_strmap_, "thread 1") &&
  1187. strmap_get(thread_test_strmap_, "thread 2")) {
  1188. done = 1;
  1189. } else if (time(NULL) > started + 150) {
  1190. timedout = done = 1;
  1191. }
  1192. tor_mutex_release(thread_test_mutex_);
  1193. #ifndef _WIN32
  1194. /* Prevent the main thread from starving the worker threads. */
  1195. select(0, NULL, NULL, NULL, &tv);
  1196. #endif
  1197. }
  1198. tor_mutex_acquire(thread_test_start1_);
  1199. tor_mutex_release(thread_test_start1_);
  1200. tor_mutex_acquire(thread_test_start2_);
  1201. tor_mutex_release(thread_test_start2_);
  1202. tor_mutex_free(thread_test_mutex_);
  1203. if (timedout) {
  1204. printf("\nTimed out: %d %d", t1_count, t2_count);
  1205. test_assert(strmap_get(thread_test_strmap_, "thread 1"));
  1206. test_assert(strmap_get(thread_test_strmap_, "thread 2"));
  1207. test_assert(!timedout);
  1208. }
  1209. /* different thread IDs. */
  1210. test_assert(strcmp(strmap_get(thread_test_strmap_, "thread 1"),
  1211. strmap_get(thread_test_strmap_, "thread 2")));
  1212. test_assert(!strcmp(strmap_get(thread_test_strmap_, "thread 1"),
  1213. strmap_get(thread_test_strmap_, "last to run")) ||
  1214. !strcmp(strmap_get(thread_test_strmap_, "thread 2"),
  1215. strmap_get(thread_test_strmap_, "last to run")));
  1216. done:
  1217. tor_free(s1);
  1218. tor_free(s2);
  1219. tor_free(thread1_name_);
  1220. tor_free(thread2_name_);
  1221. if (thread_test_strmap_)
  1222. strmap_free(thread_test_strmap_, NULL);
  1223. if (thread_test_start1_)
  1224. tor_mutex_free(thread_test_start1_);
  1225. if (thread_test_start2_)
  1226. tor_mutex_free(thread_test_start2_);
  1227. }
  1228. /** Run unit tests for compression functions */
  1229. static void
  1230. test_util_gzip(void)
  1231. {
  1232. char *buf1=NULL, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
  1233. const char *ccp2;
  1234. size_t len1, len2;
  1235. tor_zlib_state_t *state = NULL;
  1236. buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
  1237. test_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
  1238. if (is_gzip_supported()) {
  1239. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1240. GZIP_METHOD));
  1241. test_assert(buf2);
  1242. test_assert(len1 < strlen(buf1));
  1243. test_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
  1244. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  1245. GZIP_METHOD, 1, LOG_INFO));
  1246. test_assert(buf3);
  1247. test_eq(strlen(buf1) + 1, len2);
  1248. test_streq(buf1, buf3);
  1249. tor_free(buf2);
  1250. tor_free(buf3);
  1251. }
  1252. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1253. ZLIB_METHOD));
  1254. test_assert(buf2);
  1255. test_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
  1256. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  1257. ZLIB_METHOD, 1, LOG_INFO));
  1258. test_assert(buf3);
  1259. test_eq(strlen(buf1) + 1, len2);
  1260. test_streq(buf1, buf3);
  1261. /* Check whether we can uncompress concatenated, compressed strings. */
  1262. tor_free(buf3);
  1263. buf2 = tor_realloc(buf2, len1*2);
  1264. memcpy(buf2+len1, buf2, len1);
  1265. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
  1266. ZLIB_METHOD, 1, LOG_INFO));
  1267. test_eq((strlen(buf1)+1)*2, len2);
  1268. test_memeq(buf3,
  1269. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
  1270. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
  1271. (strlen(buf1)+1)*2);
  1272. tor_free(buf1);
  1273. tor_free(buf2);
  1274. tor_free(buf3);
  1275. /* Check whether we can uncompress partial strings. */
  1276. buf1 =
  1277. tor_strdup("String with low redundancy that won't be compressed much.");
  1278. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1279. ZLIB_METHOD));
  1280. tt_assert(len1>16);
  1281. /* when we allow an incomplete string, we should succeed.*/
  1282. tt_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  1283. ZLIB_METHOD, 0, LOG_INFO));
  1284. tt_assert(len2 > 5);
  1285. buf3[len2]='\0';
  1286. tt_assert(!strcmpstart(buf1, buf3));
  1287. /* when we demand a complete string, this must fail. */
  1288. tor_free(buf3);
  1289. tt_assert(tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  1290. ZLIB_METHOD, 1, LOG_INFO));
  1291. tt_assert(!buf3);
  1292. /* Now, try streaming compression. */
  1293. tor_free(buf1);
  1294. tor_free(buf2);
  1295. tor_free(buf3);
  1296. state = tor_zlib_new(1, ZLIB_METHOD);
  1297. tt_assert(state);
  1298. cp1 = buf1 = tor_malloc(1024);
  1299. len1 = 1024;
  1300. ccp2 = "ABCDEFGHIJABCDEFGHIJ";
  1301. len2 = 21;
  1302. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
  1303. == TOR_ZLIB_OK);
  1304. test_eq(0, len2); /* Make sure we compressed it all. */
  1305. test_assert(cp1 > buf1);
  1306. len2 = 0;
  1307. cp2 = cp1;
  1308. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
  1309. == TOR_ZLIB_DONE);
  1310. test_eq(0, len2);
  1311. test_assert(cp1 > cp2); /* Make sure we really added something. */
  1312. tt_assert(!tor_gzip_uncompress(&buf3, &len2, buf1, 1024-len1,
  1313. ZLIB_METHOD, 1, LOG_WARN));
  1314. test_streq(buf3, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
  1315. test_eq(21, len2);
  1316. done:
  1317. if (state)
  1318. tor_zlib_free(state);
  1319. tor_free(buf2);
  1320. tor_free(buf3);
  1321. tor_free(buf1);
  1322. }
  1323. /** Run unit tests for mmap() wrapper functionality. */
  1324. static void
  1325. test_util_mmap(void)
  1326. {
  1327. char *fname1 = tor_strdup(get_fname("mapped_1"));
  1328. char *fname2 = tor_strdup(get_fname("mapped_2"));
  1329. char *fname3 = tor_strdup(get_fname("mapped_3"));
  1330. const size_t buflen = 17000;
  1331. char *buf = tor_malloc(17000);
  1332. tor_mmap_t *mapping = NULL;
  1333. crypto_rand(buf, buflen);
  1334. mapping = tor_mmap_file(fname1);
  1335. test_assert(! mapping);
  1336. write_str_to_file(fname1, "Short file.", 1);
  1337. mapping = tor_mmap_file(fname1);
  1338. test_assert(mapping);
  1339. test_eq(mapping->size, strlen("Short file."));
  1340. test_streq(mapping->data, "Short file.");
  1341. #ifdef _WIN32
  1342. tor_munmap_file(mapping);
  1343. mapping = NULL;
  1344. test_assert(unlink(fname1) == 0);
  1345. #else
  1346. /* make sure we can unlink. */
  1347. test_assert(unlink(fname1) == 0);
  1348. test_streq(mapping->data, "Short file.");
  1349. tor_munmap_file(mapping);
  1350. mapping = NULL;
  1351. #endif
  1352. /* Now a zero-length file. */
  1353. write_str_to_file(fname1, "", 1);
  1354. mapping = tor_mmap_file(fname1);
  1355. test_eq_ptr(mapping, NULL);
  1356. test_eq(ERANGE, errno);
  1357. unlink(fname1);
  1358. /* Make sure that we fail to map a no-longer-existent file. */
  1359. mapping = tor_mmap_file(fname1);
  1360. test_assert(! mapping);
  1361. /* Now try a big file that stretches across a few pages and isn't aligned */
  1362. write_bytes_to_file(fname2, buf, buflen, 1);
  1363. mapping = tor_mmap_file(fname2);
  1364. test_assert(mapping);
  1365. test_eq(mapping->size, buflen);
  1366. test_memeq(mapping->data, buf, buflen);
  1367. tor_munmap_file(mapping);
  1368. mapping = NULL;
  1369. /* Now try a big aligned file. */
  1370. write_bytes_to_file(fname3, buf, 16384, 1);
  1371. mapping = tor_mmap_file(fname3);
  1372. test_assert(mapping);
  1373. test_eq(mapping->size, 16384);
  1374. test_memeq(mapping->data, buf, 16384);
  1375. tor_munmap_file(mapping);
  1376. mapping = NULL;
  1377. done:
  1378. unlink(fname1);
  1379. unlink(fname2);
  1380. unlink(fname3);
  1381. tor_free(fname1);
  1382. tor_free(fname2);
  1383. tor_free(fname3);
  1384. tor_free(buf);
  1385. if (mapping)
  1386. tor_munmap_file(mapping);
  1387. }
  1388. /** Run unit tests for escaping/unescaping data for use by controllers. */
  1389. static void
  1390. test_util_control_formats(void)
  1391. {
  1392. char *out = NULL;
  1393. const char *inp =
  1394. "..This is a test\r\n.of the emergency \n..system.\r\n\rZ.\r\n";
  1395. size_t sz;
  1396. sz = read_escaped_data(inp, strlen(inp), &out);
  1397. test_streq(out,
  1398. ".This is a test\nof the emergency \n.system.\n\rZ.\n");
  1399. test_eq(sz, strlen(out));
  1400. done:
  1401. tor_free(out);
  1402. }
  1403. #define test_feq(value1,value2) do { \
  1404. double v1 = (value1), v2=(value2); \
  1405. double tf_diff = v1-v2; \
  1406. double tf_tolerance = ((v1+v2)/2.0)/1e8; \
  1407. if (tf_diff<0) tf_diff=-tf_diff; \
  1408. if (tf_tolerance<0) tf_tolerance=-tf_tolerance; \
  1409. if (tf_diff<tf_tolerance) { \
  1410. TT_BLATHER(("%s ~~ %s: %f ~~ %f",#value1,#value2,v1,v2)); \
  1411. } else { \
  1412. TT_FAIL(("%s ~~ %s: %f != %f",#value1,#value2,v1,v2)); \
  1413. } \
  1414. } while (0)
  1415. static void
  1416. test_util_sscanf(void)
  1417. {
  1418. unsigned u1, u2, u3;
  1419. char s1[20], s2[10], s3[10], ch;
  1420. int r;
  1421. long lng1,lng2;
  1422. int int1, int2;
  1423. double d1,d2,d3,d4;
  1424. /* Simple tests (malformed patterns, literal matching, ...) */
  1425. test_eq(-1, tor_sscanf("123", "%i", &r)); /* %i is not supported */
  1426. test_eq(-1, tor_sscanf("wrong", "%5c", s1)); /* %c cannot have a number. */
  1427. test_eq(-1, tor_sscanf("hello", "%s", s1)); /* %s needs a number. */
  1428. test_eq(-1, tor_sscanf("prettylongstring", "%999999s", s1));
  1429. #if 0
  1430. /* GCC thinks these two are illegal. */
  1431. test_eq(-1, tor_sscanf("prettylongstring", "%0s", s1));
  1432. test_eq(0, tor_sscanf("prettylongstring", "%10s", NULL));
  1433. #endif
  1434. /* No '%'-strings: always "success" */
  1435. test_eq(0, tor_sscanf("hello world", "hello world"));
  1436. test_eq(0, tor_sscanf("hello world", "good bye"));
  1437. /* Excess data */
  1438. test_eq(0, tor_sscanf("hello 3", "%u", &u1)); /* have to match the start */
  1439. test_eq(0, tor_sscanf(" 3 hello", "%u", &u1));
  1440. test_eq(0, tor_sscanf(" 3 hello", "%2u", &u1)); /* not even in this case */
  1441. test_eq(1, tor_sscanf("3 hello", "%u", &u1)); /* but trailing is alright */
  1442. /* Numbers (ie. %u) */
  1443. test_eq(0, tor_sscanf("hello world 3", "hello worlb %u", &u1)); /* d vs b */
  1444. test_eq(1, tor_sscanf("12345", "%u", &u1));
  1445. test_eq(12345u, u1);
  1446. test_eq(1, tor_sscanf("12346 ", "%u", &u1));
  1447. test_eq(12346u, u1);
  1448. test_eq(0, tor_sscanf(" 12347", "%u", &u1));
  1449. test_eq(1, tor_sscanf(" 12348", " %u", &u1));
  1450. test_eq(12348u, u1);
  1451. test_eq(1, tor_sscanf("0", "%u", &u1));
  1452. test_eq(0u, u1);
  1453. test_eq(1, tor_sscanf("0000", "%u", &u2));
  1454. test_eq(0u, u2);
  1455. test_eq(0, tor_sscanf("", "%u", &u1)); /* absent number */
  1456. test_eq(0, tor_sscanf("A", "%u", &u1)); /* bogus number */
  1457. test_eq(0, tor_sscanf("-1", "%u", &u1)); /* negative number */
  1458. test_eq(1, tor_sscanf("4294967295", "%u", &u1)); /* UINT32_MAX should work */
  1459. test_eq(4294967295u, u1);
  1460. test_eq(0, tor_sscanf("4294967296", "%u", &u1)); /* But not at 32 bits */
  1461. test_eq(1, tor_sscanf("4294967296", "%9u", &u1)); /* but parsing only 9... */
  1462. test_eq(429496729u, u1);
  1463. /* Numbers with size (eg. %2u) */
  1464. test_eq(0, tor_sscanf("-1", "%2u", &u1));
  1465. test_eq(2, tor_sscanf("123456", "%2u%u", &u1, &u2));
  1466. test_eq(12u, u1);
  1467. test_eq(3456u, u2);
  1468. test_eq(1, tor_sscanf("123456", "%8u", &u1));
  1469. test_eq(123456u, u1);
  1470. test_eq(1, tor_sscanf("123457 ", "%8u", &u1));
  1471. test_eq(123457u, u1);
  1472. test_eq(0, tor_sscanf(" 123456", "%8u", &u1));
  1473. test_eq(3, tor_sscanf("!12:3:456", "!%2u:%2u:%3u", &u1, &u2, &u3));
  1474. test_eq(12u, u1);
  1475. test_eq(3u, u2);
  1476. test_eq(456u, u3);
  1477. test_eq(3, tor_sscanf("67:8:099", "%2u:%2u:%3u", &u1, &u2, &u3)); /* 0s */
  1478. test_eq(67u, u1);
  1479. test_eq(8u, u2);
  1480. test_eq(99u, u3);
  1481. /* %u does not match space.*/
  1482. test_eq(2, tor_sscanf("12:3: 45", "%2u:%2u:%3u", &u1, &u2, &u3));
  1483. test_eq(12u, u1);
  1484. test_eq(3u, u2);
  1485. /* %u does not match negative numbers. */
  1486. test_eq(2, tor_sscanf("67:8:-9", "%2u:%2u:%3u", &u1, &u2, &u3));
  1487. test_eq(67u, u1);
  1488. test_eq(8u, u2);
  1489. /* Arbitrary amounts of 0-padding are okay */
  1490. test_eq(3, tor_sscanf("12:03:000000000000000099", "%2u:%2u:%u",
  1491. &u1, &u2, &u3));
  1492. test_eq(12u, u1);
  1493. test_eq(3u, u2);
  1494. test_eq(99u, u3);
  1495. /* Hex (ie. %x) */
  1496. test_eq(3, tor_sscanf("1234 02aBcdEf ff", "%x %x %x", &u1, &u2, &u3));
  1497. test_eq(0x1234, u1);
  1498. test_eq(0x2ABCDEF, u2);
  1499. test_eq(0xFF, u3);
  1500. /* Width works on %x */
  1501. test_eq(3, tor_sscanf("f00dcafe444", "%4x%4x%u", &u1, &u2, &u3));
  1502. test_eq(0xf00d, u1);
  1503. test_eq(0xcafe, u2);
  1504. test_eq(444, u3);
  1505. /* Literal '%' (ie. '%%') */
  1506. test_eq(1, tor_sscanf("99% fresh", "%3u%% fresh", &u1));
  1507. test_eq(99, u1);
  1508. test_eq(0, tor_sscanf("99 fresh", "%% %3u %s", &u1, s1));
  1509. test_eq(1, tor_sscanf("99 fresh", "%3u%% %s", &u1, s1));
  1510. test_eq(2, tor_sscanf("99 fresh", "%3u %5s %%", &u1, s1));
  1511. test_eq(99, u1);
  1512. test_streq(s1, "fresh");
  1513. test_eq(1, tor_sscanf("% boo", "%% %3s", s1));
  1514. test_streq("boo", s1);
  1515. /* Strings (ie. %s) */
  1516. test_eq(2, tor_sscanf("hello", "%3s%7s", s1, s2));
  1517. test_streq(s1, "hel");
  1518. test_streq(s2, "lo");
  1519. test_eq(2, tor_sscanf("WD40", "%2s%u", s3, &u1)); /* %s%u */
  1520. test_streq(s3, "WD");
  1521. test_eq(40, u1);
  1522. test_eq(2, tor_sscanf("WD40", "%3s%u", s3, &u1)); /* %s%u */
  1523. test_streq(s3, "WD4");
  1524. test_eq(0, u1);
  1525. test_eq(2, tor_sscanf("76trombones", "%6u%9s", &u1, s1)); /* %u%s */
  1526. test_eq(76, u1);
  1527. test_streq(s1, "trombones");
  1528. test_eq(1, tor_sscanf("prettylongstring", "%999s", s1));
  1529. test_streq(s1, "prettylongstring");
  1530. /* %s doesn't eat spaces */
  1531. test_eq(2, tor_sscanf("hello world", "%9s %9s", s1, s2));
  1532. test_streq(s1, "hello");
  1533. test_streq(s2, "world");
  1534. test_eq(2, tor_sscanf("bye world?", "%9s %9s", s1, s2));
  1535. test_streq(s1, "bye");
  1536. test_streq(s2, "");
  1537. test_eq(3, tor_sscanf("hi", "%9s%9s%3s", s1, s2, s3)); /* %s can be empty. */
  1538. test_streq(s1, "hi");
  1539. test_streq(s2, "");
  1540. test_streq(s3, "");
  1541. test_eq(3, tor_sscanf("1.2.3", "%u.%u.%u%c", &u1, &u2, &u3, &ch));
  1542. test_eq(4, tor_sscanf("1.2.3 foobar", "%u.%u.%u%c", &u1, &u2, &u3, &ch));
  1543. test_eq(' ', ch);
  1544. r = tor_sscanf("12345 -67890 -1", "%d %ld %d", &int1, &lng1, &int2);
  1545. test_eq(r,3);
  1546. test_eq(int1, 12345);
  1547. test_eq(lng1, -67890);
  1548. test_eq(int2, -1);
  1549. #if SIZEOF_INT == 4
  1550. r = tor_sscanf("-2147483648. 2147483647.", "%d. %d.", &int1, &int2);
  1551. test_eq(r,2);
  1552. test_eq(int1, -2147483647-1);
  1553. test_eq(int2, 2147483647);
  1554. r = tor_sscanf("-2147483679.", "%d.", &int1);
  1555. test_eq(r,0);
  1556. r = tor_sscanf("2147483678.", "%d.", &int1);
  1557. test_eq(r,0);
  1558. #elif SIZEOF_INT == 8
  1559. r = tor_sscanf("-9223372036854775808. 9223372036854775807.",
  1560. "%d. %d.", &int1, &int2);
  1561. test_eq(r,2);
  1562. test_eq(int1, -9223372036854775807-1);
  1563. test_eq(int2, 9223372036854775807);
  1564. r = tor_sscanf("-9223372036854775809.", "%d.", &int1);
  1565. test_eq(r,0);
  1566. r = tor_sscanf("9223372036854775808.", "%d.", &int1);
  1567. test_eq(r,0);
  1568. #endif
  1569. #if SIZEOF_LONG == 4
  1570. r = tor_sscanf("-2147483648. 2147483647.", "%ld. %ld.", &lng1, &lng2);
  1571. test_eq(r,2);
  1572. test_eq(lng1, -2147483647 - 1);
  1573. test_eq(lng2, 2147483647);
  1574. #elif SIZEOF_LONG == 8
  1575. r = tor_sscanf("-9223372036854775808. 9223372036854775807.",
  1576. "%ld. %ld.", &lng1, &lng2);
  1577. test_eq(r,2);
  1578. test_eq(lng1, -9223372036854775807L - 1);
  1579. test_eq(lng2, 9223372036854775807L);
  1580. r = tor_sscanf("-9223372036854775808. 9223372036854775808.",
  1581. "%ld. %ld.", &lng1, &lng2);
  1582. test_eq(r,1);
  1583. r = tor_sscanf("-9223372036854775809. 9223372036854775808.",
  1584. "%ld. %ld.", &lng1, &lng2);
  1585. test_eq(r,0);
  1586. #endif
  1587. r = tor_sscanf("123.456 .000007 -900123123.2000787 00003.2",
  1588. "%lf %lf %lf %lf", &d1,&d2,&d3,&d4);
  1589. test_eq(r,4);
  1590. test_feq(d1, 123.456);
  1591. test_feq(d2, .000007);
  1592. test_feq(d3, -900123123.2000787);
  1593. test_feq(d4, 3.2);
  1594. done:
  1595. ;
  1596. }
  1597. static void
  1598. test_util_path_is_relative(void)
  1599. {
  1600. /* OS-independent tests */
  1601. test_eq(1, path_is_relative(""));
  1602. test_eq(1, path_is_relative("dir"));
  1603. test_eq(1, path_is_relative("dir/"));
  1604. test_eq(1, path_is_relative("./dir"));
  1605. test_eq(1, path_is_relative("../dir"));
  1606. test_eq(0, path_is_relative("/"));
  1607. test_eq(0, path_is_relative("/dir"));
  1608. test_eq(0, path_is_relative("/dir/"));
  1609. /* Windows */
  1610. #ifdef _WIN32
  1611. /* I don't have Windows so I can't test this, hence the "#ifdef
  1612. 0". These are tests that look useful, so please try to get them
  1613. running and uncomment if it all works as it should */
  1614. test_eq(1, path_is_relative("dir"));
  1615. test_eq(1, path_is_relative("dir\\"));
  1616. test_eq(1, path_is_relative("dir\\a:"));
  1617. test_eq(1, path_is_relative("dir\\a:\\"));
  1618. test_eq(1, path_is_relative("http:\\dir"));
  1619. test_eq(0, path_is_relative("\\dir"));
  1620. test_eq(0, path_is_relative("a:\\dir"));
  1621. test_eq(0, path_is_relative("z:\\dir"));
  1622. #endif
  1623. done:
  1624. ;
  1625. }
  1626. /** Run unittests for memory pool allocator */
  1627. static void
  1628. test_util_mempool(void)
  1629. {
  1630. mp_pool_t *pool = NULL;
  1631. smartlist_t *allocated = NULL;
  1632. int i;
  1633. pool = mp_pool_new(1, 100);
  1634. test_assert(pool);
  1635. test_assert(pool->new_chunk_capacity >= 100);
  1636. test_assert(pool->item_alloc_size >= sizeof(void*)+1);
  1637. mp_pool_destroy(pool);
  1638. pool = NULL;
  1639. pool = mp_pool_new(241, 2500);
  1640. test_assert(pool);
  1641. test_assert(pool->new_chunk_capacity >= 10);
  1642. test_assert(pool->item_alloc_size >= sizeof(void*)+241);
  1643. test_eq(pool->item_alloc_size & 0x03, 0);
  1644. test_assert(pool->new_chunk_capacity < 60);
  1645. allocated = smartlist_new();
  1646. for (i = 0; i < 20000; ++i) {
  1647. if (smartlist_len(allocated) < 20 || crypto_rand_int(2)) {
  1648. void *m = mp_pool_get(pool);
  1649. memset(m, 0x09, 241);
  1650. smartlist_add(allocated, m);
  1651. //printf("%d: %p\n", i, m);
  1652. //mp_pool_assert_ok(pool);
  1653. } else {
  1654. int idx = crypto_rand_int(smartlist_len(allocated));
  1655. void *m = smartlist_get(allocated, idx);
  1656. //printf("%d: free %p\n", i, m);
  1657. smartlist_del(allocated, idx);
  1658. mp_pool_release(m);
  1659. //mp_pool_assert_ok(pool);
  1660. }
  1661. if (crypto_rand_int(777)==0)
  1662. mp_pool_clean(pool, 1, 1);
  1663. if (i % 777)
  1664. mp_pool_assert_ok(pool);
  1665. }
  1666. done:
  1667. if (allocated) {
  1668. SMARTLIST_FOREACH(allocated, void *, m, mp_pool_release(m));
  1669. mp_pool_assert_ok(pool);
  1670. mp_pool_clean(pool, 0, 0);
  1671. mp_pool_assert_ok(pool);
  1672. smartlist_free(allocated);
  1673. }
  1674. if (pool)
  1675. mp_pool_destroy(pool);
  1676. }
  1677. /** Run unittests for memory area allocator */
  1678. static void
  1679. test_util_memarea(void)
  1680. {
  1681. memarea_t *area = memarea_new();
  1682. char *p1, *p2, *p3, *p1_orig;
  1683. void *malloced_ptr = NULL;
  1684. int i;
  1685. test_assert(area);
  1686. p1_orig = p1 = memarea_alloc(area,64);
  1687. p2 = memarea_alloc_zero(area,52);
  1688. p3 = memarea_alloc(area,11);
  1689. test_assert(memarea_owns_ptr(area, p1));
  1690. test_assert(memarea_owns_ptr(area, p2));
  1691. test_assert(memarea_owns_ptr(area, p3));
  1692. /* Make sure we left enough space. */
  1693. test_assert(p1+64 <= p2);
  1694. test_assert(p2+52 <= p3);
  1695. /* Make sure we aligned. */
  1696. test_eq(((uintptr_t)p1) % sizeof(void*), 0);
  1697. test_eq(((uintptr_t)p2) % sizeof(void*), 0);
  1698. test_eq(((uintptr_t)p3) % sizeof(void*), 0);
  1699. test_assert(!memarea_owns_ptr(area, p3+8192));
  1700. test_assert(!memarea_owns_ptr(area, p3+30));
  1701. test_assert(tor_mem_is_zero(p2, 52));
  1702. /* Make sure we don't overalign. */
  1703. p1 = memarea_alloc(area, 1);
  1704. p2 = memarea_alloc(area, 1);
  1705. test_eq_ptr(p1+sizeof(void*), p2);
  1706. {
  1707. malloced_ptr = tor_malloc(64);
  1708. test_assert(!memarea_owns_ptr(area, malloced_ptr));
  1709. tor_free(malloced_ptr);
  1710. }
  1711. /* memarea_memdup */
  1712. {
  1713. malloced_ptr = tor_malloc(64);
  1714. crypto_rand((char*)malloced_ptr, 64);
  1715. p1 = memarea_memdup(area, malloced_ptr, 64);
  1716. test_assert(p1 != malloced_ptr);
  1717. test_memeq(p1, malloced_ptr, 64);
  1718. tor_free(malloced_ptr);
  1719. }
  1720. /* memarea_strdup. */
  1721. p1 = memarea_strdup(area,"");
  1722. p2 = memarea_strdup(area, "abcd");
  1723. test_assert(p1);
  1724. test_assert(p2);
  1725. test_streq(p1, "");
  1726. test_streq(p2, "abcd");
  1727. /* memarea_strndup. */
  1728. {
  1729. const char *s = "Ad ogni porta batte la morte e grida: il nome!";
  1730. /* (From Turandot, act 3.) */
  1731. size_t len = strlen(s);
  1732. p1 = memarea_strndup(area, s, 1000);
  1733. p2 = memarea_strndup(area, s, 10);
  1734. test_streq(p1, s);
  1735. test_assert(p2 >= p1 + len + 1);
  1736. test_memeq(s, p2, 10);
  1737. test_eq(p2[10], '\0');
  1738. p3 = memarea_strndup(area, s, len);
  1739. test_streq(p3, s);
  1740. p3 = memarea_strndup(area, s, len-1);
  1741. test_memeq(s, p3, len-1);
  1742. test_eq(p3[len-1], '\0');
  1743. }
  1744. memarea_clear(area);
  1745. p1 = memarea_alloc(area, 1);
  1746. test_eq_ptr(p1, p1_orig);
  1747. memarea_clear(area);
  1748. /* Check for running over an area's size. */
  1749. for (i = 0; i < 512; ++i) {
  1750. p1 = memarea_alloc(area, crypto_rand_int(5)+1);
  1751. test_assert(memarea_owns_ptr(area, p1));
  1752. }
  1753. memarea_assert_ok(area);
  1754. /* Make sure we can allocate a too-big object. */
  1755. p1 = memarea_alloc_zero(area, 9000);
  1756. p2 = memarea_alloc_zero(area, 16);
  1757. test_assert(memarea_owns_ptr(area, p1));
  1758. test_assert(memarea_owns_ptr(area, p2));
  1759. done:
  1760. memarea_drop_all(area);
  1761. tor_free(malloced_ptr);
  1762. }
  1763. /** Run unit tests for utility functions to get file names relative to
  1764. * the data directory. */
  1765. static void
  1766. test_util_datadir(void)
  1767. {
  1768. char buf[1024];
  1769. char *f = NULL;
  1770. char *temp_dir = NULL;
  1771. temp_dir = get_datadir_fname(NULL);
  1772. f = get_datadir_fname("state");
  1773. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
  1774. test_streq(f, buf);
  1775. tor_free(f);
  1776. f = get_datadir_fname2("cache", "thingy");
  1777. tor_snprintf(buf, sizeof(buf),
  1778. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
  1779. test_streq(f, buf);
  1780. tor_free(f);
  1781. f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
  1782. tor_snprintf(buf, sizeof(buf),
  1783. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
  1784. test_streq(f, buf);
  1785. tor_free(f);
  1786. f = get_datadir_fname_suffix("cache", ".foo");
  1787. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
  1788. temp_dir);
  1789. test_streq(f, buf);
  1790. done:
  1791. tor_free(f);
  1792. tor_free(temp_dir);
  1793. }
  1794. static void
  1795. test_util_strtok(void)
  1796. {
  1797. char buf[128];
  1798. char buf2[128];
  1799. int i;
  1800. char *cp1, *cp2;
  1801. for (i = 0; i < 3; i++) {
  1802. const char *pad1="", *pad2="";
  1803. switch (i) {
  1804. case 0:
  1805. break;
  1806. case 1:
  1807. pad1 = " ";
  1808. pad2 = "!";
  1809. break;
  1810. case 2:
  1811. pad1 = " ";
  1812. pad2 = ";!";
  1813. break;
  1814. }
  1815. tor_snprintf(buf, sizeof(buf), "%s", pad1);
  1816. tor_snprintf(buf2, sizeof(buf2), "%s", pad2);
  1817. test_assert(NULL == tor_strtok_r_impl(buf, " ", &cp1));
  1818. test_assert(NULL == tor_strtok_r_impl(buf2, ".!..;!", &cp2));
  1819. tor_snprintf(buf, sizeof(buf),
  1820. "%sGraved on the dark in gestures of descent%s", pad1, pad1);
  1821. tor_snprintf(buf2, sizeof(buf2),
  1822. "%sthey.seemed;;their!.own;most.perfect;monument%s",pad2,pad2);
  1823. /* -- "Year's End", Richard Wilbur */
  1824. test_streq("Graved", tor_strtok_r_impl(buf, " ", &cp1));
  1825. test_streq("they", tor_strtok_r_impl(buf2, ".!..;!", &cp2));
  1826. #define S1() tor_strtok_r_impl(NULL, " ", &cp1)
  1827. #define S2() tor_strtok_r_impl(NULL, ".!..;!", &cp2)
  1828. test_streq("on", S1());
  1829. test_streq("the", S1());
  1830. test_streq("dark", S1());
  1831. test_streq("seemed", S2());
  1832. test_streq("their", S2());
  1833. test_streq("own", S2());
  1834. test_streq("in", S1());
  1835. test_streq("gestures", S1());
  1836. test_streq("of", S1());
  1837. test_streq("most", S2());
  1838. test_streq("perfect", S2());
  1839. test_streq("descent", S1());
  1840. test_streq("monument", S2());
  1841. test_eq_ptr(NULL, S1());
  1842. test_eq_ptr(NULL, S2());
  1843. }
  1844. buf[0] = 0;
  1845. test_eq_ptr(NULL, tor_strtok_r_impl(buf, " ", &cp1));
  1846. test_eq_ptr(NULL, tor_strtok_r_impl(buf, "!", &cp1));
  1847. strlcpy(buf, "Howdy!", sizeof(buf));
  1848. test_streq("Howdy", tor_strtok_r_impl(buf, "!", &cp1));
  1849. test_eq_ptr(NULL, tor_strtok_r_impl(NULL, "!", &cp1));
  1850. strlcpy(buf, " ", sizeof(buf));
  1851. test_eq_ptr(NULL, tor_strtok_r_impl(buf, " ", &cp1));
  1852. strlcpy(buf, " ", sizeof(buf));
  1853. test_eq_ptr(NULL, tor_strtok_r_impl(buf, " ", &cp1));
  1854. strlcpy(buf, "something ", sizeof(buf));
  1855. test_streq("something", tor_strtok_r_impl(buf, " ", &cp1));
  1856. test_eq_ptr(NULL, tor_strtok_r_impl(NULL, ";", &cp1));
  1857. done:
  1858. ;
  1859. }
  1860. static void
  1861. test_util_find_str_at_start_of_line(void *ptr)
  1862. {
  1863. const char *long_string =
  1864. "howdy world. how are you? i hope it's fine.\n"
  1865. "hello kitty\n"
  1866. "third line";
  1867. char *line2 = strchr(long_string,'\n')+1;
  1868. char *line3 = strchr(line2,'\n')+1;
  1869. const char *short_string = "hello kitty\n"
  1870. "second line\n";
  1871. char *short_line2 = strchr(short_string,'\n')+1;
  1872. (void)ptr;
  1873. test_eq_ptr(long_string, find_str_at_start_of_line(long_string, ""));
  1874. test_eq_ptr(NULL, find_str_at_start_of_line(short_string, "nonsense"));
  1875. test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "nonsense"));
  1876. test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "\n"));
  1877. test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "how "));
  1878. test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "kitty"));
  1879. test_eq_ptr(long_string, find_str_at_start_of_line(long_string, "h"));
  1880. test_eq_ptr(long_string, find_str_at_start_of_line(long_string, "how"));
  1881. test_eq_ptr(line2, find_str_at_start_of_line(long_string, "he"));
  1882. test_eq_ptr(line2, find_str_at_start_of_line(long_string, "hell"));
  1883. test_eq_ptr(line2, find_str_at_start_of_line(long_string, "hello k"));
  1884. test_eq_ptr(line2, find_str_at_start_of_line(long_string, "hello kitty\n"));
  1885. test_eq_ptr(line2, find_str_at_start_of_line(long_string, "hello kitty\nt"));
  1886. test_eq_ptr(line3, find_str_at_start_of_line(long_string, "third"));
  1887. test_eq_ptr(line3, find_str_at_start_of_line(long_string, "third line"));
  1888. test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "third line\n"));
  1889. test_eq_ptr(short_line2, find_str_at_start_of_line(short_string,
  1890. "second line\n"));
  1891. done:
  1892. ;
  1893. }
  1894. static void
  1895. test_util_string_is_C_identifier(void *ptr)
  1896. {
  1897. (void)ptr;
  1898. test_eq(1, string_is_C_identifier("string_is_C_identifier"));
  1899. test_eq(1, string_is_C_identifier("_string_is_C_identifier"));
  1900. test_eq(1, string_is_C_identifier("_"));
  1901. test_eq(1, string_is_C_identifier("i"));
  1902. test_eq(1, string_is_C_identifier("_____"));
  1903. test_eq(1, string_is_C_identifier("__00__"));
  1904. test_eq(1, string_is_C_identifier("__init__"));
  1905. test_eq(1, string_is_C_identifier("_0"));
  1906. test_eq(1, string_is_C_identifier("_0string_is_C_identifier"));
  1907. test_eq(1, string_is_C_identifier("_0"));
  1908. test_eq(0, string_is_C_identifier("0_string_is_C_identifier"));
  1909. test_eq(0, string_is_C_identifier("0"));
  1910. test_eq(0, string_is_C_identifier(""));
  1911. test_eq(0, string_is_C_identifier(";"));
  1912. test_eq(0, string_is_C_identifier("i;"));
  1913. test_eq(0, string_is_C_identifier("_;"));
  1914. test_eq(0, string_is_C_identifier("í"));
  1915. test_eq(0, string_is_C_identifier("ñ"));
  1916. done:
  1917. ;
  1918. }
  1919. static void
  1920. test_util_asprintf(void *ptr)
  1921. {
  1922. #define LOREMIPSUM \
  1923. "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
  1924. char *cp=NULL, *cp2=NULL;
  1925. int r;
  1926. (void)ptr;
  1927. /* simple string */
  1928. r = tor_asprintf(&cp, "simple string 100%% safe");
  1929. test_assert(cp);
  1930. test_streq("simple string 100% safe", cp);
  1931. test_eq(strlen(cp), r);
  1932. /* empty string */
  1933. r = tor_asprintf(&cp, "%s", "");
  1934. test_assert(cp);
  1935. test_streq("", cp);
  1936. test_eq(strlen(cp), r);
  1937. /* numbers (%i) */
  1938. r = tor_asprintf(&cp, "I like numbers-%2i, %i, etc.", -1, 2);
  1939. test_assert(cp);
  1940. test_streq("I like numbers--1, 2, etc.", cp);
  1941. test_eq(strlen(cp), r);
  1942. /* numbers (%d) */
  1943. r = tor_asprintf(&cp2, "First=%d, Second=%d", 101, 202);
  1944. test_assert(cp2);
  1945. test_eq(strlen(cp2), r);
  1946. test_streq("First=101, Second=202", cp2);
  1947. test_assert(cp != cp2);
  1948. tor_free(cp);
  1949. tor_free(cp2);
  1950. /* Glass-box test: a string exactly 128 characters long. */
  1951. r = tor_asprintf(&cp, "Lorem1: %sLorem2: %s", LOREMIPSUM, LOREMIPSUM);
  1952. test_assert(cp);
  1953. test_eq(128, r);
  1954. test_assert(cp[128] == '\0');
  1955. test_streq("Lorem1: "LOREMIPSUM"Lorem2: "LOREMIPSUM, cp);
  1956. tor_free(cp);
  1957. /* String longer than 128 characters */
  1958. r = tor_asprintf(&cp, "1: %s 2: %s 3: %s",
  1959. LOREMIPSUM, LOREMIPSUM, LOREMIPSUM);
  1960. test_assert(cp);
  1961. test_eq(strlen(cp), r);
  1962. test_streq("1: "LOREMIPSUM" 2: "LOREMIPSUM" 3: "LOREMIPSUM, cp);
  1963. done:
  1964. tor_free(cp);
  1965. tor_free(cp2);
  1966. }
  1967. static void
  1968. test_util_listdir(void *ptr)
  1969. {
  1970. smartlist_t *dir_contents = NULL;
  1971. char *fname1=NULL, *fname2=NULL, *fname3=NULL, *dir1=NULL, *dirname=NULL;
  1972. int r;
  1973. (void)ptr;
  1974. fname1 = tor_strdup(get_fname("hopscotch"));
  1975. fname2 = tor_strdup(get_fname("mumblety-peg"));
  1976. fname3 = tor_strdup(get_fname(".hidden-file"));
  1977. dir1 = tor_strdup(get_fname("some-directory"));
  1978. dirname = tor_strdup(get_fname(NULL));
  1979. test_eq(0, write_str_to_file(fname1, "X\n", 0));
  1980. test_eq(0, write_str_to_file(fname2, "Y\n", 0));
  1981. test_eq(0, write_str_to_file(fname3, "Z\n", 0));
  1982. #ifdef _WIN32
  1983. r = mkdir(dir1);
  1984. #else
  1985. r = mkdir(dir1, 0700);
  1986. #endif
  1987. if (r) {
  1988. fprintf(stderr, "Can't create directory %s:", dir1);
  1989. perror("");
  1990. exit(1);
  1991. }
  1992. dir_contents = tor_listdir(dirname);
  1993. test_assert(dir_contents);
  1994. /* make sure that each filename is listed. */
  1995. test_assert(smartlist_contains_string_case(dir_contents, "hopscotch"));
  1996. test_assert(smartlist_contains_string_case(dir_contents, "mumblety-peg"));
  1997. test_assert(smartlist_contains_string_case(dir_contents, ".hidden-file"));
  1998. test_assert(smartlist_contains_string_case(dir_contents, "some-directory"));
  1999. test_assert(!smartlist_contains_string(dir_contents, "."));
  2000. test_assert(!smartlist_contains_string(dir_contents, ".."));
  2001. done:
  2002. tor_free(fname1);
  2003. tor_free(fname2);
  2004. tor_free(dirname);
  2005. if (dir_contents) {
  2006. SMARTLIST_FOREACH(dir_contents, char *, cp, tor_free(cp));
  2007. smartlist_free(dir_contents);
  2008. }
  2009. }
  2010. static void
  2011. test_util_parent_dir(void *ptr)
  2012. {
  2013. char *cp;
  2014. (void)ptr;
  2015. #define T(output,expect_ok,input) \
  2016. do { \
  2017. int ok; \
  2018. cp = tor_strdup(input); \
  2019. ok = get_parent_directory(cp); \
  2020. tt_int_op(expect_ok, ==, ok); \
  2021. if (ok==0) \
  2022. tt_str_op(output, ==, cp); \
  2023. tor_free(cp); \
  2024. } while (0);
  2025. T("/home/wombat", 0, "/home/wombat/knish");
  2026. T("/home/wombat", 0, "/home/wombat/knish/");
  2027. T("/home/wombat", 0, "/home/wombat/knish///");
  2028. T("./home/wombat", 0, "./home/wombat/knish/");
  2029. T("/", 0, "/home");
  2030. T("/", 0, "/home//");
  2031. T(".", 0, "./wombat");
  2032. T(".", 0, "./wombat/");
  2033. T(".", 0, "./wombat//");
  2034. T("wombat", 0, "wombat/foo");
  2035. T("wombat/..", 0, "wombat/../foo");
  2036. T("wombat/../", 0, "wombat/..//foo"); /* Is this correct? */
  2037. T("wombat/.", 0, "wombat/./foo");
  2038. T("wombat/./", 0, "wombat/.//foo"); /* Is this correct? */
  2039. T("wombat", 0, "wombat/..//");
  2040. T("wombat", 0, "wombat/foo/");
  2041. T("wombat", 0, "wombat/.foo");
  2042. T("wombat", 0, "wombat/.foo/");
  2043. T("wombat", -1, "");
  2044. T("w", -1, "");
  2045. T("wombat", 0, "wombat/knish");
  2046. T("/", 0, "/");
  2047. T("/", 0, "////");
  2048. done:
  2049. tor_free(cp);
  2050. }
  2051. #ifdef _WIN32
  2052. static void
  2053. test_util_load_win_lib(void *ptr)
  2054. {
  2055. HANDLE h = load_windows_system_library(_T("advapi32.dll"));
  2056. (void) ptr;
  2057. tt_assert(h);
  2058. done:
  2059. if (h)
  2060. FreeLibrary(h);
  2061. }
  2062. #endif
  2063. #ifndef _WIN32
  2064. static void
  2065. clear_hex_errno(char *hex_errno)
  2066. {
  2067. memset(hex_errno, '\0', HEX_ERRNO_SIZE + 1);
  2068. }
  2069. static void
  2070. test_util_exit_status(void *ptr)
  2071. {
  2072. /* Leave an extra byte for a \0 so we can do string comparison */
  2073. char hex_errno[HEX_ERRNO_SIZE + 1];
  2074. int n;
  2075. (void)ptr;
  2076. clear_hex_errno(hex_errno);
  2077. n = format_helper_exit_status(0, 0, hex_errno);
  2078. test_streq("0/0\n", hex_errno);
  2079. test_eq(n, strlen(hex_errno));
  2080. clear_hex_errno(hex_errno);
  2081. n = format_helper_exit_status(0, 0x7FFFFFFF, hex_errno);
  2082. test_streq("0/7FFFFFFF\n", hex_errno);
  2083. test_eq(n, strlen(hex_errno));
  2084. clear_hex_errno(hex_errno);
  2085. n = format_helper_exit_status(0xFF, -0x80000000, hex_errno);
  2086. test_streq("FF/-80000000\n", hex_errno);
  2087. test_eq(n, strlen(hex_errno));
  2088. test_eq(n, HEX_ERRNO_SIZE);
  2089. clear_hex_errno(hex_errno);
  2090. n = format_helper_exit_status(0x7F, 0, hex_errno);
  2091. test_streq("7F/0\n", hex_errno);
  2092. test_eq(n, strlen(hex_errno));
  2093. clear_hex_errno(hex_errno);
  2094. n = format_helper_exit_status(0x08, -0x242, hex_errno);
  2095. test_streq("8/-242\n", hex_errno);
  2096. test_eq(n, strlen(hex_errno));
  2097. done:
  2098. ;
  2099. }
  2100. #endif
  2101. #ifndef _WIN32
  2102. /** Check that fgets waits until a full line, and not return a partial line, on
  2103. * a EAGAIN with a non-blocking pipe */
  2104. static void
  2105. test_util_fgets_eagain(void *ptr)
  2106. {
  2107. int test_pipe[2] = {-1, -1};
  2108. int retval;
  2109. ssize_t retlen;
  2110. char *retptr;
  2111. FILE *test_stream = NULL;
  2112. char buf[10];
  2113. (void)ptr;
  2114. /* Set up a pipe to test on */
  2115. retval = pipe(test_pipe);
  2116. tt_int_op(retval, >=, 0);
  2117. /* Set up the read-end to be non-blocking */
  2118. retval = fcntl(test_pipe[0], F_SETFL, O_NONBLOCK);
  2119. tt_int_op(retval, >=, 0);
  2120. /* Open it as a stdio stream */
  2121. test_stream = fdopen(test_pipe[0], "r");
  2122. tt_ptr_op(test_stream, !=, NULL);
  2123. /* Send in a partial line */
  2124. retlen = write(test_pipe[1], "A", 1);
  2125. tt_int_op(retlen, ==, 1);
  2126. retptr = fgets(buf, sizeof(buf), test_stream);
  2127. tt_want(retptr == NULL);
  2128. tt_int_op(errno, ==, EAGAIN);
  2129. /* Send in the rest */
  2130. retlen = write(test_pipe[1], "B\n", 2);
  2131. tt_int_op(retlen, ==, 2);
  2132. retptr = fgets(buf, sizeof(buf), test_stream);
  2133. tt_ptr_op(retptr, ==, buf);
  2134. tt_str_op(buf, ==, "AB\n");
  2135. /* Send in a full line */
  2136. retlen = write(test_pipe[1], "CD\n", 3);
  2137. tt_int_op(retlen, ==, 3);
  2138. retptr = fgets(buf, sizeof(buf), test_stream);
  2139. tt_ptr_op(retptr, ==, buf);
  2140. tt_str_op(buf, ==, "CD\n");
  2141. /* Send in a partial line */
  2142. retlen = write(test_pipe[1], "E", 1);
  2143. tt_int_op(retlen, ==, 1);
  2144. retptr = fgets(buf, sizeof(buf), test_stream);
  2145. tt_ptr_op(retptr, ==, NULL);
  2146. tt_int_op(errno, ==, EAGAIN);
  2147. /* Send in the rest */
  2148. retlen = write(test_pipe[1], "F\n", 2);
  2149. tt_int_op(retlen, ==, 2);
  2150. retptr = fgets(buf, sizeof(buf), test_stream);
  2151. tt_ptr_op(retptr, ==, buf);
  2152. tt_str_op(buf, ==, "EF\n");
  2153. /* Send in a full line and close */
  2154. retlen = write(test_pipe[1], "GH", 2);
  2155. tt_int_op(retlen, ==, 2);
  2156. retval = close(test_pipe[1]);
  2157. test_pipe[1] = -1;
  2158. tt_int_op(retval, ==, 0);
  2159. retptr = fgets(buf, sizeof(buf), test_stream);
  2160. tt_ptr_op(retptr, ==, buf);
  2161. tt_str_op(buf, ==, "GH");
  2162. /* Check for EOF */
  2163. retptr = fgets(buf, sizeof(buf), test_stream);
  2164. tt_ptr_op(retptr, ==, NULL);
  2165. tt_int_op(feof(test_stream), >, 0);
  2166. done:
  2167. if (test_stream != NULL)
  2168. fclose(test_stream);
  2169. if (test_pipe[0] != -1)
  2170. close(test_pipe[0]);
  2171. if (test_pipe[1] != -1)
  2172. close(test_pipe[1]);
  2173. }
  2174. #endif
  2175. /** Helper function for testing tor_spawn_background */
  2176. static void
  2177. run_util_spawn_background(const char *argv[], const char *expected_out,
  2178. const char *expected_err, int expected_exit,
  2179. int expected_status)
  2180. {
  2181. int retval, exit_code;
  2182. ssize_t pos;
  2183. process_handle_t *process_handle=NULL;
  2184. char stdout_buf[100], stderr_buf[100];
  2185. int status;
  2186. /* Start the program */
  2187. #ifdef _WIN32
  2188. status = tor_spawn_background(NULL, argv, NULL, &process_handle);
  2189. #else
  2190. status = tor_spawn_background(argv[0], argv, NULL, &process_handle);
  2191. #endif
  2192. test_eq(expected_status, status);
  2193. if (status == PROCESS_STATUS_ERROR)
  2194. return;
  2195. test_assert(process_handle != NULL);
  2196. test_eq(expected_status, process_handle->status);
  2197. #ifdef _WIN32
  2198. test_assert(process_handle->stdout_pipe != INVALID_HANDLE_VALUE);
  2199. test_assert(process_handle->stderr_pipe != INVALID_HANDLE_VALUE);
  2200. #else
  2201. test_assert(process_handle->stdout_pipe > 0);
  2202. test_assert(process_handle->stderr_pipe > 0);
  2203. #endif
  2204. /* Check stdout */
  2205. pos = tor_read_all_from_process_stdout(process_handle, stdout_buf,
  2206. sizeof(stdout_buf) - 1);
  2207. tt_assert(pos >= 0);
  2208. stdout_buf[pos] = '\0';
  2209. test_eq(strlen(expected_out), pos);
  2210. test_streq(expected_out, stdout_buf);
  2211. /* Check it terminated correctly */
  2212. retval = tor_get_exit_code(process_handle, 1, &exit_code);
  2213. test_eq(PROCESS_EXIT_EXITED, retval);
  2214. test_eq(expected_exit, exit_code);
  2215. // TODO: Make test-child exit with something other than 0
  2216. /* Check stderr */
  2217. pos = tor_read_all_from_process_stderr(process_handle, stderr_buf,
  2218. sizeof(stderr_buf) - 1);
  2219. test_assert(pos >= 0);
  2220. stderr_buf[pos] = '\0';
  2221. test_streq(expected_err, stderr_buf);
  2222. test_eq(strlen(expected_err), pos);
  2223. done:
  2224. if (process_handle)
  2225. tor_process_handle_destroy(process_handle, 1);
  2226. }
  2227. /** Check that we can launch a process and read the output */
  2228. static void
  2229. test_util_spawn_background_ok(void *ptr)
  2230. {
  2231. #ifdef _WIN32
  2232. const char *argv[] = {"test-child.exe", "--test", NULL};
  2233. const char *expected_out = "OUT\r\n--test\r\nSLEEPING\r\nDONE\r\n";
  2234. const char *expected_err = "ERR\r\n";
  2235. #else
  2236. const char *argv[] = {BUILDDIR "/src/test/test-child", "--test", NULL};
  2237. const char *expected_out = "OUT\n--test\nSLEEPING\nDONE\n";
  2238. const char *expected_err = "ERR\n";
  2239. #endif
  2240. (void)ptr;
  2241. run_util_spawn_background(argv, expected_out, expected_err, 0,
  2242. PROCESS_STATUS_RUNNING);
  2243. }
  2244. /** Check that failing to find the executable works as expected */
  2245. static void
  2246. test_util_spawn_background_fail(void *ptr)
  2247. {
  2248. #ifndef BUILDDIR
  2249. #define BUILDDIR "."
  2250. #endif
  2251. const char *argv[] = {BUILDDIR "/src/test/no-such-file", "--test", NULL};
  2252. const char *expected_err = "";
  2253. char expected_out[1024];
  2254. char code[32];
  2255. #ifdef _WIN32
  2256. const int expected_status = PROCESS_STATUS_ERROR;
  2257. #else
  2258. /* TODO: Once we can signal failure to exec, set this to be
  2259. * PROCESS_STATUS_ERROR */
  2260. const int expected_status = PROCESS_STATUS_RUNNING;
  2261. #endif
  2262. (void)ptr;
  2263. tor_snprintf(code, sizeof(code), "%x/%x",
  2264. 9 /* CHILD_STATE_FAILEXEC */ , ENOENT);
  2265. tor_snprintf(expected_out, sizeof(expected_out),
  2266. "ERR: Failed to spawn background process - code %s\n", code);
  2267. run_util_spawn_background(argv, expected_out, expected_err, 255,
  2268. expected_status);
  2269. }
  2270. /** Test that reading from a handle returns a partial read rather than
  2271. * blocking */
  2272. static void
  2273. test_util_spawn_background_partial_read(void *ptr)
  2274. {
  2275. const int expected_exit = 0;
  2276. const int expected_status = PROCESS_STATUS_RUNNING;
  2277. int retval, exit_code;
  2278. ssize_t pos = -1;
  2279. process_handle_t *process_handle=NULL;
  2280. int status;
  2281. char stdout_buf[100], stderr_buf[100];
  2282. #ifdef _WIN32
  2283. const char *argv[] = {"test-child.exe", "--test", NULL};
  2284. const char *expected_out[] = { "OUT\r\n--test\r\nSLEEPING\r\n",
  2285. "DONE\r\n",
  2286. NULL };
  2287. const char *expected_err = "ERR\r\n";
  2288. #else
  2289. const char *argv[] = {BUILDDIR "/src/test/test-child", "--test", NULL};
  2290. const char *expected_out[] = { "OUT\n--test\nSLEEPING\n",
  2291. "DONE\n",
  2292. NULL };
  2293. const char *expected_err = "ERR\n";
  2294. int eof = 0;
  2295. #endif
  2296. int expected_out_ctr;
  2297. (void)ptr;
  2298. /* Start the program */
  2299. #ifdef _WIN32
  2300. status = tor_spawn_background(NULL, argv, NULL, &process_handle);
  2301. #else
  2302. status = tor_spawn_background(argv[0], argv, NULL, &process_handle);
  2303. #endif
  2304. test_eq(expected_status, status);
  2305. test_assert(process_handle);
  2306. test_eq(expected_status, process_handle->status);
  2307. /* Check stdout */
  2308. for (expected_out_ctr = 0; expected_out[expected_out_ctr] != NULL;) {
  2309. #ifdef _WIN32
  2310. pos = tor_read_all_handle(process_handle->stdout_pipe, stdout_buf,
  2311. sizeof(stdout_buf) - 1, NULL);
  2312. #else
  2313. /* Check that we didn't read the end of file last time */
  2314. test_assert(!eof);
  2315. pos = tor_read_all_handle(process_handle->stdout_handle, stdout_buf,
  2316. sizeof(stdout_buf) - 1, NULL, &eof);
  2317. #endif
  2318. log_info(LD_GENERAL, "tor_read_all_handle() returned %d", (int)pos);
  2319. /* We would have blocked, keep on trying */
  2320. if (0 == pos)
  2321. continue;
  2322. test_assert(pos > 0);
  2323. stdout_buf[pos] = '\0';
  2324. test_streq(expected_out[expected_out_ctr], stdout_buf);
  2325. test_eq(strlen(expected_out[expected_out_ctr]), pos);
  2326. expected_out_ctr++;
  2327. }
  2328. /* The process should have exited without writing more */
  2329. #ifdef _WIN32
  2330. pos = tor_read_all_handle(process_handle->stdout_pipe, stdout_buf,
  2331. sizeof(stdout_buf) - 1,
  2332. process_handle);
  2333. test_eq(0, pos);
  2334. #else
  2335. if (!eof) {
  2336. /* We should have got all the data, but maybe not the EOF flag */
  2337. pos = tor_read_all_handle(process_handle->stdout_handle, stdout_buf,
  2338. sizeof(stdout_buf) - 1,
  2339. process_handle, &eof);
  2340. test_eq(0, pos);
  2341. test_assert(eof);
  2342. }
  2343. /* Otherwise, we got the EOF on the last read */
  2344. #endif
  2345. /* Check it terminated correctly */
  2346. retval = tor_get_exit_code(process_handle, 1, &exit_code);
  2347. test_eq(PROCESS_EXIT_EXITED, retval);
  2348. test_eq(expected_exit, exit_code);
  2349. // TODO: Make test-child exit with something other than 0
  2350. /* Check stderr */
  2351. pos = tor_read_all_from_process_stderr(process_handle, stderr_buf,
  2352. sizeof(stderr_buf) - 1);
  2353. test_assert(pos >= 0);
  2354. stderr_buf[pos] = '\0';
  2355. test_streq(expected_err, stderr_buf);
  2356. test_eq(strlen(expected_err), pos);
  2357. done:
  2358. tor_process_handle_destroy(process_handle, 1);
  2359. }
  2360. /**
  2361. * Test for format_hex_number_sigsafe()
  2362. */
  2363. static void
  2364. test_util_format_hex_number(void *ptr)
  2365. {
  2366. int i, len;
  2367. char buf[33];
  2368. const struct {
  2369. const char *str;
  2370. unsigned int x;
  2371. } test_data[] = {
  2372. {"0", 0},
  2373. {"1", 1},
  2374. {"273A", 0x273a},
  2375. {"FFFF", 0xffff},
  2376. {"7FFFFFFF", 0x7fffffff},
  2377. {"FFFFFFFF", 0xffffffff},
  2378. #if UINT_MAX >= 0xffffffff
  2379. {"31BC421D", 0x31bc421d},
  2380. {"FFFFFFFF", 0xffffffff},
  2381. #endif
  2382. {NULL, 0}
  2383. };
  2384. (void)ptr;
  2385. for (i = 0; test_data[i].str != NULL; ++i) {
  2386. len = format_hex_number_sigsafe(test_data[i].x, buf, sizeof(buf));
  2387. test_neq(len, 0);
  2388. test_eq(len, strlen(buf));
  2389. test_streq(buf, test_data[i].str);
  2390. }
  2391. test_eq(4, format_hex_number_sigsafe(0xffff, buf, 5));
  2392. test_streq(buf, "FFFF");
  2393. test_eq(0, format_hex_number_sigsafe(0xffff, buf, 4));
  2394. test_eq(0, format_hex_number_sigsafe(0, buf, 1));
  2395. done:
  2396. return;
  2397. }
  2398. /**
  2399. * Test for format_hex_number_sigsafe()
  2400. */
  2401. static void
  2402. test_util_format_dec_number(void *ptr)
  2403. {
  2404. int i, len;
  2405. char buf[33];
  2406. const struct {
  2407. const char *str;
  2408. unsigned int x;
  2409. } test_data[] = {
  2410. {"0", 0},
  2411. {"1", 1},
  2412. {"1234", 1234},
  2413. {"12345678", 12345678},
  2414. {"99999999", 99999999},
  2415. {"100000000", 100000000},
  2416. {"4294967295", 4294967295u},
  2417. #if UINT_MAX > 0xffffffff
  2418. {"18446744073709551615", 18446744073709551615u },
  2419. #endif
  2420. {NULL, 0}
  2421. };
  2422. (void)ptr;
  2423. for (i = 0; test_data[i].str != NULL; ++i) {
  2424. len = format_dec_number_sigsafe(test_data[i].x, buf, sizeof(buf));
  2425. test_neq(len, 0);
  2426. test_eq(len, strlen(buf));
  2427. test_streq(buf, test_data[i].str);
  2428. len = format_dec_number_sigsafe(test_data[i].x, buf,
  2429. (int)(strlen(test_data[i].str) + 1));
  2430. test_eq(len, strlen(buf));
  2431. test_streq(buf, test_data[i].str);
  2432. }
  2433. test_eq(4, format_dec_number_sigsafe(7331, buf, 5));
  2434. test_streq(buf, "7331");
  2435. test_eq(0, format_dec_number_sigsafe(7331, buf, 4));
  2436. test_eq(1, format_dec_number_sigsafe(0, buf, 2));
  2437. test_eq(0, format_dec_number_sigsafe(0, buf, 1));
  2438. done:
  2439. return;
  2440. }
  2441. /**
  2442. * Test that we can properly format a Windows command line
  2443. */
  2444. static void
  2445. test_util_join_win_cmdline(void *ptr)
  2446. {
  2447. /* Based on some test cases from "Parsing C++ Command-Line Arguments" in
  2448. * MSDN but we don't exercise all quoting rules because tor_join_win_cmdline
  2449. * will try to only generate simple cases for the child process to parse;
  2450. * i.e. we never embed quoted strings in arguments. */
  2451. const char *argvs[][4] = {
  2452. {"a", "bb", "CCC", NULL}, // Normal
  2453. {NULL, NULL, NULL, NULL}, // Empty argument list
  2454. {"", NULL, NULL, NULL}, // Empty argument
  2455. {"\"a", "b\"b", "CCC\"", NULL}, // Quotes
  2456. {"a\tbc", "dd dd", "E", NULL}, // Whitespace
  2457. {"a\\\\\\b", "de fg", "H", NULL}, // Backslashes
  2458. {"a\\\"b", "\\c", "D\\", NULL}, // Backslashes before quote
  2459. {"a\\\\b c", "d", "E", NULL}, // Backslashes not before quote
  2460. { NULL } // Terminator
  2461. };
  2462. const char *cmdlines[] = {
  2463. "a bb CCC",
  2464. "",
  2465. "\"\"",
  2466. "\\\"a b\\\"b CCC\\\"",
  2467. "\"a\tbc\" \"dd dd\" E",
  2468. "a\\\\\\b \"de fg\" H",
  2469. "a\\\\\\\"b \\c D\\",
  2470. "\"a\\\\b c\" d E",
  2471. NULL // Terminator
  2472. };
  2473. int i;
  2474. char *joined_argv = NULL;
  2475. (void)ptr;
  2476. for (i=0; cmdlines[i]!=NULL; i++) {
  2477. log_info(LD_GENERAL, "Joining argvs[%d], expecting <%s>", i, cmdlines[i]);
  2478. joined_argv = tor_join_win_cmdline(argvs[i]);
  2479. test_streq(cmdlines[i], joined_argv);
  2480. tor_free(joined_argv);
  2481. }
  2482. done:
  2483. tor_free(joined_argv);
  2484. }
  2485. #define MAX_SPLIT_LINE_COUNT 4
  2486. struct split_lines_test_t {
  2487. const char *orig_line; // Line to be split (may contain \0's)
  2488. int orig_length; // Length of orig_line
  2489. const char *split_line[MAX_SPLIT_LINE_COUNT]; // Split lines
  2490. };
  2491. /**
  2492. * Test that we properly split a buffer into lines
  2493. */
  2494. static void
  2495. test_util_split_lines(void *ptr)
  2496. {
  2497. /* Test cases. orig_line of last test case must be NULL.
  2498. * The last element of split_line[i] must be NULL. */
  2499. struct split_lines_test_t tests[] = {
  2500. {"", 0, {NULL}},
  2501. {"foo", 3, {"foo", NULL}},
  2502. {"\n\rfoo\n\rbar\r\n", 12, {"foo", "bar", NULL}},
  2503. {"fo o\r\nb\tar", 10, {"fo o", "b.ar", NULL}},
  2504. {"\x0f""f\0o\0\n\x01""b\0r\0\r", 12, {".f.o.", ".b.r.", NULL}},
  2505. {"line 1\r\nline 2", 14, {"line 1", "line 2", NULL}},
  2506. {"line 1\r\n\r\nline 2", 16, {"line 1", "line 2", NULL}},
  2507. {"line 1\r\n\r\r\r\nline 2", 18, {"line 1", "line 2", NULL}},
  2508. {"line 1\r\n\n\n\n\rline 2", 18, {"line 1", "line 2", NULL}},
  2509. {"line 1\r\n\r\t\r\nline 3", 18, {"line 1", ".", "line 3", NULL}},
  2510. {"\n\t\r\t\nline 3", 11, {".", ".", "line 3", NULL}},
  2511. {NULL, 0, { NULL }}
  2512. };
  2513. int i, j;
  2514. char *orig_line=NULL;
  2515. smartlist_t *sl=NULL;
  2516. (void)ptr;
  2517. for (i=0; tests[i].orig_line; i++) {
  2518. sl = smartlist_new();
  2519. /* Allocate space for string and trailing NULL */
  2520. orig_line = tor_memdup(tests[i].orig_line, tests[i].orig_length + 1);
  2521. tor_split_lines(sl, orig_line, tests[i].orig_length);
  2522. j = 0;
  2523. log_info(LD_GENERAL, "Splitting test %d of length %d",
  2524. i, tests[i].orig_length);
  2525. SMARTLIST_FOREACH_BEGIN(sl, const char *, line) {
  2526. /* Check we have not got too many lines */
  2527. test_assert(j < MAX_SPLIT_LINE_COUNT);
  2528. /* Check that there actually should be a line here */
  2529. test_assert(tests[i].split_line[j] != NULL);
  2530. log_info(LD_GENERAL, "Line %d of test %d, should be <%s>",
  2531. j, i, tests[i].split_line[j]);
  2532. /* Check that the line is as expected */
  2533. test_streq(line, tests[i].split_line[j]);
  2534. j++;
  2535. } SMARTLIST_FOREACH_END(line);
  2536. /* Check that we didn't miss some lines */
  2537. test_eq_ptr(NULL, tests[i].split_line[j]);
  2538. tor_free(orig_line);
  2539. smartlist_free(sl);
  2540. sl = NULL;
  2541. }
  2542. done:
  2543. tor_free(orig_line);
  2544. smartlist_free(sl);
  2545. }
  2546. static void
  2547. test_util_di_ops(void)
  2548. {
  2549. #define LT -1
  2550. #define GT 1
  2551. #define EQ 0
  2552. const struct {
  2553. const char *a; int want_sign; const char *b;
  2554. } examples[] = {
  2555. { "Foo", EQ, "Foo" },
  2556. { "foo", GT, "bar", },
  2557. { "foobar", EQ ,"foobar" },
  2558. { "foobar", LT, "foobaw" },
  2559. { "foobar", GT, "f00bar" },
  2560. { "foobar", GT, "boobar" },
  2561. { "", EQ, "" },
  2562. { NULL, 0, NULL },
  2563. };
  2564. int i;
  2565. for (i = 0; examples[i].a; ++i) {
  2566. size_t len = strlen(examples[i].a);
  2567. int eq1, eq2, neq1, neq2, cmp1, cmp2;
  2568. test_eq(len, strlen(examples[i].b));
  2569. /* We do all of the operations, with operands in both orders. */
  2570. eq1 = tor_memeq(examples[i].a, examples[i].b, len);
  2571. eq2 = tor_memeq(examples[i].b, examples[i].a, len);
  2572. neq1 = tor_memneq(examples[i].a, examples[i].b, len);
  2573. neq2 = tor_memneq(examples[i].b, examples[i].a, len);
  2574. cmp1 = tor_memcmp(examples[i].a, examples[i].b, len);
  2575. cmp2 = tor_memcmp(examples[i].b, examples[i].a, len);
  2576. /* Check for correctness of cmp1 */
  2577. if (cmp1 < 0 && examples[i].want_sign != LT)
  2578. test_fail();
  2579. else if (cmp1 > 0 && examples[i].want_sign != GT)
  2580. test_fail();
  2581. else if (cmp1 == 0 && examples[i].want_sign != EQ)
  2582. test_fail();
  2583. /* Check for consistency of everything else with cmp1 */
  2584. test_eq(eq1, eq2);
  2585. test_eq(neq1, neq2);
  2586. test_eq(cmp1, -cmp2);
  2587. test_eq(eq1, cmp1 == 0);
  2588. test_eq(neq1, !eq1);
  2589. }
  2590. tt_int_op(1, ==, safe_mem_is_zero("", 0));
  2591. tt_int_op(1, ==, safe_mem_is_zero("", 1));
  2592. tt_int_op(0, ==, safe_mem_is_zero("a", 1));
  2593. tt_int_op(0, ==, safe_mem_is_zero("a", 2));
  2594. tt_int_op(0, ==, safe_mem_is_zero("\0a", 2));
  2595. tt_int_op(1, ==, safe_mem_is_zero("\0\0a", 2));
  2596. tt_int_op(1, ==, safe_mem_is_zero("\0\0\0\0\0\0\0\0", 8));
  2597. tt_int_op(1, ==, safe_mem_is_zero("\0\0\0\0\0\0\0\0a", 8));
  2598. tt_int_op(0, ==, safe_mem_is_zero("\0\0\0\0\0\0\0\0a", 9));
  2599. done:
  2600. ;
  2601. }
  2602. /**
  2603. * Test counting high bits
  2604. */
  2605. static void
  2606. test_util_n_bits_set(void *ptr)
  2607. {
  2608. (void)ptr;
  2609. test_eq(0, n_bits_set_u8(0));
  2610. test_eq(1, n_bits_set_u8(1));
  2611. test_eq(3, n_bits_set_u8(7));
  2612. test_eq(1, n_bits_set_u8(8));
  2613. test_eq(2, n_bits_set_u8(129));
  2614. test_eq(8, n_bits_set_u8(255));
  2615. done:
  2616. ;
  2617. }
  2618. /**
  2619. * Test LHS whitespace (and comment) eater
  2620. */
  2621. static void
  2622. test_util_eat_whitespace(void *ptr)
  2623. {
  2624. const char ws[] = { ' ', '\t', '\r' }; /* Except NL */
  2625. char str[80];
  2626. size_t i;
  2627. (void)ptr;
  2628. /* Try one leading ws */
  2629. strlcpy(str, "fuubaar", sizeof(str));
  2630. for (i = 0; i < sizeof(ws); ++i) {
  2631. str[0] = ws[i];
  2632. test_eq_ptr(str + 1, eat_whitespace(str));
  2633. test_eq_ptr(str + 1, eat_whitespace_eos(str, str + strlen(str)));
  2634. test_eq_ptr(str + 1, eat_whitespace_no_nl(str));
  2635. test_eq_ptr(str + 1, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2636. }
  2637. str[0] = '\n';
  2638. test_eq_ptr(str + 1, eat_whitespace(str));
  2639. test_eq_ptr(str + 1, eat_whitespace_eos(str, str + strlen(str)));
  2640. test_eq_ptr(str, eat_whitespace_no_nl(str));
  2641. test_eq_ptr(str, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2642. /* Empty string */
  2643. strlcpy(str, "", sizeof(str));
  2644. test_eq_ptr(str, eat_whitespace(str));
  2645. test_eq_ptr(str, eat_whitespace_eos(str, str));
  2646. test_eq_ptr(str, eat_whitespace_no_nl(str));
  2647. test_eq_ptr(str, eat_whitespace_eos_no_nl(str, str));
  2648. /* Only ws */
  2649. strlcpy(str, " \t\r\n", sizeof(str));
  2650. test_eq_ptr(str + strlen(str), eat_whitespace(str));
  2651. test_eq_ptr(str + strlen(str), eat_whitespace_eos(str, str + strlen(str)));
  2652. test_eq_ptr(str + strlen(str) - 1,
  2653. eat_whitespace_no_nl(str));
  2654. test_eq_ptr(str + strlen(str) - 1,
  2655. eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2656. strlcpy(str, " \t\r ", sizeof(str));
  2657. test_eq_ptr(str + strlen(str), eat_whitespace(str));
  2658. test_eq_ptr(str + strlen(str),
  2659. eat_whitespace_eos(str, str + strlen(str)));
  2660. test_eq_ptr(str + strlen(str), eat_whitespace_no_nl(str));
  2661. test_eq_ptr(str + strlen(str),
  2662. eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2663. /* Multiple ws */
  2664. strlcpy(str, "fuubaar", sizeof(str));
  2665. for (i = 0; i < sizeof(ws); ++i)
  2666. str[i] = ws[i];
  2667. test_eq_ptr(str + sizeof(ws), eat_whitespace(str));
  2668. test_eq_ptr(str + sizeof(ws), eat_whitespace_eos(str, str + strlen(str)));
  2669. test_eq_ptr(str + sizeof(ws), eat_whitespace_no_nl(str));
  2670. test_eq_ptr(str + sizeof(ws),
  2671. eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2672. /* Eat comment */
  2673. strlcpy(str, "# Comment \n No Comment", sizeof(str));
  2674. test_streq("No Comment", eat_whitespace(str));
  2675. test_streq("No Comment", eat_whitespace_eos(str, str + strlen(str)));
  2676. test_eq_ptr(str, eat_whitespace_no_nl(str));
  2677. test_eq_ptr(str, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2678. /* Eat comment & ws mix */
  2679. strlcpy(str, " # \t Comment \n\t\nNo Comment", sizeof(str));
  2680. test_streq("No Comment", eat_whitespace(str));
  2681. test_streq("No Comment", eat_whitespace_eos(str, str + strlen(str)));
  2682. test_eq_ptr(str + 1, eat_whitespace_no_nl(str));
  2683. test_eq_ptr(str + 1, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2684. /* Eat entire comment */
  2685. strlcpy(str, "#Comment", sizeof(str));
  2686. test_eq_ptr(str + strlen(str), eat_whitespace(str));
  2687. test_eq_ptr(str + strlen(str), eat_whitespace_eos(str, str + strlen(str)));
  2688. test_eq_ptr(str, eat_whitespace_no_nl(str));
  2689. test_eq_ptr(str, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2690. /* Blank line, then comment */
  2691. strlcpy(str, " \t\n # Comment", sizeof(str));
  2692. test_eq_ptr(str + strlen(str), eat_whitespace(str));
  2693. test_eq_ptr(str + strlen(str), eat_whitespace_eos(str, str + strlen(str)));
  2694. test_eq_ptr(str + 2, eat_whitespace_no_nl(str));
  2695. test_eq_ptr(str + 2, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2696. done:
  2697. ;
  2698. }
  2699. /** Return a newly allocated smartlist containing the lines of text in
  2700. * <b>lines</b>. The returned strings are heap-allocated, and must be
  2701. * freed by the caller.
  2702. *
  2703. * XXXX? Move to container.[hc] ? */
  2704. static smartlist_t *
  2705. smartlist_new_from_text_lines(const char *lines)
  2706. {
  2707. smartlist_t *sl = smartlist_new();
  2708. char *last_line;
  2709. smartlist_split_string(sl, lines, "\n", 0, 0);
  2710. last_line = smartlist_pop_last(sl);
  2711. if (last_line != NULL && *last_line != '\0') {
  2712. smartlist_add(sl, last_line);
  2713. }
  2714. return sl;
  2715. }
  2716. /** Test smartlist_new_from_text_lines */
  2717. static void
  2718. test_util_sl_new_from_text_lines(void *ptr)
  2719. {
  2720. (void)ptr;
  2721. { /* Normal usage */
  2722. smartlist_t *sl = smartlist_new_from_text_lines("foo\nbar\nbaz\n");
  2723. int sl_len = smartlist_len(sl);
  2724. tt_want_int_op(sl_len, ==, 3);
  2725. if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), ==, "foo");
  2726. if (sl_len > 1) tt_want_str_op(smartlist_get(sl, 1), ==, "bar");
  2727. if (sl_len > 2) tt_want_str_op(smartlist_get(sl, 2), ==, "baz");
  2728. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  2729. smartlist_free(sl);
  2730. }
  2731. { /* No final newline */
  2732. smartlist_t *sl = smartlist_new_from_text_lines("foo\nbar\nbaz");
  2733. int sl_len = smartlist_len(sl);
  2734. tt_want_int_op(sl_len, ==, 3);
  2735. if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), ==, "foo");
  2736. if (sl_len > 1) tt_want_str_op(smartlist_get(sl, 1), ==, "bar");
  2737. if (sl_len > 2) tt_want_str_op(smartlist_get(sl, 2), ==, "baz");
  2738. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  2739. smartlist_free(sl);
  2740. }
  2741. { /* No newlines */
  2742. smartlist_t *sl = smartlist_new_from_text_lines("foo");
  2743. int sl_len = smartlist_len(sl);
  2744. tt_want_int_op(sl_len, ==, 1);
  2745. if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), ==, "foo");
  2746. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  2747. smartlist_free(sl);
  2748. }
  2749. { /* No text at all */
  2750. smartlist_t *sl = smartlist_new_from_text_lines("");
  2751. int sl_len = smartlist_len(sl);
  2752. tt_want_int_op(sl_len, ==, 0);
  2753. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  2754. smartlist_free(sl);
  2755. }
  2756. }
  2757. static void
  2758. test_util_envnames(void *ptr)
  2759. {
  2760. (void) ptr;
  2761. tt_assert(environment_variable_names_equal("abc", "abc"));
  2762. tt_assert(environment_variable_names_equal("abc", "abc="));
  2763. tt_assert(environment_variable_names_equal("abc", "abc=def"));
  2764. tt_assert(environment_variable_names_equal("abc=def", "abc"));
  2765. tt_assert(environment_variable_names_equal("abc=def", "abc=ghi"));
  2766. tt_assert(environment_variable_names_equal("abc", "abc"));
  2767. tt_assert(environment_variable_names_equal("abc", "abc="));
  2768. tt_assert(environment_variable_names_equal("abc", "abc=def"));
  2769. tt_assert(environment_variable_names_equal("abc=def", "abc"));
  2770. tt_assert(environment_variable_names_equal("abc=def", "abc=ghi"));
  2771. tt_assert(!environment_variable_names_equal("abc", "abcd"));
  2772. tt_assert(!environment_variable_names_equal("abc=", "abcd"));
  2773. tt_assert(!environment_variable_names_equal("abc=", "abcd"));
  2774. tt_assert(!environment_variable_names_equal("abc=", "def"));
  2775. tt_assert(!environment_variable_names_equal("abc=", "def="));
  2776. tt_assert(!environment_variable_names_equal("abc=x", "def=x"));
  2777. tt_assert(!environment_variable_names_equal("", "a=def"));
  2778. /* A bit surprising. */
  2779. tt_assert(environment_variable_names_equal("", "=def"));
  2780. tt_assert(environment_variable_names_equal("=y", "=x"));
  2781. done:
  2782. ;
  2783. }
  2784. /** Test process_environment_make */
  2785. static void
  2786. test_util_make_environment(void *ptr)
  2787. {
  2788. const char *env_vars_string =
  2789. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\n"
  2790. "HOME=/home/foozer\n";
  2791. const char expected_windows_env_block[] =
  2792. "HOME=/home/foozer\000"
  2793. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\000"
  2794. "\000";
  2795. size_t expected_windows_env_block_len =
  2796. sizeof(expected_windows_env_block) - 1;
  2797. smartlist_t *env_vars = smartlist_new_from_text_lines(env_vars_string);
  2798. smartlist_t *env_vars_sorted = smartlist_new();
  2799. smartlist_t *env_vars_in_unixoid_env_block_sorted = smartlist_new();
  2800. process_environment_t *env;
  2801. (void)ptr;
  2802. env = process_environment_make(env_vars);
  2803. /* Check that the Windows environment block is correct. */
  2804. tt_want(tor_memeq(expected_windows_env_block, env->windows_environment_block,
  2805. expected_windows_env_block_len));
  2806. /* Now for the Unixoid environment block. We don't care which order
  2807. * these environment variables are in, so we sort both lists first. */
  2808. smartlist_add_all(env_vars_sorted, env_vars);
  2809. {
  2810. char **v;
  2811. for (v = env->unixoid_environment_block; *v; ++v) {
  2812. smartlist_add(env_vars_in_unixoid_env_block_sorted, *v);
  2813. }
  2814. }
  2815. smartlist_sort_strings(env_vars_sorted);
  2816. smartlist_sort_strings(env_vars_in_unixoid_env_block_sorted);
  2817. tt_want_int_op(smartlist_len(env_vars_sorted), ==,
  2818. smartlist_len(env_vars_in_unixoid_env_block_sorted));
  2819. {
  2820. int len = smartlist_len(env_vars_sorted);
  2821. int i;
  2822. if (smartlist_len(env_vars_in_unixoid_env_block_sorted) < len) {
  2823. len = smartlist_len(env_vars_in_unixoid_env_block_sorted);
  2824. }
  2825. for (i = 0; i < len; ++i) {
  2826. tt_want_str_op(smartlist_get(env_vars_sorted, i), ==,
  2827. smartlist_get(env_vars_in_unixoid_env_block_sorted, i));
  2828. }
  2829. }
  2830. /* Clean up. */
  2831. smartlist_free(env_vars_in_unixoid_env_block_sorted);
  2832. smartlist_free(env_vars_sorted);
  2833. SMARTLIST_FOREACH(env_vars, char *, x, tor_free(x));
  2834. smartlist_free(env_vars);
  2835. process_environment_free(env);
  2836. }
  2837. /** Test set_environment_variable_in_smartlist */
  2838. static void
  2839. test_util_set_env_var_in_sl(void *ptr)
  2840. {
  2841. /* The environment variables in these strings are in arbitrary
  2842. * order; we sort the resulting lists before comparing them.
  2843. *
  2844. * (They *will not* end up in the order shown in
  2845. * expected_resulting_env_vars_string.) */
  2846. const char *base_env_vars_string =
  2847. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\n"
  2848. "HOME=/home/foozer\n"
  2849. "TERM=xterm\n"
  2850. "SHELL=/bin/ksh\n"
  2851. "USER=foozer\n"
  2852. "LOGNAME=foozer\n"
  2853. "USERNAME=foozer\n"
  2854. "LANG=en_US.utf8\n"
  2855. ;
  2856. const char *new_env_vars_string =
  2857. "TERM=putty\n"
  2858. "DISPLAY=:18.0\n"
  2859. ;
  2860. const char *expected_resulting_env_vars_string =
  2861. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\n"
  2862. "HOME=/home/foozer\n"
  2863. "TERM=putty\n"
  2864. "SHELL=/bin/ksh\n"
  2865. "USER=foozer\n"
  2866. "LOGNAME=foozer\n"
  2867. "USERNAME=foozer\n"
  2868. "LANG=en_US.utf8\n"
  2869. "DISPLAY=:18.0\n"
  2870. ;
  2871. smartlist_t *merged_env_vars =
  2872. smartlist_new_from_text_lines(base_env_vars_string);
  2873. smartlist_t *new_env_vars =
  2874. smartlist_new_from_text_lines(new_env_vars_string);
  2875. smartlist_t *expected_resulting_env_vars =
  2876. smartlist_new_from_text_lines(expected_resulting_env_vars_string);
  2877. /* Elements of merged_env_vars are heap-allocated, and must be
  2878. * freed. Some of them are (or should) be freed by
  2879. * set_environment_variable_in_smartlist.
  2880. *
  2881. * Elements of new_env_vars are heap-allocated, but are copied into
  2882. * merged_env_vars, so they are not freed separately at the end of
  2883. * the function.
  2884. *
  2885. * Elements of expected_resulting_env_vars are heap-allocated, and
  2886. * must be freed. */
  2887. (void)ptr;
  2888. SMARTLIST_FOREACH(new_env_vars, char *, env_var,
  2889. set_environment_variable_in_smartlist(merged_env_vars,
  2890. env_var,
  2891. tor_free_,
  2892. 1));
  2893. smartlist_sort_strings(merged_env_vars);
  2894. smartlist_sort_strings(expected_resulting_env_vars);
  2895. tt_want_int_op(smartlist_len(merged_env_vars), ==,
  2896. smartlist_len(expected_resulting_env_vars));
  2897. {
  2898. int len = smartlist_len(merged_env_vars);
  2899. int i;
  2900. if (smartlist_len(expected_resulting_env_vars) < len) {
  2901. len = smartlist_len(expected_resulting_env_vars);
  2902. }
  2903. for (i = 0; i < len; ++i) {
  2904. tt_want_str_op(smartlist_get(merged_env_vars, i), ==,
  2905. smartlist_get(expected_resulting_env_vars, i));
  2906. }
  2907. }
  2908. /* Clean up. */
  2909. SMARTLIST_FOREACH(merged_env_vars, char *, x, tor_free(x));
  2910. smartlist_free(merged_env_vars);
  2911. smartlist_free(new_env_vars);
  2912. SMARTLIST_FOREACH(expected_resulting_env_vars, char *, x, tor_free(x));
  2913. smartlist_free(expected_resulting_env_vars);
  2914. }
  2915. static void
  2916. test_util_weak_random(void *arg)
  2917. {
  2918. int i, j, n[16];
  2919. tor_weak_rng_t rng;
  2920. (void) arg;
  2921. tor_init_weak_random(&rng, (unsigned)time(NULL));
  2922. for (i = 1; i <= 256; ++i) {
  2923. for (j=0;j<100;++j) {
  2924. int r = tor_weak_random_range(&rng, i);
  2925. tt_int_op(0, <=, r);
  2926. tt_int_op(r, <, i);
  2927. }
  2928. }
  2929. memset(n,0,sizeof(n));
  2930. for (j=0;j<8192;++j) {
  2931. n[tor_weak_random_range(&rng, 16)]++;
  2932. }
  2933. for (i=0;i<16;++i)
  2934. tt_int_op(n[i], >, 0);
  2935. done:
  2936. ;
  2937. }
  2938. static void
  2939. test_util_mathlog(void *arg)
  2940. {
  2941. double d;
  2942. (void) arg;
  2943. d = tor_mathlog(2.718281828);
  2944. tt_double_op(fabs(d - 1.0), <, .000001);
  2945. d = tor_mathlog(10);
  2946. tt_double_op(fabs(d - 2.30258509), <, .000001);
  2947. done:
  2948. ;
  2949. }
  2950. static void
  2951. test_util_round_to_next_multiple_of(void *arg)
  2952. {
  2953. (void)arg;
  2954. test_assert(round_uint64_to_next_multiple_of(0,1) == 0);
  2955. test_assert(round_uint64_to_next_multiple_of(0,7) == 0);
  2956. test_assert(round_uint64_to_next_multiple_of(99,1) == 99);
  2957. test_assert(round_uint64_to_next_multiple_of(99,7) == 105);
  2958. test_assert(round_uint64_to_next_multiple_of(99,9) == 99);
  2959. done:
  2960. ;
  2961. }
  2962. static void
  2963. test_util_strclear(void *arg)
  2964. {
  2965. static const char *vals[] = { "", "a", "abcdef", "abcdefgh", NULL };
  2966. int i;
  2967. char *v = NULL;
  2968. (void)arg;
  2969. for (i = 0; vals[i]; ++i) {
  2970. size_t n;
  2971. v = tor_strdup(vals[i]);
  2972. n = strlen(v);
  2973. tor_strclear(v);
  2974. tt_assert(tor_mem_is_zero(v, n+1));
  2975. tor_free(v);
  2976. }
  2977. done:
  2978. tor_free(v);
  2979. }
  2980. #define UTIL_LEGACY(name) \
  2981. { #name, legacy_test_helper, 0, &legacy_setup, test_util_ ## name }
  2982. #define UTIL_TEST(name, flags) \
  2983. { #name, test_util_ ## name, flags, NULL, NULL }
  2984. #ifdef FD_CLOEXEC
  2985. #define CAN_CHECK_CLOEXEC
  2986. static int
  2987. fd_is_cloexec(tor_socket_t fd)
  2988. {
  2989. int flags = fcntl(fd, F_GETFD, 0);
  2990. return (flags & FD_CLOEXEC) == FD_CLOEXEC;
  2991. }
  2992. #endif
  2993. #ifndef _WIN32
  2994. #define CAN_CHECK_NONBLOCK
  2995. static int
  2996. fd_is_nonblocking(tor_socket_t fd)
  2997. {
  2998. int flags = fcntl(fd, F_GETFL, 0);
  2999. return (flags & O_NONBLOCK) == O_NONBLOCK;
  3000. }
  3001. #endif
  3002. static void
  3003. test_util_socket(void *arg)
  3004. {
  3005. tor_socket_t fd1 = TOR_INVALID_SOCKET;
  3006. tor_socket_t fd2 = TOR_INVALID_SOCKET;
  3007. tor_socket_t fd3 = TOR_INVALID_SOCKET;
  3008. tor_socket_t fd4 = TOR_INVALID_SOCKET;
  3009. int n = get_n_open_sockets();
  3010. TT_BLATHER(("Starting with %d open sockets.", n));
  3011. (void)arg;
  3012. fd1 = tor_open_socket_with_extensions(AF_INET, SOCK_STREAM, 0, 0, 0);
  3013. fd2 = tor_open_socket_with_extensions(AF_INET, SOCK_STREAM, 0, 0, 1);
  3014. tt_assert(SOCKET_OK(fd1));
  3015. tt_assert(SOCKET_OK(fd2));
  3016. tt_int_op(get_n_open_sockets(), ==, n + 2);
  3017. //fd3 = tor_open_socket_with_extensions(AF_INET, SOCK_STREAM, 0, 1, 0);
  3018. //fd4 = tor_open_socket_with_extensions(AF_INET, SOCK_STREAM, 0, 1, 1);
  3019. fd3 = tor_open_socket(AF_INET, SOCK_STREAM, 0);
  3020. fd4 = tor_open_socket_nonblocking(AF_INET, SOCK_STREAM, 0);
  3021. tt_assert(SOCKET_OK(fd3));
  3022. tt_assert(SOCKET_OK(fd4));
  3023. tt_int_op(get_n_open_sockets(), ==, n + 4);
  3024. #ifdef CAN_CHECK_CLOEXEC
  3025. tt_int_op(fd_is_cloexec(fd1), ==, 0);
  3026. tt_int_op(fd_is_cloexec(fd2), ==, 0);
  3027. tt_int_op(fd_is_cloexec(fd3), ==, 1);
  3028. tt_int_op(fd_is_cloexec(fd4), ==, 1);
  3029. #endif
  3030. #ifdef CAN_CHECK_NONBLOCK
  3031. tt_int_op(fd_is_nonblocking(fd1), ==, 0);
  3032. tt_int_op(fd_is_nonblocking(fd2), ==, 1);
  3033. tt_int_op(fd_is_nonblocking(fd3), ==, 0);
  3034. tt_int_op(fd_is_nonblocking(fd4), ==, 1);
  3035. #endif
  3036. tor_close_socket(fd1);
  3037. tor_close_socket(fd2);
  3038. fd1 = fd2 = TOR_INVALID_SOCKET;
  3039. tt_int_op(get_n_open_sockets(), ==, n + 2);
  3040. tor_close_socket(fd3);
  3041. tor_close_socket(fd4);
  3042. fd3 = fd4 = TOR_INVALID_SOCKET;
  3043. tt_int_op(get_n_open_sockets(), ==, n);
  3044. done:
  3045. if (SOCKET_OK(fd1))
  3046. tor_close_socket(fd1);
  3047. if (SOCKET_OK(fd2))
  3048. tor_close_socket(fd2);
  3049. if (SOCKET_OK(fd3))
  3050. tor_close_socket(fd3);
  3051. if (SOCKET_OK(fd4))
  3052. tor_close_socket(fd4);
  3053. }
  3054. static void *
  3055. socketpair_test_setup(const struct testcase_t *testcase)
  3056. {
  3057. return testcase->setup_data;
  3058. }
  3059. static int
  3060. socketpair_test_cleanup(const struct testcase_t *testcase, void *ptr)
  3061. {
  3062. (void)testcase;
  3063. (void)ptr;
  3064. return 1;
  3065. }
  3066. static const struct testcase_setup_t socketpair_setup = {
  3067. socketpair_test_setup, socketpair_test_cleanup
  3068. };
  3069. /* Test for socketpair and ersatz_socketpair(). We test them both, since
  3070. * the latter is a tolerably good way to exersize tor_accept_socket(). */
  3071. static void
  3072. test_util_socketpair(void *arg)
  3073. {
  3074. const int ersatz = !strcmp(arg, "1");
  3075. int (*const tor_socketpair_fn)(int, int, int, tor_socket_t[2]) =
  3076. ersatz ? tor_ersatz_socketpair : tor_socketpair;
  3077. int n = get_n_open_sockets();
  3078. tor_socket_t fds[2] = {TOR_INVALID_SOCKET, TOR_INVALID_SOCKET};
  3079. const int family = AF_UNIX;
  3080. tt_int_op(0, ==, tor_socketpair_fn(family, SOCK_STREAM, 0, fds));
  3081. tt_assert(SOCKET_OK(fds[0]));
  3082. tt_assert(SOCKET_OK(fds[1]));
  3083. tt_int_op(get_n_open_sockets(), ==, n + 2);
  3084. #ifdef CAN_CHECK_CLOEXEC
  3085. tt_int_op(fd_is_cloexec(fds[0]), ==, 1);
  3086. tt_int_op(fd_is_cloexec(fds[1]), ==, 1);
  3087. #endif
  3088. #ifdef CAN_CHECK_NONBLOCK
  3089. tt_int_op(fd_is_nonblocking(fds[0]), ==, 0);
  3090. tt_int_op(fd_is_nonblocking(fds[1]), ==, 0);
  3091. #endif
  3092. done:
  3093. if (SOCKET_OK(fds[0]))
  3094. tor_close_socket(fds[0]);
  3095. if (SOCKET_OK(fds[1]))
  3096. tor_close_socket(fds[1]);
  3097. }
  3098. struct testcase_t util_tests[] = {
  3099. UTIL_LEGACY(time),
  3100. UTIL_TEST(parse_http_time, 0),
  3101. UTIL_LEGACY(config_line),
  3102. UTIL_LEGACY(config_line_quotes),
  3103. UTIL_LEGACY(config_line_comment_character),
  3104. UTIL_LEGACY(config_line_escaped_content),
  3105. #ifndef _WIN32
  3106. UTIL_LEGACY(expand_filename),
  3107. #endif
  3108. UTIL_LEGACY(escape_string_socks),
  3109. UTIL_LEGACY(string_is_key_value),
  3110. UTIL_LEGACY(strmisc),
  3111. UTIL_LEGACY(pow2),
  3112. UTIL_LEGACY(gzip),
  3113. UTIL_LEGACY(datadir),
  3114. UTIL_LEGACY(mempool),
  3115. UTIL_LEGACY(memarea),
  3116. UTIL_LEGACY(control_formats),
  3117. UTIL_LEGACY(mmap),
  3118. UTIL_LEGACY(threads),
  3119. UTIL_LEGACY(sscanf),
  3120. UTIL_LEGACY(path_is_relative),
  3121. UTIL_LEGACY(strtok),
  3122. UTIL_LEGACY(di_ops),
  3123. UTIL_TEST(round_to_next_multiple_of, 0),
  3124. UTIL_TEST(strclear, 0),
  3125. UTIL_TEST(find_str_at_start_of_line, 0),
  3126. UTIL_TEST(string_is_C_identifier, 0),
  3127. UTIL_TEST(asprintf, 0),
  3128. UTIL_TEST(listdir, 0),
  3129. UTIL_TEST(parent_dir, 0),
  3130. #ifdef _WIN32
  3131. UTIL_TEST(load_win_lib, 0),
  3132. #endif
  3133. #ifndef _WIN32
  3134. UTIL_TEST(exit_status, 0),
  3135. UTIL_TEST(fgets_eagain, TT_SKIP),
  3136. #endif
  3137. UTIL_TEST(spawn_background_ok, 0),
  3138. UTIL_TEST(spawn_background_fail, 0),
  3139. UTIL_TEST(spawn_background_partial_read, 0),
  3140. UTIL_TEST(format_hex_number, 0),
  3141. UTIL_TEST(format_dec_number, 0),
  3142. UTIL_TEST(join_win_cmdline, 0),
  3143. UTIL_TEST(split_lines, 0),
  3144. UTIL_TEST(n_bits_set, 0),
  3145. UTIL_TEST(eat_whitespace, 0),
  3146. UTIL_TEST(sl_new_from_text_lines, 0),
  3147. UTIL_TEST(envnames, 0),
  3148. UTIL_TEST(make_environment, 0),
  3149. UTIL_TEST(set_env_var_in_sl, 0),
  3150. UTIL_TEST(read_file_eof_tiny_limit, 0),
  3151. UTIL_TEST(read_file_eof_two_loops, 0),
  3152. UTIL_TEST(read_file_eof_zero_bytes, 0),
  3153. UTIL_TEST(write_chunks_to_file, 0),
  3154. UTIL_TEST(mathlog, 0),
  3155. UTIL_TEST(weak_random, 0),
  3156. UTIL_TEST(socket, TT_FORK),
  3157. { "socketpair", test_util_socketpair, TT_FORK, &socketpair_setup,
  3158. (void*)"0" },
  3159. { "socketpair_ersatz", test_util_socketpair, TT_FORK,
  3160. &socketpair_setup, (void*)"1" },
  3161. END_OF_TESTCASES
  3162. };