util.c 87 KB

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