util.c 85 KB

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