util.c 53 KB

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