util.c 120 KB

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