util.c 89 KB

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