test_util.c 111 KB

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