util.c 74 KB

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