util.c 87 KB

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