util.c 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457
  1. /* Copyright 2003 Roger Dingledine */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /**
  5. * \file util.c
  6. *
  7. * \brief Common functions for strings, IO, network, data structures,
  8. * process control, and cross-platform portability.
  9. **/
  10. /* This is required on rh7 to make strptime not complain.
  11. */
  12. #define _GNU_SOURCE
  13. #include "orconfig.h"
  14. #ifdef MS_WINDOWS
  15. #define WIN32_WINNT 0x400
  16. #define _WIN32_WINNT 0x400
  17. #define WIN32_LEAN_AND_MEAN
  18. #if _MSC_VER > 1300
  19. #include <winsock2.h>
  20. #include <ws2tcpip.h>
  21. #elif defined(_MSC_VER)
  22. #include <winsock.h>
  23. #endif
  24. #include <io.h>
  25. #include <process.h>
  26. #include <direct.h>
  27. #include <windows.h>
  28. #endif
  29. #include <stdlib.h>
  30. #include <stdio.h>
  31. #include <string.h>
  32. #include <assert.h>
  33. #ifndef HAVE_GETTIMEOFDAY
  34. #ifdef HAVE_FTIME
  35. #include <sys/timeb.h>
  36. #endif
  37. #endif
  38. #include "util.h"
  39. #include "log.h"
  40. #include "crypto.h"
  41. #include "../or/tree.h"
  42. #ifdef HAVE_UNAME
  43. #include <sys/utsname.h>
  44. #endif
  45. #ifdef HAVE_CTYPE_H
  46. #include <ctype.h>
  47. #endif
  48. #ifdef HAVE_NETINET_IN_H
  49. #include <netinet/in.h>
  50. #endif
  51. #ifdef HAVE_ARPA_INET_H
  52. #include <arpa/inet.h>
  53. #endif
  54. #ifdef HAVE_ERRNO_H
  55. #include <errno.h>
  56. #endif
  57. #ifdef HAVE_LIMITS_H
  58. #include <limits.h>
  59. #endif
  60. #ifdef HAVE_SYS_PARAM_H
  61. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  62. #endif
  63. #ifdef HAVE_SYS_LIMITS_H
  64. #include <sys/limits.h>
  65. #endif
  66. #ifdef HAVE_MACHINE_LIMITS_H
  67. #ifndef __FreeBSD__
  68. /* FreeBSD has a bug where it complains that this file is obsolete,
  69. and I should migrate to using sys/limits. It complains even when
  70. I include both. */
  71. #include <machine/limits.h>
  72. #endif
  73. #endif
  74. #ifdef HAVE_SYS_TYPES_H
  75. #include <sys/types.h> /* Must be included before sys/stat.h for Ultrix */
  76. #endif
  77. #ifdef HAVE_SYS_SOCKET_H
  78. #include <sys/socket.h>
  79. #endif
  80. #ifdef HAVE_NETDB_H
  81. #include <netdb.h>
  82. #endif
  83. #ifdef HAVE_UNISTD_H
  84. #include <unistd.h>
  85. #endif
  86. #ifdef HAVE_SYS_STAT_H
  87. #include <sys/stat.h>
  88. #endif
  89. #ifdef HAVE_SYS_FCNTL_H
  90. #include <sys/fcntl.h>
  91. #endif
  92. #ifdef HAVE_PWD_H
  93. #include <pwd.h>
  94. #endif
  95. #ifdef HAVE_GRP_H
  96. #include <grp.h>
  97. #endif
  98. #ifdef HAVE_FCNTL_H
  99. #include <fcntl.h>
  100. #endif
  101. /* used by inet_addr, not defined on solaris anywhere!? */
  102. #ifndef INADDR_NONE
  103. #define INADDR_NONE ((unsigned long) -1)
  104. #endif
  105. /* Inline the strl functions if the plaform doesn't have them. */
  106. #ifndef HAVE_STRLCPY
  107. #include "strlcpy.c"
  108. #endif
  109. #ifndef HAVE_STRLCAT
  110. #include "strlcat.c"
  111. #endif
  112. #ifndef O_BINARY
  113. #define O_BINARY 0
  114. #endif
  115. /** Allocate a chunk of <b>size</b> bytes of memory, and return a pointer to
  116. * result. On error, log and terminate the process. (Same as malloc(size),
  117. * but never returns NULL.)
  118. */
  119. void *tor_malloc(size_t size) {
  120. void *result;
  121. /* Some libcs don't do the right thing on size==0. Override them. */
  122. if (size==0) {
  123. size=1;
  124. }
  125. result = malloc(size);
  126. if(!result) {
  127. log_fn(LOG_ERR, "Out of memory. Dying.");
  128. exit(1);
  129. }
  130. // memset(result,'X',size); /* deadbeef to encourage bugs */
  131. return result;
  132. }
  133. /* Allocate a chunk of <b>size</b> bytes of memory, fill the memory with
  134. * zero bytes, and return a pointer to the result. Log and terminate
  135. * the process on error. (Same as calloc(size,1), but never returns NULL.)
  136. */
  137. void *tor_malloc_zero(size_t size) {
  138. void *result = tor_malloc(size);
  139. memset(result, 0, size);
  140. return result;
  141. }
  142. /** Change the size of the memory block pointed to by <b>ptr</b> to <b>size</b>
  143. * bytes long; return the new memory block. On error, log and
  144. * terminate. (Like realloc(ptr,size), but never returns NULL.)
  145. */
  146. void *tor_realloc(void *ptr, size_t size) {
  147. void *result;
  148. result = realloc(ptr, size);
  149. if (!result) {
  150. log_fn(LOG_ERR, "Out of memory. Dying.");
  151. exit(1);
  152. }
  153. return result;
  154. }
  155. /** Return a newly allocated copy of the NUL-terminated string s. On
  156. * error, log and terminate. (Like strdup(s), but never returns
  157. * NULL.)
  158. */
  159. char *tor_strdup(const char *s) {
  160. char *dup;
  161. tor_assert(s);
  162. dup = strdup(s);
  163. if(!dup) {
  164. log_fn(LOG_ERR,"Out of memory. Dying.");
  165. exit(1);
  166. }
  167. return dup;
  168. }
  169. /** Allocate and return a new string containing the first <b>n</b>
  170. * characters of <b>s</b>. If <b>s</b> is longer than <b>n</b>
  171. * characters, only the first <b>n</b> are copied. The result is
  172. * always NUL-terminated. (Like strndup(s,n), but never returns
  173. * NULL.)
  174. */
  175. char *tor_strndup(const char *s, size_t n) {
  176. char *dup;
  177. tor_assert(s);
  178. dup = tor_malloc(n+1);
  179. strlcpy(dup, s, n+1);
  180. return dup;
  181. }
  182. /** Remove from the string <b>s</b> every character which appears in
  183. * <b>strip</b>. Return the number of characters removed. */
  184. int tor_strstrip(char *s, const char *strip)
  185. {
  186. char *read = s;
  187. while (*read) {
  188. if (strchr(strip, *read)) {
  189. ++read;
  190. } else {
  191. *s++ = *read++;
  192. }
  193. }
  194. *s = '\0';
  195. return read-s;
  196. }
  197. /** Set the <b>dest_len</b>-byte buffer <b>buf</b> to contain the
  198. * string <b>s</b>, with the string <b>insert</b> inserted after every
  199. * <b>n</b> characters. Return 0 on success, -1 on failure.
  200. *
  201. * If <b>rule</b> is ALWAYS_TERMINATE, then always end the string with
  202. * <b>insert</b>, even if its length is not a multiple of <b>n</b>. If
  203. * <b>rule</b> is NEVER_TERMINATE, then never end the string with
  204. * <b>insert</b>, even if its length <i>is</i> a multiple of <b>n</b>.
  205. * If <b>rule</b> is TERMINATE_IF_EVEN, then end the string with <b>insert</b>
  206. * exactly when its length <i>is</i> a multiple of <b>n</b>.
  207. */
  208. int tor_strpartition(char *dest, size_t dest_len,
  209. const char *s, const char *insert, size_t n,
  210. part_finish_rule_t rule)
  211. {
  212. char *destp;
  213. size_t len_in, len_out, len_ins;
  214. int is_even, remaining;
  215. tor_assert(s);
  216. tor_assert(insert);
  217. tor_assert(n > 0);
  218. len_in = strlen(s);
  219. len_ins = strlen(insert);
  220. len_out = len_in + (len_in/n)*len_ins;
  221. is_even = (len_in%n) == 0;
  222. switch(rule)
  223. {
  224. case ALWAYS_TERMINATE:
  225. if (!is_even) len_out += len_ins;
  226. break;
  227. case NEVER_TERMINATE:
  228. if (is_even && len_in) len_out -= len_ins;
  229. break;
  230. case TERMINATE_IF_EVEN:
  231. break;
  232. }
  233. if (dest_len < len_out+1)
  234. return -1;
  235. destp = dest;
  236. remaining = len_in;
  237. while(remaining) {
  238. strncpy(destp, s, n);
  239. remaining -= n;
  240. if (remaining < 0) {
  241. if (rule == ALWAYS_TERMINATE)
  242. strcpy(destp+n+remaining,insert);
  243. break;
  244. } else if (remaining == 0 && rule == NEVER_TERMINATE) {
  245. *(destp+n) = '\0';
  246. break;
  247. }
  248. strcpy(destp+n, insert);
  249. s += n;
  250. destp += n+len_ins;
  251. }
  252. tor_assert(len_out == strlen(dest));
  253. return 0;
  254. }
  255. #ifndef UNALIGNED_INT_ACCESS_OK
  256. /**
  257. * Read a 16-bit value beginning at <b>cp</b>. Equaivalent to
  258. * *(uint16_t*)(cp), but will not cause segfaults on platforms that forbid
  259. * unaligned memory access.
  260. */
  261. uint16_t get_uint16(const char *cp)
  262. {
  263. uint16_t v;
  264. memcpy(&v,cp,2);
  265. return v;
  266. }
  267. /**
  268. * Read a 32-bit value beginning at <b>cp</b>. Equaivalent to
  269. * *(uint32_t*)(cp), but will not cause segfaults on platforms that forbid
  270. * unaligned memory access.
  271. */
  272. uint32_t get_uint32(const char *cp)
  273. {
  274. uint32_t v;
  275. memcpy(&v,cp,4);
  276. return v;
  277. }
  278. /**
  279. * Set a 16-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  280. * *(uint16_t)(cp) = v, but will not cause segfaults on platforms that forbid
  281. * unaligned memory access. */
  282. void set_uint16(char *cp, uint16_t v)
  283. {
  284. memcpy(cp,&v,2);
  285. }
  286. /**
  287. * Set a 32-bit value beginning at <b>cp</b> to <b>v</b>. Equivalent to
  288. * *(uint32_t)(cp) = v, but will not cause segfaults on platforms that forbid
  289. * unaligned memory access. */
  290. void set_uint32(char *cp, uint32_t v)
  291. {
  292. memcpy(cp,&v,4);
  293. }
  294. #endif
  295. /** Return a pointer to a NUL-terminated hexidecimal string encoding
  296. * the first <b>fromlen</b> bytes of <b>from</b>. (fromlen must be \<= 32.) The
  297. * result does not need to be deallocated, but repeated calls to
  298. * hex_str will trash old results.
  299. */
  300. const char *hex_str(const char *from, size_t fromlen)
  301. {
  302. static char buf[65];
  303. if (fromlen>(sizeof(buf)-1)/2)
  304. fromlen = (sizeof(buf)-1)/2;
  305. base16_encode(buf,sizeof(buf),from,fromlen);
  306. return buf;
  307. }
  308. /*****
  309. * smartlist_t: a simple resizeable array abstraction.
  310. *****/
  311. /* All newly allocated smartlists have this capacity.
  312. */
  313. #define SMARTLIST_DEFAULT_CAPACITY 32
  314. struct smartlist_t {
  315. /** <b>list</b> has enough capacity to store exactly <b>capacity</b> elements
  316. * before it needs to be resized. Only the first <b>num_used</b> (\<=
  317. * capacity) elements point to valid data.
  318. */
  319. void **list;
  320. int num_used;
  321. int capacity;
  322. };
  323. /** Allocate and return an empty smartlist.
  324. */
  325. smartlist_t *smartlist_create() {
  326. smartlist_t *sl = tor_malloc(sizeof(smartlist_t));
  327. sl->num_used = 0;
  328. sl->capacity = SMARTLIST_DEFAULT_CAPACITY;
  329. sl->list = tor_malloc(sizeof(void *) * sl->capacity);
  330. return sl;
  331. }
  332. /** Deallocate a smartlist. Does not release storage associated with the
  333. * list's elements.
  334. */
  335. void smartlist_free(smartlist_t *sl) {
  336. free(sl->list);
  337. free(sl);
  338. }
  339. /** Change the capacity of the smartlist to <b>n</b>, so that we can grow
  340. * the list up to <b>n</b> elements with no further reallocation or wasted
  341. * space. If <b>n</b> is less than or equal to the number of elements
  342. * currently in the list, reduce the list's capacity as much as
  343. * possible without losing elements.
  344. */
  345. void smartlist_set_capacity(smartlist_t *sl, int n) {
  346. if (n < sl->num_used)
  347. n = sl->num_used;
  348. if (sl->capacity != n) {
  349. sl->capacity = n;
  350. sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
  351. }
  352. }
  353. /** Remove all elements from the list.
  354. */
  355. void smartlist_clear(smartlist_t *sl) {
  356. sl->num_used = 0;
  357. }
  358. /** Set the list's new length to <b>len</b> (which must be \<= the list's
  359. * current size). Remove the last smartlist_len(sl)-len elements from the
  360. * list.
  361. */
  362. void smartlist_truncate(smartlist_t *sl, int len)
  363. {
  364. tor_assert(len <= sl->num_used);
  365. sl->num_used = len;
  366. }
  367. /** Append element to the end of the list. */
  368. void smartlist_add(smartlist_t *sl, void *element) {
  369. if (sl->num_used >= sl->capacity) {
  370. sl->capacity *= 2;
  371. sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
  372. }
  373. sl->list[sl->num_used++] = element;
  374. }
  375. /** Append each element from S2 to the end of S1. */
  376. void smartlist_add_all(smartlist_t *sl, const smartlist_t *s2)
  377. {
  378. SMARTLIST_FOREACH(s2, void *, element, smartlist_add(sl, element));
  379. }
  380. /** Remove all elements E from sl such that E==element. Does not preserve
  381. * the order of s1.
  382. */
  383. void smartlist_remove(smartlist_t *sl, void *element) {
  384. int i;
  385. if(element == NULL)
  386. return;
  387. for(i=0; i < sl->num_used; i++)
  388. if(sl->list[i] == element) {
  389. sl->list[i] = sl->list[--sl->num_used]; /* swap with the end */
  390. i--; /* so we process the new i'th element */
  391. }
  392. }
  393. /** Return true iff some element E of sl has E==element.
  394. */
  395. int smartlist_isin(const smartlist_t *sl, void *element) {
  396. int i;
  397. for(i=0; i < sl->num_used; i++)
  398. if(sl->list[i] == element)
  399. return 1;
  400. return 0;
  401. }
  402. int smartlist_string_isin(const smartlist_t *sl, const char *element) {
  403. int i;
  404. for(i=0; i < sl->num_used; i++)
  405. if(strcmp((const char*)sl->list[i],element)==0)
  406. return 1;
  407. return 0;
  408. }
  409. /** Return true iff some element E of sl2 has smartlist_isin(sl1,E).
  410. */
  411. int smartlist_overlap(const smartlist_t *sl1, const smartlist_t *sl2) {
  412. int i;
  413. for(i=0; i < sl2->num_used; i++)
  414. if(smartlist_isin(sl1, sl2->list[i]))
  415. return 1;
  416. return 0;
  417. }
  418. /** Remove every element E of sl1 such that !smartlist_isin(sl2,E).
  419. * Does not preserve the order of sl1.
  420. */
  421. void smartlist_intersect(smartlist_t *sl1, const smartlist_t *sl2) {
  422. int i;
  423. for(i=0; i < sl1->num_used; i++)
  424. if(!smartlist_isin(sl2, sl1->list[i])) {
  425. sl1->list[i] = sl1->list[--sl1->num_used]; /* swap with the end */
  426. i--; /* so we process the new i'th element */
  427. }
  428. }
  429. /** Remove every element E of sl1 such that smartlist_isin(sl2,E).
  430. * Does not preserve the order of sl1.
  431. */
  432. void smartlist_subtract(smartlist_t *sl1, const smartlist_t *sl2) {
  433. int i;
  434. for(i=0; i < sl2->num_used; i++)
  435. smartlist_remove(sl1, sl2->list[i]);
  436. }
  437. /** Return the <b>idx</b>th element of sl.
  438. */
  439. void *smartlist_get(const smartlist_t *sl, int idx)
  440. {
  441. tor_assert(sl);
  442. tor_assert(idx>=0);
  443. tor_assert(idx < sl->num_used);
  444. return sl->list[idx];
  445. }
  446. /** Change the value of the <b>idx</b>th element of sl to <b>val</b>; return the old
  447. * value of the <b>idx</b>th element.
  448. */
  449. void *smartlist_set(smartlist_t *sl, int idx, void *val)
  450. {
  451. void *old;
  452. tor_assert(sl);
  453. tor_assert(idx>=0);
  454. tor_assert(idx < sl->num_used);
  455. old = sl->list[idx];
  456. sl->list[idx] = val;
  457. return old;
  458. }
  459. /** Remove the <b>idx</b>th element of sl; if idx is not the last
  460. * element, swap the last element of sl into the <b>idx</b>th space.
  461. * Return the old value of the <b>idx</b>th element.
  462. */
  463. void *smartlist_del(smartlist_t *sl, int idx)
  464. {
  465. void *old;
  466. tor_assert(sl);
  467. tor_assert(idx>=0);
  468. tor_assert(idx < sl->num_used);
  469. old = sl->list[idx];
  470. sl->list[idx] = sl->list[--sl->num_used];
  471. return old;
  472. }
  473. /** Remove the <b>idx</b>th element of sl; if idx is not the last element,
  474. * moving all subsequent elements back one space. Return the old value
  475. * of the <b>idx</b>th element.
  476. */
  477. void *smartlist_del_keeporder(smartlist_t *sl, int idx)
  478. {
  479. void *old;
  480. tor_assert(sl);
  481. tor_assert(idx>=0);
  482. tor_assert(idx < sl->num_used);
  483. old = sl->list[idx];
  484. --sl->num_used;
  485. if (idx < sl->num_used)
  486. memmove(sl->list+idx, sl->list+idx+1, sizeof(void*)*(sl->num_used-idx));
  487. return old;
  488. }
  489. /** Return the number of items in sl.
  490. */
  491. int smartlist_len(const smartlist_t *sl)
  492. {
  493. return sl->num_used;
  494. }
  495. /** Insert the value <b>val</b> as the new <b>idx</b>th element of
  496. * <b>sl</b>, moving all items previously at <b>idx</b> or later
  497. * forward one space.
  498. */
  499. void smartlist_insert(smartlist_t *sl, int idx, void *val)
  500. {
  501. tor_assert(sl);
  502. tor_assert(idx>=0);
  503. tor_assert(idx <= sl->num_used);
  504. if (idx == sl->num_used) {
  505. smartlist_add(sl, val);
  506. } else {
  507. /* Ensure sufficient capacity */
  508. if (sl->num_used >= sl->capacity) {
  509. sl->capacity *= 2;
  510. sl->list = tor_realloc(sl->list, sizeof(void*)*sl->capacity);
  511. }
  512. /* Move other elements away */
  513. if (idx < sl->num_used)
  514. memmove(sl->list + idx + 1, sl->list + idx,
  515. sizeof(void*)*(sl->num_used-idx));
  516. sl->num_used++;
  517. sl->list[idx] = val;
  518. }
  519. }
  520. /**
  521. * Split a string <b>str</b> along all occurences of <b>sep</b>,
  522. * adding the split strings, in order, to <b>sl</b>. If
  523. * <b>flags</b>&amp;SPLIT_SKIP_SPACE is true, remove initial and
  524. * trailing space from each entry. If
  525. * <b>flags</b>&amp;SPLIT_IGNORE_BLANK is true, remove any entries of
  526. * length 0. If max>0, divide the string into no more than <b>max</b>
  527. * pieces.
  528. */
  529. int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep,
  530. int flags, int max)
  531. {
  532. const char *cp, *end, *next;
  533. int n = 0;
  534. tor_assert(sl);
  535. tor_assert(str);
  536. tor_assert(sep);
  537. cp = str;
  538. while (1) {
  539. if (flags&SPLIT_SKIP_SPACE) {
  540. while (isspace((int)*cp)) ++cp;
  541. }
  542. if (max>0 && n == max-1) {
  543. end = strchr(cp,'\0');
  544. } else {
  545. end = strstr(cp,sep);
  546. if (!end)
  547. end = strchr(cp,'\0');
  548. }
  549. if (!*end) {
  550. next = NULL;
  551. } else {
  552. next = end+strlen(sep);
  553. }
  554. if (flags&SPLIT_SKIP_SPACE) {
  555. while (end > cp && isspace((int)*(end-1)))
  556. --end;
  557. }
  558. if (end != cp || !(flags&SPLIT_IGNORE_BLANK)) {
  559. smartlist_add(sl, tor_strndup(cp, end-cp));
  560. ++n;
  561. }
  562. if (!next)
  563. break;
  564. cp = next;
  565. }
  566. return n;
  567. }
  568. /** Allocate and return a new string containing the concatenation of
  569. * the elements of <b>sl</b>, in order, separated by <b>join</b>. If
  570. * <b>terminate</b> is true, also terminate the string with <b>join</b>.
  571. * Requires that every element of <b>sl</b> is NUL-terminated string.
  572. */
  573. char *smartlist_join_strings(smartlist_t *sl, const char *join, int terminate)
  574. {
  575. int i;
  576. size_t n = 0, jlen;
  577. char *r = NULL, *dst, *src;
  578. tor_assert(sl);
  579. tor_assert(join);
  580. jlen = strlen(join);
  581. for (i = 0; i < sl->num_used; ++i) {
  582. n += strlen(sl->list[i]);
  583. n += jlen;
  584. }
  585. if (!terminate) n -= jlen;
  586. dst = r = tor_malloc(n+1);
  587. for (i = 0; i < sl->num_used; ) {
  588. for (src = sl->list[i]; *src; )
  589. *dst++ = *src++;
  590. if (++i < sl->num_used || terminate) {
  591. memcpy(dst, join, jlen);
  592. dst += jlen;
  593. }
  594. }
  595. *dst = '\0';
  596. return r;
  597. }
  598. /* Splay-tree implementation of string-to-void* map
  599. */
  600. struct strmap_entry_t {
  601. SPLAY_ENTRY(strmap_entry_t) node;
  602. char *key;
  603. void *val;
  604. };
  605. struct strmap_t {
  606. SPLAY_HEAD(strmap_tree, strmap_entry_t) head;
  607. };
  608. static int compare_strmap_entries(struct strmap_entry_t *a,
  609. struct strmap_entry_t *b)
  610. {
  611. return strcmp(a->key, b->key);
  612. }
  613. SPLAY_PROTOTYPE(strmap_tree, strmap_entry_t, node, compare_strmap_entries);
  614. SPLAY_GENERATE(strmap_tree, strmap_entry_t, node, compare_strmap_entries);
  615. /** Create a new empty map from strings to void*'s.
  616. */
  617. strmap_t* strmap_new(void)
  618. {
  619. strmap_t *result;
  620. result = tor_malloc(sizeof(strmap_t));
  621. SPLAY_INIT(&result->head);
  622. return result;
  623. }
  624. /** Set the current value for <b>key</b> to <b>val</b>. Returns the previous
  625. * value for <b>key</b> if one was set, or NULL if one was not.
  626. *
  627. * This function makes a copy of <b>key</b> if necessary, but not of <b>val</b>.
  628. */
  629. void* strmap_set(strmap_t *map, const char *key, void *val)
  630. {
  631. strmap_entry_t *resolve;
  632. strmap_entry_t search;
  633. void *oldval;
  634. tor_assert(map);
  635. tor_assert(key);
  636. tor_assert(val);
  637. search.key = (char*)key;
  638. resolve = SPLAY_FIND(strmap_tree, &map->head, &search);
  639. if (resolve) {
  640. oldval = resolve->val;
  641. resolve->val = val;
  642. return oldval;
  643. } else {
  644. resolve = tor_malloc_zero(sizeof(strmap_entry_t));
  645. resolve->key = tor_strdup(key);
  646. resolve->val = val;
  647. SPLAY_INSERT(strmap_tree, &map->head, resolve);
  648. return NULL;
  649. }
  650. }
  651. /** Return the current value associated with <b>key</b>, or NULL if no
  652. * value is set.
  653. */
  654. void* strmap_get(strmap_t *map, const char *key)
  655. {
  656. strmap_entry_t *resolve;
  657. strmap_entry_t search;
  658. tor_assert(map);
  659. tor_assert(key);
  660. search.key = (char*)key;
  661. resolve = SPLAY_FIND(strmap_tree, &map->head, &search);
  662. if (resolve) {
  663. return resolve->val;
  664. } else {
  665. return NULL;
  666. }
  667. }
  668. /** Remove the value currently associated with <b>key</b> from the map.
  669. * Return the value if one was set, or NULL if there was no entry for
  670. * <b>key</b>.
  671. *
  672. * Note: you must free any storage associated with the returned value.
  673. */
  674. void* strmap_remove(strmap_t *map, const char *key)
  675. {
  676. strmap_entry_t *resolve;
  677. strmap_entry_t search;
  678. void *oldval;
  679. tor_assert(map);
  680. tor_assert(key);
  681. search.key = (char*)key;
  682. resolve = SPLAY_FIND(strmap_tree, &map->head, &search);
  683. if (resolve) {
  684. oldval = resolve->val;
  685. SPLAY_REMOVE(strmap_tree, &map->head, resolve);
  686. tor_free(resolve->key);
  687. tor_free(resolve);
  688. return oldval;
  689. } else {
  690. return NULL;
  691. }
  692. }
  693. /** Same as strmap_set, but first converts <b>key</b> to lowercase. */
  694. void* strmap_set_lc(strmap_t *map, const char *key, void *val)
  695. {
  696. /* We could be a little faster by using strcasecmp instead, and a separate
  697. * type, but I don't think it matters. */
  698. void *v;
  699. char *lc_key = tor_strdup(key);
  700. tor_strlower(lc_key);
  701. v = strmap_set(map,lc_key,val);
  702. tor_free(lc_key);
  703. return v;
  704. }
  705. /** Same as strmap_get, but first converts <b>key</b> to lowercase. */
  706. void* strmap_get_lc(strmap_t *map, const char *key)
  707. {
  708. void *v;
  709. char *lc_key = tor_strdup(key);
  710. tor_strlower(lc_key);
  711. v = strmap_get(map,lc_key);
  712. tor_free(lc_key);
  713. return v;
  714. }
  715. /** Same as strmap_remove, but first converts <b>key</b> to lowercase */
  716. void* strmap_remove_lc(strmap_t *map, const char *key)
  717. {
  718. void *v;
  719. char *lc_key = tor_strdup(key);
  720. tor_strlower(lc_key);
  721. v = strmap_remove(map,lc_key);
  722. tor_free(lc_key);
  723. return v;
  724. }
  725. /** Invoke fn() on every entry of the map, in order. For every entry,
  726. * fn() is invoked with that entry's key, that entry's value, and the
  727. * value of <b>data</b> supplied to strmap_foreach. fn() must return a new
  728. * (possibly unmodified) value for each entry: if fn() returns NULL, the
  729. * entry is removed.
  730. *
  731. * Example:
  732. * \code
  733. * static void* upcase_and_remove_empty_vals(const char *key, void *val,
  734. * void* data) {
  735. * char *cp = (char*)val;
  736. * if (!*cp) { // val is an empty string.
  737. * free(val);
  738. * return NULL;
  739. * } else {
  740. * for (; *cp; cp++)
  741. * *cp = toupper(*cp);
  742. * }
  743. * return val;
  744. * }
  745. * }
  746. *
  747. * ...
  748. *
  749. * strmap_foreach(map, upcase_and_remove_empty_vals, NULL);
  750. * \endcode
  751. */
  752. void strmap_foreach(strmap_t *map,
  753. void* (*fn)(const char *key, void *val, void *data),
  754. void *data)
  755. {
  756. strmap_entry_t *ptr, *next;
  757. tor_assert(map);
  758. tor_assert(fn);
  759. for (ptr = SPLAY_MIN(strmap_tree, &map->head); ptr != NULL; ptr = next) {
  760. /* This remove-in-place usage is specifically blessed in tree(3). */
  761. next = SPLAY_NEXT(strmap_tree, &map->head, ptr);
  762. ptr->val = fn(ptr->key, ptr->val, data);
  763. if (!ptr->val) {
  764. SPLAY_REMOVE(strmap_tree, &map->head, ptr);
  765. tor_free(ptr->key);
  766. tor_free(ptr);
  767. }
  768. }
  769. }
  770. /** return an <b>iterator</b> pointer to the front of a map.
  771. *
  772. * Iterator example:
  773. *
  774. * \code
  775. * // uppercase values in "map", removing empty values.
  776. *
  777. * strmap_iter_t *iter;
  778. * const char *key;
  779. * void *val;
  780. * char *cp;
  781. *
  782. * for (iter = strmap_iter_init(map); !strmap_iter_done(iter); ) {
  783. * strmap_iter_get(iter, &key, &val);
  784. * cp = (char*)val;
  785. * if (!*cp) {
  786. * iter = strmap_iter_next_rmv(iter);
  787. * free(val);
  788. * } else {
  789. * for(;*cp;cp++) *cp = toupper(*cp);
  790. * iter = strmap_iter_next(iter);
  791. * }
  792. * }
  793. * \endcode
  794. *
  795. */
  796. strmap_iter_t *strmap_iter_init(strmap_t *map)
  797. {
  798. tor_assert(map);
  799. return SPLAY_MIN(strmap_tree, &map->head);
  800. }
  801. /** Advance the iterator <b>iter</b> for map a single step to the next entry.
  802. */
  803. strmap_iter_t *strmap_iter_next(strmap_t *map, strmap_iter_t *iter)
  804. {
  805. tor_assert(map);
  806. tor_assert(iter);
  807. return SPLAY_NEXT(strmap_tree, &map->head, iter);
  808. }
  809. /** Advance the iterator <b>iter</b> a single step to the next entry, removing
  810. * the current entry.
  811. */
  812. strmap_iter_t *strmap_iter_next_rmv(strmap_t *map, strmap_iter_t *iter)
  813. {
  814. strmap_iter_t *next;
  815. tor_assert(map);
  816. tor_assert(iter);
  817. next = SPLAY_NEXT(strmap_tree, &map->head, iter);
  818. SPLAY_REMOVE(strmap_tree, &map->head, iter);
  819. tor_free(iter->key);
  820. tor_free(iter);
  821. return next;
  822. }
  823. /** Set *keyp and *valp to the current entry pointed to by iter.
  824. */
  825. void strmap_iter_get(strmap_iter_t *iter, const char **keyp, void **valp)
  826. {
  827. tor_assert(iter);
  828. tor_assert(keyp);
  829. tor_assert(valp);
  830. *keyp = iter->key;
  831. *valp = iter->val;
  832. }
  833. /** Return true iff iter has advanced past the last entry of map.
  834. */
  835. int strmap_iter_done(strmap_iter_t *iter)
  836. {
  837. return iter == NULL;
  838. }
  839. /** Remove all entries from <b>map</b>, and deallocate storage for those entries.
  840. * If free_val is provided, it is invoked on every value in <b>map</b>.
  841. */
  842. void strmap_free(strmap_t *map, void (*free_val)(void*))
  843. {
  844. strmap_entry_t *ent, *next;
  845. for (ent = SPLAY_MIN(strmap_tree, &map->head); ent != NULL; ent = next) {
  846. next = SPLAY_NEXT(strmap_tree, &map->head, ent);
  847. SPLAY_REMOVE(strmap_tree, &map->head, ent);
  848. tor_free(ent->key);
  849. if (free_val)
  850. tor_free(ent->val);
  851. }
  852. tor_assert(SPLAY_EMPTY(&map->head));
  853. tor_free(map);
  854. }
  855. int strmap_isempty(strmap_t *map)
  856. {
  857. return SPLAY_EMPTY(&map->head);
  858. }
  859. /*
  860. * String manipulation
  861. */
  862. /** Convert all alphabetic characters in the nul-terminated string <b>s</b> to
  863. * lowercase. */
  864. void tor_strlower(char *s)
  865. {
  866. while (*s) {
  867. *s = tolower(*s);
  868. ++s;
  869. }
  870. }
  871. /* Compares the first strlen(s2) characters of s1 with s2. Returns as for
  872. * strcmp.
  873. */
  874. int strcmpstart(const char *s1, const char *s2)
  875. {
  876. size_t n = strlen(s2);
  877. return strncmp(s1, s2, n);
  878. }
  879. /** Return a pointer to the first char of s that is not whitespace and
  880. * not a comment, or to the terminating NUL if no such character exists.
  881. */
  882. const char *eat_whitespace(const char *s) {
  883. tor_assert(s);
  884. while(isspace((int)*s) || *s == '#') {
  885. while(isspace((int)*s))
  886. s++;
  887. if(*s == '#') { /* read to a \n or \0 */
  888. while(*s && *s != '\n')
  889. s++;
  890. if(!*s)
  891. return s;
  892. }
  893. }
  894. return s;
  895. }
  896. /** Return a pointer to the first char of s that is not a space or a tab,
  897. * or to the terminating NUL if no such character exists. */
  898. const char *eat_whitespace_no_nl(const char *s) {
  899. while(*s == ' ' || *s == '\t')
  900. ++s;
  901. return s;
  902. }
  903. /** Return a pointer to the first char of s that is whitespace or <b>#</b>,
  904. * or to the terminating NUL if no such character exists.
  905. */
  906. const char *find_whitespace(const char *s) {
  907. tor_assert(s);
  908. while(*s && !isspace((int)*s) && *s != '#')
  909. s++;
  910. return s;
  911. }
  912. /*
  913. * Time
  914. */
  915. /** Set *timeval to the current time of day. On error, log and terminate.
  916. * (Same as gettimeofday(timeval,NULL), but never returns -1.)
  917. */
  918. void tor_gettimeofday(struct timeval *timeval) {
  919. #ifdef HAVE_GETTIMEOFDAY
  920. if (gettimeofday(timeval, NULL)) {
  921. log_fn(LOG_ERR, "gettimeofday failed.");
  922. /* If gettimeofday dies, we have either given a bad timezone (we didn't),
  923. or segfaulted.*/
  924. exit(1);
  925. }
  926. #elif defined(HAVE_FTIME)
  927. struct timeb tb;
  928. ftime(&tb);
  929. timeval->tv_sec = tb.time;
  930. timeval->tv_usec = tb.millitm * 1000;
  931. #else
  932. #error "No way to get time."
  933. #endif
  934. return;
  935. }
  936. /** Return the number of microseconds elapsed between *start and *end.
  937. * If start is after end, return 0.
  938. */
  939. long
  940. tv_udiff(struct timeval *start, struct timeval *end)
  941. {
  942. long udiff;
  943. long secdiff = end->tv_sec - start->tv_sec;
  944. if (secdiff+1 > LONG_MAX/1000000) {
  945. log_fn(LOG_WARN, "comparing times too far apart.");
  946. return LONG_MAX;
  947. }
  948. udiff = secdiff*1000000L + (end->tv_usec - start->tv_usec);
  949. if(udiff < 0) {
  950. log_fn(LOG_INFO, "start (%ld.%ld) is after end (%ld.%ld). Returning 0.",
  951. (long)start->tv_sec, (long)start->tv_usec, (long)end->tv_sec, (long)end->tv_usec);
  952. return 0;
  953. }
  954. return udiff;
  955. }
  956. /** Return -1 if *a \< *b, 0 if *a==*b, and 1 if *a \> *b.
  957. */
  958. int tv_cmp(struct timeval *a, struct timeval *b) {
  959. if (a->tv_sec > b->tv_sec)
  960. return 1;
  961. if (a->tv_sec < b->tv_sec)
  962. return -1;
  963. if (a->tv_usec > b->tv_usec)
  964. return 1;
  965. if (a->tv_usec < b->tv_usec)
  966. return -1;
  967. return 0;
  968. }
  969. /** Increment *a by the number of seconds and microseconds in *b.
  970. */
  971. void tv_add(struct timeval *a, struct timeval *b) {
  972. a->tv_usec += b->tv_usec;
  973. a->tv_sec += b->tv_sec + (a->tv_usec / 1000000);
  974. a->tv_usec %= 1000000;
  975. }
  976. /** Increment *a by <b>ms</b> milliseconds.
  977. */
  978. void tv_addms(struct timeval *a, long ms) {
  979. a->tv_usec += (ms * 1000) % 1000000;
  980. a->tv_sec += ((ms * 1000) / 1000000) + (a->tv_usec / 1000000);
  981. a->tv_usec %= 1000000;
  982. }
  983. #define IS_LEAPYEAR(y) (!(y % 4) && ((y % 100) || !(y % 400)))
  984. static int n_leapdays(int y1, int y2) {
  985. --y1;
  986. --y2;
  987. return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400);
  988. }
  989. /** Number of days per month in non-leap year; used by tor_timegm. */
  990. static const int days_per_month[] =
  991. { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  992. /** Return a time_t given a struct tm. The result is given in GMT, and
  993. * does not account for leap seconds.
  994. */
  995. time_t tor_timegm (struct tm *tm) {
  996. /* This is a pretty ironclad timegm implementation, snarfed from Python2.2.
  997. * It's way more brute-force than fiddling with tzset().
  998. */
  999. time_t ret;
  1000. unsigned long year, days, hours, minutes;
  1001. int i;
  1002. year = tm->tm_year + 1900;
  1003. tor_assert(year >= 1970);
  1004. tor_assert(tm->tm_mon >= 0);
  1005. tor_assert(tm->tm_mon <= 11);
  1006. days = 365 * (year-1970) + n_leapdays(1970,year);
  1007. for (i = 0; i < tm->tm_mon; ++i)
  1008. days += days_per_month[i];
  1009. if (tm->tm_mon > 1 && IS_LEAPYEAR(year))
  1010. ++days;
  1011. days += tm->tm_mday - 1;
  1012. hours = days*24 + tm->tm_hour;
  1013. minutes = hours*60 + tm->tm_min;
  1014. ret = minutes*60 + tm->tm_sec;
  1015. return ret;
  1016. }
  1017. /* strftime is locale-specific, so we need to replace those parts */
  1018. static const char *WEEKDAY_NAMES[] =
  1019. { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1020. static const char *MONTH_NAMES[] =
  1021. { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  1022. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1023. void format_rfc1123_time(char *buf, time_t t) {
  1024. struct tm *tm = gmtime(&t);
  1025. strftime(buf, RFC1123_TIME_LEN+1, "XXX, %d XXX %Y %H:%M:%S GMT", tm);
  1026. tor_assert(tm->tm_wday >= 0);
  1027. tor_assert(tm->tm_wday <= 6);
  1028. memcpy(buf, WEEKDAY_NAMES[tm->tm_wday], 3);
  1029. tor_assert(tm->tm_wday >= 0);
  1030. tor_assert(tm->tm_mon <= 11);
  1031. memcpy(buf+8, MONTH_NAMES[tm->tm_mon], 3);
  1032. }
  1033. int parse_rfc1123_time(const char *buf, time_t *t) {
  1034. struct tm tm;
  1035. char month[4];
  1036. char weekday[4];
  1037. int i, m;
  1038. if (strlen(buf) != RFC1123_TIME_LEN)
  1039. return -1;
  1040. memset(&tm, 0, sizeof(tm));
  1041. if (sscanf(buf, "%3s, %d %3s %d %d:%d:%d GMT", weekday,
  1042. &tm.tm_mday, month, &tm.tm_year, &tm.tm_hour,
  1043. &tm.tm_min, &tm.tm_sec) < 7) {
  1044. log_fn(LOG_WARN, "Got invalid RFC1123 time \"%s\"", buf);
  1045. return -1;
  1046. }
  1047. m = -1;
  1048. for (i = 0; i < 12; ++i) {
  1049. if (!strcmp(month, MONTH_NAMES[i])) {
  1050. m = i;
  1051. break;
  1052. }
  1053. }
  1054. if (m<0) {
  1055. log_fn(LOG_WARN, "Got invalid RFC1123 time \"%s\"", buf);
  1056. return -1;
  1057. }
  1058. tm.tm_mon = m;
  1059. tm.tm_year -= 1900;
  1060. *t = tor_timegm(&tm);
  1061. return 0;
  1062. }
  1063. void format_iso_time(char *buf, time_t t) {
  1064. strftime(buf, ISO_TIME_LEN+1, "%Y-%m-%d %H:%M:%S", gmtime(&t));
  1065. }
  1066. int parse_iso_time(const char *cp, time_t *t) {
  1067. struct tm st_tm;
  1068. #ifdef HAVE_STRPTIME
  1069. if (!strptime(cp, "%Y-%m-%d %H:%M:%S", &st_tm)) {
  1070. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  1071. }
  1072. #else
  1073. unsigned int year=0, month=0, day=0, hour=100, minute=100, second=100;
  1074. if (sscanf(cp, "%u-%u-%u %u:%u:%u", &year, &month,
  1075. &day, &hour, &minute, &second) < 6) {
  1076. log_fn(LOG_WARN, "Published time was unparseable"); return -1;
  1077. }
  1078. if (year < 1970 || month < 1 || month > 12 || day < 1 || day > 31 ||
  1079. hour > 23 || minute > 59 || second > 61) {
  1080. log_fn(LOG_WARN, "Published time was nonsensical"); return -1;
  1081. }
  1082. st_tm.tm_year = year;
  1083. st_tm.tm_mon = month-1;
  1084. st_tm.tm_mday = day;
  1085. st_tm.tm_hour = hour;
  1086. st_tm.tm_min = minute;
  1087. st_tm.tm_sec = second;
  1088. #endif
  1089. *t = tor_timegm(&st_tm);
  1090. return 0;
  1091. }
  1092. /*
  1093. * Low-level I/O.
  1094. */
  1095. /** Write <b>count</b> bytes from <b>buf</b> to <b>fd</b>. <b>isSocket</b>
  1096. * must be 1 if fd was returned by socket() or accept(), and 0 if fd
  1097. * was returned by open(). Return the number of bytes written, or -1
  1098. * on error. Only use if fd is a blocking fd. */
  1099. int write_all(int fd, const char *buf, size_t count, int isSocket) {
  1100. size_t written = 0;
  1101. int result;
  1102. while(written != count) {
  1103. if (isSocket)
  1104. result = send(fd, buf+written, count-written, 0);
  1105. else
  1106. result = write(fd, buf+written, count-written);
  1107. if(result<0)
  1108. return -1;
  1109. written += result;
  1110. }
  1111. return count;
  1112. }
  1113. /** Read from <b>fd</b> to <b>buf</b>, until we get <b>count</b> bytes
  1114. * or reach the end of the file.
  1115. * isSocket must be 1 if fd
  1116. * was returned by socket() or accept(), and 0 if fd was returned by
  1117. * open(). Return the number of bytes read, or -1 on error. Only use
  1118. * if fd is a blocking fd. */
  1119. int read_all(int fd, char *buf, size_t count, int isSocket) {
  1120. size_t numread = 0;
  1121. int result;
  1122. while(numread != count) {
  1123. if (isSocket)
  1124. result = recv(fd, buf+numread, count-numread, 0);
  1125. else
  1126. result = read(fd, buf+numread, count-numread);
  1127. if(result<0)
  1128. return -1;
  1129. else if (result == 0)
  1130. break;
  1131. numread += result;
  1132. }
  1133. return count;
  1134. }
  1135. /** Turn <b>socket</b> into a nonblocking socket.
  1136. */
  1137. void set_socket_nonblocking(int socket)
  1138. {
  1139. #ifdef MS_WINDOWS
  1140. /* Yes means no and no means yes. Do you not want to be nonblocking? */
  1141. int nonblocking = 0;
  1142. ioctlsocket(socket, FIONBIO, (unsigned long*) &nonblocking);
  1143. #else
  1144. fcntl(socket, F_SETFL, O_NONBLOCK);
  1145. #endif
  1146. }
  1147. /*
  1148. * Process control
  1149. */
  1150. /** Minimalist interface to run a void function in the background. On
  1151. * unix calls fork, on win32 calls beginthread. Returns -1 on failure.
  1152. * func should not return, but rather should call spawn_exit.
  1153. */
  1154. int spawn_func(int (*func)(void *), void *data)
  1155. {
  1156. #ifdef MS_WINDOWS
  1157. int rv;
  1158. rv = _beginthread(func, 0, data);
  1159. if (rv == (unsigned long) -1)
  1160. return -1;
  1161. return 0;
  1162. #else
  1163. pid_t pid;
  1164. pid = fork();
  1165. if (pid<0)
  1166. return -1;
  1167. if (pid==0) {
  1168. /* Child */
  1169. func(data);
  1170. tor_assert(0); /* Should never reach here. */
  1171. return 0; /* suppress "control-reaches-end-of-non-void" warning. */
  1172. } else {
  1173. /* Parent */
  1174. return 0;
  1175. }
  1176. #endif
  1177. }
  1178. /** End the current thread/process.
  1179. */
  1180. void spawn_exit()
  1181. {
  1182. #ifdef MS_WINDOWS
  1183. _endthread();
  1184. #else
  1185. exit(0);
  1186. #endif
  1187. }
  1188. /**
  1189. * Allocate a pair of connected sockets. (Like socketpair(family,
  1190. * type,protocol,fd), but works on systems that don't have
  1191. * socketpair.)
  1192. *
  1193. * Currently, only (AF_UNIX, SOCK_STREAM, 0 ) sockets are supported.
  1194. *
  1195. * Note that on systems without socketpair, this call will fail if
  1196. * localhost is inaccessible (for example, if the networking
  1197. * stack is down). And even if it succeeds, the socket pair will not
  1198. * be able to read while localhost is down later (the socket pair may
  1199. * even close, depending on OS-specific timeouts).
  1200. **/
  1201. int
  1202. tor_socketpair(int family, int type, int protocol, int fd[2])
  1203. {
  1204. #ifdef HAVE_SOCKETPAIR
  1205. return socketpair(family, type, protocol, fd);
  1206. #else
  1207. /* This socketpair does not work when localhost is down. So
  1208. * it's really not the same thing at all. But it's close enough
  1209. * for now, and really, when localhost is down sometimes, we
  1210. * have other problems too.
  1211. */
  1212. int listener = -1;
  1213. int connector = -1;
  1214. int acceptor = -1;
  1215. struct sockaddr_in listen_addr;
  1216. struct sockaddr_in connect_addr;
  1217. int size;
  1218. if (protocol
  1219. #ifdef AF_UNIX
  1220. || family != AF_UNIX
  1221. #endif
  1222. ) {
  1223. #ifdef MS_WINDOWS
  1224. errno = WSAEAFNOSUPPORT;
  1225. #else
  1226. errno = EAFNOSUPPORT;
  1227. #endif
  1228. return -1;
  1229. }
  1230. if (!fd) {
  1231. errno = EINVAL;
  1232. return -1;
  1233. }
  1234. listener = socket(AF_INET, type, 0);
  1235. if (listener == -1)
  1236. return -1;
  1237. memset (&listen_addr, 0, sizeof (listen_addr));
  1238. listen_addr.sin_family = AF_INET;
  1239. listen_addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
  1240. listen_addr.sin_port = 0; /* kernel choses port. */
  1241. if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
  1242. == -1)
  1243. goto tidy_up_and_fail;
  1244. if (listen(listener, 1) == -1)
  1245. goto tidy_up_and_fail;
  1246. connector = socket(AF_INET, type, 0);
  1247. if (connector == -1)
  1248. goto tidy_up_and_fail;
  1249. /* We want to find out the port number to connect to. */
  1250. size = sizeof (connect_addr);
  1251. if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
  1252. goto tidy_up_and_fail;
  1253. if (size != sizeof (connect_addr))
  1254. goto abort_tidy_up_and_fail;
  1255. if (connect(connector, (struct sockaddr *) &connect_addr,
  1256. sizeof (connect_addr)) == -1)
  1257. goto tidy_up_and_fail;
  1258. size = sizeof (listen_addr);
  1259. acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
  1260. if (acceptor == -1)
  1261. goto tidy_up_and_fail;
  1262. if (size != sizeof(listen_addr))
  1263. goto abort_tidy_up_and_fail;
  1264. tor_close_socket(listener);
  1265. /* Now check we are talking to ourself by matching port and host on the
  1266. two sockets. */
  1267. if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
  1268. goto tidy_up_and_fail;
  1269. if (size != sizeof (connect_addr)
  1270. || listen_addr.sin_family != connect_addr.sin_family
  1271. || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
  1272. || listen_addr.sin_port != connect_addr.sin_port) {
  1273. goto abort_tidy_up_and_fail;
  1274. }
  1275. fd[0] = connector;
  1276. fd[1] = acceptor;
  1277. return 0;
  1278. abort_tidy_up_and_fail:
  1279. #ifdef MS_WINDOWS
  1280. errno = WSAECONNABORTED;
  1281. #else
  1282. errno = ECONNABORTED; /* I hope this is portable and appropriate. */
  1283. #endif
  1284. tidy_up_and_fail:
  1285. {
  1286. int save_errno = errno;
  1287. if (listener != -1)
  1288. tor_close_socket(listener);
  1289. if (connector != -1)
  1290. tor_close_socket(connector);
  1291. if (acceptor != -1)
  1292. tor_close_socket(acceptor);
  1293. errno = save_errno;
  1294. return -1;
  1295. }
  1296. #endif
  1297. }
  1298. /**
  1299. * On Windows, WSAEWOULDBLOCK is not always correct: when you see it,
  1300. * you need to ask the socket for its actual errno. Also, you need to
  1301. * get your errors from WSAGetLastError, not errno. (If you supply a
  1302. * socket of -1, we check WSAGetLastError, but don't correct
  1303. * WSAEWOULDBLOCKs.)
  1304. */
  1305. #ifdef MS_WINDOWS
  1306. int tor_socket_errno(int sock)
  1307. {
  1308. int optval, optvallen=sizeof(optval);
  1309. int err = WSAGetLastError();
  1310. if (err == WSAEWOULDBLOCK && sock >= 0) {
  1311. if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval, &optvallen))
  1312. return err;
  1313. if (optval)
  1314. return optval;
  1315. }
  1316. return err;
  1317. }
  1318. #endif
  1319. #ifdef MS_WINDOWS
  1320. #define E(code, s) { code, (s " [" #code " ]") }
  1321. struct { int code; const char *msg; } windows_socket_errors[] = {
  1322. E(WSAEINTR, "Interrupted function call"),
  1323. E(WSAEACCES, "Permission denied"),
  1324. E(WSAEFAULT, "Bad address"),
  1325. E(WSAEINVAL, "Invalid argument"),
  1326. E(WSAEMFILE, "Too many open files"),
  1327. E(WSAEWOULDBLOCK, "Resource temporarily unavailable"),
  1328. E(WSAEINPROGRESS, "Operation now in progress"),
  1329. E(WSAEALREADY, "Operation already in progress"),
  1330. E(WSAENOTSOCK, "Socket operation on nonsocket"),
  1331. E(WSAEDESTADDRREQ, "Destination address required"),
  1332. E(WSAEMSGSIZE, "Message too long"),
  1333. E(WSAEPROTOTYPE, "Protocol wrong for socket"),
  1334. E(WSAENOPROTOOPT, "Bad protocol option"),
  1335. E(WSAEPROTONOSUPPORT, "Protocol not supported"),
  1336. E(WSAESOCKTNOSUPPORT, "Socket type not supported"),
  1337. /* What's the difference between NOTSUPP and NOSUPPORT? :) */
  1338. E(WSAEOPNOTSUPP, "Operation not supported"),
  1339. E(WSAEPFNOSUPPORT, "Protocol family not supported"),
  1340. E(WSAEAFNOSUPPORT, "Address family not supported by protocol family"),
  1341. E(WSAEADDRINUSE, "Address already in use"),
  1342. E(WSAEADDRNOTAVAIL, "Cannot assign requested address"),
  1343. E(WSAENETDOWN, "Network is down"),
  1344. E(WSAENETUNREACH, "Network is unreachable"),
  1345. E(WSAENETRESET, "Network dropped connection on reset"),
  1346. E(WSAECONNABORTED, "Software caused connection abort"),
  1347. E(WSAECONNRESET, "Connection reset by peer"),
  1348. E(WSAENOBUFS, "No buffer space avaialable"),
  1349. E(WSAEISCONN, "Socket is already connected"),
  1350. E(WSAENOTCONN, "Socket is not connected"),
  1351. E(WSAESHUTDOWN, "Cannot send after socket shutdown"),
  1352. E(WSAETIMEDOUT, "Connection timed out"),
  1353. E(WSAECONNREFUSED, "Connection refused"),
  1354. E(WSAEHOSTDOWN, "Host is down"),
  1355. E(WSAEHOSTUNREACH, "No route to host"),
  1356. E(WSAEPROCLIM, "Too many processes"),
  1357. /* Yes, some of these start with WSA, not WSAE. No, I don't know why. */
  1358. E(WSASYSNOTREADY, "Network subsystem is unavailable"),
  1359. E(WSAVERNOTSUPPORTED, "Winsock.dll out of range"),
  1360. E(WSANOTINITIALISED, "Successful WSAStartup not yet performed"),
  1361. E(WSAEDISCON, "Graceful shutdown now in progress"),
  1362. #ifdef WSATYPE_NOT_FOUND
  1363. E(WSATYPE_NOT_FOUND, "Class type not found"),
  1364. #endif
  1365. E(WSAHOST_NOT_FOUND, "Host not found"),
  1366. E(WSATRY_AGAIN, "Nonauthoritative host not found"),
  1367. E(WSANO_RECOVERY, "This is a nonrecoverable error"),
  1368. E(WSANO_DATA, "Valid name, no data record of requested type)"),
  1369. /* There are some more error codes whose numeric values are marked
  1370. * <b>OS dependent</b>. They start with WSA_, apparently for the same
  1371. * reason that practitioners of some craft traditions deliberately
  1372. * introduce imperfections into their baskets and rugs "to allow the
  1373. * evil spirits to escape." If we catch them, then our binaries
  1374. * might not report consistent results across versions of Windows.
  1375. * Thus, I'm going to let them all fall through.
  1376. */
  1377. { -1, NULL },
  1378. };
  1379. /** There does not seem to be a strerror equivalent for winsock errors.
  1380. * Naturally, we have to roll our own.
  1381. */
  1382. const char *tor_socket_strerror(int e)
  1383. {
  1384. int i;
  1385. for (i=0; windows_socket_errors[i].code >= 0; ++i) {
  1386. if (e == windows_socket_errors[i].code)
  1387. return windows_socket_errors[i].msg;
  1388. }
  1389. return strerror(e);
  1390. }
  1391. #endif
  1392. /*
  1393. * Filesystem operations.
  1394. */
  1395. /** Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't
  1396. * exist, FN_FILE if it is a regular file, or FN_DIR if it's a
  1397. * directory. */
  1398. file_status_t file_status(const char *fname)
  1399. {
  1400. struct stat st;
  1401. if (stat(fname, &st)) {
  1402. if (errno == ENOENT) {
  1403. return FN_NOENT;
  1404. }
  1405. return FN_ERROR;
  1406. }
  1407. if (st.st_mode & S_IFDIR)
  1408. return FN_DIR;
  1409. else if (st.st_mode & S_IFREG)
  1410. return FN_FILE;
  1411. else
  1412. return FN_ERROR;
  1413. }
  1414. /** Check whether dirname exists and is private. If yes return 0. If
  1415. * it does not exist, and create is set, try to create it and return 0
  1416. * on success. Else return -1. */
  1417. int check_private_dir(const char *dirname, int create)
  1418. {
  1419. int r;
  1420. struct stat st;
  1421. tor_assert(dirname);
  1422. if (stat(dirname, &st)) {
  1423. if (errno != ENOENT) {
  1424. log(LOG_WARN, "Directory %s cannot be read: %s", dirname,
  1425. strerror(errno));
  1426. return -1;
  1427. }
  1428. if (!create) {
  1429. log(LOG_WARN, "Directory %s does not exist.", dirname);
  1430. return -1;
  1431. }
  1432. log(LOG_INFO, "Creating directory %s", dirname);
  1433. #ifdef MS_WINDOWS
  1434. r = mkdir(dirname);
  1435. #else
  1436. r = mkdir(dirname, 0700);
  1437. #endif
  1438. if (r) {
  1439. log(LOG_WARN, "Error creating directory %s: %s", dirname,
  1440. strerror(errno));
  1441. return -1;
  1442. } else {
  1443. return 0;
  1444. }
  1445. }
  1446. if (!(st.st_mode & S_IFDIR)) {
  1447. log(LOG_WARN, "%s is not a directory", dirname);
  1448. return -1;
  1449. }
  1450. #ifndef MS_WINDOWS
  1451. if (st.st_uid != getuid()) {
  1452. log(LOG_WARN, "%s is not owned by this UID (%d). You must fix this to proceed.", dirname, (int)getuid());
  1453. return -1;
  1454. }
  1455. if (st.st_mode & 0077) {
  1456. log(LOG_WARN, "Fixing permissions on directory %s", dirname);
  1457. if (chmod(dirname, 0700)) {
  1458. log(LOG_WARN, "Could not chmod directory %s: %s", dirname,
  1459. strerror(errno));
  1460. return -1;
  1461. } else {
  1462. return 0;
  1463. }
  1464. }
  1465. #endif
  1466. return 0;
  1467. }
  1468. /** Create a file named <b>fname</b> with the contents <b>str</b>. Overwrite the
  1469. * previous <b>fname</b> if possible. Return 0 on success, -1 on failure.
  1470. *
  1471. * This function replaces the old file atomically, if possible.
  1472. */
  1473. int
  1474. write_str_to_file(const char *fname, const char *str, int bin)
  1475. {
  1476. char tempname[1024];
  1477. int fd;
  1478. size_t len;
  1479. int result;
  1480. if ((strlcpy(tempname,fname,1024) >= 1024) ||
  1481. (strlcat(tempname,".tmp",1024) >= 1024)) {
  1482. log(LOG_WARN, "Filename %s.tmp too long (>1024 chars)", fname);
  1483. return -1;
  1484. }
  1485. if ((fd = open(tempname, O_WRONLY|O_CREAT|O_TRUNC|(bin?O_BINARY:0), 0600))
  1486. < 0) {
  1487. log(LOG_WARN, "Couldn't open %s for writing: %s", tempname,
  1488. strerror(errno));
  1489. return -1;
  1490. }
  1491. len = strlen(str);
  1492. result = write_all(fd, str, len, 0);
  1493. if(result < 0 || (size_t)result != len) {
  1494. log(LOG_WARN, "Error writing to %s: %s", tempname, strerror(errno));
  1495. close(fd);
  1496. return -1;
  1497. }
  1498. if (close(fd)) {
  1499. log(LOG_WARN,"Error flushing to %s: %s", tempname, strerror(errno));
  1500. return -1;
  1501. }
  1502. #ifdef MS_WINDOWS
  1503. /* On Windows, rename doesn't replace. We could call ReplaceFile, but
  1504. * that's hard, and we can probably sneak by without atomicity. */
  1505. switch (file_status(fname)) {
  1506. case FN_ERROR:
  1507. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  1508. return -1;
  1509. case FN_DIR:
  1510. log(LOG_WARN, "Error replacing %s: is directory", fname);
  1511. return -1;
  1512. case FN_FILE:
  1513. if (unlink(fname)) {
  1514. log(LOG_WARN, "Error replacing %s while removing old copy: %s",
  1515. fname, strerror(errno));
  1516. return -1;
  1517. }
  1518. break;
  1519. case FN_NOENT:
  1520. ;
  1521. }
  1522. #endif
  1523. if (rename(tempname, fname)) {
  1524. log(LOG_WARN, "Error replacing %s: %s", fname, strerror(errno));
  1525. return -1;
  1526. }
  1527. return 0;
  1528. }
  1529. /** Read the contents of <b>filename</b> into a newly allocated string; return the
  1530. * string on success or NULL on failure.
  1531. */
  1532. char *read_file_to_str(const char *filename, int bin) {
  1533. int fd; /* router file */
  1534. struct stat statbuf;
  1535. char *string;
  1536. int r;
  1537. tor_assert(filename);
  1538. if(stat(filename, &statbuf) < 0) {
  1539. log_fn(LOG_INFO,"Could not stat %s.",filename);
  1540. return NULL;
  1541. }
  1542. fd = open(filename,O_RDONLY|(bin?O_BINARY:0),0);
  1543. if (fd<0) {
  1544. log_fn(LOG_WARN,"Could not open %s.",filename);
  1545. return NULL;
  1546. }
  1547. string = tor_malloc(statbuf.st_size+1);
  1548. r = read_all(fd,string,statbuf.st_size,0);
  1549. if (r<0) {
  1550. log_fn(LOG_WARN,"Error reading from file '%s': %s", filename,
  1551. strerror(errno));
  1552. tor_free(string);
  1553. close(fd);
  1554. return NULL;
  1555. } else if (bin && r != statbuf.st_size) {
  1556. /* If we're in binary mode, then we'd better have an exact match for
  1557. * size. Otherwise, win32 encoding may throw us off, and that's okay. */
  1558. log_fn(LOG_WARN,"Could read only %d of %ld bytes of file '%s'.",
  1559. r, (long)statbuf.st_size,filename);
  1560. tor_free(string);
  1561. close(fd);
  1562. return NULL;
  1563. }
  1564. close(fd);
  1565. string[statbuf.st_size] = 0; /* null terminate it */
  1566. return string;
  1567. }
  1568. /** read lines from f (no more than maxlen-1 bytes each) until we
  1569. * get a non-whitespace line. If it isn't of the form "key value"
  1570. * (value can have spaces), return -1.
  1571. * Point *key to the first word in line, point *value * to the second.
  1572. * Put a \0 at the end of key, remove everything at the end of value
  1573. * that is whitespace or comment.
  1574. * Return 1 if success, 0 if no more lines, -1 if error.
  1575. */
  1576. int parse_line_from_file(char *line, size_t maxlen, FILE *f, char **key_out, char **value_out) {
  1577. char *s, *key, *end, *value;
  1578. try_next_line:
  1579. if(!fgets(line, maxlen, f)) {
  1580. if(feof(f))
  1581. return 0;
  1582. return -1; /* real error */
  1583. }
  1584. if((s = strchr(line,'#'))) /* strip comments */
  1585. *s = 0; /* stop the line there */
  1586. /* remove end whitespace */
  1587. s = strchr(line, 0); /* now we're at the null */
  1588. do {
  1589. *s = 0;
  1590. s--;
  1591. } while (s >= line && isspace((int)*s));
  1592. key = line;
  1593. while(isspace((int)*key))
  1594. key++;
  1595. if(*key == 0)
  1596. goto try_next_line; /* this line has nothing on it */
  1597. end = key;
  1598. while(*end && !isspace((int)*end))
  1599. end++;
  1600. value = end;
  1601. while(*value && isspace((int)*value))
  1602. value++;
  1603. #if 0
  1604. if(!*end || !*value) { /* only a key on this line. no value. */
  1605. *end = 0;
  1606. log_fn(LOG_WARN,"Line has keyword '%s' but no value. Failing.",key);
  1607. return -1;
  1608. }
  1609. #endif
  1610. *end = 0; /* null it out */
  1611. tor_assert(key);
  1612. tor_assert(value);
  1613. log_fn(LOG_DEBUG,"got keyword '%s', value '%s'", key, value);
  1614. *key_out = key, *value_out = value;
  1615. return 1;
  1616. }
  1617. /** Expand any homedir prefix on 'filename'; return a newly allocated
  1618. * string. */
  1619. char *expand_filename(const char *filename)
  1620. {
  1621. tor_assert(filename);
  1622. /* XXXX Should eventually check for ~username/ */
  1623. if (!strncmp(filename,"~/",2)) {
  1624. size_t len;
  1625. const char *home = getenv("HOME");
  1626. char *result;
  1627. if (!home) {
  1628. log_fn(LOG_WARN, "Couldn't find $HOME environment variable while expanding %s", filename);
  1629. return NULL;
  1630. }
  1631. /* minus two characters for ~/, plus one for /, plus one for NUL.
  1632. * Round up to 16 in case we can't do math. */
  1633. len = strlen(home)+strlen(filename)+16;
  1634. result = tor_malloc(len);
  1635. tor_snprintf(result,len,"%s/%s",home,filename+2);
  1636. return result;
  1637. } else {
  1638. return tor_strdup(filename);
  1639. }
  1640. }
  1641. /**
  1642. * Rename the file 'from' to the file 'to'. On unix, this is the same as
  1643. * rename(2). On windows, this removes 'to' first if it already exists.
  1644. * Returns 0 on success. Returns -1 and sets errno on failure.
  1645. */
  1646. int replace_file(const char *from, const char *to)
  1647. {
  1648. #ifndef MS_WINDOWS
  1649. return rename(from,to);
  1650. #else
  1651. switch(file_status(to))
  1652. {
  1653. case FN_NOENT:
  1654. break;
  1655. case FN_FILE:
  1656. if (unlink(to)) return -1;
  1657. break;
  1658. case FN_ERROR:
  1659. return -1;
  1660. case FN_DIR:
  1661. errno = EISDIR;
  1662. return -1;
  1663. }
  1664. return rename(from,to);
  1665. #endif
  1666. }
  1667. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  1668. * or reserved for local networks by RFC 1918.
  1669. */
  1670. int is_internal_IP(uint32_t ip) {
  1671. if (((ip & 0xff000000) == 0x0a000000) || /* 10/8 */
  1672. ((ip & 0xff000000) == 0x00000000) || /* 0/8 */
  1673. ((ip & 0xff000000) == 0x7f000000) || /* 127/8 */
  1674. ((ip & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  1675. ((ip & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  1676. ((ip & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  1677. return 1;
  1678. return 0;
  1679. }
  1680. /** Return true iff <b>ip</b> (in host order) is judged to be on the
  1681. * same network as us. For now, check if it's an internal IP. For XXX008,
  1682. * also check if it's on the same class C network as our public IP.
  1683. */
  1684. int is_local_IP(uint32_t ip) {
  1685. return is_internal_IP(ip);
  1686. }
  1687. /* Hold the result of our call to <b>uname</b>. */
  1688. static char uname_result[256];
  1689. /* True iff uname_result is set. */
  1690. static int uname_result_is_set = 0;
  1691. /* Return a pointer to a description of our platform.
  1692. */
  1693. const char *
  1694. get_uname(void)
  1695. {
  1696. #ifdef HAVE_UNAME
  1697. struct utsname u;
  1698. #endif
  1699. if (!uname_result_is_set) {
  1700. #ifdef HAVE_UNAME
  1701. if (uname(&u) != -1) {
  1702. /* (linux says 0 is success, solaris says 1 is success) */
  1703. tor_snprintf(uname_result, sizeof(uname_result), "%s %s %s",
  1704. u.sysname, u.nodename, u.machine);
  1705. } else
  1706. #endif
  1707. {
  1708. strlcpy(uname_result, "Unknown platform", sizeof(uname_result));
  1709. }
  1710. uname_result_is_set = 1;
  1711. }
  1712. return uname_result;
  1713. }
  1714. #ifndef MS_WINDOWS
  1715. /* Based on code contributed by christian grothoff */
  1716. static int start_daemon_called = 0;
  1717. static int finish_daemon_called = 0;
  1718. static int daemon_filedes[2];
  1719. /** Start putting the process into daemon mode: fork and drop all resources
  1720. * except standard fds. The parent process never returns, but stays around
  1721. * until finish_daemon is called. (Note: it's safe to call this more
  1722. * than once: calls after the first are ignored.)
  1723. */
  1724. void start_daemon(const char *desired_cwd)
  1725. {
  1726. pid_t pid;
  1727. if (start_daemon_called)
  1728. return;
  1729. start_daemon_called = 1;
  1730. if(!desired_cwd)
  1731. desired_cwd = "/";
  1732. /* Don't hold the wrong FS mounted */
  1733. if (chdir(desired_cwd) < 0) {
  1734. log_fn(LOG_ERR,"chdir to %s failed. Exiting.",desired_cwd);
  1735. exit(1);
  1736. }
  1737. pipe(daemon_filedes);
  1738. pid = fork();
  1739. if (pid < 0) {
  1740. log_fn(LOG_ERR,"fork failed. Exiting.");
  1741. exit(1);
  1742. }
  1743. if (pid) { /* Parent */
  1744. int ok;
  1745. char c;
  1746. close(daemon_filedes[1]); /* we only read */
  1747. ok = -1;
  1748. while (0 < read(daemon_filedes[0], &c, sizeof(char))) {
  1749. if (c == '.')
  1750. ok = 1;
  1751. }
  1752. fflush(stdout);
  1753. if (ok == 1)
  1754. exit(0);
  1755. else
  1756. exit(1); /* child reported error */
  1757. } else { /* Child */
  1758. close(daemon_filedes[0]); /* we only write */
  1759. pid = setsid(); /* Detach from controlling terminal */
  1760. /*
  1761. * Fork one more time, so the parent (the session group leader) can exit.
  1762. * This means that we, as a non-session group leader, can never regain a
  1763. * controlling terminal. This part is recommended by Stevens's
  1764. * _Advanced Programming in the Unix Environment_.
  1765. */
  1766. if (fork() != 0) {
  1767. exit(0);
  1768. }
  1769. return;
  1770. }
  1771. }
  1772. /** Finish putting the process into daemon mode: drop standard fds, and tell
  1773. * the parent process to exit. (Note: it's safe to call this more than once:
  1774. * calls after the first are ignored. Calls start_daemon first if it hasn't
  1775. * been called already.)
  1776. */
  1777. void finish_daemon(void)
  1778. {
  1779. int nullfd;
  1780. char c = '.';
  1781. if (finish_daemon_called)
  1782. return;
  1783. if (!start_daemon_called)
  1784. start_daemon(NULL);
  1785. finish_daemon_called = 1;
  1786. nullfd = open("/dev/null",
  1787. O_CREAT | O_RDWR | O_APPEND);
  1788. if (nullfd < 0) {
  1789. log_fn(LOG_ERR,"/dev/null can't be opened. Exiting.");
  1790. exit(1);
  1791. }
  1792. /* close fds linking to invoking terminal, but
  1793. * close usual incoming fds, but redirect them somewhere
  1794. * useful so the fds don't get reallocated elsewhere.
  1795. */
  1796. if (dup2(nullfd,0) < 0 ||
  1797. dup2(nullfd,1) < 0 ||
  1798. dup2(nullfd,2) < 0) {
  1799. log_fn(LOG_ERR,"dup2 failed. Exiting.");
  1800. exit(1);
  1801. }
  1802. write(daemon_filedes[1], &c, sizeof(char)); /* signal success */
  1803. close(daemon_filedes[1]);
  1804. }
  1805. #else
  1806. /* defined(MS_WINDOWS) */
  1807. void start_daemon(const char *cp) {}
  1808. void finish_daemon(void) {}
  1809. #endif
  1810. /** Write the current process ID, followed by NL, into <b>filename</b>.
  1811. */
  1812. void write_pidfile(char *filename) {
  1813. #ifndef MS_WINDOWS
  1814. FILE *pidfile;
  1815. if ((pidfile = fopen(filename, "w")) == NULL) {
  1816. log_fn(LOG_WARN, "Unable to open %s for writing: %s", filename,
  1817. strerror(errno));
  1818. } else {
  1819. fprintf(pidfile, "%d\n", (int)getpid());
  1820. fclose(pidfile);
  1821. }
  1822. #endif
  1823. }
  1824. /** Call setuid and setgid to run as <b>user</b>:<b>group</b>. Return 0 on
  1825. * success. On failure, log and return -1.
  1826. */
  1827. int switch_id(char *user, char *group) {
  1828. #ifndef MS_WINDOWS
  1829. struct passwd *pw = NULL;
  1830. struct group *gr = NULL;
  1831. if (user) {
  1832. pw = getpwnam(user);
  1833. if (pw == NULL) {
  1834. log_fn(LOG_ERR,"User '%s' not found.", user);
  1835. return -1;
  1836. }
  1837. }
  1838. /* switch the group first, while we still have the privileges to do so */
  1839. if (group) {
  1840. gr = getgrnam(group);
  1841. if (gr == NULL) {
  1842. log_fn(LOG_ERR,"Group '%s' not found.", group);
  1843. return -1;
  1844. }
  1845. if (setgid(gr->gr_gid) != 0) {
  1846. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  1847. return -1;
  1848. }
  1849. } else if (user) {
  1850. if (setgid(pw->pw_gid) != 0) {
  1851. log_fn(LOG_ERR,"Error setting GID: %s", strerror(errno));
  1852. return -1;
  1853. }
  1854. }
  1855. /* now that the group is switched, we can switch users and lose
  1856. privileges */
  1857. if (user) {
  1858. if (setuid(pw->pw_uid) != 0) {
  1859. log_fn(LOG_ERR,"Error setting UID: %s", strerror(errno));
  1860. return -1;
  1861. }
  1862. }
  1863. return 0;
  1864. #endif
  1865. log_fn(LOG_ERR,
  1866. "User or group specified, but switching users is not supported.");
  1867. return -1;
  1868. }
  1869. /** Set *addr to the IP address (in dotted-quad notation) stored in c.
  1870. * Return 1 on success, 0 if c is badly formatted. (Like inet_aton(c,addr),
  1871. * but works on Windows and Solaris.)
  1872. */
  1873. int tor_inet_aton(const char *c, struct in_addr* addr)
  1874. {
  1875. #ifdef HAVE_INET_ATON
  1876. return inet_aton(c, addr);
  1877. #else
  1878. uint32_t r;
  1879. tor_assert(c);
  1880. tor_assert(addr);
  1881. if (strcmp(c, "255.255.255.255") == 0) {
  1882. addr->s_addr = 0xFFFFFFFFu;
  1883. return 1;
  1884. }
  1885. r = inet_addr(c);
  1886. if (r == INADDR_NONE)
  1887. return 0;
  1888. addr->s_addr = r;
  1889. return 1;
  1890. #endif
  1891. }
  1892. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  1893. * *addr to the proper IP address, in network byte order. Returns 0
  1894. * on success, -1 on failure; 1 on transient failure.
  1895. *
  1896. * (This function exists because standard windows gethostbyname
  1897. * doesn't treat raw IP addresses properly.)
  1898. */
  1899. int tor_lookup_hostname(const char *name, uint32_t *addr)
  1900. {
  1901. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  1902. * something.
  1903. */
  1904. struct in_addr iaddr;
  1905. struct hostent *ent;
  1906. tor_assert(addr);
  1907. if (!*name) {
  1908. /* Empty address is an error. */
  1909. return -1;
  1910. } else if (tor_inet_aton(name, &iaddr)) {
  1911. /* It's an IP. */
  1912. memcpy(addr, &iaddr.s_addr, 4);
  1913. return 0;
  1914. } else {
  1915. ent = gethostbyname(name);
  1916. if (ent) {
  1917. /* break to remind us if we move away from IPv4 */
  1918. tor_assert(ent->h_length == 4);
  1919. memcpy(addr, ent->h_addr, 4);
  1920. return 0;
  1921. }
  1922. memset(addr, 0, 4);
  1923. #ifdef MS_WINDOWS
  1924. return (WSAGetLastError() == WSATRY_AGAIN) ? 1 : -1;
  1925. #else
  1926. return (h_errno == TRY_AGAIN) ? 1 : -1;
  1927. #endif
  1928. }
  1929. }
  1930. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  1931. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  1932. * host portion of the string. If <b>addr</b> is provided, try to
  1933. * resolve the host portion of the string and store it into
  1934. * *<b>addr</b> (in host byte order). If <b>port</b> is provided,
  1935. * store the port number into *<b>port</b>, or 0 if no port is given.
  1936. * Return 0 on success, -1 on failure.
  1937. */
  1938. int
  1939. parse_addr_port(const char *addrport, char **address, uint32_t *addr,
  1940. uint16_t *port)
  1941. {
  1942. const char *colon;
  1943. char *_address = NULL;
  1944. int _port;
  1945. int ok = 1;
  1946. tor_assert(addrport);
  1947. tor_assert(port);
  1948. colon = strchr(addrport, ':');
  1949. if (colon) {
  1950. _address = tor_strndup(addrport, colon-addrport);
  1951. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1952. if (!_port) {
  1953. log_fn(LOG_WARN, "Port '%s' out of range", colon+1);
  1954. ok = 0;
  1955. }
  1956. } else {
  1957. _address = tor_strdup(addrport);
  1958. _port = 0;
  1959. }
  1960. if (addr) {
  1961. /* There's an addr pointer, so we need to resolve the hostname. */
  1962. if (tor_lookup_hostname(_address,addr)) {
  1963. log_fn(LOG_WARN, "Couldn't look up '%s'", _address);
  1964. ok = 0;
  1965. *addr = 0;
  1966. }
  1967. *addr = ntohl(*addr);
  1968. }
  1969. if (address && ok) {
  1970. *address = _address;
  1971. } else {
  1972. if (address)
  1973. *address = NULL;
  1974. tor_free(_address);
  1975. }
  1976. if (port)
  1977. *port = ok ? ((uint16_t) _port) : 0;
  1978. return ok ? 0 : -1;
  1979. }
  1980. /** Parse a string <b>s</b> in the format of
  1981. * (IP(/mask|/mask-bits)?|*):(*|port(-maxport)?), setting the various
  1982. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  1983. */
  1984. int
  1985. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  1986. uint32_t *mask_out, uint16_t *port_min_out,
  1987. uint16_t *port_max_out)
  1988. {
  1989. char *address;
  1990. char *mask, *port, *endptr;
  1991. struct in_addr in;
  1992. int bits;
  1993. tor_assert(s);
  1994. tor_assert(addr_out);
  1995. tor_assert(mask_out);
  1996. tor_assert(port_min_out);
  1997. tor_assert(port_max_out);
  1998. address = tor_strdup(s);
  1999. /* Break 'address' into separate strings.
  2000. */
  2001. mask = strchr(address,'/');
  2002. port = strchr(mask?mask:address,':');
  2003. if (mask)
  2004. *mask++ = '\0';
  2005. if (port)
  2006. *port++ = '\0';
  2007. /* Now "address" is the IP|'*' part...
  2008. * "mask" is the Mask|Maskbits part...
  2009. * and "port" is the *|port|min-max part.
  2010. */
  2011. if (strcmp(address,"*")==0) {
  2012. *addr_out = 0;
  2013. } else if (tor_inet_aton(address, &in) != 0) {
  2014. *addr_out = ntohl(in.s_addr);
  2015. } else {
  2016. log_fn(LOG_WARN, "Malformed IP %s in address pattern; rejecting.",address);
  2017. goto err;
  2018. }
  2019. if (!mask) {
  2020. if (strcmp(address,"*")==0)
  2021. *mask_out = 0;
  2022. else
  2023. *mask_out = 0xFFFFFFFFu;
  2024. } else {
  2025. endptr = NULL;
  2026. bits = (int) strtol(mask, &endptr, 10);
  2027. if (!*endptr) {
  2028. /* strtol handled the whole mask. */
  2029. if (bits < 0 || bits > 32) {
  2030. log_fn(LOG_WARN, "Bad number of mask bits on address range; rejecting.");
  2031. goto err;
  2032. }
  2033. *mask_out = ~((1<<(32-bits))-1);
  2034. } else if (tor_inet_aton(mask, &in) != 0) {
  2035. *mask_out = ntohl(in.s_addr);
  2036. } else {
  2037. log_fn(LOG_WARN, "Malformed mask %s on address range; rejecting.",
  2038. mask);
  2039. goto err;
  2040. }
  2041. }
  2042. if (!port || strcmp(port, "*") == 0) {
  2043. *port_min_out = 1;
  2044. *port_max_out = 65535;
  2045. } else {
  2046. endptr = NULL;
  2047. *port_min_out = (uint16_t) tor_parse_long(port, 10, 1, 65535,
  2048. NULL, &endptr);
  2049. if (*endptr == '-') {
  2050. port = endptr+1;
  2051. endptr = NULL;
  2052. *port_max_out = (uint16_t) tor_parse_long(port, 10, 1, 65535, NULL,
  2053. &endptr);
  2054. if (*endptr || !*port_max_out) {
  2055. log_fn(LOG_WARN, "Malformed port %s on address range rejecting.",
  2056. port);
  2057. }
  2058. } else if (*endptr || !*port_min_out) {
  2059. log_fn(LOG_WARN, "Malformed port %s on address range; rejecting.",
  2060. port);
  2061. goto err;
  2062. } else {
  2063. *port_max_out = *port_min_out;
  2064. }
  2065. if (*port_min_out > *port_max_out) {
  2066. log_fn(LOG_WARN,"Insane port range on address policy; rejecting.");
  2067. goto err;
  2068. }
  2069. }
  2070. tor_free(address);
  2071. return 0;
  2072. err:
  2073. tor_free(address);
  2074. return -1;
  2075. }
  2076. /** Extract a long from the start of s, in the given numeric base. If
  2077. * there is unconverted data and next is provided, set *next to the
  2078. * first unconverted character. An error has occurred if no characters
  2079. * are converted; or if there are unconverted characters and next is NULL; or
  2080. * if the parsed value is not between min and max. When no error occurs,
  2081. * return the parsed value and set *ok (if provided) to 1. When an error
  2082. * ocurs, return 0 and set *ok (if provided) to 0.
  2083. */
  2084. long
  2085. tor_parse_long(const char *s, int base, long min, long max,
  2086. int *ok, char **next)
  2087. {
  2088. char *endptr;
  2089. long r;
  2090. r = strtol(s, &endptr, base);
  2091. /* Was at least one character converted? */
  2092. if (endptr == s)
  2093. goto err;
  2094. /* Were there unexpected unconverted characters? */
  2095. if (!next && *endptr)
  2096. goto err;
  2097. /* Is r within limits? */
  2098. if (r < min || r > max)
  2099. goto err;
  2100. if (ok) *ok = 1;
  2101. if (next) *next = endptr;
  2102. return r;
  2103. err:
  2104. if (ok) *ok = 0;
  2105. if (next) *next = endptr;
  2106. return 0;
  2107. }
  2108. unsigned long
  2109. tor_parse_ulong(const char *s, int base, unsigned long min,
  2110. unsigned long max, int *ok, char **next)
  2111. {
  2112. char *endptr;
  2113. unsigned long r;
  2114. r = strtol(s, &endptr, base);
  2115. /* Was at least one character converted? */
  2116. if (endptr == s)
  2117. goto err;
  2118. /* Were there unexpected unconverted characters? */
  2119. if (!next && *endptr)
  2120. goto err;
  2121. /* Is r within limits? */
  2122. if (r < min || r > max)
  2123. goto err;
  2124. if (ok) *ok = 1;
  2125. if (next) *next = endptr;
  2126. return r;
  2127. err:
  2128. if (ok) *ok = 0;
  2129. if (next) *next = endptr;
  2130. return 0;
  2131. }
  2132. /** Replacement for snprintf. Differs from platform snprintf in two
  2133. * ways: First, always NUL-terminates its output. Second, always
  2134. * returns -1 if the result is truncated. (Note that this return
  2135. * behavior does <i>not</i> conform to C99; it just happens to be the
  2136. * easiest to emulate "return -1" with conformant implementations than
  2137. * it is to emulate "return number that would be written" with
  2138. * non-conformant implementations.) */
  2139. int tor_snprintf(char *str, size_t size, const char *format, ...)
  2140. {
  2141. va_list ap;
  2142. int r;
  2143. va_start(ap,format);
  2144. r = tor_vsnprintf(str,size,format,ap);
  2145. va_end(ap);
  2146. return r;
  2147. }
  2148. /** Replacement for vsnpritnf; behavior differs as tor_snprintf differs from
  2149. * snprintf.
  2150. */
  2151. int tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
  2152. {
  2153. int r;
  2154. #ifdef MS_WINDOWS
  2155. r = _vsnprintf(str, size, format, args);
  2156. #else
  2157. r = vsnprintf(str, size, format, args);
  2158. #endif
  2159. str[size-1] = '\0';
  2160. if (r < 0 || ((size_t)r) >= size)
  2161. return -1;
  2162. return r;
  2163. }
  2164. #ifndef MS_WINDOWS
  2165. struct tor_mutex_t {
  2166. };
  2167. tor_mutex_t *tor_mutex_new(void) { return NULL; }
  2168. void tor_mutex_acquire(tor_mutex_t *m) { }
  2169. void tor_mutex_release(tor_mutex_t *m) { }
  2170. void tor_mutex_free(tor_mutex_t *m) { }
  2171. #else
  2172. struct tor_mutex_t {
  2173. HANDLE handle;
  2174. };
  2175. tor_mutex_t *tor_mutex_new(void)
  2176. {
  2177. tor_mutex_t *m;
  2178. m = tor_malloc_zero(sizeof(tor_mutex_t));
  2179. m->handle = CreateMutex(NULL, FALSE, NULL);
  2180. tor_assert(m->handle != NULL);
  2181. return m;
  2182. }
  2183. void tor_mutex_free(tor_mutex_t *m)
  2184. {
  2185. CloseHandle(m->handle);
  2186. tor_free(m);
  2187. }
  2188. void tor_mutex_acquire(tor_mutex_t *m)
  2189. {
  2190. DWORD r;
  2191. r = WaitForSingleObject(m->handle, INFINITE);
  2192. switch (r) {
  2193. case WAIT_ABANDONED: /* holding thread exited. */
  2194. case WAIT_OBJECT_0: /* we got the mutex normally. */
  2195. break;
  2196. case WAIT_TIMEOUT: /* Should never happen. */
  2197. tor_assert(0);
  2198. break;
  2199. case WAIT_FAILED:
  2200. log_fn(LOG_WARN, "Failed to acquire mutex: %d", GetLastError());
  2201. }
  2202. }
  2203. void tor_mutex_release(tor_mutex_t *m)
  2204. {
  2205. BOOL r;
  2206. r = ReleaseMutex(m->handle);
  2207. if (!r) {
  2208. log_fn(LOG_WARN, "Failed to release mutex: %d", GetLastError());
  2209. }
  2210. }
  2211. #endif
  2212. void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
  2213. {
  2214. const char *end;
  2215. char *cp;
  2216. tor_assert(destlen >= srclen*2+1);
  2217. cp = dest;
  2218. end = src+srclen;
  2219. while (src<end) {
  2220. sprintf(cp,"%02X",*(const uint8_t*)src);
  2221. ++src;
  2222. cp += 2;
  2223. }
  2224. *cp = '\0';
  2225. }
  2226. static const char HEX_DIGITS[] = "0123456789ABCDEFabcdef";
  2227. static INLINE int hex_decode_digit(char c)
  2228. {
  2229. const char *cp;
  2230. int n;
  2231. cp = strchr(HEX_DIGITS, c);
  2232. if (!cp)
  2233. return -1;
  2234. n = cp-HEX_DIGITS;
  2235. if (n<=15)
  2236. return n; /* digit or uppercase */
  2237. else
  2238. return n-6; /* lowercase */
  2239. }
  2240. int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
  2241. {
  2242. const char *end;
  2243. int v1,v2;
  2244. if ((srclen % 2) != 0)
  2245. return -1;
  2246. if (destlen < srclen/2)
  2247. return -1;
  2248. end = src+srclen;
  2249. while (src<end) {
  2250. v1 = hex_decode_digit(*src);
  2251. v2 = hex_decode_digit(*(src+1));
  2252. if(v1<0||v2<0)
  2253. return -1;
  2254. *(uint8_t*)dest = (v1<<4)|v2;
  2255. ++dest;
  2256. src+=2;
  2257. }
  2258. return 0;
  2259. }
  2260. /*
  2261. Local Variables:
  2262. mode:c
  2263. indent-tabs-mode:nil
  2264. c-basic-offset:2
  2265. End:
  2266. */