util.c 114 KB

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