util.c 82 KB

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