util.c 109 KB

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