util.c 82 KB

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