util.c 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093
  1. /* Copyright 2003 Roger Dingledine
  2. * Copyright 2004-2006 Roger Dingledine, Nick Mathewson */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char util_c_id[] = "$Id$";
  6. /**
  7. * \file util.c
  8. * \brief Common functions for strings, IO, network, data structures,
  9. * process control.
  10. **/
  11. /* This is required on rh7 to make strptime not complain.
  12. */
  13. #define _GNU_SOURCE
  14. #include "orconfig.h"
  15. #include "util.h"
  16. #include "log.h"
  17. #include "crypto.h"
  18. #include "torint.h"
  19. #include "container.h"
  20. #ifdef MS_WINDOWS
  21. #include <io.h>
  22. #include <direct.h>
  23. #include <process.h>
  24. #else
  25. #include <dirent.h>
  26. #include <pwd.h>
  27. #endif
  28. #ifdef HAVE_CTYPE_H
  29. #include <ctype.h>
  30. #endif
  31. #include <stdlib.h>
  32. #include <stdio.h>
  33. #include <string.h>
  34. #include <assert.h>
  35. #ifdef HAVE_NETINET_IN_H
  36. #include <netinet/in.h>
  37. #endif
  38. #ifdef HAVE_ARPA_INET_H
  39. #include <arpa/inet.h>
  40. #endif
  41. #ifdef HAVE_ERRNO_H
  42. #include <errno.h>
  43. #endif
  44. #ifdef HAVE_SYS_SOCKET_H
  45. #include <sys/socket.h>
  46. #endif
  47. #ifdef HAVE_SYS_TIME_H
  48. #include <sys/time.h>
  49. #endif
  50. #ifdef HAVE_UNISTD_H
  51. #include <unistd.h>
  52. #endif
  53. #ifdef HAVE_SYS_STAT_H
  54. #include <sys/stat.h>
  55. #endif
  56. #ifdef HAVE_SYS_FCNTL_H
  57. #include <sys/fcntl.h>
  58. #endif
  59. #ifdef HAVE_FCNTL_H
  60. #include <fcntl.h>
  61. #endif
  62. #ifdef HAVE_TIME_H
  63. #include <time.h>
  64. #endif
  65. #ifndef O_BINARY
  66. #define O_BINARY 0
  67. #endif
  68. #ifndef O_TEXT
  69. #define O_TEXT 0
  70. #endif
  71. /* =====
  72. * Memory management
  73. * ===== */
  74. #ifdef USE_DMALLOC
  75. #include <dmalloc.h>
  76. #define DMALLOC_FN_ARGS , file, line
  77. #else
  78. #define dmalloc_strdup(file, line, string, xalloc_b) strdup(string)
  79. #define dmalloc_malloc(file, line, size, func_id, alignment, xalloc_b) \
  80. malloc(size)
  81. #define DMALLOC_FUNC_MALLOC 0
  82. #define dmalloc_realloc(file, line, old_pnt, new_size, func_id, xalloc_b) \
  83. realloc((old_pnt), (new_size))
  84. #define DMALLOC_FUNC_REALLOC 0
  85. #define DMALLOC_FN_ARGS
  86. #endif
  87. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  88. * result. On error, log and terminate the process. (Same as malloc(size),
  89. * but never returns NULL.)
  90. *
  91. * <b>file</b> and <b>line</b> are used if dmalloc is enabled, and
  92. * ignored otherwise.
  93. */
  94. void *
  95. _tor_malloc(size_t size DMALLOC_PARAMS)
  96. {
  97. void *result;
  98. #ifndef MALLOC_ZERO_WORKS
  99. /* Some libcs don't do the right thing on size==0. Override them. */
  100. if (size==0) {
  101. size=1;
  102. }
  103. #endif
  104. result = dmalloc_malloc(file, line, size, DMALLOC_FUNC_MALLOC, 0, 0);
  105. if (PREDICT(result == NULL, 0)) {
  106. log_err(LD_MM,"Out of memory on malloc(). Dying.");
  107. /* If these functions die within a worker process, they won't call
  108. * spawn_exit, but that's ok, since the parent will run out of memory soon
  109. * anyway. */
  110. exit(1);
  111. }
  112. return result;
  113. }
  114. /* Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  115. * zero bytes, and return a pointer to the result. Log and terminate
  116. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  117. */
  118. void *
  119. _tor_malloc_zero(size_t size DMALLOC_PARAMS)
  120. {
  121. void *result = _tor_malloc(size DMALLOC_FN_ARGS);
  122. memset(result, 0, size);
  123. return result;
  124. }
  125. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  126. * bytes long; return the new memory block. On error, log and
  127. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  128. */
  129. void *
  130. _tor_realloc(void *ptr, size_t size DMALLOC_PARAMS)
  131. {
  132. void *result;
  133. result = dmalloc_realloc(file, line, ptr, size, DMALLOC_FUNC_REALLOC, 0);
  134. if (PREDICT(result == NULL, 0)) {
  135. log_err(LD_MM,"Out of memory on realloc(). Dying.");
  136. exit(1);
  137. }
  138. return result;
  139. }
  140. /** Return a newly allocated copy of the NUL-terminated string s. On
  141. * error, log and terminate. (Like strdup(s), but never returns
  142. * NULL.)
  143. */
  144. char *
  145. _tor_strdup(const char *s DMALLOC_PARAMS)
  146. {
  147. char *dup;
  148. tor_assert(s);
  149. dup = dmalloc_strdup(file, line, s, 0);
  150. if (PREDICT(dup == NULL, 0)) {
  151. log_err(LD_MM,"Out of memory on strdup(). Dying.");
  152. exit(1);
  153. }
  154. return dup;
  155. }
  156. /** Allocate and return a new string containing the first <b>n</b>
  157. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  158. * characters, only the first <b>n</b> are copied. The result is
  159. * always NUL-terminated. (Like strndup(s,n), but never returns
  160. * NULL.)
  161. */
  162. char *
  163. _tor_strndup(const char *s, size_t n DMALLOC_PARAMS)
  164. {
  165. char *dup;
  166. tor_assert(s);
  167. dup = _tor_malloc((n+1) DMALLOC_FN_ARGS);
  168. /* Performance note: Ordinarily we prefer strlcpy to strncpy. But
  169. * this function gets called a whole lot, and platform strncpy is
  170. * much faster than strlcpy when strlen(s) is much longer than n.
  171. */
  172. strncpy(dup, s, n);
  173. dup[n]='\0';
  174. return dup;
  175. }
  176. /** Allocate a chunk of <b>len</b> bytes, with the same contents starting at
  177. * <b>mem</b>. */
  178. void *
  179. _tor_memdup(const void *mem, size_t len DMALLOC_PARAMS)
  180. {
  181. char *dup;
  182. tor_assert(mem);
  183. dup = _tor_malloc(len DMALLOC_FN_ARGS);
  184. memcpy(dup, mem, len);
  185. return dup;
  186. }
  187. /** Helper for places that need to take a function pointer to the right
  188. * spelling of "free()". */
  189. void
  190. _tor_free(void *mem)
  191. {
  192. tor_free(mem);
  193. }
  194. /* =====
  195. * String manipulation
  196. * ===== */
  197. /** Remove from the string <b>s</b> every character which appears in
  198. * <b>strip</b>. Return the number of characters removed. */
  199. int
  200. tor_strstrip(char *s, const char *strip)
  201. {
  202. char *read = s;
  203. while (*read) {
  204. if (strchr(strip, *read)) {
  205. ++read;
  206. } else {
  207. *s++ = *read++;
  208. }
  209. }
  210. *s = '\0';
  211. return read-s;
  212. }
  213. /** Set the <b>dest_len</b>-byte buffer <b>buf</b> to contain the
  214. * string <b>s</b>, with the string <b>insert</b> inserted after every
  215. * <b>n</b> characters. Return 0 on success, -1 on failure.
  216. *
  217. * If <b>rule</b> is ALWAYS_TERMINATE, then always end the string with
  218. * <b>insert</b>, even if its length is not a multiple of <b>n</b>. If
  219. * <b>rule</b> is NEVER_TERMINATE, then never end the string with
  220. * <b>insert</b>, even if its length <i>is</i> a multiple of <b>n</b>.
  221. * If <b>rule</b> is TERMINATE_IF_EVEN, then end the string with <b>insert</b>
  222. * exactly when its length <i>is</i> a multiple of <b>n</b>.
  223. */
  224. int
  225. tor_strpartition(char *dest, size_t dest_len,
  226. const char *s, const char *insert, size_t n,
  227. part_finish_rule_t rule)
  228. {
  229. char *destp;
  230. size_t len_in, len_out, len_ins;
  231. int is_even, remaining;
  232. tor_assert(s);
  233. tor_assert(insert);
  234. tor_assert(n > 0);
  235. tor_assert(n < SIZE_T_CEILING);
  236. tor_assert(dest_len < SIZE_T_CEILING);
  237. len_in = strlen(s);
  238. len_ins = strlen(insert);
  239. tor_assert(len_in < SIZE_T_CEILING);
  240. tor_assert(len_in/n < SIZE_T_CEILING/len_ins); /* avoid overflow */
  241. len_out = len_in + (len_in/n)*len_ins;
  242. is_even = (len_in%n) == 0;
  243. switch (rule)
  244. {
  245. case ALWAYS_TERMINATE:
  246. if (!is_even) len_out += len_ins;
  247. break;
  248. case NEVER_TERMINATE:
  249. if (is_even && len_in) len_out -= len_ins;
  250. break;
  251. case TERMINATE_IF_EVEN:
  252. break;
  253. }
  254. if (dest_len < len_out+1)
  255. return -1;
  256. destp = dest;
  257. remaining = len_in;
  258. while (remaining) {
  259. strncpy(destp, s, n);
  260. remaining -= n;
  261. if (remaining < 0) {
  262. if (rule == ALWAYS_TERMINATE)
  263. strcpy(destp+n+remaining,insert);
  264. break;
  265. } else if (remaining == 0 && rule == NEVER_TERMINATE) {
  266. *(destp+n) = '\0';
  267. break;
  268. }
  269. strcpy(destp+n, insert);
  270. s += n;
  271. destp += n+len_ins;
  272. }
  273. tor_assert(len_out == strlen(dest));
  274. return 0;
  275. }
  276. /** Return a pointer to a NUL-terminated hexadecimal string encoding
  277. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  278. * result does not need to be deallocated, but repeated calls to
  279. * hex_str will trash old results.
  280. */
  281. const char *
  282. hex_str(const char *from, size_t fromlen)
  283. {
  284. static char buf[65];
  285. if (fromlen>(sizeof(buf)-1)/2)
  286. fromlen = (sizeof(buf)-1)/2;
  287. base16_encode(buf,sizeof(buf),from,fromlen);
  288. return buf;
  289. }
  290. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  291. * lowercase. */
  292. void
  293. tor_strlower(char *s)
  294. {
  295. while (*s) {
  296. *s = TOR_TOLOWER(*s);
  297. ++s;
  298. }
  299. }
  300. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  301. * lowercase. */
  302. void
  303. tor_strupper(char *s)
  304. {
  305. while (*s) {
  306. *s = TOR_TOUPPER(*s);
  307. ++s;
  308. }
  309. }
  310. /** Return 1 if every character in <b>s</b> is printable, else return 0.
  311. */
  312. int
  313. tor_strisprint(const char *s)
  314. {
  315. while (*s) {
  316. if (!TOR_ISPRINT(*s))
  317. return 0;
  318. s++;
  319. }
  320. return 1;
  321. }
  322. /** Return 1 if no character in <b>s</b> is uppercase, else return 0.
  323. */
  324. int
  325. tor_strisnonupper(const char *s)
  326. {
  327. while (*s) {
  328. if (TOR_ISUPPER(*s))
  329. return 0;
  330. s++;
  331. }
  332. return 1;
  333. }
  334. /* Compares the first strlen(s2) characters of s1 with s2. Returns as for
  335. * strcmp.
  336. */
  337. int
  338. strcmpstart(const char *s1, const char *s2)
  339. {
  340. size_t n = strlen(s2);
  341. return strncmp(s1, s2, n);
  342. }
  343. /* Compares the first strlen(s2) characters of s1 with s2. Returns as for
  344. * strcasecmp.
  345. */
  346. int
  347. strcasecmpstart(const char *s1, const char *s2)
  348. {
  349. size_t n = strlen(s2);
  350. return strncasecmp(s1, s2, n);
  351. }
  352. /* Compares the last strlen(s2) characters of s1 with s2. Returns as for
  353. * strcmp.
  354. */
  355. int
  356. strcmpend(const char *s1, const char *s2)
  357. {
  358. size_t n1 = strlen(s1), n2 = strlen(s2);
  359. if (n2>n1)
  360. return strcmp(s1,s2);
  361. else
  362. return strncmp(s1+(n1-n2), s2, n2);
  363. }
  364. /* Compares the last strlen(s2) characters of s1 with s2. Returns as for
  365. * strcasecmp.
  366. */
  367. int
  368. strcasecmpend(const char *s1, const char *s2)
  369. {
  370. size_t n1 = strlen(s1), n2 = strlen(s2);
  371. if (n2>n1) /* then they can't be the same; figure out which is bigger */
  372. return strcasecmp(s1,s2);
  373. else
  374. return strncasecmp(s1+(n1-n2), s2, n2);
  375. }
  376. /** Return a pointer to the first char of s that is not whitespace and
  377. * not a comment, or to the terminating NUL if no such character exists.
  378. */
  379. const char *
  380. eat_whitespace(const char *s)
  381. {
  382. tor_assert(s);
  383. while (1) {
  384. switch (*s) {
  385. case '\0':
  386. default:
  387. return s;
  388. case ' ':
  389. case '\t':
  390. case '\n':
  391. case '\r':
  392. ++s;
  393. break;
  394. case '#':
  395. ++s;
  396. while (*s && *s != '\n')
  397. ++s;
  398. }
  399. }
  400. }
  401. /** Return a pointer to the first char of s that is not a space or a tab,
  402. * or to the terminating NUL if no such character exists. */
  403. const char *
  404. eat_whitespace_no_nl(const char *s)
  405. {
  406. while (*s == ' ' || *s == '\t')
  407. ++s;
  408. return s;
  409. }
  410. /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
  411. * or to the terminating NUL if no such character exists.
  412. */
  413. const char *
  414. find_whitespace(const char *s)
  415. {
  416. /* tor_assert(s); */
  417. while (1) {
  418. switch (*s)
  419. {
  420. case '\0':
  421. case '#':
  422. case ' ':
  423. case '\r':
  424. case '\n':
  425. case '\t':
  426. return s;
  427. default:
  428. ++s;
  429. }
  430. }
  431. }
  432. /** Return true iff the 'len' bytes at 'mem' are all zero. */
  433. int
  434. tor_mem_is_zero(const char *mem, size_t len)
  435. {
  436. static const char ZERO[] = {
  437. 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,
  438. };
  439. while (len >= sizeof(ZERO)) {
  440. if (memcmp(mem, ZERO, sizeof(ZERO)))
  441. return 0;
  442. len -= sizeof(ZERO);
  443. mem += sizeof(ZERO);
  444. }
  445. /* Deal with leftover bytes. */
  446. if (len)
  447. return ! memcmp(mem, ZERO, len);
  448. return 1;
  449. }
  450. /** Return true iff the DIGEST_LEN bytes in digest are all zero. */
  451. int
  452. tor_digest_is_zero(const char *digest)
  453. {
  454. return tor_mem_is_zero(digest, DIGEST_LEN);
  455. }
  456. /* Helper: common code to check whether the result of a strtol or strtoul or
  457. * strtoll is correct. */
  458. #define CHECK_STRTOX_RESULT() \
  459. /* Was at least one character converted? */ \
  460. if (endptr == s) \
  461. goto err; \
  462. /* Were there unexpected unconverted characters? */ \
  463. if (!next && *endptr) \
  464. goto err; \
  465. /* Is r within limits? */ \
  466. if (r < min || r > max) \
  467. goto err; \
  468. if (ok) *ok = 1; \
  469. if (next) *next = endptr; \
  470. return r; \
  471. err: \
  472. if (ok) *ok = 0; \
  473. if (next) *next = endptr; \
  474. return 0
  475. /** Extract a long from the start of s, in the given numeric base. If
  476. * there is unconverted data and next is provided, set *next to the
  477. * first unconverted character. An error has occurred if no characters
  478. * are converted; or if there are unconverted characters and next is NULL; or
  479. * if the parsed value is not between min and max. When no error occurs,
  480. * return the parsed value and set *ok (if provided) to 1. When an error
  481. * occurs, return 0 and set *ok (if provided) to 0.
  482. */
  483. long
  484. tor_parse_long(const char *s, int base, long min, long max,
  485. int *ok, char **next)
  486. {
  487. char *endptr;
  488. long r;
  489. r = strtol(s, &endptr, base);
  490. CHECK_STRTOX_RESULT();
  491. }
  492. /** As tor_parse_log, but return an unsigned long. */
  493. unsigned long
  494. tor_parse_ulong(const char *s, int base, unsigned long min,
  495. unsigned long max, int *ok, char **next)
  496. {
  497. char *endptr;
  498. unsigned long r;
  499. r = strtoul(s, &endptr, base);
  500. CHECK_STRTOX_RESULT();
  501. }
  502. /** As tor_parse_log, but return a unit64_t. Only base 10 is guaranteed to
  503. * work for now. */
  504. uint64_t
  505. tor_parse_uint64(const char *s, int base, uint64_t min,
  506. uint64_t max, int *ok, char **next)
  507. {
  508. char *endptr;
  509. uint64_t r;
  510. #ifdef HAVE_STRTOULL
  511. r = (uint64_t)strtoull(s, &endptr, base);
  512. #elif defined(MS_WINDOWS)
  513. #if _MSC_VER < 1300
  514. tor_assert(base <= 10);
  515. r = (uint64_t)_atoi64(s);
  516. endptr = (char*)s;
  517. while (TOR_ISSPACE(*endptr)) endptr++;
  518. while (TOR_ISDIGIT(*endptr)) endptr++;
  519. #else
  520. r = (uint64_t)_strtoui64(s, &endptr, base);
  521. #endif
  522. #elif SIZEOF_LONG == 8
  523. r = (uint64_t)strtoul(s, &endptr, base);
  524. #else
  525. #error "I don't know how to parse 64-bit numbers."
  526. #endif
  527. CHECK_STRTOX_RESULT();
  528. }
  529. /** Encode the <b>srclen</b> bytes at <b>src</b> in a NUL-terminated,
  530. * uppercase hexadecimal string; store it in the <b>destlen</b>-byte buffer
  531. * <b>dest</b>.
  532. */
  533. void
  534. base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  535. {
  536. const char *end;
  537. char *cp;
  538. tor_assert(destlen >= srclen*2+1);
  539. tor_assert(destlen < SIZE_T_CEILING);
  540. cp = dest;
  541. end = src+srclen;
  542. while (src<end) {
  543. sprintf(cp,"%02X",*(const uint8_t*)src);
  544. ++src;
  545. cp += 2;
  546. }
  547. *cp = '\0';
  548. }
  549. /** Helper: given a hex digit, return its value, or -1 if it isn't hex. */
  550. static INLINE int
  551. hex_decode_digit(char c)
  552. {
  553. switch (c) {
  554. case '0': return 0;
  555. case '1': return 1;
  556. case '2': return 2;
  557. case '3': return 3;
  558. case '4': return 4;
  559. case '5': return 5;
  560. case '6': return 6;
  561. case '7': return 7;
  562. case '8': return 8;
  563. case '9': return 9;
  564. case 'A': case 'a': return 10;
  565. case 'B': case 'b': return 11;
  566. case 'C': case 'c': return 12;
  567. case 'D': case 'd': return 13;
  568. case 'E': case 'e': return 14;
  569. case 'F': case 'f': return 15;
  570. default:
  571. return -1;
  572. }
  573. }
  574. /** Given a hexadecimal string of <b>srclen</b> bytes in <b>src/b>, decode it
  575. * and store the result in the <b>destlen</b>-byte buffer at <b>dest</b>.
  576. * Return 0 on success, -1 on failure. */
  577. int
  578. base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  579. {
  580. const char *end;
  581. int v1,v2;
  582. if ((srclen % 2) != 0)
  583. return -1;
  584. if (destlen < srclen/2 || destlen > SIZE_T_CEILING)
  585. return -1;
  586. end = src+srclen;
  587. while (src<end) {
  588. v1 = hex_decode_digit(*src);
  589. v2 = hex_decode_digit(*(src+1));
  590. if (v1<0||v2<0)
  591. return -1;
  592. *(uint8_t*)dest = (v1<<4)|v2;
  593. ++dest;
  594. src+=2;
  595. }
  596. return 0;
  597. }
  598. /** Allocate and return a new string representing the contents of <b>s</b>,
  599. * surrounded by quotes and using standard C escapes.
  600. *
  601. * Generally, we use this for logging values that come in over the network
  602. * to keep them from tricking users.
  603. *
  604. * We trust values from the resolver, OS, configuration file, and command line
  605. * to not be maliciously ill-formed. We validate incoming routerdescs and
  606. * SOCKS requests and addresses from BEGIN cells as they're parsed;
  607. * afterwards, we trust them as non-malicious.
  608. */
  609. char *
  610. esc_for_log(const char *s)
  611. {
  612. const char *cp;
  613. char *result, *outp;
  614. size_t len = 3;
  615. if (!s) {
  616. return tor_strdup("");
  617. }
  618. for (cp = s; *cp; ++cp) {
  619. switch (*cp) {
  620. case '\\':
  621. case '\"':
  622. case '\'':
  623. len += 2;
  624. break;
  625. default:
  626. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127)
  627. ++len;
  628. else
  629. len += 4;
  630. break;
  631. }
  632. }
  633. result = outp = tor_malloc(len);
  634. *outp++ = '\"';
  635. for (cp = s; *cp; ++cp) {
  636. switch (*cp) {
  637. case '\\':
  638. case '\"':
  639. case '\'':
  640. *outp++ = '\\';
  641. *outp++ = *cp;
  642. break;
  643. case '\n':
  644. *outp++ = '\\';
  645. *outp++ = 'n';
  646. break;
  647. case '\t':
  648. *outp++ = '\\';
  649. *outp++ = 't';
  650. break;
  651. case '\r':
  652. *outp++ = '\\';
  653. *outp++ = 'r';
  654. break;
  655. default:
  656. if (TOR_ISPRINT(*cp) && ((uint8_t)*cp)<127) {
  657. *outp++ = *cp;
  658. } else {
  659. tor_snprintf(outp, 5, "\\%03o", (int)(uint8_t) *cp);
  660. outp += 4;
  661. }
  662. break;
  663. }
  664. }
  665. *outp++ = '\"';
  666. *outp++ = 0;
  667. return result;
  668. }
  669. /** Allocate and return a new string representing the contents of <b>s</b>,
  670. * surrounded by quotes and using standard C escapes.
  671. *
  672. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  673. * thread. Also, each call invalidates the last-returned value, so don't
  674. * try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));
  675. */
  676. const char *
  677. escaped(const char *s)
  678. {
  679. static char *_escaped_val = NULL;
  680. if (_escaped_val)
  681. tor_free(_escaped_val);
  682. if (s)
  683. _escaped_val = esc_for_log(s);
  684. else
  685. _escaped_val = NULL;
  686. return _escaped_val;
  687. }
  688. /** Rudimentary string wrapping code: given a un-wrapped <b>string</b> (no
  689. * newlines!), break the string into newline-terminated lines of no more than
  690. * <b>width</b> characters long (not counting newline) and insert them into
  691. * <b>out</b> in order. Precede the first line with prefix0, and subsequent
  692. * lines with prefixRest.
  693. */
  694. /* This uses a stupid greedy wrapping algorithm right now:
  695. * - For each line:
  696. * - Try to fit as much stuff as possible, but break on a space.
  697. * - If the first "word" of the line will extend beyond the allowable
  698. * width, break the word at the end of the width.
  699. */
  700. void
  701. wrap_string(smartlist_t *out, const char *string, size_t width,
  702. const char *prefix0, const char *prefixRest)
  703. {
  704. size_t p0Len, pRestLen, pCurLen;
  705. const char *eos, *prefixCur;
  706. tor_assert(out);
  707. tor_assert(string);
  708. tor_assert(width);
  709. if (!prefix0)
  710. prefix0 = "";
  711. if (!prefixRest)
  712. prefixRest = "";
  713. p0Len = strlen(prefix0);
  714. pRestLen = strlen(prefixRest);
  715. tor_assert(width > p0Len && width > pRestLen);
  716. eos = strchr(string, '\0');
  717. tor_assert(eos);
  718. pCurLen = p0Len;
  719. prefixCur = prefix0;
  720. while ((eos-string)+pCurLen > width) {
  721. const char *eol = string + width - pCurLen;
  722. while (eol > string && *eol != ' ')
  723. --eol;
  724. /* eol is now the last space that can fit, or the start of the string. */
  725. if (eol > string) {
  726. size_t line_len = (eol-string) + pCurLen + 2;
  727. char *line = tor_malloc(line_len);
  728. memcpy(line, prefixCur, pCurLen);
  729. memcpy(line+pCurLen, string, eol-string);
  730. line[line_len-2] = '\n';
  731. line[line_len-1] = '\0';
  732. smartlist_add(out, line);
  733. string = eol + 1;
  734. } else {
  735. size_t line_len = width + 2;
  736. char *line = tor_malloc(line_len);
  737. memcpy(line, prefixCur, pCurLen);
  738. memcpy(line+pCurLen, string, width - pCurLen);
  739. line[line_len-2] = '\n';
  740. line[line_len-1] = '\0';
  741. smartlist_add(out, line);
  742. string += width-pCurLen;
  743. }
  744. prefixCur = prefixRest;
  745. pCurLen = pRestLen;
  746. }
  747. if (string < eos) {
  748. size_t line_len = (eos-string) + pCurLen + 2;
  749. char *line = tor_malloc(line_len);
  750. memcpy(line, prefixCur, pCurLen);
  751. memcpy(line+pCurLen, string, eos-string);
  752. line[line_len-2] = '\n';
  753. line[line_len-1] = '\0';
  754. smartlist_add(out, line);
  755. }
  756. }
  757. /* =====
  758. * Time
  759. * ===== */
  760. /** Return the number of microseconds elapsed between *start and *end.
  761. */
  762. long
  763. tv_udiff(struct timeval *start, struct timeval *end)
  764. {
  765. long udiff;
  766. long secdiff = end->tv_sec - start->tv_sec;
  767. if (labs(secdiff+1) > LONG_MAX/1000000) {
  768. log_warn(LD_GENERAL, "comparing times too far apart.");
  769. return LONG_MAX;
  770. }
  771. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  772. return udiff;
  773. }
  774. /** Return -1 if *a \< *b, 0 if *a==*b, and 1 if *a \> *b.
  775. */
  776. int
  777. tv_cmp(struct timeval *a, struct timeval *b)
  778. {
  779. if (a->tv_sec > b->tv_sec)
  780. return 1;
  781. if (a->tv_sec < b->tv_sec)
  782. return -1;
  783. if (a->tv_usec > b->tv_usec)
  784. return 1;
  785. if (a->tv_usec < b->tv_usec)
  786. return -1;
  787. return 0;
  788. }
  789. /** Increment *a by the number of seconds and microseconds in *b.
  790. */
  791. void
  792. tv_add(struct timeval *a, struct timeval *b)
  793. {
  794. a->tv_usec += b->tv_usec;
  795. a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
  796. a->tv_usec %= 1000000;
  797. }
  798. /** Increment *a by <b>ms</b> milliseconds.
  799. */
  800. void
  801. tv_addms(struct timeval *a, long ms)
  802. {
  803. a->tv_usec += (ms * 1000) % 1000000;
  804. a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
  805. a->tv_usec %= 1000000;
  806. }
  807. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  808. static int
  809. n_leapdays(int y1, int y2)
  810. {
  811. --y1;
  812. --y2;
  813. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  814. }
  815. /** Number of days per month in non-leap year; used by tor_timegm. */
  816. static const int days_per_month[] =
  817. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  818. /** Return a time_t given a struct tm. The result is given in GMT, and
  819. * does not account for leap seconds.
  820. */
  821. time_t
  822. tor_timegm(struct tm *tm)
  823. {
  824. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  825. * It's way more brute-force than fiddling with tzset().
  826. */
  827. time_t ret;
  828. unsigned long year, days, hours, minutes;
  829. int i;
  830. year = tm->tm_year + 1900;
  831. if (year < 1970 || tm->tm_mon < 0 || tm->tm_mon > 11) {
  832. log_warn(LD_BUG, "Out-of-range argument to tor_timegm");
  833. return -1;
  834. }
  835. days = 365 * (year-1970) + n_leapdays(1970,year);
  836. for (i = 0; i < tm->tm_mon; ++i)
  837. days += days_per_month[i];
  838. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  839. ++days;
  840. days += tm->tm_mday - 1;
  841. hours = days*24 + tm->tm_hour;
  842. minutes = hours*60 + tm->tm_min;
  843. ret = minutes*60 + tm->tm_sec;
  844. return ret;
  845. }
  846. /* strftime is locale-specific, so we need to replace those parts */
  847. static const char *WEEKDAY_NAMES[] =
  848. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  849. static const char *MONTH_NAMES[] =
  850. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  851. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  852. /** Set <b>buf</b> to the RFC1123 encoding of the GMT value of <b>t</b>.
  853. * The buffer must be at least RFC1123_TIME_LEN+1 bytes long.
  854. *
  855. * (RFC1123 format is Fri, 29 Sep 2006 15:54:20 GMT)
  856. */
  857. void
  858. format_rfc1123_time(char *buf, time_t t)
  859. {
  860. struct tm tm;
  861. tor_gmtime_r(&t, &tm);
  862. strftime(buf, RFC1123_TIME_LEN+1, "___, %d ___ %Y %H:%M:%S GMT", &tm);
  863. tor_assert(tm.tm_wday >= 0);
  864. tor_assert(tm.tm_wday <= 6);
  865. memcpy(buf, WEEKDAY_NAMES[tm.tm_wday], 3);
  866. tor_assert(tm.tm_wday >= 0);
  867. tor_assert(tm.tm_mon <= 11);
  868. memcpy(buf+8, MONTH_NAMES[tm.tm_mon], 3);
  869. }
  870. /** Parse the the RFC1123 encoding of some time (in GMT) from <b>buf</b>,
  871. * and store the result in *<b>t</b>.
  872. *
  873. * Return 0 on succcess, -1 on failure.
  874. */
  875. int
  876. parse_rfc1123_time(const char *buf, time_t *t)
  877. {
  878. struct tm tm;
  879. char month[4];
  880. char weekday[4];
  881. int i, m;
  882. if (strlen(buf) != RFC1123_TIME_LEN)
  883. return -1;
  884. memset(&tm, 0, sizeof(tm));
  885. if (sscanf(buf, "%3s, %d %3s %d %d:%d:%d GMT", weekday,
  886. &tm.tm_mday, month, &tm.tm_year, &tm.tm_hour,
  887. &tm.tm_min, &tm.tm_sec) < 7) {
  888. char *esc = esc_for_log(buf);
  889. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s", esc);
  890. tor_free(esc);
  891. return -1;
  892. }
  893. m = -1;
  894. for (i = 0; i < 12; ++i) {
  895. if (!strcmp(month, MONTH_NAMES[i])) {
  896. m = i;
  897. break;
  898. }
  899. }
  900. if (m<0) {
  901. char *esc = esc_for_log(buf);
  902. log_warn(LD_GENERAL, "Got invalid RFC1123 time %s: No such month", esc);
  903. tor_free(esc);
  904. return -1;
  905. }
  906. tm.tm_mon = m;
  907. if (tm.tm_year < 1970) {
  908. char *esc = esc_for_log(buf);
  909. log_warn(LD_GENERAL,
  910. "Got invalid RFC1123 time %s. (Before 1970)", esc);
  911. tor_free(esc);
  912. return -1;
  913. }
  914. tm.tm_year -= 1900;
  915. *t = tor_timegm(&tm);
  916. return 0;
  917. }
  918. /** Set <b>buf</b> to the ISO8601 encoding of the local value of <b>t</b>.
  919. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  920. *
  921. * (ISO8601 format is 2006-10-29 10:57:20)
  922. */
  923. void
  924. format_local_iso_time(char *buf, time_t t)
  925. {
  926. struct tm tm;
  927. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_localtime_r(&t, &tm));
  928. }
  929. /** Set <b>buf</b> to the ISO8601 encoding of the GMT value of <b>t</b>.
  930. * The buffer must be at least ISO_TIME_LEN+1 bytes long.
  931. */
  932. void
  933. format_iso_time(char *buf, time_t t)
  934. {
  935. struct tm tm;
  936. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", tor_gmtime_r(&t, &tm));
  937. }
  938. /** Given an ISO-formatted UTC time value (after the epoch) in <b>cp</b>,
  939. * parse it and store its value in *<b>t</b>. Return 0 on success, -1 on
  940. * failure. Ignore extraneous stuff in <b>cp</b> separated by whitespace from
  941. * the end of the time string. */
  942. int
  943. parse_iso_time(const char *cp, time_t *t)
  944. {
  945. struct tm st_tm;
  946. #ifdef HAVE_STRPTIME
  947. if (!strptime(cp, "%Y-%m-%d %H:%M:%S", &st_tm)) {
  948. log_warn(LD_GENERAL, "ISO time was unparseable by strptime"); return -1;
  949. }
  950. #else
  951. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  952. if (sscanf(cp, "%u-%u-%u %u:%u:%u", &year, &month,
  953. &day, &hour, &minute, &second) < 6) {
  954. log_warn(LD_GENERAL, "ISO time was unparseable"); return -1;
  955. }
  956. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  957. hour > 23 || minute > 59 || second > 61) {
  958. log_warn(LD_GENERAL, "ISO time was nonsensical"); return -1;
  959. }
  960. st_tm.tm_year = year-1900;
  961. st_tm.tm_mon = month-1;
  962. st_tm.tm_mday = day;
  963. st_tm.tm_hour = hour;
  964. st_tm.tm_min = minute;
  965. st_tm.tm_sec = second;
  966. #endif
  967. if (st_tm.tm_year < 70) {
  968. char *esc = esc_for_log(cp);
  969. log_warn(LD_GENERAL, "Got invalid ISO time %s. (Before 1970)", esc);
  970. tor_free(esc);
  971. return -1;
  972. }
  973. *t = tor_timegm(&st_tm);
  974. return 0;
  975. }
  976. /* =====
  977. * File helpers
  978. * ===== */
  979. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  980. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  981. * was returned by open(). Return the number of bytes written, or -1
  982. * on error. Only use if fd is a blocking fd. */
  983. int
  984. write_all(int fd, const char *buf, size_t count, int isSocket)
  985. {
  986. size_t written = 0;
  987. int result;
  988. while (written != count) {
  989. if (isSocket)
  990. result = tor_socket_send(fd, buf+written, count-written, 0);
  991. else
  992. result = write(fd, buf+written, count-written);
  993. if (result<0)
  994. return -1;
  995. written += result;
  996. }
  997. return count;
  998. }
  999. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1000. * or reach the end of the file. <b>isSocket</b> must be 1 if fd
  1001. * was returned by socket() or accept(), and 0 if fd was returned by
  1002. * open(). Return the number of bytes read, or -1 on error. Only use
  1003. * if fd is a blocking fd. */
  1004. int
  1005. read_all(int fd, char *buf, size_t count, int isSocket)
  1006. {
  1007. size_t numread = 0;
  1008. int result;
  1009. if (count > SIZE_T_CEILING)
  1010. return -1;
  1011. while (numread != count) {
  1012. if (isSocket)
  1013. result = tor_socket_recv(fd, buf+numread, count-numread, 0);
  1014. else
  1015. result = read(fd, buf+numread, count-numread);
  1016. if (result<0)
  1017. return -1;
  1018. else if (result == 0)
  1019. break;
  1020. numread += result;
  1021. }
  1022. return numread;
  1023. }
  1024. /*
  1025. * Filesystem operations.
  1026. */
  1027. /** Clean up <b>name</b> so that we can use it in a call to "stat". On Unix,
  1028. * we do nothing. On Windows, we remove a trailing slash, unless the path is
  1029. * the root of a disk. */
  1030. static void
  1031. clean_name_for_stat(char *name)
  1032. {
  1033. #ifdef MS_WINDOWS
  1034. size_t len = strlen(name);
  1035. if (!len)
  1036. return;
  1037. if (name[len-1]=='\\' || name[len-1]=='/') {
  1038. if (len == 1 || (len==3 && name[1]==':'))
  1039. return;
  1040. name[len-1]='\0';
  1041. }
  1042. #else
  1043. (void)name;
  1044. #endif
  1045. }
  1046. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1047. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1048. * directory. */
  1049. file_status_t
  1050. file_status(const char *fname)
  1051. {
  1052. struct stat st;
  1053. char *f;
  1054. int r;
  1055. f = tor_strdup(fname);
  1056. clean_name_for_stat(f);
  1057. r = stat(f, &st);
  1058. tor_free(f);
  1059. if (r) {
  1060. if (errno == ENOENT) {
  1061. return FN_NOENT;
  1062. }
  1063. return FN_ERROR;
  1064. }
  1065. if (st.st_mode & S_IFDIR)
  1066. return FN_DIR;
  1067. else if (st.st_mode & S_IFREG)
  1068. return FN_FILE;
  1069. else
  1070. return FN_ERROR;
  1071. }
  1072. /** Check whether dirname exists and is private. If yes return 0. If
  1073. * it does not exist, and check==CPD_CREATE is set, try to create it
  1074. * and return 0 on success. If it does not exist, and
  1075. * check==CPD_CHECK, and we think we can create it, return 0. Else
  1076. * return -1. */
  1077. int
  1078. check_private_dir(const char *dirname, cpd_check_t check)
  1079. {
  1080. int r;
  1081. struct stat st;
  1082. char *f;
  1083. tor_assert(dirname);
  1084. f = tor_strdup(dirname);
  1085. clean_name_for_stat(f);
  1086. r = stat(f, &st);
  1087. tor_free(f);
  1088. if (r) {
  1089. if (errno != ENOENT) {
  1090. log(LOG_WARN, LD_FS, "Directory %s cannot be read: %s", dirname,
  1091. strerror(errno));
  1092. return -1;
  1093. }
  1094. if (check == CPD_NONE) {
  1095. log(LOG_WARN, LD_FS, "Directory %s does not exist.", dirname);
  1096. return -1;
  1097. } else if (check == CPD_CREATE) {
  1098. log_info(LD_GENERAL, "Creating directory %s", dirname);
  1099. #ifdef MS_WINDOWS
  1100. r = mkdir(dirname);
  1101. #else
  1102. r = mkdir(dirname, 0700);
  1103. #endif
  1104. if (r) {
  1105. log(LOG_WARN, LD_FS, "Error creating directory %s: %s", dirname,
  1106. strerror(errno));
  1107. return -1;
  1108. }
  1109. }
  1110. /* XXXX In the case where check==CPD_CHECK, we should look at the
  1111. * parent directory a little harder. */
  1112. return 0;
  1113. }
  1114. if (!(st.st_mode & S_IFDIR)) {
  1115. log(LOG_WARN, LD_FS, "%s is not a directory", dirname);
  1116. return -1;
  1117. }
  1118. #ifndef MS_WINDOWS
  1119. if (st.st_uid != getuid()) {
  1120. struct passwd *pw = NULL;
  1121. char *process_ownername = NULL;
  1122. pw = getpwuid(getuid());
  1123. process_ownername = pw ? tor_strdup(pw->pw_name) : tor_strdup("<unknown>");
  1124. pw = getpwuid(st.st_uid);
  1125. log(LOG_WARN, LD_FS, "%s is not owned by this user (%s, %d) but by "
  1126. "%s (%d). Perhaps you are running Tor as the wrong user?",
  1127. dirname, process_ownername, (int)getuid(),
  1128. pw ? pw->pw_name : "<unknown>", (int)st.st_uid);
  1129. tor_free(process_ownername);
  1130. return -1;
  1131. }
  1132. if (st.st_mode & 0077) {
  1133. log(LOG_WARN, LD_FS, "Fixing permissions on directory %s", dirname);
  1134. if (chmod(dirname, 0700)) {
  1135. log(LOG_WARN, LD_FS, "Could not chmod directory %s: %s", dirname,
  1136. strerror(errno));
  1137. return -1;
  1138. } else {
  1139. return 0;
  1140. }
  1141. }
  1142. #endif
  1143. return 0;
  1144. }
  1145. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite
  1146. * the previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1147. *
  1148. * This function replaces the old file atomically, if possible.
  1149. */
  1150. int
  1151. write_str_to_file(const char *fname, const char *str, int bin)
  1152. {
  1153. #ifdef MS_WINDOWS
  1154. if (!bin && strchr(str, '\r')) {
  1155. log_warn(LD_BUG,
  1156. "Bug: we're writing a text string that already contains a CR.");
  1157. }
  1158. #endif
  1159. return write_bytes_to_file(fname, str, strlen(str), bin);
  1160. }
  1161. /** Helper: given a set of flags as passed to open(2), open the file
  1162. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</t> to
  1163. * the file. Do so as atomically as possible e.g. by opening temp files and
  1164. * renaming. */
  1165. static int
  1166. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1167. int open_flags)
  1168. {
  1169. size_t tempname_len;
  1170. char *tempname;
  1171. int fd;
  1172. int result;
  1173. tempname_len = strlen(fname)+16;
  1174. tor_assert(tempname_len > strlen(fname)); /*check for overflow*/
  1175. tempname = tor_malloc(tempname_len);
  1176. if (open_flags & O_APPEND) {
  1177. strlcpy(tempname, fname, tempname_len);
  1178. } else {
  1179. if (tor_snprintf(tempname, tempname_len, "%s.tmp", fname)<0) {
  1180. log(LOG_WARN, LD_GENERAL, "Failed to generate filename");
  1181. goto err;
  1182. }
  1183. }
  1184. if ((fd = open(tempname, open_flags, 0600))
  1185. < 0) {
  1186. log(LOG_WARN, LD_FS, "Couldn't open \"%s\" for writing: %s", tempname,
  1187. strerror(errno));
  1188. goto err;
  1189. }
  1190. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1191. {
  1192. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1193. if (result < 0 || (size_t)result != chunk->len) {
  1194. log(LOG_WARN, LD_FS, "Error writing to \"%s\": %s", tempname,
  1195. strerror(errno));
  1196. close(fd);
  1197. goto err;
  1198. }
  1199. });
  1200. if (close(fd)) {
  1201. log(LOG_WARN, LD_FS, "Error flushing to \"%s\": %s", tempname,
  1202. strerror(errno));
  1203. goto err;
  1204. }
  1205. if (!(open_flags & O_APPEND)) {
  1206. if (replace_file(tempname, fname)) {
  1207. log(LOG_WARN, LD_FS, "Error replacing \"%s\": %s", fname,
  1208. strerror(errno));
  1209. goto err;
  1210. }
  1211. }
  1212. tor_free(tempname);
  1213. return 0;
  1214. err:
  1215. tor_free(tempname);
  1216. return -1;
  1217. }
  1218. /* Given a smartlist of sized_chunk_t, write them atomically to a file
  1219. * <b>fname</b>, overwriting or creating the file as necessary. */
  1220. int
  1221. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
  1222. {
  1223. int flags = O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:O_TEXT);
  1224. return write_chunks_to_file_impl(fname, chunks, flags);
  1225. }
  1226. /** As write_str_to_file, but does not assume a NUL-terminated
  1227. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  1228. int
  1229. write_bytes_to_file(const char *fname, const char *str, size_t len,
  1230. int bin)
  1231. {
  1232. int flags = O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:O_TEXT);
  1233. int r;
  1234. sized_chunk_t c = { str, len };
  1235. smartlist_t *chunks = smartlist_create();
  1236. smartlist_add(chunks, &c);
  1237. r = write_chunks_to_file_impl(fname, chunks, flags);
  1238. smartlist_free(chunks);
  1239. return r;
  1240. }
  1241. /** As write_bytes_to_file, but if the file already exists, append the bytes
  1242. * to the end of the file instead of overwriting it. */
  1243. int
  1244. append_bytes_to_file(const char *fname, const char *str, size_t len,
  1245. int bin)
  1246. {
  1247. int flags = O_WRONLY|O_CREAT|O_APPEND|(bin?O_BINARY:O_TEXT);
  1248. int r;
  1249. sized_chunk_t c = { str, len };
  1250. smartlist_t *chunks = smartlist_create();
  1251. smartlist_add(chunks, &c);
  1252. r = write_chunks_to_file_impl(fname, chunks, flags);
  1253. smartlist_free(chunks);
  1254. return r;
  1255. }
  1256. /** Read the contents of <b>filename</b> into a newly allocated
  1257. * string; return the string on success or NULL on failure.
  1258. *
  1259. * If <b>size_out</b> is provided, store the length of the result in
  1260. * <b>size_out</b>
  1261. */
  1262. /*
  1263. * This function <em>may</em> return an erroneous result if the file
  1264. * is modified while it is running, but must not crash or overflow.
  1265. * Right now, the error case occurs when the file length grows between
  1266. * the call to stat and the call to read_all: the resulting string will
  1267. * be truncated.
  1268. */
  1269. char *
  1270. read_file_to_str(const char *filename, int bin, size_t *size_out)
  1271. {
  1272. int fd; /* router file */
  1273. struct stat statbuf;
  1274. char *string, *f;
  1275. int r;
  1276. tor_assert(filename);
  1277. f = tor_strdup(filename);
  1278. clean_name_for_stat(f);
  1279. r = stat(f, &statbuf);
  1280. tor_free(f);
  1281. if (r < 0) {
  1282. log_info(LD_FS,"Could not stat \"%s\".",filename);
  1283. return NULL;
  1284. }
  1285. fd = open(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  1286. if (fd<0) {
  1287. log_warn(LD_FS,"Could not open \"%s\".",filename);
  1288. return NULL;
  1289. }
  1290. if ((uint64_t)(statbuf.st_size)+1 > SIZE_T_MAX)
  1291. return NULL;
  1292. string = tor_malloc((size_t)(statbuf.st_size+1));
  1293. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  1294. if (r<0) {
  1295. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  1296. strerror(errno));
  1297. tor_free(string);
  1298. close(fd);
  1299. return NULL;
  1300. }
  1301. string[r] = '\0'; /* NUL-terminate the result. */
  1302. if (bin && r != statbuf.st_size) {
  1303. /* If we're in binary mode, then we'd better have an exact match for
  1304. * size. Otherwise, win32 encoding may throw us off, and that's okay. */
  1305. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  1306. r, (long)statbuf.st_size,filename);
  1307. tor_free(string);
  1308. close(fd);
  1309. return NULL;
  1310. }
  1311. #ifdef MS_WINDOWS
  1312. if (!bin && strchr(string, '\r')) {
  1313. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  1314. "when reading %s. Coping.",
  1315. filename);
  1316. tor_strstrip(string, "\r");
  1317. }
  1318. #endif
  1319. close(fd);
  1320. if (size_out)
  1321. *size_out = (size_t) r;
  1322. return string;
  1323. }
  1324. /** Given a string containing part of a configuration file or similar format,
  1325. * advance past comments and whitespace and try to parse a single line. If we
  1326. * parse a line successfully, set *<b>key_out</b> to the key portion and
  1327. * *<b>value_out</b> to the value portion of the line, and return a pointer to
  1328. * the start of the next line. If we run out of data, return a pointer to the
  1329. * end of the string. If we encounter an error, return NULL.
  1330. *
  1331. * NOTE: We modify <b>line</b> as we parse it, by inserting NULs to terminate
  1332. * the key and value.
  1333. */
  1334. char *
  1335. parse_line_from_str(char *line, char **key_out, char **value_out)
  1336. {
  1337. char *key, *val, *cp;
  1338. tor_assert(key_out);
  1339. tor_assert(value_out);
  1340. *key_out = *value_out = key = val = NULL;
  1341. /* Skip until the first keyword. */
  1342. while (1) {
  1343. while (TOR_ISSPACE(*line))
  1344. ++line;
  1345. if (*line == '#') {
  1346. while (*line && *line != '\n')
  1347. ++line;
  1348. } else {
  1349. break;
  1350. }
  1351. }
  1352. if (!*line) { /* End of string? */
  1353. *key_out = *value_out = NULL;
  1354. return line;
  1355. }
  1356. /* Skip until the next space. */
  1357. key = line;
  1358. while (*line && !TOR_ISSPACE(*line) && *line != '#')
  1359. ++line;
  1360. /* Skip until the value */
  1361. while (*line == ' ' || *line == '\t')
  1362. *line++ = '\0';
  1363. val = line;
  1364. /* Find the end of the line. */
  1365. while (*line && *line != '\n' && *line != '#')
  1366. ++line;
  1367. if (*line == '\n')
  1368. cp = line++;
  1369. else {
  1370. cp = line-1;
  1371. }
  1372. while (cp>=val && TOR_ISSPACE(*cp))
  1373. *cp-- = '\0';
  1374. if (*line == '#') {
  1375. do {
  1376. *line++ = '\0';
  1377. } while (*line && *line != '\n');
  1378. if (*line == '\n')
  1379. ++line;
  1380. }
  1381. *key_out = key;
  1382. *value_out = val;
  1383. return line;
  1384. }
  1385. /** Expand any homedir prefix on 'filename'; return a newly allocated
  1386. * string. */
  1387. char *
  1388. expand_filename(const char *filename)
  1389. {
  1390. tor_assert(filename);
  1391. if (*filename == '~') {
  1392. size_t len;
  1393. char *home, *result;
  1394. const char *rest;
  1395. if (filename[1] == '/' || filename[1] == '\0') {
  1396. home = getenv("HOME");
  1397. if (!home) {
  1398. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  1399. "expanding \"%s\"", filename);
  1400. return NULL;
  1401. }
  1402. home = tor_strdup(home);
  1403. rest = strlen(filename)>=2?(filename+2):NULL;
  1404. } else {
  1405. #ifdef HAVE_PWD_H
  1406. char *username, *slash;
  1407. slash = strchr(filename, '/');
  1408. if (slash)
  1409. username = tor_strndup(filename+1,slash-filename-1);
  1410. else
  1411. username = tor_strdup(filename+1);
  1412. if (!(home = get_user_homedir(username))) {
  1413. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  1414. tor_free(username);
  1415. return NULL;
  1416. }
  1417. tor_free(username);
  1418. rest = slash ? (slash+1) : NULL;
  1419. #else
  1420. log_warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  1421. return tor_strdup(filename);
  1422. #endif
  1423. }
  1424. tor_assert(home);
  1425. /* Remove trailing slash. */
  1426. if (strlen(home)>1 && !strcmpend(home,"/")) {
  1427. home[strlen(home)-1] = '\0';
  1428. }
  1429. /* Plus one for /, plus one for NUL.
  1430. * Round up to 16 in case we can't do math. */
  1431. len = strlen(home)+strlen(rest)+16;
  1432. result = tor_malloc(len);
  1433. tor_snprintf(result,len,"%s/%s",home,rest?rest:"");
  1434. tor_free(home);
  1435. return result;
  1436. } else {
  1437. return tor_strdup(filename);
  1438. }
  1439. }
  1440. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  1441. * Return NULL on error or if <b>dirname</b> is not a directory.
  1442. */
  1443. smartlist_t *
  1444. tor_listdir(const char *dirname)
  1445. {
  1446. smartlist_t *result;
  1447. #ifdef MS_WINDOWS
  1448. char *pattern;
  1449. HANDLE handle;
  1450. WIN32_FIND_DATA findData;
  1451. size_t pattern_len = strlen(dirname)+16;
  1452. pattern = tor_malloc(pattern_len);
  1453. tor_snprintf(pattern, pattern_len, "%s\\*", dirname);
  1454. if (!(handle = FindFirstFile(pattern, &findData))) {
  1455. tor_free(pattern);
  1456. return NULL;
  1457. }
  1458. result = smartlist_create();
  1459. while (1) {
  1460. if (strcmp(findData.cFileName, ".") &&
  1461. strcmp(findData.cFileName, "..")) {
  1462. smartlist_add(result, tor_strdup(findData.cFileName));
  1463. }
  1464. if (!FindNextFile(handle, &findData)) {
  1465. if (GetLastError() != ERROR_NO_MORE_FILES) {
  1466. log_warn(LD_FS, "Error reading directory.");
  1467. }
  1468. break;
  1469. }
  1470. }
  1471. FindClose(handle);
  1472. tor_free(pattern);
  1473. #else
  1474. DIR *d;
  1475. struct dirent *de;
  1476. if (!(d = opendir(dirname)))
  1477. return NULL;
  1478. result = smartlist_create();
  1479. while ((de = readdir(d))) {
  1480. if (!strcmp(de->d_name, ".") ||
  1481. !strcmp(de->d_name, ".."))
  1482. continue;
  1483. smartlist_add(result, tor_strdup(de->d_name));
  1484. }
  1485. closedir(d);
  1486. #endif
  1487. return result;
  1488. }
  1489. /** Return true iff <b>filename</b> is a relative path. */
  1490. int
  1491. path_is_relative(const char *filename)
  1492. {
  1493. if (filename && filename[0] == '/')
  1494. return 0;
  1495. #ifdef MS_WINDOWS
  1496. else if (filename && filename[0] == '\\')
  1497. return 0;
  1498. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  1499. filename[1] == ':' && filename[2] == '\\')
  1500. return 0;
  1501. #endif
  1502. else
  1503. return 1;
  1504. }
  1505. /* =====
  1506. * Net helpers
  1507. * ===== */
  1508. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  1509. * or reserved for local networks by RFC 1918.
  1510. */
  1511. int
  1512. is_internal_IP(uint32_t ip, int for_listening)
  1513. {
  1514. if (for_listening && !ip) /* special case for binding to 0.0.0.0 */
  1515. return 0;
  1516. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  1517. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  1518. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  1519. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  1520. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  1521. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  1522. return 1;
  1523. return 0;
  1524. }
  1525. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  1526. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  1527. * host portion of the string. If <b>addr</b> is provided, try to
  1528. * resolve the host portion of the string and store it into
  1529. * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
  1530. * store the port number into *<b>port_out</b>, or 0 if no port is given.
  1531. * If <b>port_out</b> is NULL, then there must be no port number in
  1532. * <b>addrport</b>.
  1533. * Return 0 on success, -1 on failure.
  1534. */
  1535. int
  1536. parse_addr_port(int severity, const char *addrport, char **address,
  1537. uint32_t *addr, uint16_t *port_out)
  1538. {
  1539. const char *colon;
  1540. char *_address = NULL;
  1541. int _port;
  1542. int ok = 1;
  1543. tor_assert(addrport);
  1544. colon = strchr(addrport, ':');
  1545. if (colon) {
  1546. _address = tor_strndup(addrport, colon-addrport);
  1547. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1548. if (!_port) {
  1549. log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
  1550. ok = 0;
  1551. }
  1552. if (!port_out) {
  1553. char *esc_addrport = esc_for_log(addrport);
  1554. log_fn(severity, LD_GENERAL,
  1555. "Port %s given on %s when not required",
  1556. escaped(colon+1), esc_addrport);
  1557. tor_free(esc_addrport);
  1558. ok = 0;
  1559. }
  1560. } else {
  1561. _address = tor_strdup(addrport);
  1562. _port = 0;
  1563. }
  1564. if (addr) {
  1565. /* There's an addr pointer, so we need to resolve the hostname. */
  1566. if (tor_lookup_hostname(_address,addr)) {
  1567. log_fn(severity, LD_NET, "Couldn't look up %s", escaped(_address));
  1568. ok = 0;
  1569. *addr = 0;
  1570. }
  1571. *addr = ntohl(*addr);
  1572. }
  1573. if (address && ok) {
  1574. *address = _address;
  1575. } else {
  1576. if (address)
  1577. *address = NULL;
  1578. tor_free(_address);
  1579. }
  1580. if (port_out)
  1581. *port_out = ok ? ((uint16_t) _port) : 0;
  1582. return ok ? 0 : -1;
  1583. }
  1584. /** If <b>mask</b> is an address mask for a bit-prefix, return the number of
  1585. * bits. Otherwise, return -1. */
  1586. int
  1587. addr_mask_get_bits(uint32_t mask)
  1588. {
  1589. int i;
  1590. if (mask == 0)
  1591. return 0;
  1592. if (mask == 0xFFFFFFFFu)
  1593. return 32;
  1594. for (i=0; i<=32; ++i) {
  1595. if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
  1596. return i;
  1597. }
  1598. }
  1599. return -1;
  1600. }
  1601. /** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the
  1602. * various *out pointers as appropriate. Return 0 on success, -1 on failure.
  1603. */
  1604. int
  1605. parse_port_range(const char *port, uint16_t *port_min_out,
  1606. uint16_t *port_max_out)
  1607. {
  1608. int port_min, port_max, ok;
  1609. tor_assert(port_min_out);
  1610. tor_assert(port_max_out);
  1611. if (!port || *port == '\0' || strcmp(port, "*") == 0) {
  1612. port_min = 1;
  1613. port_max = 65535;
  1614. } else {
  1615. char *endptr = NULL;
  1616. port_min = tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
  1617. if (!ok) {
  1618. log_warn(LD_GENERAL,
  1619. "Malformed port %s on address range; rejecting.",
  1620. escaped(port));
  1621. return -1;
  1622. } else if (endptr && *endptr == '-') {
  1623. port = endptr+1;
  1624. endptr = NULL;
  1625. port_max = tor_parse_long(port, 10, 1, 65536, &ok, &endptr);
  1626. if (!ok) {
  1627. log_warn(LD_GENERAL,
  1628. "Malformed port %s on address range; rejecting.",
  1629. escaped(port));
  1630. return -1;
  1631. }
  1632. } else {
  1633. port_max = port_min;
  1634. }
  1635. if (port_min > port_max) {
  1636. log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
  1637. return -1;
  1638. }
  1639. }
  1640. if (port_min < 1)
  1641. port_min = 1;
  1642. if (port_max > 65535)
  1643. port_max = 65535;
  1644. *port_min_out = (uint16_t) port_min;
  1645. *port_max_out = (uint16_t) port_max;
  1646. return 0;
  1647. }
  1648. /** Parse a string <b>s</b> in the format of
  1649. * (IP(/mask|/mask-bits)?|*)(:*|port(-maxport)?)?, setting the various
  1650. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  1651. */
  1652. int
  1653. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  1654. uint32_t *mask_out, uint16_t *port_min_out,
  1655. uint16_t *port_max_out)
  1656. {
  1657. char *address;
  1658. char *mask, *port, *endptr;
  1659. struct in_addr in;
  1660. int bits;
  1661. tor_assert(s);
  1662. tor_assert(addr_out);
  1663. tor_assert(mask_out);
  1664. tor_assert(port_min_out);
  1665. tor_assert(port_max_out);
  1666. address = tor_strdup(s);
  1667. /* Break 'address' into separate strings.
  1668. */
  1669. mask = strchr(address,'/');
  1670. port = strchr(mask?mask:address,':');
  1671. if (mask)
  1672. *mask++ = '\0';
  1673. if (port)
  1674. *port++ = '\0';
  1675. /* Now "address" is the IP|'*' part...
  1676. * "mask" is the Mask|Maskbits part...
  1677. * and "port" is the *|port|min-max part.
  1678. */
  1679. if (strcmp(address,"*")==0) {
  1680. *addr_out = 0;
  1681. } else if (tor_inet_aton(address, &in) != 0) {
  1682. *addr_out = ntohl(in.s_addr);
  1683. } else {
  1684. log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
  1685. escaped(address));
  1686. goto err;
  1687. }
  1688. if (!mask) {
  1689. if (strcmp(address,"*")==0)
  1690. *mask_out = 0;
  1691. else
  1692. *mask_out = 0xFFFFFFFFu;
  1693. } else {
  1694. endptr = NULL;
  1695. bits = (int) strtol(mask, &endptr, 10);
  1696. if (!*endptr) {
  1697. /* strtol handled the whole mask. */
  1698. if (bits < 0 || bits > 32) {
  1699. log_warn(LD_GENERAL,
  1700. "Bad number of mask bits on address range; rejecting.");
  1701. goto err;
  1702. }
  1703. *mask_out = ~((1u<<(32-bits))-1);
  1704. } else if (tor_inet_aton(mask, &in) != 0) {
  1705. *mask_out = ntohl(in.s_addr);
  1706. } else {
  1707. log_warn(LD_GENERAL,
  1708. "Malformed mask %s on address range; rejecting.",
  1709. escaped(mask));
  1710. goto err;
  1711. }
  1712. }
  1713. if (parse_port_range(port, port_min_out, port_max_out)<0)
  1714. goto err;
  1715. tor_free(address);
  1716. return 0;
  1717. err:
  1718. tor_free(address);
  1719. return -1;
  1720. }
  1721. /** Given an IPv4 address <b>in</b> (in network order, as usual),
  1722. * write it as a string into the <b>buf_len</b>-byte buffer in
  1723. * <b>buf</b>.
  1724. */
  1725. int
  1726. tor_inet_ntoa(struct in_addr *in, char *buf, size_t buf_len)
  1727. {
  1728. uint32_t a = ntohl(in->s_addr);
  1729. return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
  1730. (int)(uint8_t)((a>>24)&0xff),
  1731. (int)(uint8_t)((a>>16)&0xff),
  1732. (int)(uint8_t)((a>>8 )&0xff),
  1733. (int)(uint8_t)((a )&0xff));
  1734. }
  1735. /** Given a host-order <b>addr</b>, call tor_inet_ntoa() on it
  1736. * and return a strdup of the resulting address.
  1737. */
  1738. char *
  1739. tor_dup_addr(uint32_t addr)
  1740. {
  1741. char buf[INET_NTOA_BUF_LEN];
  1742. struct in_addr in;
  1743. in.s_addr = htonl(addr);
  1744. tor_inet_ntoa(&in, buf, sizeof(buf));
  1745. return tor_strdup(buf);
  1746. }
  1747. /**
  1748. * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
  1749. * interface connects to the internet. This address should only be used in
  1750. * checking whether our address has changed. Return 0 on success, -1 on
  1751. * failure.
  1752. */
  1753. int
  1754. get_interface_address(int severity, uint32_t *addr)
  1755. {
  1756. int sock=-1, r=-1;
  1757. struct sockaddr_in target_addr, my_addr;
  1758. socklen_t my_addr_len = sizeof(my_addr);
  1759. tor_assert(addr);
  1760. *addr = 0;
  1761. sock = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
  1762. if (sock < 0) {
  1763. int e = tor_socket_errno(-1);
  1764. log_fn(severity, LD_NET, "unable to create socket: %s",
  1765. tor_socket_strerror(e));
  1766. goto err;
  1767. }
  1768. memset(&target_addr, 0, sizeof(target_addr));
  1769. target_addr.sin_family = AF_INET;
  1770. /* discard port */
  1771. target_addr.sin_port = 9;
  1772. /* 18.0.0.1 (Don't worry: no packets are sent. We just need a real address
  1773. * on the internet.) */
  1774. target_addr.sin_addr.s_addr = htonl(0x12000001);
  1775. if (connect(sock,(struct sockaddr *)&target_addr,sizeof(target_addr))<0) {
  1776. int e = tor_socket_errno(sock);
  1777. log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
  1778. goto err;
  1779. }
  1780. if (getsockname(sock, (struct sockaddr*)&my_addr, &my_addr_len)) {
  1781. int e = tor_socket_errno(sock);
  1782. log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
  1783. tor_socket_strerror(e));
  1784. goto err;
  1785. }
  1786. *addr = ntohl(my_addr.sin_addr.s_addr);
  1787. r=0;
  1788. err:
  1789. if (sock >= 0)
  1790. tor_close_socket(sock);
  1791. return r;
  1792. }
  1793. /* =====
  1794. * Process helpers
  1795. * ===== */
  1796. #ifndef MS_WINDOWS
  1797. /* Based on code contributed by christian grothoff */
  1798. static int start_daemon_called = 0;
  1799. static int finish_daemon_called = 0;
  1800. static int daemon_filedes[2];
  1801. /** Start putting the process into daemon mode: fork and drop all resources
  1802. * except standard fds. The parent process never returns, but stays around
  1803. * until finish_daemon is called. (Note: it's safe to call this more
  1804. * than once: calls after the first are ignored.)
  1805. */
  1806. void
  1807. start_daemon(void)
  1808. {
  1809. pid_t pid;
  1810. if (start_daemon_called)
  1811. return;
  1812. start_daemon_called = 1;
  1813. pipe(daemon_filedes);
  1814. pid = fork();
  1815. if (pid < 0) {
  1816. log_err(LD_GENERAL,"fork failed. Exiting.");
  1817. exit(1);
  1818. }
  1819. if (pid) { /* Parent */
  1820. int ok;
  1821. char c;
  1822. close(daemon_filedes[1]); /* we only read */
  1823. ok = -1;
  1824. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  1825. if (c == '.')
  1826. ok = 1;
  1827. }
  1828. fflush(stdout);
  1829. if (ok == 1)
  1830. exit(0);
  1831. else
  1832. exit(1); /* child reported error */
  1833. } else { /* Child */
  1834. close(daemon_filedes[0]); /* we only write */
  1835. pid = setsid(); /* Detach from controlling terminal */
  1836. /*
  1837. * Fork one more time, so the parent (the session group leader) can exit.
  1838. * This means that we, as a non-session group leader, can never regain a
  1839. * controlling terminal. This part is recommended by Stevens's
  1840. * _Advanced Programming in the Unix Environment_.
  1841. */
  1842. if (fork() != 0) {
  1843. exit(0);
  1844. }
  1845. return;
  1846. }
  1847. }
  1848. /** Finish putting the process into daemon mode: drop standard fds, and tell
  1849. * the parent process to exit. (Note: it's safe to call this more than once:
  1850. * calls after the first are ignored. Calls start_daemon first if it hasn't
  1851. * been called already.)
  1852. */
  1853. void
  1854. finish_daemon(const char *desired_cwd)
  1855. {
  1856. int nullfd;
  1857. char c = '.';
  1858. if (finish_daemon_called)
  1859. return;
  1860. if (!start_daemon_called)
  1861. start_daemon();
  1862. finish_daemon_called = 1;
  1863. if (!desired_cwd)
  1864. desired_cwd = "/";
  1865. /* Don't hold the wrong FS mounted */
  1866. if (chdir(desired_cwd) < 0) {
  1867. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  1868. exit(1);
  1869. }
  1870. nullfd = open("/dev/null",
  1871. O_CREAT | O_RDWR | O_APPEND);
  1872. if (nullfd < 0) {
  1873. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  1874. exit(1);
  1875. }
  1876. /* close fds linking to invoking terminal, but
  1877. * close usual incoming fds, but redirect them somewhere
  1878. * useful so the fds don't get reallocated elsewhere.
  1879. */
  1880. if (dup2(nullfd,0) < 0 ||
  1881. dup2(nullfd,1) < 0 ||
  1882. dup2(nullfd,2) < 0) {
  1883. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  1884. exit(1);
  1885. }
  1886. if (nullfd > 2)
  1887. close(nullfd);
  1888. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  1889. close(daemon_filedes[1]);
  1890. }
  1891. #else
  1892. /* defined(MS_WINDOWS) */
  1893. void
  1894. start_daemon(void)
  1895. {
  1896. }
  1897. void
  1898. finish_daemon(const char *cp)
  1899. {
  1900. }
  1901. #endif
  1902. /** Write the current process ID, followed by NL, into <b>filename</b>.
  1903. */
  1904. void
  1905. write_pidfile(char *filename)
  1906. {
  1907. FILE *pidfile;
  1908. if ((pidfile = fopen(filename, "w")) == NULL) {
  1909. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  1910. strerror(errno));
  1911. } else {
  1912. #ifdef MS_WINDOWS
  1913. fprintf(pidfile, "%d\n", (int)_getpid());
  1914. #else
  1915. fprintf(pidfile, "%d\n", (int)getpid());
  1916. #endif
  1917. fclose(pidfile);
  1918. }
  1919. }