util.c 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306
  1. /* Copyright (c) 2003, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2011, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file util.c
  7. * \brief Common functions for strings, IO, network, data structures,
  8. * process control.
  9. **/
  10. /* This is required on rh7 to make strptime not complain.
  11. */
  12. #define _GNU_SOURCE
  13. #include "orconfig.h"
  14. #define UTIL_PRIVATE
  15. #include "util.h"
  16. #include "torlog.h"
  17. #undef log
  18. #include "crypto.h"
  19. #include "torint.h"
  20. #include "container.h"
  21. #include "address.h"
  22. #ifdef MS_WINDOWS
  23. #include <io.h>
  24. #include <direct.h>
  25. #include <process.h>
  26. #include <tchar.h>
  27. #else
  28. #include <dirent.h>
  29. #include <pwd.h>
  30. #include <grp.h>
  31. #endif
  32. /* math.h needs this on Linux */
  33. #ifndef __USE_ISOC99
  34. #define __USE_ISOC99 1
  35. #endif
  36. #include <math.h>
  37. #include <stdlib.h>
  38. #include <stdio.h>
  39. #include <string.h>
  40. #include <assert.h>
  41. #ifdef HAVE_NETINET_IN_H
  42. #include <netinet/in.h>
  43. #endif
  44. #ifdef HAVE_ARPA_INET_H
  45. #include <arpa/inet.h>
  46. #endif
  47. #ifdef HAVE_ERRNO_H
  48. #include <errno.h>
  49. #endif
  50. #ifdef HAVE_SYS_SOCKET_H
  51. #include <sys/socket.h>
  52. #endif
  53. #ifdef HAVE_SYS_TIME_H
  54. #include <sys/time.h>
  55. #endif
  56. #ifdef HAVE_UNISTD_H
  57. #include <unistd.h>
  58. #endif
  59. #ifdef HAVE_SYS_STAT_H
  60. #include <sys/stat.h>
  61. #endif
  62. #ifdef HAVE_SYS_FCNTL_H
  63. #include <sys/fcntl.h>
  64. #endif
  65. #ifdef HAVE_FCNTL_H
  66. #include <fcntl.h>
  67. #endif
  68. #ifdef HAVE_TIME_H
  69. #include <time.h>
  70. #endif
  71. #ifdef HAVE_MALLOC_MALLOC_H
  72. #include <malloc/malloc.h>
  73. #endif
  74. #ifdef HAVE_MALLOC_H
  75. #ifndef OPENBSD
  76. /* OpenBSD has a malloc.h, but for our purposes, it only exists in order to
  77. * scold us for being so stupid as to autodetect its presence. To be fair,
  78. * they've done this since 1996, when autoconf was only 5 years old. */
  79. #include <malloc.h>
  80. #endif
  81. #endif
  82. #ifdef HAVE_MALLOC_NP_H
  83. #include <malloc_np.h>
  84. #endif
  85. /* =====
  86. * Memory management
  87. * ===== */
  88. #ifdef USE_DMALLOC
  89. #undef strndup
  90. #include <dmalloc.h>
  91. /* Macro to pass the extra dmalloc args to another function. */
  92. #define DMALLOC_FN_ARGS , file, line
  93. #if defined(HAVE_DMALLOC_STRDUP)
  94. /* the dmalloc_strdup should be fine as defined */
  95. #elif defined(HAVE_DMALLOC_STRNDUP)
  96. #define dmalloc_strdup(file, line, string, xalloc_b) \
  97. dmalloc_strndup(file, line, (string), -1, xalloc_b)
  98. #else
  99. #error "No dmalloc_strdup or equivalent"
  100. #endif
  101. #else /* not using dmalloc */
  102. #define DMALLOC_FN_ARGS
  103. #endif
  104. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  105. * result. On error, log and terminate the process. (Same as malloc(size),
  106. * but never returns NULL.)
  107. *
  108. * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
  109. * ignored otherwise.
  110. */
  111. void *
  112. _tor_malloc(size_t size DMALLOC_PARAMS)
  113. {
  114. void *result;
  115. tor_assert(size < SIZE_T_CEILING);
  116. #ifndef MALLOC_ZERO_WORKS
  117. /* Some libc mallocs don't work when size==0. Override them. */
  118. if (size==0) {
  119. size=1;
  120. }
  121. #endif
  122. #ifdef USE_DMALLOC
  123. result = dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
  124. #else
  125. result = malloc(size);
  126. #endif
  127. if (PREDICT_UNLIKELY(result == NULL)) {
  128. log_err(LD_MM,"Out of memory on malloc(). Dying.");
  129. /* If these functions die within a worker process, they won't call
  130. * spawn_exit, but that's ok, since the parent will run out of memory soon
  131. * anyway. */
  132. exit(1);
  133. }
  134. return result;
  135. }
  136. /** Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  137. * zero bytes, and return a pointer to the result. Log and terminate
  138. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  139. */
  140. void *
  141. _tor_malloc_zero(size_t size DMALLOC_PARAMS)
  142. {
  143. /* You may ask yourself, "wouldn't it be smart to use calloc instead of
  144. * malloc+memset? Perhaps libc's calloc knows some nifty optimization trick
  145. * we don't!" Indeed it does, but its optimizations are only a big win when
  146. * we're allocating something very big (it knows if it just got the memory
  147. * from the OS in a pre-zeroed state). We don't want to use tor_malloc_zero
  148. * for big stuff, so we don't bother with calloc. */
  149. void *result = _tor_malloc(size DMALLOC_FN_ARGS);
  150. memset(result, 0, size);
  151. return result;
  152. }
  153. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  154. * bytes long; return the new memory block. On error, log and
  155. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  156. */
  157. void *
  158. _tor_realloc(void *ptr, size_t size DMALLOC_PARAMS)
  159. {
  160. void *result;
  161. tor_assert(size < SIZE_T_CEILING);
  162. #ifdef USE_DMALLOC
  163. result = dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
  164. #else
  165. result = realloc(ptr, size);
  166. #endif
  167. if (PREDICT_UNLIKELY(result == NULL)) {
  168. log_err(LD_MM,"Out of memory on realloc(). Dying.");
  169. exit(1);
  170. }
  171. return result;
  172. }
  173. /** Return a newly allocated copy of the NUL-terminated string s. On
  174. * error, log and terminate. (Like strdup(s), but never returns
  175. * NULL.)
  176. */
  177. char *
  178. _tor_strdup(const char *s DMALLOC_PARAMS)
  179. {
  180. char *dup;
  181. tor_assert(s);
  182. #ifdef USE_DMALLOC
  183. dup = dmalloc_strdup(file, line, s, 0);
  184. #else
  185. dup = strdup(s);
  186. #endif
  187. if (PREDICT_UNLIKELY(dup == NULL)) {
  188. log_err(LD_MM,"Out of memory on strdup(). Dying.");
  189. exit(1);
  190. }
  191. return dup;
  192. }
  193. /** Allocate and return a new string containing the first <b>n</b>
  194. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  195. * characters, only the first <b>n</b> are copied. The result is
  196. * always NUL-terminated. (Like strndup(s,n), but never returns
  197. * NULL.)
  198. */
  199. char *
  200. _tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
  201. {
  202. char *dup;
  203. tor_assert(s);
  204. tor_assert(n < SIZE_T_CEILING);
  205. dup = _tor_malloc((n+1) DMALLOC_FN_ARGS);
  206. /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
  207. * this function gets called a whole lot, and platform strncpy is
  208. * much faster than strlcpy when strlen(s) is much longer than n.
  209. */
  210. strncpy(dup, s, n);
  211. dup[n]='\0';
  212. return dup;
  213. }
  214. /** Allocate a chunk of <b>len</b> bytes, with the same contents as the
  215. * <b>len</b> bytes starting at <b>mem</b>. */
  216. void *
  217. _tor_memdup(const void *mem, size_t len DMALLOC_PARAMS)
  218. {
  219. char *dup;
  220. tor_assert(len < SIZE_T_CEILING);
  221. tor_assert(mem);
  222. dup = _tor_malloc(len DMALLOC_FN_ARGS);
  223. memcpy(dup, mem, len);
  224. return dup;
  225. }
  226. /** Helper for places that need to take a function pointer to the right
  227. * spelling of "free()". */
  228. void
  229. _tor_free(void *mem)
  230. {
  231. tor_free(mem);
  232. }
  233. #if defined(HAVE_MALLOC_GOOD_SIZE) && !defined(HAVE_MALLOC_GOOD_SIZE_PROTOTYPE)
  234. /* Some version of Mac OSX have malloc_good_size in their libc, but not
  235. * actually defined in malloc/malloc.h. We detect this and work around it by
  236. * prototyping.
  237. */
  238. extern size_t malloc_good_size(size_t size);
  239. #endif
  240. /** Allocate and return a chunk of memory of size at least *<b>size</b>, using
  241. * the same resources we would use to malloc *<b>sizep</b>. Set *<b>sizep</b>
  242. * to the number of usable bytes in the chunk of memory. */
  243. void *
  244. _tor_malloc_roundup(size_t *sizep DMALLOC_PARAMS)
  245. {
  246. #ifdef HAVE_MALLOC_GOOD_SIZE
  247. tor_assert(*sizep < SIZE_T_CEILING);
  248. *sizep = malloc_good_size(*sizep);
  249. return _tor_malloc(*sizep DMALLOC_FN_ARGS);
  250. #elif 0 && defined(HAVE_MALLOC_USABLE_SIZE) && !defined(USE_DMALLOC)
  251. /* Never use malloc_usable_size(); it makes valgrind really unhappy,
  252. * and doesn't win much in terms of usable space where it exists. */
  253. void *result;
  254. tor_assert(*sizep < SIZE_T_CEILING);
  255. result = _tor_malloc(*sizep DMALLOC_FN_ARGS);
  256. *sizep = malloc_usable_size(result);
  257. return result;
  258. #else
  259. return _tor_malloc(*sizep DMALLOC_FN_ARGS);
  260. #endif
  261. }
  262. /** Call the platform malloc info function, and dump the results to the log at
  263. * level <b>severity</b>. If no such function exists, do nothing. */
  264. void
  265. tor_log_mallinfo(int severity)
  266. {
  267. #ifdef HAVE_MALLINFO
  268. struct mallinfo mi;
  269. memset(&mi, 0, sizeof(mi));
  270. mi = mallinfo();
  271. tor_log(severity, LD_MM,
  272. "mallinfo() said: arena=%d, ordblks=%d, smblks=%d, hblks=%d, "
  273. "hblkhd=%d, usmblks=%d, fsmblks=%d, uordblks=%d, fordblks=%d, "
  274. "keepcost=%d",
  275. mi.arena, mi.ordblks, mi.smblks, mi.hblks,
  276. mi.hblkhd, mi.usmblks, mi.fsmblks, mi.uordblks, mi.fordblks,
  277. mi.keepcost);
  278. #else
  279. (void)severity;
  280. #endif
  281. #ifdef USE_DMALLOC
  282. dmalloc_log_changed(0, /* Since the program started. */
  283. 1, /* Log info about non-freed pointers. */
  284. 0, /* Do not log info about freed pointers. */
  285. 0 /* Do not log individual pointers. */
  286. );
  287. #endif
  288. }
  289. /* =====
  290. * Math
  291. * ===== */
  292. /**
  293. * Returns the natural logarithm of d base 2. We define this wrapper here so
  294. * as to make it easier not to conflict with Tor's log() macro.
  295. */
  296. double
  297. tor_mathlog(double d)
  298. {
  299. return log(d);
  300. }
  301. /** Return the long integer closest to d. We define this wrapper here so
  302. * that not all users of math.h need to use the right incancations to get
  303. * the c99 functions. */
  304. long
  305. tor_lround(double d)
  306. {
  307. return lround(d);
  308. }
  309. /** Returns floor(log2(u64)). If u64 is 0, (incorrectly) returns 0. */
  310. int
  311. tor_log2(uint64_t u64)
  312. {
  313. int r = 0;
  314. if (u64 >= (U64_LITERAL(1)<<32)) {
  315. u64 >>= 32;
  316. r = 32;
  317. }
  318. if (u64 >= (U64_LITERAL(1)<<16)) {
  319. u64 >>= 16;
  320. r += 16;
  321. }
  322. if (u64 >= (U64_LITERAL(1)<<8)) {
  323. u64 >>= 8;
  324. r += 8;
  325. }
  326. if (u64 >= (U64_LITERAL(1)<<4)) {
  327. u64 >>= 4;
  328. r += 4;
  329. }
  330. if (u64 >= (U64_LITERAL(1)<<2)) {
  331. u64 >>= 2;
  332. r += 2;
  333. }
  334. if (u64 >= (U64_LITERAL(1)<<1)) {
  335. u64 >>= 1;
  336. r += 1;
  337. }
  338. return r;
  339. }
  340. /** Return the power of 2 closest to <b>u64</b>. */
  341. uint64_t
  342. round_to_power_of_2(uint64_t u64)
  343. {
  344. int lg2 = tor_log2(u64);
  345. uint64_t low = U64_LITERAL(1) << lg2, high = U64_LITERAL(1) << (lg2+1);
  346. if (high - u64 < u64 - low)
  347. return high;
  348. else
  349. return low;
  350. }
  351. /** Return the lowest x such that x is at least <b>number</b>, and x modulo
  352. * <b>divisor</b> == 0. */
  353. unsigned
  354. round_to_next_multiple_of(unsigned number, unsigned divisor)
  355. {
  356. number += divisor - 1;
  357. number -= number % divisor;
  358. return number;
  359. }
  360. /** Return the lowest x such that x is at least <b>number</b>, and x modulo
  361. * <b>divisor</b> == 0. */
  362. uint32_t
  363. round_uint32_to_next_multiple_of(uint32_t number, uint32_t divisor)
  364. {
  365. number += divisor - 1;
  366. number -= number % divisor;
  367. return number;
  368. }
  369. /** Return the lowest x such that x is at least <b>number</b>, and x modulo
  370. * <b>divisor</b> == 0. */
  371. uint64_t
  372. round_uint64_to_next_multiple_of(uint64_t number, uint64_t divisor)
  373. {
  374. number += divisor - 1;
  375. number -= number % divisor;
  376. return number;
  377. }
  378. /* =====
  379. * String manipulation
  380. * ===== */
  381. /** Remove from the string <b>s</b> every character which appears in
  382. * <b>strip</b>. */
  383. void
  384. tor_strstrip(char *s, const char *strip)
  385. {
  386. char *read = s;
  387. while (*read) {
  388. if (strchr(strip, *read)) {
  389. ++read;
  390. } else {
  391. *s++ = *read++;
  392. }
  393. }
  394. *s = '\0';
  395. }
  396. /** Return a pointer to a NUL-terminated hexadecimal string encoding
  397. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  398. * result does not need to be deallocated, but repeated calls to
  399. * hex_str will trash old results.
  400. */
  401. const char *
  402. hex_str(const char *from, size_t fromlen)
  403. {
  404. static char buf[65];
  405. if (fromlen>(sizeof(buf)-1)/2)
  406. fromlen = (sizeof(buf)-1)/2;
  407. base16_encode(buf,sizeof(buf),from,fromlen);
  408. return buf;
  409. }
  410. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  411. * lowercase. */
  412. void
  413. tor_strlower(char *s)
  414. {
  415. while (*s) {
  416. *s = TOR_TOLOWER(*s);
  417. ++s;
  418. }
  419. }
  420. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  421. * lowercase. */
  422. void
  423. tor_strupper(char *s)
  424. {
  425. while (*s) {
  426. *s = TOR_TOUPPER(*s);
  427. ++s;
  428. }
  429. }
  430. /** Return 1 if every character in <b>s</b> is printable, else return 0.
  431. */
  432. int
  433. tor_strisprint(const char *s)
  434. {
  435. while (*s) {
  436. if (!TOR_ISPRINT(*s))
  437. return 0;
  438. s++;
  439. }
  440. return 1;
  441. }
  442. /** Return 1 if no character in <b>s</b> is uppercase, else return 0.
  443. */
  444. int
  445. tor_strisnonupper(const char *s)
  446. {
  447. while (*s) {
  448. if (TOR_ISUPPER(*s))
  449. return 0;
  450. s++;
  451. }
  452. return 1;
  453. }
  454. /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
  455. * strcmp.
  456. */
  457. int
  458. strcmpstart(const char *s1, const char *s2)
  459. {
  460. size_t n = strlen(s2);
  461. return strncmp(s1, s2, n);
  462. }
  463. /** Compare the s1_len-byte string <b>s1</b> with <b>s2</b>,
  464. * without depending on a terminating nul in s1. Sorting order is first by
  465. * length, then lexically; return values are as for strcmp.
  466. */
  467. int
  468. strcmp_len(const char *s1, const char *s2, size_t s1_len)
  469. {
  470. size_t s2_len = strlen(s2);
  471. if (s1_len < s2_len)
  472. return -1;
  473. if (s1_len > s2_len)
  474. return 1;
  475. return fast_memcmp(s1, s2, s2_len);
  476. }
  477. /** Compares the first strlen(s2) characters of s1 with s2. Returns as for
  478. * strcasecmp.
  479. */
  480. int
  481. strcasecmpstart(const char *s1, const char *s2)
  482. {
  483. size_t n = strlen(s2);
  484. return strncasecmp(s1, s2, n);
  485. }
  486. /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
  487. * strcmp.
  488. */
  489. int
  490. strcmpend(const char *s1, const char *s2)
  491. {
  492. size_t n1 = strlen(s1), n2 = strlen(s2);
  493. if (n2>n1)
  494. return strcmp(s1,s2);
  495. else
  496. return strncmp(s1+(n1-n2), s2, n2);
  497. }
  498. /** Compares the last strlen(s2) characters of s1 with s2. Returns as for
  499. * strcasecmp.
  500. */
  501. int
  502. strcasecmpend(const char *s1, const char *s2)
  503. {
  504. size_t n1 = strlen(s1), n2 = strlen(s2);
  505. if (n2>n1) /* then they can't be the same; figure out which is bigger */
  506. return strcasecmp(s1,s2);
  507. else
  508. return strncasecmp(s1+(n1-n2), s2, n2);
  509. }
  510. /** Compare the value of the string <b>prefix</b> with the start of the
  511. * <b>memlen</b>-byte memory chunk at <b>mem</b>. Return as for strcmp.
  512. *
  513. * [As fast_memcmp(mem, prefix, strlen(prefix)) but returns -1 if memlen is
  514. * less than strlen(prefix).]
  515. */
  516. int
  517. fast_memcmpstart(const void *mem, size_t memlen,
  518. const char *prefix)
  519. {
  520. size_t plen = strlen(prefix);
  521. if (memlen < plen)
  522. return -1;
  523. return fast_memcmp(mem, prefix, plen);
  524. }
  525. /** Return a pointer to the first char of s that is not whitespace and
  526. * not a comment, or to the terminating NUL if no such character exists.
  527. */
  528. const char *
  529. eat_whitespace(const char *s)
  530. {
  531. tor_assert(s);
  532. while (1) {
  533. switch (*s) {
  534. case '\0':
  535. default:
  536. return s;
  537. case ' ':
  538. case '\t':
  539. case '\n':
  540. case '\r':
  541. ++s;
  542. break;
  543. case '#':
  544. ++s;
  545. while (*s && *s != '\n')
  546. ++s;
  547. }
  548. }
  549. }
  550. /** Return a pointer to the first char of s that is not whitespace and
  551. * not a comment, or to the terminating NUL if no such character exists.
  552. */
  553. const char *
  554. eat_whitespace_eos(const char *s, const char *eos)
  555. {
  556. tor_assert(s);
  557. tor_assert(eos && s <= eos);
  558. while (s < eos) {
  559. switch (*s) {
  560. case '\0':
  561. default:
  562. return s;
  563. case ' ':
  564. case '\t':
  565. case '\n':
  566. case '\r':
  567. ++s;
  568. break;
  569. case '#':
  570. ++s;
  571. while (s < eos && *s && *s != '\n')
  572. ++s;
  573. }
  574. }
  575. return s;
  576. }
  577. /** Return a pointer to the first char of s that is not a space or a tab
  578. * or a \\r, or to the terminating NUL if no such character exists. */
  579. const char *
  580. eat_whitespace_no_nl(const char *s)
  581. {
  582. while (*s == ' ' || *s == '\t' || *s == '\r')
  583. ++s;
  584. return s;
  585. }
  586. /** As eat_whitespace_no_nl, but stop at <b>eos</b> whether we have
  587. * found a non-whitespace character or not. */
  588. const char *
  589. eat_whitespace_eos_no_nl(const char *s, const char *eos)
  590. {
  591. while (s < eos && (*s == ' ' || *s == '\t' || *s == '\r'))
  592. ++s;
  593. return s;
  594. }
  595. /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
  596. * or to the terminating NUL if no such character exists.
  597. */
  598. const char *
  599. find_whitespace(const char *s)
  600. {
  601. /* tor_assert(s); */
  602. while (1) {
  603. switch (*s)
  604. {
  605. case '\0':
  606. case '#':
  607. case ' ':
  608. case '\r':
  609. case '\n':
  610. case '\t':
  611. return s;
  612. default:
  613. ++s;
  614. }
  615. }
  616. }
  617. /** As find_whitespace, but stop at <b>eos</b> whether we have found a
  618. * whitespace or not. */
  619. const char *
  620. find_whitespace_eos(const char *s, const char *eos)
  621. {
  622. /* tor_assert(s); */
  623. while (s < eos) {
  624. switch (*s)
  625. {
  626. case '\0':
  627. case '#':
  628. case ' ':
  629. case '\r':
  630. case '\n':
  631. case '\t':
  632. return s;
  633. default:
  634. ++s;
  635. }
  636. }
  637. return s;
  638. }
  639. /** Return the first occurrence of <b>needle</b> in <b>haystack</b> that
  640. * occurs at the start of a line (that is, at the beginning of <b>haystack</b>
  641. * or immediately after a newline). Return NULL if no such string is found.
  642. */
  643. const char *
  644. find_str_at_start_of_line(const char *haystack, const char *needle)
  645. {
  646. size_t needle_len = strlen(needle);
  647. do {
  648. if (!strncmp(haystack, needle, needle_len))
  649. return haystack;
  650. haystack = strchr(haystack, '\n');
  651. if (!haystack)
  652. return NULL;
  653. else
  654. ++haystack;
  655. } while (*haystack);
  656. return NULL;
  657. }
  658. /** Return true iff the 'len' bytes at 'mem' are all zero. */
  659. int
  660. tor_mem_is_zero(const char *mem, size_t len)
  661. {
  662. static const char ZERO[] = {
  663. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0,
  664. };
  665. while (len >= sizeof(ZERO)) {
  666. /* It's safe to use fast_memcmp here, since the very worst thing an
  667. * attacker could learn is how many initial bytes of a secret were zero */
  668. if (fast_memcmp(mem, ZERO, sizeof(ZERO)))
  669. return 0;
  670. len -= sizeof(ZERO);
  671. mem += sizeof(ZERO);
  672. }
  673. /* Deal with leftover bytes. */
  674. if (len)
  675. return fast_memeq(mem, ZERO, len);
  676. return 1;
  677. }
  678. /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
  679. int
  680. tor_digest_is_zero(const char *digest)
  681. {
  682. static const uint8_t ZERO_DIGEST[] = {
  683. 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0
  684. };
  685. return tor_memeq(digest, ZERO_DIGEST, DIGEST_LEN);
  686. }
  687. /** Return true iff the DIGEST256_LEN bytes in digest are all zero. */
  688. int
  689. tor_digest256_is_zero(const char *digest)
  690. {
  691. return tor_mem_is_zero(digest, DIGEST256_LEN);
  692. }
  693. /* Helper: common code to check whether the result of a strtol or strtoul or
  694. * strtoll is correct. */
  695. #define CHECK_STRTOX_RESULT() \
  696. /* Was at least one character converted? */ \
  697. if (endptr == s) \
  698. goto err; \
  699. /* Were there unexpected unconverted characters? */ \
  700. if (!next && *endptr) \
  701. goto err; \
  702. /* Is r within limits? */ \
  703. if (r < min || r > max) \
  704. goto err; \
  705. if (ok) *ok = 1; \
  706. if (next) *next = endptr; \
  707. return r; \
  708. err: \
  709. if (ok) *ok = 0; \
  710. if (next) *next = endptr; \
  711. return 0
  712. /** Extract a long from the start of s, in the given numeric base. If
  713. * there is unconverted data and next is provided, set *next to the
  714. * first unconverted character. An error has occurred if no characters
  715. * are converted; or if there are unconverted characters and next is NULL; or
  716. * if the parsed value is not between min and max. When no error occurs,
  717. * return the parsed value and set *ok (if provided) to 1. When an error
  718. * occurs, return 0 and set *ok (if provided) to 0.
  719. */
  720. long
  721. tor_parse_long(const char *s, int base, long min, long max,
  722. int *ok, char **next)
  723. {
  724. char *endptr;
  725. long r;
  726. r = strtol(s, &endptr, base);
  727. CHECK_STRTOX_RESULT();
  728. }
  729. /** As tor_parse_long(), but return an unsigned long. */
  730. unsigned long
  731. tor_parse_ulong(const char *s, int base, unsigned long min,
  732. unsigned long max, int *ok, char **next)
  733. {
  734. char *endptr;
  735. unsigned long r;
  736. r = strtoul(s, &endptr, base);
  737. CHECK_STRTOX_RESULT();
  738. }
  739. /** As tor_parse_long(), but return a double. */
  740. double
  741. tor_parse_double(const char *s, double min, double max, int *ok, char **next)
  742. {
  743. char *endptr;
  744. double r;
  745. r = strtod(s, &endptr);
  746. CHECK_STRTOX_RESULT();
  747. }
  748. /** As tor_parse_long, but return a uint64_t. Only base 10 is guaranteed to
  749. * work for now. */
  750. uint64_t
  751. tor_parse_uint64(const char *s, int base, uint64_t min,
  752. uint64_t max, int *ok, char **next)
  753. {
  754. char *endptr;
  755. uint64_t r;
  756. #ifdef HAVE_STRTOULL
  757. r = (uint64_t)strtoull(s, &endptr, base);
  758. #elif defined(MS_WINDOWS)
  759. #if defined(_MSC_VER) && _MSC_VER < 1300
  760. tor_assert(base <= 10);
  761. r = (uint64_t)_atoi64(s);
  762. endptr = (char*)s;
  763. while (TOR_ISSPACE(*endptr)) endptr++;
  764. while (TOR_ISDIGIT(*endptr)) endptr++;
  765. #else
  766. r = (uint64_t)_strtoui64(s, &endptr, base);
  767. #endif
  768. #elif SIZEOF_LONG == 8
  769. r = (uint64_t)strtoul(s, &endptr, base);
  770. #else
  771. #error "I don't know how to parse 64-bit numbers."
  772. #endif
  773. CHECK_STRTOX_RESULT();
  774. }
  775. /** Encode the <b>srclen</b> bytes at <b>src</b> in a NUL-terminated,
  776. * uppercase hexadecimal string; store it in the <b>destlen</b>-byte buffer
  777. * <b>dest</b>.
  778. */
  779. void
  780. base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  781. {
  782. const char *end;
  783. char *cp;
  784. tor_assert(destlen >= srclen*2+1);
  785. tor_assert(destlen < SIZE_T_CEILING);
  786. cp = dest;
  787. end = src+srclen;
  788. while (src<end) {
  789. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) >> 4 ];
  790. *cp++ = "0123456789ABCDEF"[ (*(const uint8_t*)src) & 0xf ];
  791. ++src;
  792. }
  793. *cp = '\0';
  794. }
  795. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  796. static INLINE int
  797. _hex_decode_digit(char c)
  798. {
  799. switch (c) {
  800. case '0': return 0;
  801. case '1': return 1;
  802. case '2': return 2;
  803. case '3': return 3;
  804. case '4': return 4;
  805. case '5': return 5;
  806. case '6': return 6;
  807. case '7': return 7;
  808. case '8': return 8;
  809. case '9': return 9;
  810. case 'A': case 'a': return 10;
  811. case 'B': case 'b': return 11;
  812. case 'C': case 'c': return 12;
  813. case 'D': case 'd': return 13;
  814. case 'E': case 'e': return 14;
  815. case 'F': case 'f': return 15;
  816. default:
  817. return -1;
  818. }
  819. }
  820. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  821. int
  822. hex_decode_digit(char c)
  823. {
  824. return _hex_decode_digit(c);
  825. }
  826. /** Given a hexadecimal string of <b>srclen</b> bytes in <b>src</b>, decode it
  827. * and store the result in the <b>destlen</b>-byte buffer at <b>dest</b>.
  828. * Return 0 on success, -1 on failure. */
  829. int
  830. base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  831. {
  832. const char *end;
  833. int v1,v2;
  834. if ((srclen % 2) != 0)
  835. return -1;
  836. if (destlen < srclen/2 || destlen > SIZE_T_CEILING)
  837. return -1;
  838. end = src+srclen;
  839. while (src<end) {
  840. v1 = _hex_decode_digit(*src);
  841. v2 = _hex_decode_digit(*(src+1));
  842. if (v1<0||v2<0)
  843. return -1;
  844. *(uint8_t*)dest = (v1<<4)|v2;
  845. ++dest;
  846. src+=2;
  847. }
  848. return 0;
  849. }
  850. /** Allocate and return a new string representing the contents of <b>s</b>,
  851. * surrounded by quotes and using standard C escapes.
  852. *
  853. * Generally, we use this for logging values that come in over the network to
  854. * keep them from tricking users, and for sending certain values to the
  855. * controller.
  856. *
  857. * We trust values from the resolver, OS, configuration file, and command line
  858. * to not be maliciously ill-formed. We validate incoming routerdescs and
  859. * SOCKS requests and addresses from BEGIN cells as they're parsed;
  860. * afterwards, we trust them as non-malicious.
  861. */
  862. char *
  863. esc_for_log(const char *s)
  864. {
  865. const char *cp;
  866. char *result, *outp;
  867. size_t len = 3;
  868. if (!s) {
  869. return tor_strdup("(null)");
  870. }
  871. for (cp = s; *cp; ++cp) {
  872. switch (*cp) {
  873. case '\\':
  874. case '\"':
  875. case '\'':
  876. case '\r':
  877. case '\n':
  878. case '\t':
  879. len += 2;
  880. break;
  881. default:
  882. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127)
  883. ++len;
  884. else
  885. len += 4;
  886. break;
  887. }
  888. }
  889. result = outp = tor_malloc(len);
  890. *outp++ = '\"';
  891. for (cp = s; *cp; ++cp) {
  892. switch (*cp) {
  893. case '\\':
  894. case '\"':
  895. case '\'':
  896. *outp++ = '\\';
  897. *outp++ = *cp;
  898. break;
  899. case '\n':
  900. *outp++ = '\\';
  901. *outp++ = 'n';
  902. break;
  903. case '\t':
  904. *outp++ = '\\';
  905. *outp++ = 't';
  906. break;
  907. case '\r':
  908. *outp++ = '\\';
  909. *outp++ = 'r';
  910. break;
  911. default:
  912. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127) {
  913. *outp++ = *cp;
  914. } else {
  915. tor_snprintf(outp, 5, "\\%03o", (int)(uint8_t) *cp);
  916. outp += 4;
  917. }
  918. break;
  919. }
  920. }
  921. *outp++ = '\"';
  922. *outp++ = 0;
  923. return result;
  924. }
  925. /** Allocate and return a new string representing the contents of <b>s</b>,
  926. * surrounded by quotes and using standard C escapes.
  927. *
  928. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  929. * thread. Also, each call invalidates the last-returned value, so don't
  930. * try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));
  931. */
  932. const char *
  933. escaped(const char *s)
  934. {
  935. static char *_escaped_val = NULL;
  936. tor_free(_escaped_val);
  937. if (s)
  938. _escaped_val = esc_for_log(s);
  939. else
  940. _escaped_val = NULL;
  941. return _escaped_val;
  942. }
  943. /** Rudimentary string wrapping code: given a un-wrapped <b>string</b> (no
  944. * newlines!), break the string into newline-terminated lines of no more than
  945. * <b>width</b> characters long (not counting newline) and insert them into
  946. * <b>out</b> in order. Precede the first line with prefix0, and subsequent
  947. * lines with prefixRest.
  948. */
  949. /* This uses a stupid greedy wrapping algorithm right now:
  950. * - For each line:
  951. * - Try to fit as much stuff as possible, but break on a space.
  952. * - If the first "word" of the line will extend beyond the allowable
  953. * width, break the word at the end of the width.
  954. */
  955. void
  956. wrap_string(smartlist_t *out, const char *string, size_t width,
  957. const char *prefix0, const char *prefixRest)
  958. {
  959. size_t p0Len, pRestLen, pCurLen;
  960. const char *eos, *prefixCur;
  961. tor_assert(out);
  962. tor_assert(string);
  963. tor_assert(width);
  964. if (!prefix0)
  965. prefix0 = "";
  966. if (!prefixRest)
  967. prefixRest = "";
  968. p0Len = strlen(prefix0);
  969. pRestLen = strlen(prefixRest);
  970. tor_assert(width > p0Len && width > pRestLen);
  971. eos = strchr(string, '\0');
  972. tor_assert(eos);
  973. pCurLen = p0Len;
  974. prefixCur = prefix0;
  975. while ((eos-string)+pCurLen > width) {
  976. const char *eol = string + width - pCurLen;
  977. while (eol > string && *eol != ' ')
  978. --eol;
  979. /* eol is now the last space that can fit, or the start of the string. */
  980. if (eol > string) {
  981. size_t line_len = (eol-string) + pCurLen + 2;
  982. char *line = tor_malloc(line_len);
  983. memcpy(line, prefixCur, pCurLen);
  984. memcpy(line+pCurLen, string, eol-string);
  985. line[line_len-2] = '\n';
  986. line[line_len-1] = '\0';
  987. smartlist_add(out, line);
  988. string = eol + 1;
  989. } else {
  990. size_t line_len = width + 2;
  991. char *line = tor_malloc(line_len);
  992. memcpy(line, prefixCur, pCurLen);
  993. memcpy(line+pCurLen, string, width - pCurLen);
  994. line[line_len-2] = '\n';
  995. line[line_len-1] = '\0';
  996. smartlist_add(out, line);
  997. string += width-pCurLen;
  998. }
  999. prefixCur = prefixRest;
  1000. pCurLen = pRestLen;
  1001. }
  1002. if (string < eos) {
  1003. size_t line_len = (eos-string) + pCurLen + 2;
  1004. char *line = tor_malloc(line_len);
  1005. memcpy(line, prefixCur, pCurLen);
  1006. memcpy(line+pCurLen, string, eos-string);
  1007. line[line_len-2] = '\n';
  1008. line[line_len-1] = '\0';
  1009. smartlist_add(out, line);
  1010. }
  1011. }
  1012. /* =====
  1013. * Time
  1014. * ===== */
  1015. /**
  1016. * Converts struct timeval to a double value.
  1017. * Preserves microsecond precision, but just barely.
  1018. * Error is approx +/- 0.1 usec when dealing with epoch values.
  1019. */
  1020. double
  1021. tv_to_double(const struct timeval *tv)
  1022. {
  1023. double conv = tv->tv_sec;
  1024. conv += tv->tv_usec/1000000.0;
  1025. return conv;
  1026. }
  1027. /**
  1028. * Converts timeval to milliseconds.
  1029. */
  1030. int64_t
  1031. tv_to_msec(const struct timeval *tv)
  1032. {
  1033. int64_t conv = ((int64_t)tv->tv_sec)*1000L;
  1034. /* Round ghetto-style */
  1035. conv += ((int64_t)tv->tv_usec+500)/1000L;
  1036. return conv;
  1037. }
  1038. /**
  1039. * Converts timeval to microseconds.
  1040. */
  1041. int64_t
  1042. tv_to_usec(const struct timeval *tv)
  1043. {
  1044. int64_t conv = ((int64_t)tv->tv_sec)*1000000L;
  1045. conv += tv->tv_usec;
  1046. return conv;
  1047. }
  1048. /** Return the number of microseconds elapsed between *start and *end.
  1049. */
  1050. long
  1051. tv_udiff(const struct timeval *start, const struct timeval *end)
  1052. {
  1053. long udiff;
  1054. long secdiff = end->tv_sec - start->tv_sec;
  1055. if (labs(secdiff+1) > LONG_MAX/1000000) {
  1056. log_warn(LD_GENERAL, "comparing times on microsecond detail too far "
  1057. "apart: %ld seconds", secdiff);
  1058. return LONG_MAX;
  1059. }
  1060. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  1061. return udiff;
  1062. }
  1063. /** Return the number of milliseconds elapsed between *start and *end.
  1064. */
  1065. long
  1066. tv_mdiff(const struct timeval *start, const struct timeval *end)
  1067. {
  1068. long mdiff;
  1069. long secdiff = end->tv_sec - start->tv_sec;
  1070. if (labs(secdiff+1) > LONG_MAX/1000) {
  1071. log_warn(LD_GENERAL, "comparing times on millisecond detail too far "
  1072. "apart: %ld seconds", secdiff);
  1073. return LONG_MAX;
  1074. }
  1075. /* Subtract and round */
  1076. mdiff = secdiff*1000L +
  1077. ((long)end->tv_usec - (long)start->tv_usec + 500L) / 1000L;
  1078. return mdiff;
  1079. }
  1080. /** Yield true iff <b>y</b> is a leap-year. */
  1081. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  1082. /** Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2. */
  1083. static int
  1084. n_leapdays(int y1, int y2)
  1085. {
  1086. --y1;
  1087. --y2;
  1088. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  1089. }
  1090. /** Number of days per month in non-leap year; used by tor_timegm. */
  1091. static const int days_per_month[] =
  1092. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  1093. /** Return a time_t given a struct tm. The result is given in GMT, and
  1094. * does not account for leap seconds.
  1095. */
  1096. time_t
  1097. tor_timegm(struct tm *tm)
  1098. {
  1099. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  1100. * It's way more brute-force than fiddling with tzset().
  1101. */
  1102. time_t year, days, hours, minutes, seconds;
  1103. int i;
  1104. year = tm->tm_year + 1900;
  1105. if (year < 1970 || tm->tm_mon < 0 || tm->tm_mon > 11) {
  1106. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  1107. return -1;
  1108. }
  1109. tor_assert(year < INT_MAX);
  1110. days = 365 * (year-1970) + n_leapdays(1970,(int)year);
  1111. for (i = 0; i < tm->tm_mon; ++i)
  1112. days += days_per_month[i];
  1113. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  1114. ++days;
  1115. days += tm->tm_mday - 1;
  1116. hours = days*24 + tm->tm_hour;
  1117. minutes = hours*60 + tm->tm_min;
  1118. seconds = minutes*60 + tm->tm_sec;
  1119. return seconds;
  1120. }
  1121. /* strftime is locale-specific, so we need to replace those parts */
  1122. /** A c-locale array of 3-letter names of weekdays, starting with Sun. */
  1123. static const char *WEEKDAY_NAMES[] =
  1124. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1125. /** A c-locale array of 3-letter names of months, starting with Jan. */
  1126. static const char *MONTH_NAMES[] =
  1127. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  1128. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1129. /** Set <b>buf</b> to the RFC1123 encoding of the GMT value of <b>t</b>.
  1130. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  1131. *
  1132. * (RFC1123 format is Fri, 29 Sep 2006 15:54:20 GMT)
  1133. */
  1134. void
  1135. format_rfc1123_time(char *buf, time_t t)
  1136. {
  1137. struct tm tm;
  1138. tor_gmtime_r(&t, &tm);
  1139. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  1140. tor_assert(tm.tm_wday >= 0);
  1141. tor_assert(tm.tm_wday <= 6);
  1142. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  1143. tor_assert(tm.tm_wday >= 0);
  1144. tor_assert(tm.tm_mon <= 11);
  1145. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  1146. }
  1147. /** Parse the RFC1123 encoding of some time (in GMT) from <b>buf</b>,
  1148. * and store the result in *<b>t</b>.
  1149. *
  1150. * Return 0 on success, -1 on failure.
  1151. */
  1152. int
  1153. parse_rfc1123_time(const char *buf, time_t *t)
  1154. {
  1155. struct tm tm;
  1156. char month[4];
  1157. char weekday[4];
  1158. int i, m;
  1159. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1160. if (strlen(buf) != RFC1123_TIME_LEN)
  1161. return -1;
  1162. memset(&tm, 0, sizeof(tm));
  1163. if (tor_sscanf(buf, "%3s, %2u %3s %u %2u:%2u:%2u GMT", weekday,
  1164. &tm_mday, month, &tm_year, &tm_hour,
  1165. &tm_min, &tm_sec) < 7) {
  1166. char *esc = esc_for_log(buf);
  1167. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1168. tor_free(esc);
  1169. return -1;
  1170. }
  1171. if (tm_mday > 31 || tm_hour > 23 || tm_min > 59 || tm_sec > 61) {
  1172. char *esc = esc_for_log(buf);
  1173. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  1174. tor_free(esc);
  1175. return -1;
  1176. }
  1177. tm.tm_mday = (int)tm_mday;
  1178. tm.tm_year = (int)tm_year;
  1179. tm.tm_hour = (int)tm_hour;
  1180. tm.tm_min = (int)tm_min;
  1181. tm.tm_sec = (int)tm_sec;
  1182. m = -1;
  1183. for (i = 0; i < 12; ++i) {
  1184. if (!strcmp(month, MONTH_NAMES[i])) {
  1185. m = i;
  1186. break;
  1187. }
  1188. }
  1189. if (m<0) {
  1190. char *esc = esc_for_log(buf);
  1191. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  1192. tor_free(esc);
  1193. return -1;
  1194. }
  1195. tm.tm_mon = m;
  1196. if (tm.tm_year < 1970) {
  1197. char *esc = esc_for_log(buf);
  1198. log_warn(LD_GENERAL,
  1199. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  1200. tor_free(esc);
  1201. return -1;
  1202. }
  1203. tm.tm_year -= 1900;
  1204. *t = tor_timegm(&tm);
  1205. return 0;
  1206. }
  1207. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  1208. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1209. *
  1210. * (ISO8601 format is 2006-10-29 10:57:20)
  1211. */
  1212. void
  1213. format_local_iso_time(char *buf, time_t t)
  1214. {
  1215. struct tm tm;
  1216. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  1217. }
  1218. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  1219. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  1220. */
  1221. void
  1222. format_iso_time(char *buf, time_t t)
  1223. {
  1224. struct tm tm;
  1225. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  1226. }
  1227. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  1228. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  1229. * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
  1230. * the end of the time string. */
  1231. int
  1232. parse_iso_time(const char *cp, time_t *t)
  1233. {
  1234. struct tm st_tm;
  1235. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  1236. if (tor_sscanf(cp, "%u-%2u-%2u %2u:%2u:%2u", &year, &month,
  1237. &day, &hour, &minute, &second) < 6) {
  1238. char *esc = esc_for_log(cp);
  1239. log_warn(LD_GENERAL, "ISO time %s was unparseable", esc);
  1240. tor_free(esc);
  1241. return -1;
  1242. }
  1243. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  1244. hour > 23 || minute > 59 || second > 61) {
  1245. char *esc = esc_for_log(cp);
  1246. log_warn(LD_GENERAL, "ISO time %s was nonsensical", esc);
  1247. tor_free(esc);
  1248. return -1;
  1249. }
  1250. st_tm.tm_year = year-1900;
  1251. st_tm.tm_mon = month-1;
  1252. st_tm.tm_mday = day;
  1253. st_tm.tm_hour = hour;
  1254. st_tm.tm_min = minute;
  1255. st_tm.tm_sec = second;
  1256. if (st_tm.tm_year < 70) {
  1257. char *esc = esc_for_log(cp);
  1258. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  1259. tor_free(esc);
  1260. return -1;
  1261. }
  1262. *t = tor_timegm(&st_tm);
  1263. return 0;
  1264. }
  1265. /** Given a <b>date</b> in one of the three formats allowed by HTTP (ugh),
  1266. * parse it into <b>tm</b>. Return 0 on success, negative on failure. */
  1267. int
  1268. parse_http_time(const char *date, struct tm *tm)
  1269. {
  1270. const char *cp;
  1271. char month[4];
  1272. char wkday[4];
  1273. int i;
  1274. unsigned tm_mday, tm_year, tm_hour, tm_min, tm_sec;
  1275. tor_assert(tm);
  1276. memset(tm, 0, sizeof(*tm));
  1277. /* First, try RFC1123 or RFC850 format: skip the weekday. */
  1278. if ((cp = strchr(date, ','))) {
  1279. ++cp;
  1280. if (tor_sscanf(date, "%2u %3s %4u %2u:%2u:%2u GMT",
  1281. &tm_mday, month, &tm_year,
  1282. &tm_hour, &tm_min, &tm_sec) == 6) {
  1283. /* rfc1123-date */
  1284. tm_year -= 1900;
  1285. } else if (tor_sscanf(date, "%2u-%3s-%2u %2u:%2u:%2u GMT",
  1286. &tm_mday, month, &tm_year,
  1287. &tm_hour, &tm_min, &tm_sec) == 6) {
  1288. /* rfc850-date */
  1289. } else {
  1290. return -1;
  1291. }
  1292. } else {
  1293. /* No comma; possibly asctime() format. */
  1294. if (tor_sscanf(date, "%3s %3s %2u %2u:%2u:%2u %4u",
  1295. wkday, month, &tm_mday,
  1296. &tm_hour, &tm_min, &tm_sec, &tm_year) == 7) {
  1297. tm_year -= 1900;
  1298. } else {
  1299. return -1;
  1300. }
  1301. }
  1302. tm->tm_mday = (int)tm_mday;
  1303. tm->tm_year = (int)tm_year;
  1304. tm->tm_hour = (int)tm_hour;
  1305. tm->tm_min = (int)tm_min;
  1306. tm->tm_sec = (int)tm_sec;
  1307. month[3] = '\0';
  1308. /* Okay, now decode the month. */
  1309. for (i = 0; i < 12; ++i) {
  1310. if (!strcasecmp(MONTH_NAMES[i], month)) {
  1311. tm->tm_mon = i+1;
  1312. }
  1313. }
  1314. if (tm->tm_year < 0 ||
  1315. tm->tm_mon < 1 || tm->tm_mon > 12 ||
  1316. tm->tm_mday < 0 || tm->tm_mday > 31 ||
  1317. tm->tm_hour < 0 || tm->tm_hour > 23 ||
  1318. tm->tm_min < 0 || tm->tm_min > 59 ||
  1319. tm->tm_sec < 0 || tm->tm_sec > 61)
  1320. return -1; /* Out of range, or bad month. */
  1321. return 0;
  1322. }
  1323. /** Given an <b>interval</b> in seconds, try to write it to the
  1324. * <b>out_len</b>-byte buffer in <b>out</b> in a human-readable form.
  1325. * Return 0 on success, -1 on failure.
  1326. */
  1327. int
  1328. format_time_interval(char *out, size_t out_len, long interval)
  1329. {
  1330. /* We only report seconds if there's no hours. */
  1331. long sec = 0, min = 0, hour = 0, day = 0;
  1332. if (interval < 0)
  1333. interval = -interval;
  1334. if (interval >= 86400) {
  1335. day = interval / 86400;
  1336. interval %= 86400;
  1337. }
  1338. if (interval >= 3600) {
  1339. hour = interval / 3600;
  1340. interval %= 3600;
  1341. }
  1342. if (interval >= 60) {
  1343. min = interval / 60;
  1344. interval %= 60;
  1345. }
  1346. sec = interval;
  1347. if (day) {
  1348. return tor_snprintf(out, out_len, "%ld days, %ld hours, %ld minutes",
  1349. day, hour, min);
  1350. } else if (hour) {
  1351. return tor_snprintf(out, out_len, "%ld hours, %ld minutes", hour, min);
  1352. } else if (min) {
  1353. return tor_snprintf(out, out_len, "%ld minutes, %ld seconds", min, sec);
  1354. } else {
  1355. return tor_snprintf(out, out_len, "%ld seconds", sec);
  1356. }
  1357. }
  1358. /* =====
  1359. * Cached time
  1360. * ===== */
  1361. #ifndef TIME_IS_FAST
  1362. /** Cached estimate of the current time. Updated around once per second;
  1363. * may be a few seconds off if we are really busy. This is a hack to avoid
  1364. * calling time(NULL) (which not everybody has optimized) on critical paths.
  1365. */
  1366. static time_t cached_approx_time = 0;
  1367. /** Return a cached estimate of the current time from when
  1368. * update_approx_time() was last called. This is a hack to avoid calling
  1369. * time(NULL) on critical paths: please do not even think of calling it
  1370. * anywhere else. */
  1371. time_t
  1372. approx_time(void)
  1373. {
  1374. return cached_approx_time;
  1375. }
  1376. /** Update the cached estimate of the current time. This function SHOULD be
  1377. * called once per second, and MUST be called before the first call to
  1378. * get_approx_time. */
  1379. void
  1380. update_approx_time(time_t now)
  1381. {
  1382. cached_approx_time = now;
  1383. }
  1384. #endif
  1385. /* =====
  1386. * Rate limiting
  1387. * ===== */
  1388. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return the number
  1389. * of calls to rate_limit_is_ready (including this one!) since the last time
  1390. * rate_limit_is_ready returned nonzero. Otherwise return 0. */
  1391. static int
  1392. rate_limit_is_ready(ratelim_t *lim, time_t now)
  1393. {
  1394. if (lim->rate + lim->last_allowed <= now) {
  1395. int res = lim->n_calls_since_last_time + 1;
  1396. lim->last_allowed = now;
  1397. lim->n_calls_since_last_time = 0;
  1398. return res;
  1399. } else {
  1400. ++lim->n_calls_since_last_time;
  1401. return 0;
  1402. }
  1403. }
  1404. /** If the rate-limiter <b>lim</b> is ready at <b>now</b>, return a newly
  1405. * allocated string indicating how many messages were suppressed, suitable to
  1406. * append to a log message. Otherwise return NULL. */
  1407. char *
  1408. rate_limit_log(ratelim_t *lim, time_t now)
  1409. {
  1410. int n;
  1411. if ((n = rate_limit_is_ready(lim, now))) {
  1412. if (n == 1) {
  1413. return tor_strdup("");
  1414. } else {
  1415. char *cp=NULL;
  1416. tor_asprintf(&cp,
  1417. " [%d similar message(s) suppressed in last %d seconds]",
  1418. n-1, lim->rate);
  1419. return cp;
  1420. }
  1421. } else {
  1422. return NULL;
  1423. }
  1424. }
  1425. /* =====
  1426. * File helpers
  1427. * ===== */
  1428. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1429. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1430. * was returned by open(). Return the number of bytes written, or -1
  1431. * on error. Only use if fd is a blocking fd. */
  1432. ssize_t
  1433. write_all(int fd, const char *buf, size_t count, int isSocket)
  1434. {
  1435. size_t written = 0;
  1436. ssize_t result;
  1437. tor_assert(count < SSIZE_T_MAX);
  1438. while (written != count) {
  1439. if (isSocket)
  1440. result = tor_socket_send(fd, buf+written, count-written, 0);
  1441. else
  1442. result = write(fd, buf+written, count-written);
  1443. if (result<0)
  1444. return -1;
  1445. written += result;
  1446. }
  1447. return (ssize_t)count;
  1448. }
  1449. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1450. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1451. * was returned by socket() or accept(), and 0 if fd was returned by
  1452. * open(). Return the number of bytes read, or -1 on error. Only use
  1453. * if fd is a blocking fd. */
  1454. ssize_t
  1455. read_all(int fd, char *buf, size_t count, int isSocket)
  1456. {
  1457. size_t numread = 0;
  1458. ssize_t result;
  1459. if (count > SIZE_T_CEILING || count > SSIZE_T_MAX)
  1460. return -1;
  1461. while (numread != count) {
  1462. if (isSocket)
  1463. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1464. else
  1465. result = read(fd, buf+numread, count-numread);
  1466. if (result<0)
  1467. return -1;
  1468. else if (result == 0)
  1469. break;
  1470. numread += result;
  1471. }
  1472. return (ssize_t)numread;
  1473. }
  1474. /*
  1475. * Filesystem operations.
  1476. */
  1477. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1478. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1479. * the root of a disk. */
  1480. static void
  1481. clean_name_for_stat(char *name)
  1482. {
  1483. #ifdef MS_WINDOWS
  1484. size_t len = strlen(name);
  1485. if (!len)
  1486. return;
  1487. if (name[len-1]=='\\' || name[len-1]=='/') {
  1488. if (len == 1 || (len==3 && name[1]==':'))
  1489. return;
  1490. name[len-1]='\0';
  1491. }
  1492. #else
  1493. (void)name;
  1494. #endif
  1495. }
  1496. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1497. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1498. * directory. On FN_ERROR, sets errno. */
  1499. file_status_t
  1500. file_status(const char *fname)
  1501. {
  1502. struct stat st;
  1503. char *f;
  1504. int r;
  1505. f = tor_strdup(fname);
  1506. clean_name_for_stat(f);
  1507. r = stat(f, &st);
  1508. tor_free(f);
  1509. if (r) {
  1510. if (errno == ENOENT) {
  1511. return FN_NOENT;
  1512. }
  1513. return FN_ERROR;
  1514. }
  1515. if (st.st_mode & S_IFDIR)
  1516. return FN_DIR;
  1517. else if (st.st_mode & S_IFREG)
  1518. return FN_FILE;
  1519. else
  1520. return FN_ERROR;
  1521. }
  1522. /** Check whether <b>dirname</b> exists and is private. If yes return 0. If
  1523. * it does not exist, and <b>check</b>&CPD_CREATE is set, try to create it
  1524. * and return 0 on success. If it does not exist, and
  1525. * <b>check</b>&CPD_CHECK, and we think we can create it, return 0. Else
  1526. * return -1. If CPD_GROUP_OK is set, then it's okay if the directory
  1527. * is group-readable, but in all cases we create the directory mode 0700.
  1528. * If CPD_CHECK_MODE_ONLY is set, then we don't alter the directory permissions
  1529. * if they are too permissive: we just return -1.
  1530. */
  1531. int
  1532. check_private_dir(const char *dirname, cpd_check_t check)
  1533. {
  1534. int r;
  1535. struct stat st;
  1536. char *f;
  1537. #ifndef MS_WINDOWS
  1538. int mask;
  1539. #endif
  1540. tor_assert(dirname);
  1541. f = tor_strdup(dirname);
  1542. clean_name_for_stat(f);
  1543. r = stat(f, &st);
  1544. tor_free(f);
  1545. if (r) {
  1546. if (errno != ENOENT) {
  1547. log_warn(LD_FS, "Directory %s cannot be read: %s", dirname,
  1548. strerror(errno));
  1549. return -1;
  1550. }
  1551. if (check & CPD_CREATE) {
  1552. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1553. #if defined (MS_WINDOWS) && !defined (WINCE)
  1554. r = mkdir(dirname);
  1555. #else
  1556. r = mkdir(dirname, 0700);
  1557. #endif
  1558. if (r) {
  1559. log_warn(LD_FS, "Error creating directory %s: %s", dirname,
  1560. strerror(errno));
  1561. return -1;
  1562. }
  1563. } else if (!(check & CPD_CHECK)) {
  1564. log_warn(LD_FS, "Directory %s does not exist.", dirname);
  1565. return -1;
  1566. }
  1567. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1568. * parent directory a little harder. */
  1569. return 0;
  1570. }
  1571. if (!(st.st_mode & S_IFDIR)) {
  1572. log_warn(LD_FS, "%s is not a directory", dirname);
  1573. return -1;
  1574. }
  1575. #ifndef MS_WINDOWS
  1576. if (st.st_uid != getuid()) {
  1577. struct passwd *pw = NULL;
  1578. char *process_ownername = NULL;
  1579. pw = getpwuid(getuid());
  1580. process_ownername = pw ? tor_strdup(pw->pw_name) : tor_strdup("<unknown>");
  1581. pw = getpwuid(st.st_uid);
  1582. log_warn(LD_FS, "%s is not owned by this user (%s, %d) but by "
  1583. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1584. dirname, process_ownername, (int)getuid(),
  1585. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  1586. tor_free(process_ownername);
  1587. return -1;
  1588. }
  1589. if ((check & CPD_GROUP_OK) && st.st_gid != getgid()) {
  1590. struct group *gr;
  1591. char *process_groupname = NULL;
  1592. gr = getgrgid(getgid());
  1593. process_groupname = gr ? tor_strdup(gr->gr_name) : tor_strdup("<unknown>");
  1594. gr = getgrgid(st.st_gid);
  1595. log_warn(LD_FS, "%s is not owned by this group (%s, %d) but by group "
  1596. "%s (%d). Are you running Tor as the wrong user?",
  1597. dirname, process_groupname, (int)getgid(),
  1598. gr ? gr->gr_name : "<unknown>", (int)st.st_gid);
  1599. tor_free(process_groupname);
  1600. return -1;
  1601. }
  1602. if (check & CPD_GROUP_OK) {
  1603. mask = 0027;
  1604. } else {
  1605. mask = 0077;
  1606. }
  1607. if (st.st_mode & mask) {
  1608. unsigned new_mode;
  1609. if (check & CPD_CHECK_MODE_ONLY) {
  1610. log_warn(LD_FS, "Permissions on directory %s are too permissive.",
  1611. dirname);
  1612. return -1;
  1613. }
  1614. log_warn(LD_FS, "Fixing permissions on directory %s", dirname);
  1615. new_mode = st.st_mode;
  1616. new_mode |= 0700; /* Owner should have rwx */
  1617. new_mode &= ~mask; /* Clear the other bits that we didn't want set...*/
  1618. if (chmod(dirname, new_mode)) {
  1619. log_warn(LD_FS, "Could not chmod directory %s: %s", dirname,
  1620. strerror(errno));
  1621. return -1;
  1622. } else {
  1623. return 0;
  1624. }
  1625. }
  1626. #endif
  1627. return 0;
  1628. }
  1629. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1630. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1631. *
  1632. * This function replaces the old file atomically, if possible. This
  1633. * function, and all other functions in util.c that create files, create them
  1634. * with mode 0600.
  1635. */
  1636. int
  1637. write_str_to_file(const char *fname, const char *str, int bin)
  1638. {
  1639. #ifdef MS_WINDOWS
  1640. if (!bin && strchr(str, '\r')) {
  1641. log_warn(LD_BUG,
  1642. "We're writing a text string that already contains a CR.");
  1643. }
  1644. #endif
  1645. return write_bytes_to_file(fname, str, strlen(str), bin);
  1646. }
  1647. /** Represents a file that we're writing to, with support for atomic commit:
  1648. * we can write into a temporary file, and either remove the file on
  1649. * failure, or replace the original file on success. */
  1650. struct open_file_t {
  1651. char *tempname; /**< Name of the temporary file. */
  1652. char *filename; /**< Name of the original file. */
  1653. unsigned rename_on_close:1; /**< Are we using the temporary file or not? */
  1654. unsigned binary:1; /**< Did we open in binary mode? */
  1655. int fd; /**< fd for the open file. */
  1656. FILE *stdio_file; /**< stdio wrapper for <b>fd</b>. */
  1657. };
  1658. /** Try to start writing to the file in <b>fname</b>, passing the flags
  1659. * <b>open_flags</b> to the open() syscall, creating the file (if needed) with
  1660. * access value <b>mode</b>. If the O_APPEND flag is set, we append to the
  1661. * original file. Otherwise, we open a new temporary file in the same
  1662. * directory, and either replace the original or remove the temporary file
  1663. * when we're done.
  1664. *
  1665. * Return the fd for the newly opened file, and store working data in
  1666. * *<b>data_out</b>. The caller should not close the fd manually:
  1667. * instead, call finish_writing_to_file() or abort_writing_to_file().
  1668. * Returns -1 on failure.
  1669. *
  1670. * NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated
  1671. * as true and the flag O_EXCL is treated as false.
  1672. *
  1673. * NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each
  1674. * write()". We don't do that.
  1675. */
  1676. int
  1677. start_writing_to_file(const char *fname, int open_flags, int mode,
  1678. open_file_t **data_out)
  1679. {
  1680. size_t tempname_len = strlen(fname)+16;
  1681. open_file_t *new_file = tor_malloc_zero(sizeof(open_file_t));
  1682. const char *open_name;
  1683. int append = 0;
  1684. tor_assert(fname);
  1685. tor_assert(data_out);
  1686. #if (O_BINARY != 0 && O_TEXT != 0)
  1687. tor_assert((open_flags & (O_BINARY|O_TEXT)) != 0);
  1688. #endif
  1689. new_file->fd = -1;
  1690. tor_assert(tempname_len > strlen(fname)); /*check for overflow*/
  1691. new_file->filename = tor_strdup(fname);
  1692. if (open_flags & O_APPEND) {
  1693. open_name = fname;
  1694. new_file->rename_on_close = 0;
  1695. append = 1;
  1696. open_flags &= ~O_APPEND;
  1697. } else {
  1698. open_name = new_file->tempname = tor_malloc(tempname_len);
  1699. if (tor_snprintf(new_file->tempname, tempname_len, "%s.tmp", fname)<0) {
  1700. log_warn(LD_GENERAL, "Failed to generate filename");
  1701. goto err;
  1702. }
  1703. /* We always replace an existing temporary file if there is one. */
  1704. open_flags |= O_CREAT|O_TRUNC;
  1705. open_flags &= ~O_EXCL;
  1706. new_file->rename_on_close = 1;
  1707. }
  1708. if (open_flags & O_BINARY)
  1709. new_file->binary = 1;
  1710. new_file->fd = tor_open_cloexec(open_name, open_flags, mode);
  1711. if (new_file->fd < 0) {
  1712. log_warn(LD_FS, "Couldn't open \"%s\" (%s) for writing: %s",
  1713. open_name, fname, strerror(errno));
  1714. goto err;
  1715. }
  1716. if (append) {
  1717. if (tor_fd_seekend(new_file->fd) < 0) {
  1718. log_warn(LD_FS, "Couldn't seek to end of file \"%s\": %s", open_name,
  1719. strerror(errno));
  1720. goto err;
  1721. }
  1722. }
  1723. *data_out = new_file;
  1724. return new_file->fd;
  1725. err:
  1726. if (new_file->fd >= 0)
  1727. close(new_file->fd);
  1728. *data_out = NULL;
  1729. tor_free(new_file->filename);
  1730. tor_free(new_file->tempname);
  1731. tor_free(new_file);
  1732. return -1;
  1733. }
  1734. /** Given <b>file_data</b> from start_writing_to_file(), return a stdio FILE*
  1735. * that can be used to write to the same file. The caller should not mix
  1736. * stdio calls with non-stdio calls. */
  1737. FILE *
  1738. fdopen_file(open_file_t *file_data)
  1739. {
  1740. tor_assert(file_data);
  1741. if (file_data->stdio_file)
  1742. return file_data->stdio_file;
  1743. tor_assert(file_data->fd >= 0);
  1744. if (!(file_data->stdio_file = fdopen(file_data->fd,
  1745. file_data->binary?"ab":"a"))) {
  1746. log_warn(LD_FS, "Couldn't fdopen \"%s\" [%d]: %s", file_data->filename,
  1747. file_data->fd, strerror(errno));
  1748. }
  1749. return file_data->stdio_file;
  1750. }
  1751. /** Combines start_writing_to_file with fdopen_file(): arguments are as
  1752. * for start_writing_to_file, but */
  1753. FILE *
  1754. start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  1755. open_file_t **data_out)
  1756. {
  1757. FILE *res;
  1758. if (start_writing_to_file(fname, open_flags, mode, data_out)<0)
  1759. return NULL;
  1760. if (!(res = fdopen_file(*data_out))) {
  1761. abort_writing_to_file(*data_out);
  1762. *data_out = NULL;
  1763. }
  1764. return res;
  1765. }
  1766. /** Helper function: close and free the underlying file and memory in
  1767. * <b>file_data</b>. If we were writing into a temporary file, then delete
  1768. * that file (if abort_write is true) or replaces the target file with
  1769. * the temporary file (if abort_write is false). */
  1770. static int
  1771. finish_writing_to_file_impl(open_file_t *file_data, int abort_write)
  1772. {
  1773. int r = 0;
  1774. tor_assert(file_data && file_data->filename);
  1775. if (file_data->stdio_file) {
  1776. if (fclose(file_data->stdio_file)) {
  1777. log_warn(LD_FS, "Error closing \"%s\": %s", file_data->filename,
  1778. strerror(errno));
  1779. abort_write = r = -1;
  1780. }
  1781. } else if (file_data->fd >= 0 && close(file_data->fd) < 0) {
  1782. log_warn(LD_FS, "Error flushing \"%s\": %s", file_data->filename,
  1783. strerror(errno));
  1784. abort_write = r = -1;
  1785. }
  1786. if (file_data->rename_on_close) {
  1787. tor_assert(file_data->tempname && file_data->filename);
  1788. if (abort_write) {
  1789. unlink(file_data->tempname);
  1790. } else {
  1791. tor_assert(strcmp(file_data->filename, file_data->tempname));
  1792. if (replace_file(file_data->tempname, file_data->filename)) {
  1793. log_warn(LD_FS, "Error replacing \"%s\": %s", file_data->filename,
  1794. strerror(errno));
  1795. r = -1;
  1796. }
  1797. }
  1798. }
  1799. tor_free(file_data->filename);
  1800. tor_free(file_data->tempname);
  1801. tor_free(file_data);
  1802. return r;
  1803. }
  1804. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1805. * needed, and if using a temporary file, replace the original file with
  1806. * the temporary file. */
  1807. int
  1808. finish_writing_to_file(open_file_t *file_data)
  1809. {
  1810. return finish_writing_to_file_impl(file_data, 0);
  1811. }
  1812. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1813. * needed, and if using a temporary file, delete it. */
  1814. int
  1815. abort_writing_to_file(open_file_t *file_data)
  1816. {
  1817. return finish_writing_to_file_impl(file_data, 1);
  1818. }
  1819. /** Helper: given a set of flags as passed to open(2), open the file
  1820. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1821. * the file. Do so as atomically as possible e.g. by opening temp files and
  1822. * renaming. */
  1823. static int
  1824. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1825. int open_flags)
  1826. {
  1827. open_file_t *file = NULL;
  1828. int fd;
  1829. ssize_t result;
  1830. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  1831. if (fd<0)
  1832. return -1;
  1833. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1834. {
  1835. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1836. if (result < 0) {
  1837. log_warn(LD_FS, "Error writing to \"%s\": %s", fname,
  1838. strerror(errno));
  1839. goto err;
  1840. }
  1841. tor_assert((size_t)result == chunk->len);
  1842. });
  1843. return finish_writing_to_file(file);
  1844. err:
  1845. abort_writing_to_file(file);
  1846. return -1;
  1847. }
  1848. /** Given a smartlist of sized_chunk_t, write them atomically to a file
  1849. * <b>fname</b>, overwriting or creating the file as necessary. */
  1850. int
  1851. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
  1852. {
  1853. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1854. return write_chunks_to_file_impl(fname, chunks, flags);
  1855. }
  1856. /** As write_str_to_file, but does not assume a NUL-terminated
  1857. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  1858. int
  1859. write_bytes_to_file(const char *fname, const char *str, size_t len,
  1860. int bin)
  1861. {
  1862. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1863. int r;
  1864. sized_chunk_t c = { str, len };
  1865. smartlist_t *chunks = smartlist_create();
  1866. smartlist_add(chunks, &c);
  1867. r = write_chunks_to_file_impl(fname, chunks, flags);
  1868. smartlist_free(chunks);
  1869. return r;
  1870. }
  1871. /** As write_bytes_to_file, but if the file already exists, append the bytes
  1872. * to the end of the file instead of overwriting it. */
  1873. int
  1874. append_bytes_to_file(const char *fname, const char *str, size_t len,
  1875. int bin)
  1876. {
  1877. int flags = OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT);
  1878. int r;
  1879. sized_chunk_t c = { str, len };
  1880. smartlist_t *chunks = smartlist_create();
  1881. smartlist_add(chunks, &c);
  1882. r = write_chunks_to_file_impl(fname, chunks, flags);
  1883. smartlist_free(chunks);
  1884. return r;
  1885. }
  1886. /** Read the contents of <b>filename</b> into a newly allocated
  1887. * string; return the string on success or NULL on failure.
  1888. *
  1889. * If <b>stat_out</b> is provided, store the result of stat()ing the
  1890. * file into <b>stat_out</b>.
  1891. *
  1892. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  1893. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  1894. * doesn't exist.
  1895. */
  1896. /*
  1897. * This function <em>may</em> return an erroneous result if the file
  1898. * is modified while it is running, but must not crash or overflow.
  1899. * Right now, the error case occurs when the file length grows between
  1900. * the call to stat and the call to read_all: the resulting string will
  1901. * be truncated.
  1902. */
  1903. char *
  1904. read_file_to_str(const char *filename, int flags, struct stat *stat_out)
  1905. {
  1906. int fd; /* router file */
  1907. struct stat statbuf;
  1908. char *string;
  1909. ssize_t r;
  1910. int bin = flags & RFTS_BIN;
  1911. tor_assert(filename);
  1912. fd = tor_open_cloexec(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  1913. if (fd<0) {
  1914. int severity = LOG_WARN;
  1915. int save_errno = errno;
  1916. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  1917. severity = LOG_INFO;
  1918. log_fn(severity, LD_FS,"Could not open \"%s\": %s",filename,
  1919. strerror(errno));
  1920. errno = save_errno;
  1921. return NULL;
  1922. }
  1923. if (fstat(fd, &statbuf)<0) {
  1924. int save_errno = errno;
  1925. close(fd);
  1926. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  1927. errno = save_errno;
  1928. return NULL;
  1929. }
  1930. if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING)
  1931. return NULL;
  1932. string = tor_malloc((size_t)(statbuf.st_size+1));
  1933. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  1934. if (r<0) {
  1935. int save_errno = errno;
  1936. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  1937. strerror(errno));
  1938. tor_free(string);
  1939. close(fd);
  1940. errno = save_errno;
  1941. return NULL;
  1942. }
  1943. string[r] = '\0'; /* NUL-terminate the result. */
  1944. #ifdef MS_WINDOWS
  1945. if (!bin && strchr(string, '\r')) {
  1946. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  1947. "when reading %s. Coping.",
  1948. filename);
  1949. tor_strstrip(string, "\r");
  1950. r = strlen(string);
  1951. }
  1952. if (!bin) {
  1953. statbuf.st_size = (size_t) r;
  1954. } else
  1955. #endif
  1956. if (r != statbuf.st_size) {
  1957. /* Unless we're using text mode on win32, we'd better have an exact
  1958. * match for size. */
  1959. int save_errno = errno;
  1960. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  1961. (int)r, (long)statbuf.st_size,filename);
  1962. tor_free(string);
  1963. close(fd);
  1964. errno = save_errno;
  1965. return NULL;
  1966. }
  1967. close(fd);
  1968. if (stat_out) {
  1969. memcpy(stat_out, &statbuf, sizeof(struct stat));
  1970. }
  1971. return string;
  1972. }
  1973. #define TOR_ISODIGIT(c) ('0' <= (c) && (c) <= '7')
  1974. /** Given a c-style double-quoted escaped string in <b>s</b>, extract and
  1975. * decode its contents into a newly allocated string. On success, assign this
  1976. * string to *<b>result</b>, assign its length to <b>size_out</b> (if
  1977. * provided), and return a pointer to the position in <b>s</b> immediately
  1978. * after the string. On failure, return NULL.
  1979. */
  1980. static const char *
  1981. unescape_string(const char *s, char **result, size_t *size_out)
  1982. {
  1983. const char *cp;
  1984. char *out;
  1985. if (s[0] != '\"')
  1986. return NULL;
  1987. cp = s+1;
  1988. while (1) {
  1989. switch (*cp) {
  1990. case '\0':
  1991. case '\n':
  1992. return NULL;
  1993. case '\"':
  1994. goto end_of_loop;
  1995. case '\\':
  1996. if ((cp[1] == 'x' || cp[1] == 'X')
  1997. && TOR_ISXDIGIT(cp[2]) && TOR_ISXDIGIT(cp[3])) {
  1998. cp += 4;
  1999. } else if (TOR_ISODIGIT(cp[1])) {
  2000. cp += 2;
  2001. if (TOR_ISODIGIT(*cp)) ++cp;
  2002. if (TOR_ISODIGIT(*cp)) ++cp;
  2003. } else if (cp[1]) {
  2004. cp += 2;
  2005. } else {
  2006. return NULL;
  2007. }
  2008. break;
  2009. default:
  2010. ++cp;
  2011. break;
  2012. }
  2013. }
  2014. end_of_loop:
  2015. out = *result = tor_malloc(cp-s + 1);
  2016. cp = s+1;
  2017. while (1) {
  2018. switch (*cp)
  2019. {
  2020. case '\"':
  2021. *out = '\0';
  2022. if (size_out) *size_out = out - *result;
  2023. return cp+1;
  2024. case '\0':
  2025. tor_fragile_assert();
  2026. tor_free(*result);
  2027. return NULL;
  2028. case '\\':
  2029. switch (cp[1])
  2030. {
  2031. case 'n': *out++ = '\n'; cp += 2; break;
  2032. case 'r': *out++ = '\r'; cp += 2; break;
  2033. case 't': *out++ = '\t'; cp += 2; break;
  2034. case 'x': case 'X':
  2035. *out++ = ((hex_decode_digit(cp[2])<<4) +
  2036. hex_decode_digit(cp[3]));
  2037. cp += 4;
  2038. break;
  2039. case '0': case '1': case '2': case '3': case '4': case '5':
  2040. case '6': case '7':
  2041. {
  2042. int n = cp[1]-'0';
  2043. cp += 2;
  2044. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2045. if (TOR_ISODIGIT(*cp)) { n = n*8 + *cp-'0'; cp++; }
  2046. if (n > 255) { tor_free(*result); return NULL; }
  2047. *out++ = (char)n;
  2048. }
  2049. break;
  2050. case '\'':
  2051. case '\"':
  2052. case '\\':
  2053. case '\?':
  2054. *out++ = cp[1];
  2055. cp += 2;
  2056. break;
  2057. default:
  2058. tor_free(*result); return NULL;
  2059. }
  2060. break;
  2061. default:
  2062. *out++ = *cp++;
  2063. }
  2064. }
  2065. }
  2066. /** Given a string containing part of a configuration file or similar format,
  2067. * advance past comments and whitespace and try to parse a single line. If we
  2068. * parse a line successfully, set *<b>key_out</b> to a new string holding the
  2069. * key portion and *<b>value_out</b> to a new string holding the value portion
  2070. * of the line, and return a pointer to the start of the next line. If we run
  2071. * out of data, return a pointer to the end of the string. If we encounter an
  2072. * error, return NULL.
  2073. */
  2074. const char *
  2075. parse_config_line_from_str(const char *line, char **key_out, char **value_out)
  2076. {
  2077. /* I believe the file format here is supposed to be:
  2078. FILE = (EMPTYLINE | LINE)* (EMPTYLASTLINE | LASTLINE)?
  2079. EMPTYLASTLINE = SPACE* | COMMENT
  2080. EMPTYLINE = EMPTYLASTLINE NL
  2081. SPACE = ' ' | '\r' | '\t'
  2082. COMMENT = '#' NOT-NL*
  2083. NOT-NL = Any character except '\n'
  2084. NL = '\n'
  2085. LASTLINE = SPACE* KEY SPACE* VALUES
  2086. LINE = LASTLINE NL
  2087. KEY = KEYCHAR+
  2088. KEYCHAR = Any character except ' ', '\r', '\n', '\t', '#', "\"
  2089. VALUES = QUOTEDVALUE | NORMALVALUE
  2090. QUOTEDVALUE = QUOTE QVITEM* QUOTE EOLSPACE?
  2091. QUOTE = '"'
  2092. QVCHAR = KEYCHAR | ESC ('n' | 't' | 'r' | '"' | ESC |'\'' | OCTAL | HEX)
  2093. ESC = "\\"
  2094. OCTAL = ODIGIT (ODIGIT ODIGIT?)?
  2095. HEX = ('x' | 'X') HEXDIGIT HEXDIGIT
  2096. ODIGIT = '0' .. '7'
  2097. HEXDIGIT = '0'..'9' | 'a' .. 'f' | 'A' .. 'F'
  2098. EOLSPACE = SPACE* COMMENT?
  2099. NORMALVALUE = (VALCHAR | ESC ESC_IGNORE | CONTINUATION)* EOLSPACE?
  2100. VALCHAR = Any character except ESC, '#', and '\n'
  2101. ESC_IGNORE = Any character except '#' or '\n'
  2102. CONTINUATION = ESC NL ( COMMENT NL )*
  2103. */
  2104. const char *key, *val, *cp;
  2105. int continuation = 0;
  2106. tor_assert(key_out);
  2107. tor_assert(value_out);
  2108. *key_out = *value_out = NULL;
  2109. key = val = NULL;
  2110. /* Skip until the first keyword. */
  2111. while (1) {
  2112. while (TOR_ISSPACE(*line))
  2113. ++line;
  2114. if (*line == '#') {
  2115. while (*line && *line != '\n')
  2116. ++line;
  2117. } else {
  2118. break;
  2119. }
  2120. }
  2121. if (!*line) { /* End of string? */
  2122. *key_out = *value_out = NULL;
  2123. return line;
  2124. }
  2125. /* Skip until the next space or \ followed by newline. */
  2126. key = line;
  2127. while (*line && !TOR_ISSPACE(*line) && *line != '#' &&
  2128. ! (line[0] == '\\' && line[1] == '\n'))
  2129. ++line;
  2130. *key_out = tor_strndup(key, line-key);
  2131. /* Skip until the value. */
  2132. while (*line == ' ' || *line == '\t')
  2133. ++line;
  2134. val = line;
  2135. /* Find the end of the line. */
  2136. if (*line == '\"') { // XXX No continuation handling is done here
  2137. if (!(line = unescape_string(line, value_out, NULL)))
  2138. return NULL;
  2139. while (*line == ' ' || *line == '\t')
  2140. ++line;
  2141. if (*line && *line != '#' && *line != '\n')
  2142. return NULL;
  2143. } else {
  2144. /* Look for the end of the line. */
  2145. while (*line && *line != '\n' && (*line != '#' || continuation)) {
  2146. if (*line == '\\' && line[1] == '\n') {
  2147. continuation = 1;
  2148. line += 2;
  2149. } else if (*line == '#') {
  2150. do {
  2151. ++line;
  2152. } while (*line && *line != '\n');
  2153. if (*line == '\n')
  2154. ++line;
  2155. } else {
  2156. ++line;
  2157. }
  2158. }
  2159. if (*line == '\n') {
  2160. cp = line++;
  2161. } else {
  2162. cp = line;
  2163. }
  2164. /* Now back cp up to be the last nonspace character */
  2165. while (cp>val && TOR_ISSPACE(*(cp-1)))
  2166. --cp;
  2167. tor_assert(cp >= val);
  2168. /* Now copy out and decode the value. */
  2169. *value_out = tor_strndup(val, cp-val);
  2170. if (continuation) {
  2171. char *v_out, *v_in;
  2172. v_out = v_in = *value_out;
  2173. while (*v_in) {
  2174. if (*v_in == '#') {
  2175. do {
  2176. ++v_in;
  2177. } while (*v_in && *v_in != '\n');
  2178. if (*v_in == '\n')
  2179. ++v_in;
  2180. } else if (v_in[0] == '\\' && v_in[1] == '\n') {
  2181. v_in += 2;
  2182. } else {
  2183. *v_out++ = *v_in++;
  2184. }
  2185. }
  2186. *v_out = '\0';
  2187. }
  2188. }
  2189. if (*line == '#') {
  2190. do {
  2191. ++line;
  2192. } while (*line && *line != '\n');
  2193. }
  2194. while (TOR_ISSPACE(*line)) ++line;
  2195. return line;
  2196. }
  2197. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  2198. * string. */
  2199. char *
  2200. expand_filename(const char *filename)
  2201. {
  2202. tor_assert(filename);
  2203. #ifdef MS_WINDOWS
  2204. return tor_strdup(filename);
  2205. #else
  2206. if (*filename == '~') {
  2207. char *home, *result=NULL;
  2208. const char *rest;
  2209. if (filename[1] == '/' || filename[1] == '\0') {
  2210. home = getenv("HOME");
  2211. if (!home) {
  2212. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  2213. "expanding \"%s\"; defaulting to \"\".", filename);
  2214. home = tor_strdup("");
  2215. } else {
  2216. home = tor_strdup(home);
  2217. }
  2218. rest = strlen(filename)>=2?(filename+2):"";
  2219. } else {
  2220. #ifdef HAVE_PWD_H
  2221. char *username, *slash;
  2222. slash = strchr(filename, '/');
  2223. if (slash)
  2224. username = tor_strndup(filename+1,slash-filename-1);
  2225. else
  2226. username = tor_strdup(filename+1);
  2227. if (!(home = get_user_homedir(username))) {
  2228. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  2229. tor_free(username);
  2230. return NULL;
  2231. }
  2232. tor_free(username);
  2233. rest = slash ? (slash+1) : "";
  2234. #else
  2235. log_warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  2236. return tor_strdup(filename);
  2237. #endif
  2238. }
  2239. tor_assert(home);
  2240. /* Remove trailing slash. */
  2241. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  2242. home[strlen(home)-1] = '\0';
  2243. }
  2244. tor_asprintf(&result,"%s"PATH_SEPARATOR"%s",home,rest);
  2245. tor_free(home);
  2246. return result;
  2247. } else {
  2248. return tor_strdup(filename);
  2249. }
  2250. #endif
  2251. }
  2252. #define MAX_SCANF_WIDTH 9999
  2253. /** Helper: given an ASCII-encoded decimal digit, return its numeric value.
  2254. * NOTE: requires that its input be in-bounds. */
  2255. static int
  2256. digit_to_num(char d)
  2257. {
  2258. int num = ((int)d) - (int)'0';
  2259. tor_assert(num <= 9 && num >= 0);
  2260. return num;
  2261. }
  2262. /** Helper: Read an unsigned int from *<b>bufp</b> of up to <b>width</b>
  2263. * characters. (Handle arbitrary width if <b>width</b> is less than 0.) On
  2264. * success, store the result in <b>out</b>, advance bufp to the next
  2265. * character, and return 0. On failure, return -1. */
  2266. static int
  2267. scan_unsigned(const char **bufp, unsigned *out, int width, int base)
  2268. {
  2269. unsigned result = 0;
  2270. int scanned_so_far = 0;
  2271. const int hex = base==16;
  2272. tor_assert(base == 10 || base == 16);
  2273. if (!bufp || !*bufp || !out)
  2274. return -1;
  2275. if (width<0)
  2276. width=MAX_SCANF_WIDTH;
  2277. while (**bufp && (hex?TOR_ISXDIGIT(**bufp):TOR_ISDIGIT(**bufp))
  2278. && scanned_so_far < width) {
  2279. int digit = hex?hex_decode_digit(*(*bufp)++):digit_to_num(*(*bufp)++);
  2280. unsigned new_result = result * base + digit;
  2281. if (new_result > UINT32_MAX || new_result < result)
  2282. return -1; /* over/underflow. */
  2283. result = new_result;
  2284. ++scanned_so_far;
  2285. }
  2286. if (!scanned_so_far) /* No actual digits scanned */
  2287. return -1;
  2288. *out = result;
  2289. return 0;
  2290. }
  2291. /** Helper: copy up to <b>width</b> non-space characters from <b>bufp</b> to
  2292. * <b>out</b>. Make sure <b>out</b> is nul-terminated. Advance <b>bufp</b>
  2293. * to the next non-space character or the EOS. */
  2294. static int
  2295. scan_string(const char **bufp, char *out, int width)
  2296. {
  2297. int scanned_so_far = 0;
  2298. if (!bufp || !out || width < 0)
  2299. return -1;
  2300. while (**bufp && ! TOR_ISSPACE(**bufp) && scanned_so_far < width) {
  2301. *out++ = *(*bufp)++;
  2302. ++scanned_so_far;
  2303. }
  2304. *out = '\0';
  2305. return 0;
  2306. }
  2307. /** Locale-independent, minimal, no-surprises scanf variant, accepting only a
  2308. * restricted pattern format. For more info on what it supports, see
  2309. * tor_sscanf() documentation. */
  2310. int
  2311. tor_vsscanf(const char *buf, const char *pattern, va_list ap)
  2312. {
  2313. int n_matched = 0;
  2314. while (*pattern) {
  2315. if (*pattern != '%') {
  2316. if (*buf == *pattern) {
  2317. ++buf;
  2318. ++pattern;
  2319. continue;
  2320. } else {
  2321. return n_matched;
  2322. }
  2323. } else {
  2324. int width = -1;
  2325. ++pattern;
  2326. if (TOR_ISDIGIT(*pattern)) {
  2327. width = digit_to_num(*pattern++);
  2328. while (TOR_ISDIGIT(*pattern)) {
  2329. width *= 10;
  2330. width += digit_to_num(*pattern++);
  2331. if (width > MAX_SCANF_WIDTH)
  2332. return -1;
  2333. }
  2334. if (!width) /* No zero-width things. */
  2335. return -1;
  2336. }
  2337. if (*pattern == 'u' || *pattern == 'x') {
  2338. unsigned *u = va_arg(ap, unsigned *);
  2339. const int base = (*pattern == 'u') ? 10 : 16;
  2340. if (!*buf)
  2341. return n_matched;
  2342. if (scan_unsigned(&buf, u, width, base)<0)
  2343. return n_matched;
  2344. ++pattern;
  2345. ++n_matched;
  2346. } else if (*pattern == 's') {
  2347. char *s = va_arg(ap, char *);
  2348. if (width < 0)
  2349. return -1;
  2350. if (scan_string(&buf, s, width)<0)
  2351. return n_matched;
  2352. ++pattern;
  2353. ++n_matched;
  2354. } else if (*pattern == 'c') {
  2355. char *ch = va_arg(ap, char *);
  2356. if (width != -1)
  2357. return -1;
  2358. if (!*buf)
  2359. return n_matched;
  2360. *ch = *buf++;
  2361. ++pattern;
  2362. ++n_matched;
  2363. } else if (*pattern == '%') {
  2364. if (*buf != '%')
  2365. return -1;
  2366. ++buf;
  2367. ++pattern;
  2368. } else {
  2369. return -1; /* Unrecognized pattern component. */
  2370. }
  2371. }
  2372. }
  2373. return n_matched;
  2374. }
  2375. /** Minimal sscanf replacement: parse <b>buf</b> according to <b>pattern</b>
  2376. * and store the results in the corresponding argument fields. Differs from
  2377. * sscanf in that it: Only handles %u and %x and %Ns. Does not handle
  2378. * arbitrarily long widths. %u and %x do not consume any space. Is
  2379. * locale-independent. Returns -1 on malformed patterns.
  2380. *
  2381. * (As with other locale-independent functions, we need this to parse data that
  2382. * is in ASCII without worrying that the C library's locale-handling will make
  2383. * miscellaneous characters look like numbers, spaces, and so on.)
  2384. */
  2385. int
  2386. tor_sscanf(const char *buf, const char *pattern, ...)
  2387. {
  2388. int r;
  2389. va_list ap;
  2390. va_start(ap, pattern);
  2391. r = tor_vsscanf(buf, pattern, ap);
  2392. va_end(ap);
  2393. return r;
  2394. }
  2395. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  2396. * Return NULL on error or if <b>dirname</b> is not a directory.
  2397. */
  2398. smartlist_t *
  2399. tor_listdir(const char *dirname)
  2400. {
  2401. smartlist_t *result;
  2402. #ifdef MS_WINDOWS
  2403. char *pattern;
  2404. TCHAR tpattern[MAX_PATH] = {0};
  2405. char name[MAX_PATH] = {0};
  2406. HANDLE handle;
  2407. WIN32_FIND_DATA findData;
  2408. size_t pattern_len = strlen(dirname)+16;
  2409. pattern = tor_malloc(pattern_len);
  2410. tor_snprintf(pattern, pattern_len, "%s\\*", dirname);
  2411. #ifdef UNICODE
  2412. mbstowcs(tpattern,pattern,MAX_PATH);
  2413. #else
  2414. strlcpy(tpattern, pattern, MAX_PATH);
  2415. #endif
  2416. if (INVALID_HANDLE_VALUE == (handle = FindFirstFile(tpattern, &findData))) {
  2417. tor_free(pattern);
  2418. return NULL;
  2419. }
  2420. result = smartlist_create();
  2421. while (1) {
  2422. #ifdef UNICODE
  2423. wcstombs(name,findData.cFileName,MAX_PATH);
  2424. #else
  2425. strlcpy(name,findData.cFileName,sizeof(name));
  2426. #endif
  2427. if (strcmp(name, ".") &&
  2428. strcmp(name, "..")) {
  2429. smartlist_add(result, tor_strdup(name));
  2430. }
  2431. if (!FindNextFile(handle, &findData)) {
  2432. DWORD err;
  2433. if ((err = GetLastError()) != ERROR_NO_MORE_FILES) {
  2434. char *errstr = format_win32_error(err);
  2435. log_warn(LD_FS, "Error reading directory '%s': %s", dirname, errstr);
  2436. tor_free(errstr);
  2437. }
  2438. break;
  2439. }
  2440. }
  2441. FindClose(handle);
  2442. tor_free(pattern);
  2443. #else
  2444. DIR *d;
  2445. struct dirent *de;
  2446. if (!(d = opendir(dirname)))
  2447. return NULL;
  2448. result = smartlist_create();
  2449. while ((de = readdir(d))) {
  2450. if (!strcmp(de->d_name, ".") ||
  2451. !strcmp(de->d_name, ".."))
  2452. continue;
  2453. smartlist_add(result, tor_strdup(de->d_name));
  2454. }
  2455. closedir(d);
  2456. #endif
  2457. return result;
  2458. }
  2459. /** Return true iff <b>filename</b> is a relative path. */
  2460. int
  2461. path_is_relative(const char *filename)
  2462. {
  2463. if (filename && filename[0] == '/')
  2464. return 0;
  2465. #ifdef MS_WINDOWS
  2466. else if (filename && filename[0] == '\\')
  2467. return 0;
  2468. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  2469. filename[1] == ':' && filename[2] == '\\')
  2470. return 0;
  2471. #endif
  2472. else
  2473. return 1;
  2474. }
  2475. /* =====
  2476. * Process helpers
  2477. * ===== */
  2478. #ifndef MS_WINDOWS
  2479. /* Based on code contributed by christian grothoff */
  2480. /** True iff we've called start_daemon(). */
  2481. static int start_daemon_called = 0;
  2482. /** True iff we've called finish_daemon(). */
  2483. static int finish_daemon_called = 0;
  2484. /** Socketpair used to communicate between parent and child process while
  2485. * daemonizing. */
  2486. static int daemon_filedes[2];
  2487. /** Start putting the process into daemon mode: fork and drop all resources
  2488. * except standard fds. The parent process never returns, but stays around
  2489. * until finish_daemon is called. (Note: it's safe to call this more
  2490. * than once: calls after the first are ignored.)
  2491. */
  2492. void
  2493. start_daemon(void)
  2494. {
  2495. pid_t pid;
  2496. if (start_daemon_called)
  2497. return;
  2498. start_daemon_called = 1;
  2499. if (pipe(daemon_filedes)) {
  2500. log_err(LD_GENERAL,"pipe failed; exiting. Error was %s", strerror(errno));
  2501. exit(1);
  2502. }
  2503. pid = fork();
  2504. if (pid < 0) {
  2505. log_err(LD_GENERAL,"fork failed. Exiting.");
  2506. exit(1);
  2507. }
  2508. if (pid) { /* Parent */
  2509. int ok;
  2510. char c;
  2511. close(daemon_filedes[1]); /* we only read */
  2512. ok = -1;
  2513. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  2514. if (c == '.')
  2515. ok = 1;
  2516. }
  2517. fflush(stdout);
  2518. if (ok == 1)
  2519. exit(0);
  2520. else
  2521. exit(1); /* child reported error */
  2522. } else { /* Child */
  2523. close(daemon_filedes[0]); /* we only write */
  2524. pid = setsid(); /* Detach from controlling terminal */
  2525. /*
  2526. * Fork one more time, so the parent (the session group leader) can exit.
  2527. * This means that we, as a non-session group leader, can never regain a
  2528. * controlling terminal. This part is recommended by Stevens's
  2529. * _Advanced Programming in the Unix Environment_.
  2530. */
  2531. if (fork() != 0) {
  2532. exit(0);
  2533. }
  2534. set_main_thread(); /* We are now the main thread. */
  2535. return;
  2536. }
  2537. }
  2538. /** Finish putting the process into daemon mode: drop standard fds, and tell
  2539. * the parent process to exit. (Note: it's safe to call this more than once:
  2540. * calls after the first are ignored. Calls start_daemon first if it hasn't
  2541. * been called already.)
  2542. */
  2543. void
  2544. finish_daemon(const char *desired_cwd)
  2545. {
  2546. int nullfd;
  2547. char c = '.';
  2548. if (finish_daemon_called)
  2549. return;
  2550. if (!start_daemon_called)
  2551. start_daemon();
  2552. finish_daemon_called = 1;
  2553. if (!desired_cwd)
  2554. desired_cwd = "/";
  2555. /* Don't hold the wrong FS mounted */
  2556. if (chdir(desired_cwd) < 0) {
  2557. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  2558. exit(1);
  2559. }
  2560. nullfd = tor_open_cloexec("/dev/null", O_RDWR, 0);
  2561. if (nullfd < 0) {
  2562. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  2563. exit(1);
  2564. }
  2565. /* close fds linking to invoking terminal, but
  2566. * close usual incoming fds, but redirect them somewhere
  2567. * useful so the fds don't get reallocated elsewhere.
  2568. */
  2569. if (dup2(nullfd,0) < 0 ||
  2570. dup2(nullfd,1) < 0 ||
  2571. dup2(nullfd,2) < 0) {
  2572. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  2573. exit(1);
  2574. }
  2575. if (nullfd > 2)
  2576. close(nullfd);
  2577. /* signal success */
  2578. if (write(daemon_filedes[1], &c, sizeof(char)) != sizeof(char)) {
  2579. log_err(LD_GENERAL,"write failed. Exiting.");
  2580. }
  2581. close(daemon_filedes[1]);
  2582. }
  2583. #else
  2584. /* defined(MS_WINDOWS) */
  2585. void
  2586. start_daemon(void)
  2587. {
  2588. }
  2589. void
  2590. finish_daemon(const char *cp)
  2591. {
  2592. (void)cp;
  2593. }
  2594. #endif
  2595. /** Write the current process ID, followed by NL, into <b>filename</b>.
  2596. */
  2597. void
  2598. write_pidfile(char *filename)
  2599. {
  2600. FILE *pidfile;
  2601. if ((pidfile = fopen(filename, "w")) == NULL) {
  2602. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  2603. strerror(errno));
  2604. } else {
  2605. #ifdef MS_WINDOWS
  2606. fprintf(pidfile, "%d\n", (int)_getpid());
  2607. #else
  2608. fprintf(pidfile, "%d\n", (int)getpid());
  2609. #endif
  2610. fclose(pidfile);
  2611. }
  2612. }
  2613. #ifdef MS_WINDOWS
  2614. HANDLE
  2615. load_windows_system_library(const TCHAR *library_name)
  2616. {
  2617. TCHAR path[MAX_PATH];
  2618. unsigned n;
  2619. n = GetSystemDirectory(path, MAX_PATH);
  2620. if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
  2621. return 0;
  2622. _tcscat(path, TEXT("\\"));
  2623. _tcscat(path, library_name);
  2624. return LoadLibrary(path);
  2625. }
  2626. #endif
  2627. /** Format <b>child_state</b> and <b>saved_errno</b> as a hex string placed in
  2628. * <b>hex_errno</b>. Called between fork and _exit, so must be signal-handler
  2629. * safe.
  2630. *
  2631. * <b>hex_errno</b> must have at least HEX_ERRNO_SIZE bytes available.
  2632. *
  2633. * The format of <b>hex_errno</b> is: "CHILD_STATE/ERRNO\n", left-padded
  2634. * with spaces. Note that there is no trailing \0. CHILD_STATE indicates where
  2635. * in the processs of starting the child process did the failure occur (see
  2636. * CHILD_STATE_* macros for definition), and SAVED_ERRNO is the value of
  2637. * errno when the failure occurred.
  2638. */
  2639. void
  2640. format_helper_exit_status(unsigned char child_state, int saved_errno,
  2641. char *hex_errno)
  2642. {
  2643. unsigned int unsigned_errno;
  2644. char *cur;
  2645. size_t i;
  2646. /* Fill hex_errno with spaces, and a trailing newline (memset may
  2647. not be signal handler safe, so we can't use it) */
  2648. for (i = 0; i < (HEX_ERRNO_SIZE - 1); i++)
  2649. hex_errno[i] = ' ';
  2650. hex_errno[HEX_ERRNO_SIZE - 1] = '\n';
  2651. /* Convert errno to be unsigned for hex conversion */
  2652. if (saved_errno < 0) {
  2653. unsigned_errno = (unsigned int) -saved_errno;
  2654. } else {
  2655. unsigned_errno = (unsigned int) saved_errno;
  2656. }
  2657. /* Convert errno to hex (start before \n) */
  2658. cur = hex_errno + HEX_ERRNO_SIZE - 2;
  2659. /* Check for overflow on first iteration of the loop */
  2660. if (cur < hex_errno)
  2661. return;
  2662. do {
  2663. *cur-- = "0123456789ABCDEF"[unsigned_errno % 16];
  2664. unsigned_errno /= 16;
  2665. } while (unsigned_errno != 0 && cur >= hex_errno);
  2666. /* Prepend the minus sign if errno was negative */
  2667. if (saved_errno < 0 && cur >= hex_errno)
  2668. *cur-- = '-';
  2669. /* Leave a gap */
  2670. if (cur >= hex_errno)
  2671. *cur-- = '/';
  2672. /* Check for overflow on first iteration of the loop */
  2673. if (cur < hex_errno)
  2674. return;
  2675. /* Convert child_state to hex */
  2676. do {
  2677. *cur-- = "0123456789ABCDEF"[child_state % 16];
  2678. child_state /= 16;
  2679. } while (child_state != 0 && cur >= hex_errno);
  2680. }
  2681. /* Maximum number of file descriptors, if we cannot get it via sysconf() */
  2682. #define DEFAULT_MAX_FD 256
  2683. #define CHILD_STATE_INIT 0
  2684. #define CHILD_STATE_PIPE 1
  2685. #define CHILD_STATE_MAXFD 2
  2686. #define CHILD_STATE_FORK 3
  2687. #define CHILD_STATE_DUPOUT 4
  2688. #define CHILD_STATE_DUPERR 5
  2689. #define CHILD_STATE_REDIRECT 6
  2690. #define CHILD_STATE_CLOSEFD 7
  2691. #define CHILD_STATE_EXEC 8
  2692. #define CHILD_STATE_FAILEXEC 9
  2693. #define SPAWN_ERROR_MESSAGE "ERR: Failed to spawn background process - code "
  2694. /** Start a program in the background. If <b>filename</b> contains a '/',
  2695. * then it will be treated as an absolute or relative path. Otherwise the
  2696. * system path will be searched for <b>filename</b>. The strings in
  2697. * <b>argv</b> will be passed as the command line arguments of the child
  2698. * program (following convention, argv[0] should normally be the filename of
  2699. * the executable). The last element of argv must be NULL. If the child
  2700. * program is launched, the PID will be returned and <b>stdout_read</b> and
  2701. * <b>stdout_err</b> will be set to file descriptors from which the stdout
  2702. * and stderr, respectively, output of the child program can be read, and the
  2703. * stdin of the child process shall be set to /dev/null. Otherwise returns
  2704. * -1. Some parts of this code are based on the POSIX subprocess module from
  2705. * Python.
  2706. */
  2707. int
  2708. tor_spawn_background(const char *const filename, int *stdout_read,
  2709. int *stderr_read, const char **argv)
  2710. {
  2711. #ifdef MS_WINDOWS
  2712. (void) filename; (void) stdout_read; (void) stderr_read; (void) argv;
  2713. log_warn(LD_BUG, "not yet implemented on Windows.");
  2714. return -1;
  2715. #else
  2716. pid_t pid;
  2717. int stdout_pipe[2];
  2718. int stderr_pipe[2];
  2719. int fd, retval;
  2720. ssize_t nbytes;
  2721. const char *error_message = SPAWN_ERROR_MESSAGE;
  2722. size_t error_message_length;
  2723. /* Represents where in the process of spawning the program is;
  2724. this is used for printing out the error message */
  2725. unsigned char child_state = CHILD_STATE_INIT;
  2726. char hex_errno[HEX_ERRNO_SIZE];
  2727. static int max_fd = -1;
  2728. /* We do the strlen here because strlen() is not signal handler safe,
  2729. and we are not allowed to use unsafe functions between fork and exec */
  2730. error_message_length = strlen(error_message);
  2731. child_state = CHILD_STATE_PIPE;
  2732. /* Set up pipe for redirecting stdout and stderr of child */
  2733. retval = pipe(stdout_pipe);
  2734. if (-1 == retval) {
  2735. log_warn(LD_GENERAL,
  2736. "Failed to set up pipe for stdout communication with child process: %s",
  2737. strerror(errno));
  2738. return -1;
  2739. }
  2740. retval = pipe(stderr_pipe);
  2741. if (-1 == retval) {
  2742. log_warn(LD_GENERAL,
  2743. "Failed to set up pipe for stderr communication with child process: %s",
  2744. strerror(errno));
  2745. return -1;
  2746. }
  2747. child_state = CHILD_STATE_MAXFD;
  2748. #ifdef _SC_OPEN_MAX
  2749. if (-1 != max_fd) {
  2750. max_fd = (int) sysconf(_SC_OPEN_MAX);
  2751. if (max_fd == -1)
  2752. max_fd = DEFAULT_MAX_FD;
  2753. log_warn(LD_GENERAL,
  2754. "Cannot find maximum file descriptor, assuming %d", max_fd);
  2755. }
  2756. #else
  2757. max_fd = DEFAULT_MAX_FD;
  2758. #endif
  2759. child_state = CHILD_STATE_FORK;
  2760. pid = fork();
  2761. if (0 == pid) {
  2762. /* In child */
  2763. child_state = CHILD_STATE_DUPOUT;
  2764. /* Link child stdout to the write end of the pipe */
  2765. retval = dup2(stdout_pipe[1], STDOUT_FILENO);
  2766. if (-1 == retval)
  2767. goto error;
  2768. child_state = CHILD_STATE_DUPERR;
  2769. /* Link child stderr to the write end of the pipe */
  2770. retval = dup2(stderr_pipe[1], STDERR_FILENO);
  2771. if (-1 == retval)
  2772. goto error;
  2773. child_state = CHILD_STATE_REDIRECT;
  2774. /* Link stdin to /dev/null */
  2775. fd = open("/dev/null", O_RDONLY); /* NOT cloexec, obviously. */
  2776. if (fd != -1)
  2777. dup2(fd, STDIN_FILENO);
  2778. else
  2779. goto error;
  2780. child_state = CHILD_STATE_CLOSEFD;
  2781. close(stderr_pipe[0]);
  2782. close(stderr_pipe[1]);
  2783. close(stdout_pipe[0]);
  2784. close(stdout_pipe[1]);
  2785. close(fd);
  2786. /* Close all other fds, including the read end of the pipe */
  2787. /* XXX: We should now be doing enough FD_CLOEXEC setting to make
  2788. * this needless. */
  2789. for (fd = STDERR_FILENO + 1; fd < max_fd; fd++) {
  2790. close(fd);
  2791. }
  2792. child_state = CHILD_STATE_EXEC;
  2793. /* Call the requested program. We need the cast because
  2794. execvp doesn't define argv as const, even though it
  2795. does not modify the arguments */
  2796. execvp(filename, (char *const *) argv);
  2797. /* If we got here, the exec or open(/dev/null) failed */
  2798. child_state = CHILD_STATE_FAILEXEC;
  2799. error:
  2800. /* XXX: are we leaking fds from the pipe? */
  2801. format_helper_exit_status(child_state, errno, hex_errno);
  2802. /* Write the error message. GCC requires that we check the return
  2803. value, but there is nothing we can do if it fails */
  2804. nbytes = write(STDOUT_FILENO, error_message, error_message_length);
  2805. nbytes = write(STDOUT_FILENO, hex_errno, sizeof(hex_errno));
  2806. _exit(255);
  2807. return -1; /* Never reached, but avoids compiler warning */
  2808. }
  2809. /* In parent */
  2810. if (-1 == pid) {
  2811. log_warn(LD_GENERAL, "Failed to fork child process: %s", strerror(errno));
  2812. close(stdout_pipe[0]);
  2813. close(stdout_pipe[1]);
  2814. close(stderr_pipe[0]);
  2815. close(stderr_pipe[1]);
  2816. return -1;
  2817. }
  2818. /* Return read end of the pipes to caller, and close write end */
  2819. *stdout_read = stdout_pipe[0];
  2820. retval = close(stdout_pipe[1]);
  2821. if (-1 == retval) {
  2822. log_warn(LD_GENERAL,
  2823. "Failed to close write end of stdout pipe in parent process: %s",
  2824. strerror(errno));
  2825. /* Do not return -1, because the child is running, so the parent
  2826. needs to know about the pid in order to reap it later */
  2827. }
  2828. *stderr_read = stderr_pipe[0];
  2829. retval = close(stderr_pipe[1]);
  2830. if (-1 == retval) {
  2831. log_warn(LD_GENERAL,
  2832. "Failed to close write end of stderr pipe in parent process: %s",
  2833. strerror(errno));
  2834. /* Do not return -1, because the child is running, so the parent
  2835. needs to know about the pid in order to reap it later */
  2836. }
  2837. return pid;
  2838. #endif
  2839. }
  2840. /** Read from stream, and send lines to log at the specified log level.
  2841. * Returns 1 if stream is closed normally, -1 if there is a error reading, and
  2842. * 0 otherwise. Handles lines from tor-fw-helper and
  2843. * tor_spawn_background() specially.
  2844. */
  2845. static int
  2846. log_from_pipe(FILE *stream, int severity, const char *executable,
  2847. int *child_status)
  2848. {
  2849. char buf[256];
  2850. for (;;) {
  2851. char *retval;
  2852. retval = fgets(buf, sizeof(buf), stream);
  2853. if (NULL == retval) {
  2854. if (feof(stream)) {
  2855. /* Program has closed stream (probably it exited) */
  2856. /* TODO: check error */
  2857. fclose(stream);
  2858. return 1;
  2859. } else {
  2860. if (EAGAIN == errno) {
  2861. /* Nothing more to read, try again next time */
  2862. return 0;
  2863. } else {
  2864. /* There was a problem, abandon this child process */
  2865. fclose(stream);
  2866. return -1;
  2867. }
  2868. }
  2869. } else {
  2870. /* We have some data, log it and keep asking for more */
  2871. size_t len;
  2872. len = strlen(buf);
  2873. if (buf[len - 1] == '\n') {
  2874. /* Remove the trailing newline */
  2875. buf[len - 1] = '\0';
  2876. } else {
  2877. /* No newline; check whether we overflowed the buffer */
  2878. if (!feof(stream))
  2879. log_warn(LD_GENERAL,
  2880. "Line from port forwarding helper was truncated: %s", buf);
  2881. /* TODO: What to do with this error? */
  2882. }
  2883. /* Check if buf starts with SPAWN_ERROR_MESSAGE */
  2884. if (strcmpstart(buf, SPAWN_ERROR_MESSAGE) == 0) {
  2885. /* Parse error message */
  2886. int retval, child_state, saved_errno;
  2887. retval = tor_sscanf(buf, SPAWN_ERROR_MESSAGE "%x/%x",
  2888. &child_state, &saved_errno);
  2889. if (retval == 2) {
  2890. log_warn(LD_GENERAL,
  2891. "Failed to start child process \"%s\" in state %d: %s",
  2892. executable, child_state, strerror(saved_errno));
  2893. if (child_status)
  2894. *child_status = 1;
  2895. } else {
  2896. /* Failed to parse message from child process, log it as a
  2897. warning */
  2898. log_warn(LD_GENERAL,
  2899. "Unexpected message from port forwarding helper \"%s\": %s",
  2900. executable, buf);
  2901. }
  2902. } else {
  2903. log_fn(severity, LD_GENERAL, "Port forwarding helper says: %s", buf);
  2904. }
  2905. }
  2906. }
  2907. /* We should never get here */
  2908. return -1;
  2909. }
  2910. void
  2911. tor_check_port_forwarding(const char *filename, int dir_port, int or_port,
  2912. time_t now)
  2913. {
  2914. #ifdef MS_WINDOWS
  2915. (void) filename; (void) dir_port; (void) or_port; (void) now;
  2916. (void) tor_spawn_background;
  2917. (void) log_from_pipe;
  2918. log_warn(LD_GENERAL, "Sorry, port forwarding is not yet supported "
  2919. "on windows.");
  2920. #else
  2921. /* When fw-helper succeeds, how long do we wait until running it again */
  2922. #define TIME_TO_EXEC_FWHELPER_SUCCESS 300
  2923. /* When fw-helper fails, how long do we wait until running it again */
  2924. #define TIME_TO_EXEC_FWHELPER_FAIL 60
  2925. static int child_pid = -1;
  2926. static FILE *stdout_read = NULL;
  2927. static FILE *stderr_read = NULL;
  2928. static time_t time_to_run_helper = 0;
  2929. int stdout_status, stderr_status, retval;
  2930. const char *argv[10];
  2931. char s_dirport[6], s_orport[6];
  2932. tor_assert(filename);
  2933. /* Set up command line for tor-fw-helper */
  2934. snprintf(s_dirport, sizeof s_dirport, "%d", dir_port);
  2935. snprintf(s_orport, sizeof s_orport, "%d", or_port);
  2936. /* TODO: Allow different internal and external ports */
  2937. argv[0] = filename;
  2938. argv[1] = "--internal-or-port";
  2939. argv[2] = s_orport;
  2940. argv[3] = "--external-or-port";
  2941. argv[4] = s_orport;
  2942. argv[5] = "--internal-dir-port";
  2943. argv[6] = s_dirport;
  2944. argv[7] = "--external-dir-port";
  2945. argv[8] = s_dirport;
  2946. argv[9] = NULL;
  2947. /* Start the child, if it is not already running */
  2948. if (-1 == child_pid &&
  2949. time_to_run_helper < now) {
  2950. int fd_out=-1, fd_err=-1;
  2951. /* Assume tor-fw-helper will succeed, start it later*/
  2952. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_SUCCESS;
  2953. child_pid = tor_spawn_background(filename, &fd_out, &fd_err, argv);
  2954. if (child_pid < 0) {
  2955. log_warn(LD_GENERAL, "Failed to start port forwarding helper %s",
  2956. filename);
  2957. child_pid = -1;
  2958. return;
  2959. }
  2960. /* Set stdout/stderr pipes to be non-blocking */
  2961. fcntl(fd_out, F_SETFL, O_NONBLOCK);
  2962. fcntl(fd_err, F_SETFL, O_NONBLOCK);
  2963. /* Open the buffered IO streams */
  2964. stdout_read = fdopen(fd_out, "r");
  2965. stderr_read = fdopen(fd_err, "r");
  2966. log_info(LD_GENERAL,
  2967. "Started port forwarding helper (%s) with pid %d", filename, child_pid);
  2968. }
  2969. /* If child is running, read from its stdout and stderr) */
  2970. if (child_pid > 0) {
  2971. /* Read from stdout/stderr and log result */
  2972. retval = 0;
  2973. stdout_status = log_from_pipe(stdout_read, LOG_INFO, filename, &retval);
  2974. stderr_status = log_from_pipe(stderr_read, LOG_WARN, filename, &retval);
  2975. if (retval) {
  2976. /* There was a problem in the child process */
  2977. time_to_run_helper = now + TIME_TO_EXEC_FWHELPER_FAIL;
  2978. }
  2979. /* Combine the two statuses in order of severity */
  2980. if (-1 == stdout_status || -1 == stderr_status)
  2981. /* There was a failure */
  2982. retval = -1;
  2983. else if (1 == stdout_status || 1 == stderr_status)
  2984. /* stdout or stderr was closed */
  2985. retval = 1;
  2986. else
  2987. /* Both are fine */
  2988. retval = 0;
  2989. /* If either pipe indicates a failure, act on it */
  2990. if (0 != retval) {
  2991. if (1 == retval) {
  2992. log_info(LD_GENERAL, "Port forwarding helper terminated");
  2993. } else {
  2994. log_warn(LD_GENERAL, "Failed to read from port forwarding helper");
  2995. }
  2996. /* TODO: The child might not actually be finished (maybe it failed or
  2997. closed stdout/stderr), so maybe we shouldn't start another? */
  2998. child_pid = -1;
  2999. }
  3000. }
  3001. #endif
  3002. }