util.c 87 KB

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