util.c 74 KB

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