util.c 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029
  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 temporary file in the same
  1413. * directory, and either replace the original or remove the temporary 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. tor_free(file_data->filename);
  1532. tor_free(file_data->tempname);
  1533. tor_free(file_data);
  1534. return r;
  1535. }
  1536. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1537. * needed, and if using a temporary file, replace the original file with
  1538. * the temporary file. */
  1539. int
  1540. finish_writing_to_file(open_file_t *file_data)
  1541. {
  1542. return finish_writing_to_file_impl(file_data, 0);
  1543. }
  1544. /** Finish writing to <b>file_data</b>: close the file handle, free memory as
  1545. * needed, and if using a temporary file, delete it. */
  1546. int
  1547. abort_writing_to_file(open_file_t *file_data)
  1548. {
  1549. return finish_writing_to_file_impl(file_data, 1);
  1550. }
  1551. /** Helper: given a set of flags as passed to open(2), open the file
  1552. * <b>fname</b> and write all the sized_chunk_t structs in <b>chunks</b> to
  1553. * the file. Do so as atomically as possible e.g. by opening temp files and
  1554. * renaming. */
  1555. static int
  1556. write_chunks_to_file_impl(const char *fname, const smartlist_t *chunks,
  1557. int open_flags)
  1558. {
  1559. open_file_t *file = NULL;
  1560. int fd, result;
  1561. fd = start_writing_to_file(fname, open_flags, 0600, &file);
  1562. if (fd<0)
  1563. return -1;
  1564. SMARTLIST_FOREACH(chunks, sized_chunk_t *, chunk,
  1565. {
  1566. result = write_all(fd, chunk->bytes, chunk->len, 0);
  1567. if (result < 0 || (size_t)result != chunk->len) {
  1568. log(LOG_WARN, LD_FS, "Error writing to \"%s\": %s", fname,
  1569. strerror(errno));
  1570. goto err;
  1571. }
  1572. });
  1573. return finish_writing_to_file(file);
  1574. err:
  1575. abort_writing_to_file(file);
  1576. return -1;
  1577. }
  1578. /** Given a smartlist of sized_chunk_t, write them atomically to a file
  1579. * <b>fname</b>, overwriting or creating the file as necessary. */
  1580. int
  1581. write_chunks_to_file(const char *fname, const smartlist_t *chunks, int bin)
  1582. {
  1583. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1584. return write_chunks_to_file_impl(fname, chunks, flags);
  1585. }
  1586. /** As write_str_to_file, but does not assume a NUL-terminated
  1587. * string. Instead, we write <b>len</b> bytes, starting at <b>str</b>. */
  1588. int
  1589. write_bytes_to_file(const char *fname, const char *str, size_t len,
  1590. int bin)
  1591. {
  1592. int flags = OPEN_FLAGS_REPLACE|(bin?O_BINARY:O_TEXT);
  1593. int r;
  1594. sized_chunk_t c = { str, len };
  1595. smartlist_t *chunks = smartlist_create();
  1596. smartlist_add(chunks, &c);
  1597. r = write_chunks_to_file_impl(fname, chunks, flags);
  1598. smartlist_free(chunks);
  1599. return r;
  1600. }
  1601. /** As write_bytes_to_file, but if the file already exists, append the bytes
  1602. * to the end of the file instead of overwriting it. */
  1603. int
  1604. append_bytes_to_file(const char *fname, const char *str, size_t len,
  1605. int bin)
  1606. {
  1607. int flags = OPEN_FLAGS_APPEND|(bin?O_BINARY:O_TEXT);
  1608. int r;
  1609. sized_chunk_t c = { str, len };
  1610. smartlist_t *chunks = smartlist_create();
  1611. smartlist_add(chunks, &c);
  1612. r = write_chunks_to_file_impl(fname, chunks, flags);
  1613. smartlist_free(chunks);
  1614. return r;
  1615. }
  1616. /** Read the contents of <b>filename</b> into a newly allocated
  1617. * string; return the string on success or NULL on failure.
  1618. *
  1619. * If <b>stat_out</b> is provided, store the result of stat()ing the
  1620. * file into <b>stat_out</b>.
  1621. *
  1622. * If <b>flags</b> &amp; RFTS_BIN, open the file in binary mode.
  1623. * If <b>flags</b> &amp; RFTS_IGNORE_MISSING, don't warn if the file
  1624. * doesn't exist.
  1625. */
  1626. /*
  1627. * This function <em>may</em> return an erroneous result if the file
  1628. * is modified while it is running, but must not crash or overflow.
  1629. * Right now, the error case occurs when the file length grows between
  1630. * the call to stat and the call to read_all: the resulting string will
  1631. * be truncated.
  1632. */
  1633. char *
  1634. read_file_to_str(const char *filename, int flags, struct stat *stat_out)
  1635. {
  1636. int fd; /* router file */
  1637. struct stat statbuf;
  1638. char *string;
  1639. int r;
  1640. int bin = flags & RFTS_BIN;
  1641. tor_assert(filename);
  1642. fd = open(filename,O_RDONLY|(bin?O_BINARY:O_TEXT),0);
  1643. if (fd<0) {
  1644. int severity = LOG_WARN;
  1645. if (errno == ENOENT && (flags & RFTS_IGNORE_MISSING))
  1646. severity = LOG_INFO;
  1647. log_fn(severity, LD_FS,"Could not open \"%s\": %s ",filename,
  1648. strerror(errno));
  1649. return NULL;
  1650. }
  1651. if (fstat(fd, &statbuf)<0) {
  1652. close(fd);
  1653. log_warn(LD_FS,"Could not fstat \"%s\".",filename);
  1654. return NULL;
  1655. }
  1656. if ((uint64_t)(statbuf.st_size)+1 > SIZE_T_MAX)
  1657. return NULL;
  1658. string = tor_malloc((size_t)(statbuf.st_size+1));
  1659. r = read_all(fd,string,(size_t)statbuf.st_size,0);
  1660. if (r<0) {
  1661. log_warn(LD_FS,"Error reading from file \"%s\": %s", filename,
  1662. strerror(errno));
  1663. tor_free(string);
  1664. close(fd);
  1665. return NULL;
  1666. }
  1667. string[r] = '\0'; /* NUL-terminate the result. */
  1668. #ifdef MS_WINDOWS
  1669. if (!bin && strchr(string, '\r')) {
  1670. log_debug(LD_FS, "We didn't convert CRLF to LF as well as we hoped "
  1671. "when reading %s. Coping.",
  1672. filename);
  1673. tor_strstrip(string, "\r");
  1674. r = strlen(string);
  1675. }
  1676. if (!bin) {
  1677. statbuf.st_size = (size_t) r;
  1678. } else
  1679. #endif
  1680. if (r != statbuf.st_size) {
  1681. /* Unless we're using text mode on win32, we'd better have an exact
  1682. * match for size. */
  1683. log_warn(LD_FS,"Could read only %d of %ld bytes of file \"%s\".",
  1684. r, (long)statbuf.st_size,filename);
  1685. tor_free(string);
  1686. close(fd);
  1687. return NULL;
  1688. }
  1689. close(fd);
  1690. if (stat_out) {
  1691. memcpy(stat_out, &statbuf, sizeof(struct stat));
  1692. }
  1693. return string;
  1694. }
  1695. /** Given a string containing part of a configuration file or similar format,
  1696. * advance past comments and whitespace and try to parse a single line. If we
  1697. * parse a line successfully, set *<b>key_out</b> to the key portion and
  1698. * *<b>value_out</b> to the value portion of the line, and return a pointer to
  1699. * the start of the next line. If we run out of data, return a pointer to the
  1700. * end of the string. If we encounter an error, return NULL.
  1701. *
  1702. * NOTE: We modify <b>line</b> as we parse it, by inserting NULs to terminate
  1703. * the key and value.
  1704. */
  1705. char *
  1706. parse_line_from_str(char *line, char **key_out, char **value_out)
  1707. {
  1708. char *key, *val, *cp;
  1709. tor_assert(key_out);
  1710. tor_assert(value_out);
  1711. *key_out = *value_out = key = val = NULL;
  1712. /* Skip until the first keyword. */
  1713. while (1) {
  1714. while (TOR_ISSPACE(*line))
  1715. ++line;
  1716. if (*line == '#') {
  1717. while (*line && *line != '\n')
  1718. ++line;
  1719. } else {
  1720. break;
  1721. }
  1722. }
  1723. if (!*line) { /* End of string? */
  1724. *key_out = *value_out = NULL;
  1725. return line;
  1726. }
  1727. /* Skip until the next space. */
  1728. key = line;
  1729. while (*line && !TOR_ISSPACE(*line) && *line != '#')
  1730. ++line;
  1731. /* Skip until the value */
  1732. while (*line == ' ' || *line == '\t')
  1733. *line++ = '\0';
  1734. val = line;
  1735. /* Find the end of the line. */
  1736. while (*line && *line != '\n' && *line != '#')
  1737. ++line;
  1738. if (*line == '\n')
  1739. cp = line++;
  1740. else {
  1741. cp = line-1;
  1742. }
  1743. while (cp>=val && TOR_ISSPACE(*cp))
  1744. *cp-- = '\0';
  1745. if (*line == '#') {
  1746. do {
  1747. *line++ = '\0';
  1748. } while (*line && *line != '\n');
  1749. if (*line == '\n')
  1750. ++line;
  1751. }
  1752. *key_out = key;
  1753. *value_out = val;
  1754. return line;
  1755. }
  1756. /** Expand any homedir prefix on <b>filename</b>; return a newly allocated
  1757. * string. */
  1758. char *
  1759. expand_filename(const char *filename)
  1760. {
  1761. tor_assert(filename);
  1762. if (*filename == '~') {
  1763. size_t len;
  1764. char *home, *result;
  1765. const char *rest;
  1766. if (filename[1] == '/' || filename[1] == '\0') {
  1767. home = getenv("HOME");
  1768. if (!home) {
  1769. log_warn(LD_CONFIG, "Couldn't find $HOME environment variable while "
  1770. "expanding \"%s\"", filename);
  1771. return NULL;
  1772. }
  1773. home = tor_strdup(home);
  1774. rest = strlen(filename)>=2?(filename+2):"";
  1775. } else {
  1776. #ifdef HAVE_PWD_H
  1777. char *username, *slash;
  1778. slash = strchr(filename, '/');
  1779. if (slash)
  1780. username = tor_strndup(filename+1,slash-filename-1);
  1781. else
  1782. username = tor_strdup(filename+1);
  1783. if (!(home = get_user_homedir(username))) {
  1784. log_warn(LD_CONFIG,"Couldn't get homedir for \"%s\"",username);
  1785. tor_free(username);
  1786. return NULL;
  1787. }
  1788. tor_free(username);
  1789. rest = slash ? (slash+1) : "";
  1790. #else
  1791. log_warn(LD_CONFIG, "Couldn't expend homedir on system without pwd.h");
  1792. return tor_strdup(filename);
  1793. #endif
  1794. }
  1795. tor_assert(home);
  1796. /* Remove trailing slash. */
  1797. if (strlen(home)>1 && !strcmpend(home,PATH_SEPARATOR)) {
  1798. home[strlen(home)-1] = '\0';
  1799. }
  1800. /* Plus one for /, plus one for NUL.
  1801. * Round up to 16 in case we can't do math. */
  1802. len = strlen(home)+strlen(rest)+16;
  1803. result = tor_malloc(len);
  1804. tor_snprintf(result,len,"%s"PATH_SEPARATOR"%s",home,rest);
  1805. tor_free(home);
  1806. return result;
  1807. } else {
  1808. return tor_strdup(filename);
  1809. }
  1810. }
  1811. /** Return a new list containing the filenames in the directory <b>dirname</b>.
  1812. * Return NULL on error or if <b>dirname</b> is not a directory.
  1813. */
  1814. smartlist_t *
  1815. tor_listdir(const char *dirname)
  1816. {
  1817. smartlist_t *result;
  1818. #ifdef MS_WINDOWS
  1819. char *pattern;
  1820. HANDLE handle;
  1821. WIN32_FIND_DATA findData;
  1822. size_t pattern_len = strlen(dirname)+16;
  1823. pattern = tor_malloc(pattern_len);
  1824. tor_snprintf(pattern, pattern_len, "%s\\*", dirname);
  1825. if (!(handle = FindFirstFile(pattern, &findData))) {
  1826. tor_free(pattern);
  1827. return NULL;
  1828. }
  1829. result = smartlist_create();
  1830. while (1) {
  1831. if (strcmp(findData.cFileName, ".") &&
  1832. strcmp(findData.cFileName, "..")) {
  1833. smartlist_add(result, tor_strdup(findData.cFileName));
  1834. }
  1835. if (!FindNextFile(handle, &findData)) {
  1836. if (GetLastError() != ERROR_NO_MORE_FILES) {
  1837. log_warn(LD_FS, "Error reading directory.");
  1838. }
  1839. break;
  1840. }
  1841. }
  1842. FindClose(handle);
  1843. tor_free(pattern);
  1844. #else
  1845. DIR *d;
  1846. struct dirent *de;
  1847. if (!(d = opendir(dirname)))
  1848. return NULL;
  1849. result = smartlist_create();
  1850. while ((de = readdir(d))) {
  1851. if (!strcmp(de->d_name, ".") ||
  1852. !strcmp(de->d_name, ".."))
  1853. continue;
  1854. smartlist_add(result, tor_strdup(de->d_name));
  1855. }
  1856. closedir(d);
  1857. #endif
  1858. return result;
  1859. }
  1860. /** Return true iff <b>filename</b> is a relative path. */
  1861. int
  1862. path_is_relative(const char *filename)
  1863. {
  1864. if (filename && filename[0] == '/')
  1865. return 0;
  1866. #ifdef MS_WINDOWS
  1867. else if (filename && filename[0] == '\\')
  1868. return 0;
  1869. else if (filename && strlen(filename)>3 && TOR_ISALPHA(filename[0]) &&
  1870. filename[1] == ':' && filename[2] == '\\')
  1871. return 0;
  1872. #endif
  1873. else
  1874. return 1;
  1875. }
  1876. /* =====
  1877. * Net helpers
  1878. * ===== */
  1879. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  1880. * or reserved for local networks by RFC 1918.
  1881. */
  1882. int
  1883. is_internal_IP(uint32_t ip, int for_listening)
  1884. {
  1885. tor_addr_t myaddr;
  1886. myaddr.sa.sin_family = AF_INET;
  1887. myaddr.sa.sin_addr.s_addr = htonl(ip);
  1888. return tor_addr_is_internal(&myaddr, for_listening);
  1889. }
  1890. /** Return true iff <b>ip</b> is an IP reserved to localhost or local networks
  1891. * in RFC1918 or RFC4193 or RFC4291. (fec0::/10, deprecated by RFC3879, is
  1892. * also treated as internal for now.)
  1893. */
  1894. int
  1895. tor_addr_is_internal(const tor_addr_t *addr, int for_listening)
  1896. {
  1897. uint32_t iph4 = 0;
  1898. uint32_t iph6[4];
  1899. sa_family_t v_family;
  1900. v_family = IN_FAMILY(addr);
  1901. if (v_family == AF_INET) {
  1902. iph4 = IPV4IPh(addr);
  1903. } else if (v_family == AF_INET6) {
  1904. if (tor_addr_is_v4(addr)) { /* v4-mapped */
  1905. v_family = AF_INET;
  1906. iph4 = ntohl(IN6_ADDRESS32(addr)[3]);
  1907. }
  1908. }
  1909. if (v_family == AF_INET6) {
  1910. iph6[0] = ntohl(IN6_ADDRESS32(addr)[0]);
  1911. iph6[1] = ntohl(IN6_ADDRESS32(addr)[1]);
  1912. iph6[2] = ntohl(IN6_ADDRESS32(addr)[2]);
  1913. iph6[3] = ntohl(IN6_ADDRESS32(addr)[3]);
  1914. if (for_listening && !iph6[0] && !iph6[1] && !iph6[2] && !iph6[3]) /* :: */
  1915. return 0;
  1916. if (((iph6[0] & 0xfe000000) == 0xfc000000) || /* fc00/7 - RFC4193 */
  1917. ((iph6[0] & 0xffc00000) == 0xfe800000) || /* fe80/10 - RFC4291 */
  1918. ((iph6[0] & 0xffc00000) == 0xfec00000)) /* fec0/10 D- RFC3879 */
  1919. return 1;
  1920. if (!iph6[0] && !iph6[1] && !iph6[2] &&
  1921. ((iph6[3] & 0xfffffffe) == 0x00000000)) /* ::/127 */
  1922. return 1;
  1923. return 0;
  1924. } else if (v_family == AF_INET) {
  1925. if (for_listening && !iph4) /* special case for binding to 0.0.0.0 */
  1926. return 0;
  1927. if (((iph4 & 0xff000000) == 0x0a000000) || /* 10/8 */
  1928. ((iph4 & 0xff000000) == 0x00000000) || /* 0/8 */
  1929. ((iph4 & 0xff000000) == 0x7f000000) || /* 127/8 */
  1930. ((iph4 & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  1931. ((iph4 & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  1932. ((iph4 & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  1933. return 1;
  1934. return 0;
  1935. }
  1936. /* unknown address family... assume it's not safe for external use */
  1937. /* rather than tor_assert(0) */
  1938. log_warn(LD_BUG, "tor_addr_is_internal() called with a non-IP address.");
  1939. return 1;
  1940. }
  1941. #if 0
  1942. /** Convert a tor_addr_t <b>addr</b> into a string, and store it in
  1943. * <b>dest</b> of size <b>len</b>. Returns a pointer to dest on success,
  1944. * or NULL on failure.
  1945. */
  1946. void
  1947. tor_addr_to_str(char *dest, const tor_addr_t *addr, int len)
  1948. {
  1949. const char *ptr;
  1950. tor_assert(addr && dest);
  1951. switch (IN_FAMILY(addr)) {
  1952. case AF_INET:
  1953. ptr = tor_inet_ntop(AF_INET, &addr->sa.sin_addr, dest, len);
  1954. break;
  1955. case AF_INET6:
  1956. ptr = tor_inet_ntop(AF_INET6, &addr->sa6.sin6_addr, dest, len);
  1957. break;
  1958. default:
  1959. return NULL;
  1960. }
  1961. return ptr;
  1962. }
  1963. #endif
  1964. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  1965. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  1966. * host portion of the string. If <b>addr</b> is provided, try to
  1967. * resolve the host portion of the string and store it into
  1968. * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
  1969. * store the port number into *<b>port_out</b>, or 0 if no port is given.
  1970. * If <b>port_out</b> is NULL, then there must be no port number in
  1971. * <b>addrport</b>.
  1972. * Return 0 on success, -1 on failure.
  1973. */
  1974. int
  1975. parse_addr_port(int severity, const char *addrport, char **address,
  1976. uint32_t *addr, uint16_t *port_out)
  1977. {
  1978. const char *colon;
  1979. char *_address = NULL;
  1980. int _port;
  1981. int ok = 1;
  1982. tor_assert(addrport);
  1983. colon = strchr(addrport, ':');
  1984. if (colon) {
  1985. _address = tor_strndup(addrport, colon-addrport);
  1986. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1987. if (!_port) {
  1988. log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
  1989. ok = 0;
  1990. }
  1991. if (!port_out) {
  1992. char *esc_addrport = esc_for_log(addrport);
  1993. log_fn(severity, LD_GENERAL,
  1994. "Port %s given on %s when not required",
  1995. escaped(colon+1), esc_addrport);
  1996. tor_free(esc_addrport);
  1997. ok = 0;
  1998. }
  1999. } else {
  2000. _address = tor_strdup(addrport);
  2001. _port = 0;
  2002. }
  2003. if (addr) {
  2004. /* There's an addr pointer, so we need to resolve the hostname. */
  2005. if (tor_lookup_hostname(_address,addr)) {
  2006. log_fn(severity, LD_NET, "Couldn't look up %s", escaped(_address));
  2007. ok = 0;
  2008. *addr = 0;
  2009. }
  2010. }
  2011. if (address && ok) {
  2012. *address = _address;
  2013. } else {
  2014. if (address)
  2015. *address = NULL;
  2016. tor_free(_address);
  2017. }
  2018. if (port_out)
  2019. *port_out = ok ? ((uint16_t) _port) : 0;
  2020. return ok ? 0 : -1;
  2021. }
  2022. /** If <b>mask</b> is an address mask for a bit-prefix, return the number of
  2023. * bits. Otherwise, return -1. */
  2024. int
  2025. addr_mask_get_bits(uint32_t mask)
  2026. {
  2027. int i;
  2028. if (mask == 0)
  2029. return 0;
  2030. if (mask == 0xFFFFFFFFu)
  2031. return 32;
  2032. for (i=0; i<=32; ++i) {
  2033. if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
  2034. return i;
  2035. }
  2036. }
  2037. return -1;
  2038. }
  2039. /** Compare two addresses <b>a1</b> and <b>a2</b> for equality under a
  2040. * etmask of <b>mbits</b> bits. Return -1, 0, or 1.
  2041. *
  2042. * XXXX020Temporary function to allow masks as bitcounts everywhere. This
  2043. * will be replaced with an IPv6-aware version as soon as 32-bit addresses are
  2044. * no longer passed around.
  2045. */
  2046. int
  2047. addr_mask_cmp_bits(uint32_t a1, uint32_t a2, maskbits_t bits)
  2048. {
  2049. if (bits > 32)
  2050. bits = 32;
  2051. else if (bits == 0)
  2052. return 0;
  2053. a1 >>= (32-bits);
  2054. a2 >>= (32-bits);
  2055. if (a1 < a2)
  2056. return -1;
  2057. else if (a1 > a2)
  2058. return 1;
  2059. else
  2060. return 0;
  2061. }
  2062. /** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the
  2063. * various *out pointers as appropriate. Return 0 on success, -1 on failure.
  2064. */
  2065. int
  2066. parse_port_range(const char *port, uint16_t *port_min_out,
  2067. uint16_t *port_max_out)
  2068. {
  2069. int port_min, port_max, ok;
  2070. tor_assert(port_min_out);
  2071. tor_assert(port_max_out);
  2072. if (!port || *port == '\0' || strcmp(port, "*") == 0) {
  2073. port_min = 1;
  2074. port_max = 65535;
  2075. } else {
  2076. char *endptr = NULL;
  2077. port_min = tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
  2078. if (!ok) {
  2079. log_warn(LD_GENERAL,
  2080. "Malformed port %s on address range; rejecting.",
  2081. escaped(port));
  2082. return -1;
  2083. } else if (endptr && *endptr == '-') {
  2084. port = endptr+1;
  2085. endptr = NULL;
  2086. port_max = tor_parse_long(port, 10, 1, 65536, &ok, &endptr);
  2087. if (!ok) {
  2088. log_warn(LD_GENERAL,
  2089. "Malformed port %s on address range; rejecting.",
  2090. escaped(port));
  2091. return -1;
  2092. }
  2093. } else {
  2094. port_max = port_min;
  2095. }
  2096. if (port_min > port_max) {
  2097. log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
  2098. return -1;
  2099. }
  2100. }
  2101. if (port_min < 1)
  2102. port_min = 1;
  2103. if (port_max > 65535)
  2104. port_max = 65535;
  2105. *port_min_out = (uint16_t) port_min;
  2106. *port_max_out = (uint16_t) port_max;
  2107. return 0;
  2108. }
  2109. /** Parse a string <b>s</b> in the format of
  2110. * (IP(/mask|/mask-bits)?|*)(:*|port(-maxport)?)?, setting the various
  2111. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  2112. */
  2113. int
  2114. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  2115. maskbits_t *maskbits_out, uint16_t *port_min_out,
  2116. uint16_t *port_max_out)
  2117. {
  2118. char *address;
  2119. char *mask, *port, *endptr;
  2120. struct in_addr in;
  2121. int bits;
  2122. tor_assert(s);
  2123. tor_assert(addr_out);
  2124. tor_assert(maskbits_out);
  2125. tor_assert(port_min_out);
  2126. tor_assert(port_max_out);
  2127. address = tor_strdup(s);
  2128. /* Break 'address' into separate strings.
  2129. */
  2130. mask = strchr(address,'/');
  2131. port = strchr(mask?mask:address,':');
  2132. if (mask)
  2133. *mask++ = '\0';
  2134. if (port)
  2135. *port++ = '\0';
  2136. /* Now "address" is the IP|'*' part...
  2137. * "mask" is the Mask|Maskbits part...
  2138. * and "port" is the *|port|min-max part.
  2139. */
  2140. if (strcmp(address,"*")==0) {
  2141. *addr_out = 0;
  2142. } else if (tor_inet_aton(address, &in) != 0) {
  2143. *addr_out = ntohl(in.s_addr);
  2144. } else {
  2145. log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
  2146. escaped(address));
  2147. goto err;
  2148. }
  2149. if (!mask) {
  2150. if (strcmp(address,"*")==0)
  2151. *maskbits_out = 0;
  2152. else
  2153. *maskbits_out = 32;
  2154. } else {
  2155. endptr = NULL;
  2156. bits = (int) strtol(mask, &endptr, 10);
  2157. if (!*endptr) {
  2158. /* strtol handled the whole mask. */
  2159. if (bits < 0 || bits > 32) {
  2160. log_warn(LD_GENERAL,
  2161. "Bad number of mask bits on address range; rejecting.");
  2162. goto err;
  2163. }
  2164. *maskbits_out = bits;
  2165. } else if (tor_inet_aton(mask, &in) != 0) {
  2166. bits = addr_mask_get_bits(ntohl(in.s_addr));
  2167. if (bits < 0) {
  2168. log_warn(LD_GENERAL,
  2169. "Mask %s on address range isn't a prefix; dropping",
  2170. escaped(mask));
  2171. goto err;
  2172. }
  2173. *maskbits_out = bits;
  2174. } else {
  2175. log_warn(LD_GENERAL,
  2176. "Malformed mask %s on address range; rejecting.",
  2177. escaped(mask));
  2178. goto err;
  2179. }
  2180. }
  2181. if (parse_port_range(port, port_min_out, port_max_out)<0)
  2182. goto err;
  2183. tor_free(address);
  2184. return 0;
  2185. err:
  2186. tor_free(address);
  2187. return -1;
  2188. }
  2189. /** Parse a string <b>s</b> containing an IPv4/IPv6 address, and possibly
  2190. * a mask and port or port range. Store the parsed address in
  2191. * <b>addr_out</b>, a mask (if any) in <b>mask_out</b>, and port(s) (if any)
  2192. * in <b>port_min_out</b> and <b>port_max_out</b>.
  2193. *
  2194. * The syntax is:
  2195. * Address OptMask OptPortRange
  2196. * Address ::= IPv4Address / "[" IPv6Address "]" / "*"
  2197. * OptMask ::= "/" Integer /
  2198. * OptPortRange ::= ":*" / ":" Integer / ":" Integer "-" Integer /
  2199. *
  2200. * - If mask, minport, or maxport are NULL, we do not want these
  2201. * options to be set; treat them as an error if present.
  2202. * - If the string has no mask, the mask is set to /32 (IPv4) or /128 (IPv6).
  2203. * - If the string has one port, it is placed in both min and max port
  2204. * variables.
  2205. * - If the string has no port(s), port_(min|max)_out are set to 1 and 65535.
  2206. *
  2207. * Return an address family on success, or -1 if an invalid address string is
  2208. * provided.
  2209. */
  2210. int
  2211. tor_addr_parse_mask_ports(const char *s, tor_addr_t *addr_out,
  2212. maskbits_t *maskbits_out,
  2213. uint16_t *port_min_out, uint16_t *port_max_out)
  2214. {
  2215. char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
  2216. char *endptr;
  2217. int any_flag=0, v4map=0;
  2218. tor_assert(s);
  2219. tor_assert(addr_out);
  2220. /* IP, [], /mask, ports */
  2221. #define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)
  2222. if (strlen(s) > MAX_ADDRESS_LENGTH) {
  2223. log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
  2224. goto err;
  2225. }
  2226. base = tor_strdup(s);
  2227. /* Break 'base' into separate strings. */
  2228. address = base;
  2229. if (*address == '[') { /* Probably IPv6 */
  2230. address++;
  2231. rbracket = strchr(address, ']');
  2232. if (!rbracket) {
  2233. log_warn(LD_GENERAL,
  2234. "No closing IPv6 bracket in address pattern; rejecting.");
  2235. goto err;
  2236. }
  2237. }
  2238. mask = strchr((rbracket?rbracket:address),'/');
  2239. port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
  2240. if (port)
  2241. *port++ = '\0';
  2242. if (mask)
  2243. *mask++ = '\0';
  2244. if (rbracket)
  2245. *rbracket = '\0';
  2246. if (port && mask)
  2247. tor_assert(port > mask);
  2248. if (mask && rbracket)
  2249. tor_assert(mask > rbracket);
  2250. /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
  2251. * "mask" is the Mask|Maskbits part...
  2252. * and "port" is the *|port|min-max part.
  2253. */
  2254. /* Process the address portion */
  2255. memset(addr_out, 0, sizeof(tor_addr_t));
  2256. if (!strcmp(address, "*")) {
  2257. addr_out->sa.sin_family = AF_INET; /* AF_UNSPEC ???? XXXXX020 */
  2258. any_flag = 1;
  2259. } else if (tor_inet_pton(AF_INET6, address, &addr_out->sa6.sin6_addr) > 0) {
  2260. addr_out->sa6.sin6_family = AF_INET6;
  2261. } else if (tor_inet_pton(AF_INET, address, &addr_out->sa.sin_addr) > 0) {
  2262. addr_out->sa.sin_family = AF_INET;
  2263. } else {
  2264. log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
  2265. escaped(address));
  2266. goto err;
  2267. }
  2268. v4map = tor_addr_is_v4(addr_out);
  2269. /*
  2270. #ifdef ALWAYS_V6_MAP
  2271. if (v_family == AF_INET) {
  2272. v_family = AF_INET6;
  2273. IN_ADDR6(addr_out).s6_addr32[3] = IN6_ADDRESS(addr_out).s_addr;
  2274. memset(&IN6_ADDRESS(addr_out), 0, 10);
  2275. IN_ADDR6(addr_out).s6_addr16[5] = 0xffff;
  2276. }
  2277. #else
  2278. if (v_family == AF_INET6 && v4map) {
  2279. v_family = AF_INET;
  2280. IN4_ADDRESS((addr_out).s_addr = IN6_ADDRESS(addr_out).s6_addr32[3];
  2281. }
  2282. #endif
  2283. */
  2284. /* Parse mask */
  2285. if (maskbits_out) {
  2286. int bits = 0;
  2287. struct in_addr v4mask;
  2288. if (mask) { /* the caller (tried to) specify a mask */
  2289. bits = (int) strtol(mask, &endptr, 10);
  2290. if (!*endptr) { /* strtol converted everything, so it was an integer */
  2291. if ((bits<0 || bits>128) ||
  2292. ((IN_FAMILY(addr_out) == AF_INET) && bits > 32)) {
  2293. log_warn(LD_GENERAL,
  2294. "Bad number of mask bits (%d) on address range; rejecting.",
  2295. bits);
  2296. goto err;
  2297. }
  2298. } else { /* mask might still be an address-style mask */
  2299. if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
  2300. bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
  2301. if (bits < 0) {
  2302. log_warn(LD_GENERAL,
  2303. "IPv4-style mask %s is not a prefix address; rejecting.",
  2304. escaped(mask));
  2305. goto err;
  2306. }
  2307. } else { /* Not IPv4; we don't do address-style IPv6 masks. */
  2308. log_warn(LD_GENERAL,
  2309. "Malformed mask on address range %s; rejecting.",
  2310. escaped(s));
  2311. goto err;
  2312. }
  2313. }
  2314. if (IN_FAMILY(addr_out) == AF_INET6 && v4map) {
  2315. if (bits > 32 && bits < 96) { /* Crazy */
  2316. log_warn(LD_GENERAL,
  2317. "Bad mask bits %i for V4-mapped V6 address; rejecting.",
  2318. bits);
  2319. goto err;
  2320. }
  2321. /* XXXX020 is this really what we want? */
  2322. bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
  2323. }
  2324. } else { /* pick an appropriate mask, as none was given */
  2325. if (any_flag)
  2326. bits = 0; /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
  2327. else if (IN_FAMILY(addr_out) == AF_INET)
  2328. bits = 32;
  2329. else if (IN_FAMILY(addr_out) == AF_INET6)
  2330. bits = 128;
  2331. }
  2332. *maskbits_out = (maskbits_t) bits;
  2333. } else {
  2334. if (mask) {
  2335. log_warn(LD_GENERAL,
  2336. "Unexpected mask in addrss %s; rejecting", escaped(s));
  2337. goto err;
  2338. }
  2339. }
  2340. /* Parse port(s) */
  2341. if (port_min_out) {
  2342. uint16_t port2;
  2343. if (!port_max_out) /* caller specified one port; fake the second one */
  2344. port_max_out = &port2;
  2345. if (parse_port_range(port, port_min_out, port_max_out) < 0) {
  2346. goto err;
  2347. } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
  2348. log_warn(LD_GENERAL,
  2349. "Wanted one port from address range, but there are two.");
  2350. port_max_out = NULL; /* caller specified one port, so set this back */
  2351. goto err;
  2352. }
  2353. } else {
  2354. if (port) {
  2355. log_warn(LD_GENERAL,
  2356. "Unexpected ports in addrss %s; rejecting", escaped(s));
  2357. goto err;
  2358. }
  2359. }
  2360. tor_free(base);
  2361. return IN_FAMILY(addr_out);
  2362. err:
  2363. tor_free(base);
  2364. return -1;
  2365. }
  2366. /** Determine whether an address is IPv4, either native or ipv4-mapped ipv6.
  2367. * Note that this is about representation only, as any decent stack will
  2368. * reject ipv4-mapped addresses received on the wire (and won't use them
  2369. * on the wire either).
  2370. */
  2371. int
  2372. tor_addr_is_v4(const tor_addr_t *addr)
  2373. {
  2374. tor_assert(addr);
  2375. if (IN_FAMILY(addr) == AF_INET)
  2376. return 1;
  2377. if (IN_FAMILY(addr) == AF_INET6) { /* First two don't need to be ordered */
  2378. if ((IN6_ADDRESS32(addr)[0] == 0) &&
  2379. (IN6_ADDRESS32(addr)[1] == 0) &&
  2380. (ntohl(IN6_ADDRESS32(addr)[2]) == 0x0000ffffu))
  2381. return 1;
  2382. }
  2383. return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
  2384. }
  2385. /** Determine whether an address <b>addr</b> is null, either all zeroes or
  2386. * belonging to family AF_UNSPEC.
  2387. */
  2388. int
  2389. tor_addr_is_null(const tor_addr_t *addr)
  2390. {
  2391. tor_assert(addr);
  2392. switch (IN_FAMILY(addr)) {
  2393. case AF_INET6:
  2394. return (!IN6_ADDRESS32(addr)[0] &&
  2395. !IN6_ADDRESS32(addr)[1] &&
  2396. !IN6_ADDRESS32(addr)[2] &&
  2397. !IN6_ADDRESS32(addr)[3]);
  2398. case AF_INET:
  2399. return (!IN4_ADDRESS(addr)->s_addr);
  2400. default:
  2401. return 1;
  2402. }
  2403. //return 1;
  2404. }
  2405. /** Given an IPv4 in_addr struct *<b>in</b> (in network order, as usual),
  2406. * write it as a string into the <b>buf_len</b>-byte buffer in
  2407. * <b>buf</b>.
  2408. */
  2409. int
  2410. tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len)
  2411. {
  2412. uint32_t a = ntohl(in->s_addr);
  2413. return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
  2414. (int)(uint8_t)((a>>24)&0xff),
  2415. (int)(uint8_t)((a>>16)&0xff),
  2416. (int)(uint8_t)((a>>8 )&0xff),
  2417. (int)(uint8_t)((a )&0xff));
  2418. }
  2419. /** Take a 32-bit host-order ipv4 address <b>v4addr</b> and store it in the
  2420. * tor_addr *<b>dest</b>.
  2421. *
  2422. * XXXX020 Temporary, for use while 32-bit int addresses are still being
  2423. * passed around.
  2424. */
  2425. void
  2426. tor_addr_from_ipv4(tor_addr_t *dest, uint32_t v4addr)
  2427. {
  2428. tor_assert(dest);
  2429. memset(dest, 0, sizeof(dest));
  2430. dest->sa.sin_family = AF_INET;
  2431. dest->sa.sin_addr.s_addr = htonl(v4addr);
  2432. }
  2433. /** Copy a tor_addr_t from <b>src</b> to <b>dest</b>.
  2434. */
  2435. void
  2436. tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
  2437. {
  2438. tor_assert(src && dest);
  2439. memcpy(dest, src, sizeof(tor_addr_t));
  2440. }
  2441. /** Given two addresses <b>addr1</b> and <b>addr2</b>, return 0 if the two
  2442. * addresses are equivalent under the mask mbits, less than 0 if addr1
  2443. * preceeds addr2, and greater than 0 otherwise.
  2444. *
  2445. * Different address families (IPv4 vs IPv6) are always considered unequal.
  2446. */
  2447. int
  2448. tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2)
  2449. {
  2450. return tor_addr_compare_masked(addr1, addr2, 128);
  2451. }
  2452. /** As tor_addr_compare(), but only looks at the first <b>mask</b> bits of
  2453. * the address.
  2454. *
  2455. * Reduce over-specific masks (>128 for ipv6, >32 for ipv4) to 128 or 32.
  2456. */
  2457. int
  2458. tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
  2459. maskbits_t mbits)
  2460. {
  2461. uint32_t ip4a=0, ip4b=0;
  2462. sa_family_t v_family[2];
  2463. int idx;
  2464. uint32_t masked_a, masked_b;
  2465. tor_assert(addr1 && addr2);
  2466. /* XXXX020 this code doesn't handle mask bits right it's using v4-mapped v6
  2467. * addresses. If I ask whether ::ffff:1.2.3.4 and ::ffff:1.2.7.8 are the
  2468. * same in the first 16 bits, it will say "yes." That's not so intuitive.
  2469. */
  2470. v_family[0] = IN_FAMILY(addr1);
  2471. v_family[1] = IN_FAMILY(addr2);
  2472. if (v_family[0] == AF_INET) { /* If this is native IPv4, note the address */
  2473. ip4a = IPV4IPh(addr1); /* Later we risk overwriting a v4-mapped address */
  2474. } else if ((v_family[0] == AF_INET6) && tor_addr_is_v4(addr1)) {
  2475. v_family[0] = AF_INET;
  2476. ip4a = IPV4MAPh(addr1);
  2477. }
  2478. if (v_family[1] == AF_INET) { /* If this is native IPv4, note the address */
  2479. ip4b = IPV4IPh(addr2); /* Later we risk overwriting a v4-mapped address */
  2480. } else if ((v_family[1] == AF_INET6) && tor_addr_is_v4(addr2)) {
  2481. v_family[1] = AF_INET;
  2482. ip4b = IPV4MAPh(addr2);
  2483. }
  2484. if (v_family[0] > v_family[1]) /* Comparison of virtual families */
  2485. return 1;
  2486. else if (v_family[0] < v_family[1])
  2487. return -1;
  2488. if (mbits == 0) /* Under a complete wildcard mask, consider them equal */
  2489. return 0;
  2490. if (v_family[0] == AF_INET) { /* Real or mapped IPv4 */
  2491. if (mbits >= 32) {
  2492. masked_a = ip4a;
  2493. masked_b = ip4b;
  2494. } else if (mbits == 0) {
  2495. return 0;
  2496. } else {
  2497. masked_a = ip4a >> (32-mbits);
  2498. masked_b = ip4b >> (32-mbits);
  2499. }
  2500. if (masked_a < masked_b)
  2501. return -1;
  2502. else if (masked_a > masked_b)
  2503. return 1;
  2504. return 0;
  2505. } else if (v_family[0] == AF_INET6) { /* Real IPv6 */
  2506. const uint32_t *a1 = IN6_ADDRESS32(addr1);
  2507. const uint32_t *a2 = IN6_ADDRESS32(addr2);
  2508. for (idx = 0; idx < 4; ++idx) {
  2509. uint32_t masked_a = ntohl(a1[idx]);
  2510. uint32_t masked_b = ntohl(a2[idx]);
  2511. if (!mbits) {
  2512. return 0; /* Mask covers both addresses from here on */
  2513. } else if (mbits < 32) {
  2514. masked_a >>= (32-mbits);
  2515. masked_b >>= (32-mbits);
  2516. }
  2517. if (masked_a > masked_b)
  2518. return 1;
  2519. else if (masked_a < masked_b)
  2520. return -1;
  2521. if (mbits < 32)
  2522. return 0;
  2523. mbits -= 32;
  2524. }
  2525. return 0;
  2526. }
  2527. tor_assert(0); /* Unknown address family */
  2528. return -1; /* unknown address family, return unequal? */
  2529. }
  2530. /** Given a host-order <b>addr</b>, call tor_inet_ntop() on it
  2531. * and return a strdup of the resulting address.
  2532. */
  2533. char *
  2534. tor_dup_addr(uint32_t addr)
  2535. {
  2536. char buf[TOR_ADDR_BUF_LEN];
  2537. struct in_addr in;
  2538. in.s_addr = htonl(addr);
  2539. tor_inet_ntop(AF_INET, &in, buf, sizeof(buf));
  2540. return tor_strdup(buf);
  2541. }
  2542. /** Convert the tor_addr_t *<b>addr</b> into string form and store it in
  2543. * <b>dest</b>, which can hold at least <b>len</b> bytes. Returns <b>dest</b>
  2544. * on success, NULL on failure.
  2545. */
  2546. const char *
  2547. tor_addr_to_str(char *dest, const tor_addr_t *addr, int len)
  2548. {
  2549. tor_assert(addr && dest);
  2550. if (IN_FAMILY(addr) == AF_INET) {
  2551. return tor_inet_ntop(AF_INET, IN4_ADDRESS(addr), dest, len);
  2552. } else if (IN_FAMILY(addr) == AF_INET6) {
  2553. return tor_inet_ntop(AF_INET6, IN6_ADDRESS(addr), dest, len);
  2554. } else {
  2555. return NULL;
  2556. }
  2557. }
  2558. /** Convert the string in <b>src</b> to a tor_addr_t <b>addr</b>.
  2559. *
  2560. * Return an address family on success, or -1 if an invalid address string is
  2561. * provided. */
  2562. int
  2563. tor_addr_from_str(tor_addr_t *addr, const char *src)
  2564. {
  2565. tor_assert(addr && src);
  2566. return tor_addr_parse_mask_ports(src, addr, NULL, NULL, NULL);
  2567. }
  2568. /** Set *<b>addr</b> to the IP address (if any) of whatever interface
  2569. * connects to the internet. This address should only be used in checking
  2570. * whether our address has changed. Return 0 on success, -1 on failure.
  2571. */
  2572. int
  2573. get_interface_address6(int severity, sa_family_t family, tor_addr_t *addr)
  2574. {
  2575. int sock=-1, r=-1;
  2576. struct sockaddr_storage my_addr, target_addr;
  2577. socklen_t my_addr_len;
  2578. tor_assert(addr);
  2579. memset(addr, 0, sizeof(tor_addr_t));
  2580. memset(&target_addr, 0, sizeof(target_addr));
  2581. my_addr_len = sizeof(my_addr);
  2582. ((struct sockaddr_in*)&target_addr)->sin_port = 9; /* DISGARD port */
  2583. /* Don't worry: no packets are sent. We just need to use a real address
  2584. * on the actual internet. */
  2585. if (family == AF_INET6) {
  2586. struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
  2587. sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
  2588. my_addr_len = sizeof(struct sockaddr_in6);
  2589. sin6->sin6_family = AF_INET6;
  2590. S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
  2591. } else if (family == AF_INET) {
  2592. struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
  2593. sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
  2594. my_addr_len = sizeof(struct sockaddr_in);
  2595. sin->sin_family = AF_INET;
  2596. sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
  2597. } else {
  2598. return -1;
  2599. }
  2600. if (sock < 0) {
  2601. int e = tor_socket_errno(-1);
  2602. log_fn(severity, LD_NET, "unable to create socket: %s",
  2603. tor_socket_strerror(e));
  2604. goto err;
  2605. }
  2606. if (connect(sock,(struct sockaddr *)&target_addr,sizeof(target_addr))<0) {
  2607. int e = tor_socket_errno(sock);
  2608. log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
  2609. goto err;
  2610. }
  2611. if (getsockname(sock,(struct sockaddr*)&my_addr, &my_addr_len)) {
  2612. int e = tor_socket_errno(sock);
  2613. log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
  2614. tor_socket_strerror(e));
  2615. goto err;
  2616. }
  2617. memcpy(addr, &my_addr, sizeof(tor_addr_t));
  2618. r=0;
  2619. err:
  2620. if (sock >= 0)
  2621. tor_close_socket(sock);
  2622. return r;
  2623. }
  2624. /**
  2625. * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
  2626. * interface connects to the internet. This address should only be used in
  2627. * checking whether our address has changed. Return 0 on success, -1 on
  2628. * failure.
  2629. */
  2630. int
  2631. get_interface_address(int severity, uint32_t *addr)
  2632. {
  2633. tor_addr_t local_addr;
  2634. int r;
  2635. r = get_interface_address6(severity, AF_INET, &local_addr);
  2636. if (r>=0)
  2637. *addr = IPV4IPh(&local_addr);
  2638. return r;
  2639. }
  2640. /* =====
  2641. * Process helpers
  2642. * ===== */
  2643. #ifndef MS_WINDOWS
  2644. /* Based on code contributed by christian grothoff */
  2645. /** True iff we've called start_daemon(). */
  2646. static int start_daemon_called = 0;
  2647. /** True iff we've called finish_daemon(). */
  2648. static int finish_daemon_called = 0;
  2649. /** Socketpair used to communicate between parent and child process while
  2650. * daemonizing. */
  2651. static int daemon_filedes[2];
  2652. /** Start putting the process into daemon mode: fork and drop all resources
  2653. * except standard fds. The parent process never returns, but stays around
  2654. * until finish_daemon is called. (Note: it's safe to call this more
  2655. * than once: calls after the first are ignored.)
  2656. */
  2657. void
  2658. start_daemon(void)
  2659. {
  2660. pid_t pid;
  2661. if (start_daemon_called)
  2662. return;
  2663. start_daemon_called = 1;
  2664. pipe(daemon_filedes);
  2665. pid = fork();
  2666. if (pid < 0) {
  2667. log_err(LD_GENERAL,"fork failed. Exiting.");
  2668. exit(1);
  2669. }
  2670. if (pid) { /* Parent */
  2671. int ok;
  2672. char c;
  2673. close(daemon_filedes[1]); /* we only read */
  2674. ok = -1;
  2675. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  2676. if (c == '.')
  2677. ok = 1;
  2678. }
  2679. fflush(stdout);
  2680. if (ok == 1)
  2681. exit(0);
  2682. else
  2683. exit(1); /* child reported error */
  2684. } else { /* Child */
  2685. close(daemon_filedes[0]); /* we only write */
  2686. pid = setsid(); /* Detach from controlling terminal */
  2687. /*
  2688. * Fork one more time, so the parent (the session group leader) can exit.
  2689. * This means that we, as a non-session group leader, can never regain a
  2690. * controlling terminal. This part is recommended by Stevens's
  2691. * _Advanced Programming in the Unix Environment_.
  2692. */
  2693. if (fork() != 0) {
  2694. exit(0);
  2695. }
  2696. return;
  2697. }
  2698. }
  2699. /** Finish putting the process into daemon mode: drop standard fds, and tell
  2700. * the parent process to exit. (Note: it's safe to call this more than once:
  2701. * calls after the first are ignored. Calls start_daemon first if it hasn't
  2702. * been called already.)
  2703. */
  2704. void
  2705. finish_daemon(const char *desired_cwd)
  2706. {
  2707. int nullfd;
  2708. char c = '.';
  2709. if (finish_daemon_called)
  2710. return;
  2711. if (!start_daemon_called)
  2712. start_daemon();
  2713. finish_daemon_called = 1;
  2714. if (!desired_cwd)
  2715. desired_cwd = "/";
  2716. /* Don't hold the wrong FS mounted */
  2717. if (chdir(desired_cwd) < 0) {
  2718. log_err(LD_GENERAL,"chdir to \"%s\" failed. Exiting.",desired_cwd);
  2719. exit(1);
  2720. }
  2721. nullfd = open("/dev/null",
  2722. O_CREAT | O_RDWR | O_APPEND);
  2723. if (nullfd < 0) {
  2724. log_err(LD_GENERAL,"/dev/null can't be opened. Exiting.");
  2725. exit(1);
  2726. }
  2727. /* close fds linking to invoking terminal, but
  2728. * close usual incoming fds, but redirect them somewhere
  2729. * useful so the fds don't get reallocated elsewhere.
  2730. */
  2731. if (dup2(nullfd,0) < 0 ||
  2732. dup2(nullfd,1) < 0 ||
  2733. dup2(nullfd,2) < 0) {
  2734. log_err(LD_GENERAL,"dup2 failed. Exiting.");
  2735. exit(1);
  2736. }
  2737. if (nullfd > 2)
  2738. close(nullfd);
  2739. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  2740. close(daemon_filedes[1]);
  2741. }
  2742. #else
  2743. /* defined(MS_WINDOWS) */
  2744. void
  2745. start_daemon(void)
  2746. {
  2747. }
  2748. void
  2749. finish_daemon(const char *cp)
  2750. {
  2751. (void)cp;
  2752. }
  2753. #endif
  2754. /** Write the current process ID, followed by NL, into <b>filename</b>.
  2755. */
  2756. void
  2757. write_pidfile(char *filename)
  2758. {
  2759. FILE *pidfile;
  2760. if ((pidfile = fopen(filename, "w")) == NULL) {
  2761. log_warn(LD_FS, "Unable to open \"%s\" for writing: %s", filename,
  2762. strerror(errno));
  2763. } else {
  2764. #ifdef MS_WINDOWS
  2765. fprintf(pidfile, "%d\n", (int)_getpid());
  2766. #else
  2767. fprintf(pidfile, "%d\n", (int)getpid());
  2768. #endif
  2769. fclose(pidfile);
  2770. }
  2771. }