util.c 51 KB

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