util.c 85 KB

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