util.c 80 KB

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