util.c 107 KB

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