util.c 74 KB

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