util.c 53 KB

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