util.c 82 KB

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