buffers.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char buffers_c_id[] =
  7. "$Id$";
  8. /**
  9. * \file buffers.c
  10. * \brief Implements a generic buffer interface. Buffers are
  11. * fairly opaque string holders that can read to or flush from:
  12. * memory, file descriptors, or TLS connections.
  13. **/
  14. #include "or.h"
  15. #define SENTINELS
  16. #undef CHECK_AFTER_RESIZE
  17. #undef PARANOIA
  18. #undef NOINLINE
  19. /* If SENTINELS is defined, check for attempts to write beyond the
  20. * end/before the start of the buffer.
  21. */
  22. #ifdef SENTINELS
  23. /** 4-byte value to write at the start of each buffer memory region. */
  24. #define START_MAGIC 0x70370370u
  25. /** 4-byte value to write at the end of each buffer memory region. */
  26. #define END_MAGIC 0xA0B0C0D0u
  27. /** Given buf->mem, yield a pointer to the raw memory region (for free(),
  28. * realloc(), and so on). */
  29. #define RAW_MEM(m) ((void*)(((char*)m)-4))
  30. /** Given a pointer to the raw memory region (from malloc() or realloc()),
  31. * yield the correct value for buf->mem (just past the first sentinel). */
  32. #define GUARDED_MEM(m) ((void*)(((char*)m)+4))
  33. /** How much memory do we need to allocate for a buffer to hold <b>ln</b> bytes
  34. * of data? */
  35. #define ALLOC_LEN(ln) ((ln)+8)
  36. /** Initialize the sentinel values on <b>m</b> (a value of buf-&gt;mem), which
  37. * has <b>ln</b> useful bytes. */
  38. #define SET_GUARDS(m, ln) \
  39. do { set_uint32((m)-4,START_MAGIC); set_uint32((m)+ln,END_MAGIC); } while (0)
  40. #else
  41. #define RAW_MEM(m) (m)
  42. #define GUARDED_MEM(m) (m)
  43. #define ALLOC_LEN(ln) (ln)
  44. #define SET_GUARDS(m,ln) do {} while (0)
  45. #endif
  46. #ifdef PARANOIA
  47. #define check() do { assert_buf_ok(buf); } while (0)
  48. #else
  49. #define check() do { } while (0)
  50. #endif
  51. #ifdef NOINLINE
  52. #undef INLINE
  53. #define INLINE
  54. #endif
  55. /** Magic value for buf_t.magic, to catch pointer errors. */
  56. #define BUFFER_MAGIC 0xB0FFF312u
  57. /** A resizeable buffer, optimized for reading and writing. */
  58. struct buf_t {
  59. uint32_t magic; /**< Magic cookie for debugging: Must be set to
  60. * BUFFER_MAGIC. */
  61. char *mem; /**< Storage for data in the buffer. */
  62. char *cur; /**< The first byte used for storing data in the buffer. */
  63. size_t highwater; /**< Largest observed datalen since last buf_shrink. */
  64. size_t len; /**< Maximum amount of data that <b>mem</b> can hold. */
  65. size_t memsize; /**< How many bytes did we actually allocate? Can be less
  66. * than 'len' if we shortened 'len' by a few bytes to make
  67. * zlib wrap around more easily. */
  68. size_t datalen; /**< Number of bytes currently in <b>mem</b>. */
  69. };
  70. /** Size, in bytes, for newly allocated buffers. Should be a power of 2. */
  71. #define INITIAL_BUF_SIZE (4*1024)
  72. /** Size, in bytes, for minimum 'shrink' size for buffers. Buffers may start
  73. * out smaller than this, but they will never autoshrink to less
  74. * than this size. */
  75. #define MIN_LAZY_SHRINK_SIZE (4*1024)
  76. static INLINE void peek_from_buf(char *string, size_t string_len, buf_t *buf);
  77. /** If the contents of buf wrap around the end of the allocated space,
  78. * malloc a new buf and copy the contents in starting at the
  79. * beginning. This operation is relatively expensive, so it shouldn't
  80. * be used e.g. for every single read or write.
  81. */
  82. static void
  83. buf_normalize(buf_t *buf)
  84. {
  85. check();
  86. if (buf->cur + buf->datalen <= buf->mem+buf->len) {
  87. return;
  88. } else {
  89. char *newmem, *oldmem;
  90. size_t sz = (buf->mem+buf->len)-buf->cur;
  91. log_warn(LD_BUG, "Unexpected non-normalized buffer.");
  92. newmem = GUARDED_MEM(tor_malloc(ALLOC_LEN(buf->memsize)));
  93. SET_GUARDS(newmem, buf->memsize);
  94. memcpy(newmem, buf->cur, sz);
  95. memcpy(newmem+sz, buf->mem, buf->datalen-sz);
  96. oldmem = RAW_MEM(buf->mem);
  97. tor_free(oldmem); /* Can't use tor_free directly. */
  98. buf->mem = buf->cur = newmem;
  99. buf->len = buf->memsize;
  100. check();
  101. }
  102. }
  103. /** Return the point in the buffer where the next byte will get stored. */
  104. static INLINE char *
  105. _buf_end(buf_t *buf)
  106. {
  107. char *next = buf->cur + buf->datalen;
  108. char *end = buf->mem + buf->len;
  109. return (next < end) ? next : (next - buf->len);
  110. }
  111. /** If the pointer <b>cp</b> has passed beyond the end of the buffer, wrap it
  112. * around. */
  113. static INLINE char *
  114. _wrap_ptr(buf_t *buf, char *cp)
  115. {
  116. return (cp >= buf->mem + buf->len) ? (cp - buf->len) : cp;
  117. }
  118. /** Return the offset of <b>cp</b> within the buffer. */
  119. static INLINE int
  120. _buf_offset(buf_t *buf, char *cp)
  121. {
  122. if (cp >= buf->cur)
  123. return cp - buf->cur;
  124. else
  125. /* return (cp - buf->mem) + buf->mem+buf->len - buf->cur */
  126. return cp + buf->len - buf->cur;
  127. }
  128. /** If the range of *<b>len</b> bytes starting at <b>at</b> wraps around the
  129. * end of the buffer, then set *<b>len</b> to the number of bytes starting
  130. * at <b>at</b>, and set *<b>more_len</b> to the number of bytes starting
  131. * at <b>buf-&gt;mem</b>. Otherwise, set *<b>more_len</b> to 0.
  132. */
  133. static INLINE void
  134. _split_range(buf_t *buf, char *at, size_t *len,
  135. size_t *more_len)
  136. {
  137. char *eos = at + *len;
  138. check();
  139. if (eos >= (buf->mem + buf->len)) {
  140. *more_len = eos - (buf->mem + buf->len);
  141. *len -= *more_len;
  142. } else {
  143. *more_len = 0;
  144. }
  145. }
  146. /** A freelist of buffer RAM chunks. */
  147. typedef struct free_mem_list_t {
  148. char *list; /**< The first item on the list; begins with pointer to the
  149. * next item. */
  150. int len; /**< How many entries in <b>list</b>. */
  151. int lowwater; /**< The smallest that list has gotten since the last call to
  152. * buf_shrink_freelists(). */
  153. const size_t chunksize; /**< How big are the items on the list? */
  154. const int slack; /**< We always keep at least this many items on the list
  155. * when shrinking it. */
  156. const int max; /**< How many elements are we willing to throw onto the list?
  157. */
  158. } free_mem_list_t;
  159. /** Freelists to hold 4k and 16k memory chunks. This seems to be what
  160. * we use most. */
  161. static free_mem_list_t free_mem_list_4k = { NULL, 0, 0, 4096, 16, INT_MAX };
  162. static free_mem_list_t free_mem_list_16k = { NULL, 0, 0, 16384, 4, 128 };
  163. /** Macro: True iff the size is one for which we keep a freelist. */
  164. #define IS_FREELIST_SIZE(sz) ((sz) == 4096 || (sz) == 16384)
  165. /** Return the proper freelist for chunks of size <b>sz</b>, or fail
  166. * with an assertion. */
  167. static INLINE free_mem_list_t *
  168. get_free_mem_list(size_t sz)
  169. {
  170. if (sz == 4096) {
  171. return &free_mem_list_4k;
  172. } else {
  173. tor_assert(sz == 16384);
  174. return &free_mem_list_16k;
  175. }
  176. }
  177. /** Throw the memory from <b>buf</b> onto the appropriate freelist.
  178. * Return true if we added the memory, 0 if the freelist was full. */
  179. static int
  180. add_buf_mem_to_freelist(buf_t *buf)
  181. {
  182. char *mem;
  183. free_mem_list_t *list;
  184. tor_assert(buf->datalen == 0);
  185. tor_assert(buf->mem);
  186. list = get_free_mem_list(buf->len);
  187. if (list->len >= list->max)
  188. return 0;
  189. mem = RAW_MEM(buf->mem);
  190. buf->len = buf->memsize = 0;
  191. buf->mem = buf->cur = NULL;
  192. *(char**)mem = list->list;
  193. list->list = mem;
  194. ++list->len;
  195. log_debug(LD_GENERAL, "Add buf mem to %d-byte freelist. Freelist has "
  196. "%d entries.", (int)list->chunksize, list->len);
  197. return 1;
  198. }
  199. /** Pull memory of size <b>sz</b> from the appropriate freelist for use by
  200. * <b>buf</b>, or allocate it as needed. */
  201. static void
  202. buf_get_initial_mem(buf_t *buf, size_t sz)
  203. {
  204. char *mem;
  205. free_mem_list_t *list = get_free_mem_list(sz);
  206. tor_assert(!buf->mem);
  207. if (list->list) {
  208. mem = list->list;
  209. list->list = *(char**)mem;
  210. if (--list->len < list->lowwater)
  211. list->lowwater = list->len;
  212. log_debug(LD_GENERAL, "Got buf mem from %d-byte freelist. Freelist has "
  213. "%d entries.", (int)list->chunksize, list->len);
  214. } else {
  215. log_debug(LD_GENERAL, "%d-byte freelist empty; allocating another chunk.",
  216. (int)list->chunksize);
  217. tor_assert(list->len == 0);
  218. mem = tor_malloc(ALLOC_LEN(sz));
  219. }
  220. buf->mem = GUARDED_MEM(mem);
  221. SET_GUARDS(buf->mem, sz);
  222. buf->len = sz;
  223. buf->memsize = ALLOC_LEN(sz);
  224. buf->cur = buf->mem;
  225. }
  226. /** Remove elements from the freelists that haven't been needed since the
  227. * last call to this function. */
  228. void
  229. buf_shrink_freelists(void)
  230. {
  231. int j;
  232. for (j = 0; j < 2; ++j) {
  233. free_mem_list_t *list = j ? &free_mem_list_16k : &free_mem_list_4k;
  234. if (list->lowwater > list->slack) {
  235. int i, n_to_skip, n_to_free;
  236. char **ptr;
  237. log_info(LD_GENERAL, "We haven't used %d/%d allocated %d-byte buffer "
  238. "memory chunks since the last call; freeing all but %d of them",
  239. list->lowwater, list->len, (int)list->chunksize, list->slack);
  240. /* Skip over the slack and non-lowwater entries */
  241. n_to_free = list->lowwater - list->slack;
  242. n_to_skip = list->len - n_to_free;
  243. for (ptr = &list->list, i = 0; i < n_to_skip; ++i) {
  244. char *mem = *ptr;
  245. tor_assert(mem);
  246. ptr = (char**)mem;
  247. }
  248. /* And free the remaining entries. */
  249. for (i = 0; i < n_to_free; ++i) {
  250. char *mem = *ptr;
  251. tor_assert(mem);
  252. *ptr = *(char**)mem;
  253. tor_free(mem);
  254. --list->len;
  255. }
  256. #if 0
  257. /* XXXX020 Put this code back if the above gives us nasty segfaults. */
  258. for (i = list->slack; i < list->lowwater; ++i) {
  259. char *mem = list->list;
  260. tor_assert(mem);
  261. list->list = *(char**)mem;
  262. tor_free(mem);
  263. --list->len;
  264. }
  265. #endif
  266. }
  267. list->lowwater = list->len;
  268. }
  269. }
  270. /** Change a buffer's capacity. <b>new_capacity</b> must be \>=
  271. * buf->datalen. */
  272. static void
  273. buf_resize(buf_t *buf, size_t new_capacity)
  274. {
  275. off_t offset;
  276. #ifdef CHECK_AFTER_RESIZE
  277. char *tmp, *tmp2;
  278. #endif
  279. tor_assert(buf->datalen <= new_capacity);
  280. tor_assert(new_capacity);
  281. #ifdef CHECK_AFTER_RESIZE
  282. assert_buf_ok(buf);
  283. tmp = tor_malloc(buf->datalen);
  284. tmp2 = tor_malloc(buf->datalen);
  285. peek_from_buf(tmp, buf->datalen, buf);
  286. #endif
  287. if (buf->len == new_capacity)
  288. return;
  289. offset = buf->cur - buf->mem;
  290. if (offset + buf->datalen > new_capacity) {
  291. /* We need to move stuff before we shrink. */
  292. if (offset + buf->datalen > buf->len) {
  293. /* We have:
  294. *
  295. * mem[0] ... mem[datalen-(len-offset)] (end of data)
  296. * mem[offset] ... mem[len-1] (the start of the data)
  297. *
  298. * We're shrinking the buffer by (len-new_capacity) bytes, so we need
  299. * to move the start portion back by that many bytes.
  300. */
  301. memmove(buf->cur-(buf->len-new_capacity), buf->cur,
  302. (size_t)(buf->len-offset));
  303. offset -= (buf->len-new_capacity);
  304. } else {
  305. /* The data doesn't wrap around, but it does extend beyond the new
  306. * buffer length:
  307. * mem[offset] ... mem[offset+datalen-1] (the data)
  308. */
  309. memmove(buf->mem, buf->cur, buf->datalen);
  310. offset = 0;
  311. }
  312. }
  313. if (buf->len == 0 && new_capacity < MIN_LAZY_SHRINK_SIZE)
  314. new_capacity = MIN_LAZY_SHRINK_SIZE;
  315. if (buf->len == 0 && IS_FREELIST_SIZE(new_capacity)) {
  316. tor_assert(!buf->mem);
  317. buf_get_initial_mem(buf, new_capacity);
  318. } else {
  319. char *raw;
  320. if (buf->mem)
  321. raw = tor_realloc(RAW_MEM(buf->mem), ALLOC_LEN(new_capacity));
  322. else {
  323. log_info(LD_GENERAL, "Jumping straight from 0 bytes to %d",
  324. (int)new_capacity);
  325. raw = tor_malloc(ALLOC_LEN(new_capacity));
  326. }
  327. buf->mem = GUARDED_MEM(raw);
  328. SET_GUARDS(buf->mem, new_capacity);
  329. buf->cur = buf->mem+offset;
  330. }
  331. if (offset + buf->datalen > buf->len) {
  332. /* We need to move data now that we are done growing. The buffer
  333. * now contains:
  334. *
  335. * mem[0] ... mem[datalen-(len-offset)] (end of data)
  336. * mem[offset] ... mem[len-1] (the start of the data)
  337. * mem[len]...mem[new_capacity] (empty space)
  338. *
  339. * We're growing by (new_capacity-len) bytes, so we need to move the
  340. * end portion forward by that many bytes.
  341. */
  342. memmove(buf->cur+(new_capacity-buf->len), buf->cur,
  343. (size_t)(buf->len-offset));
  344. buf->cur += new_capacity-buf->len;
  345. }
  346. buf->len = new_capacity;
  347. buf->memsize = ALLOC_LEN(buf->len);
  348. #ifdef CHECK_AFTER_RESIZE
  349. assert_buf_ok(buf);
  350. peek_from_buf(tmp2, buf->datalen, buf);
  351. if (memcmp(tmp, tmp2, buf->datalen)) {
  352. tor_assert(0);
  353. }
  354. tor_free(tmp);
  355. tor_free(tmp2);
  356. #endif
  357. }
  358. /** If the buffer is not large enough to hold <b>capacity</b> bytes, resize
  359. * it so that it can. (The new size will be a power of 2 times the old
  360. * size.)
  361. */
  362. static INLINE int
  363. buf_ensure_capacity(buf_t *buf, size_t capacity)
  364. {
  365. size_t new_len, min_len;
  366. if (buf->len >= capacity) /* Don't grow if we're already big enough. */
  367. return 0;
  368. if (capacity > MAX_BUF_SIZE) /* Don't grow past the maximum. */
  369. return -1;
  370. /* Find the smallest new_len equal to (2**X) for some X; such that
  371. * new_len is at least capacity, and at least 2*buf->len.
  372. */
  373. min_len = buf->len*2;
  374. new_len = 16;
  375. while (new_len < min_len)
  376. new_len *= 2;
  377. while (new_len < capacity)
  378. new_len *= 2;
  379. /* Resize the buffer. */
  380. log_debug(LD_MM,"Growing buffer from %d to %d bytes.",
  381. (int)buf->len, (int)new_len);
  382. buf_resize(buf,new_len);
  383. return 0;
  384. }
  385. /** Resize buf so it won't hold extra memory that we haven't been
  386. * using lately (that is, since the last time we called buf_shrink).
  387. * Try to shrink the buf until it is the largest factor of two that
  388. * can contain <b>buf</b>-&gt;highwater, but never smaller than
  389. * MIN_LAZY_SHRINK_SIZE.
  390. */
  391. void
  392. buf_shrink(buf_t *buf)
  393. {
  394. size_t new_len;
  395. new_len = buf->len;
  396. if (buf->datalen == 0 && buf->highwater == 0 &&
  397. IS_FREELIST_SIZE(buf->len)) {
  398. if (add_buf_mem_to_freelist(buf))
  399. return;
  400. }
  401. while (buf->highwater < (new_len>>2) && new_len > MIN_LAZY_SHRINK_SIZE*2)
  402. new_len >>= 1;
  403. buf->highwater = buf->datalen;
  404. if (new_len == buf->len)
  405. return;
  406. log_debug(LD_MM,"Shrinking buffer from %d to %d bytes.",
  407. (int)buf->len, (int)new_len);
  408. buf_resize(buf, new_len);
  409. }
  410. /** Remove the first <b>n</b> bytes from buf. */
  411. static INLINE void
  412. buf_remove_from_front(buf_t *buf, size_t n)
  413. {
  414. tor_assert(buf->datalen >= n);
  415. buf->datalen -= n;
  416. if (buf->datalen) {
  417. buf->cur = _wrap_ptr(buf, buf->cur+n);
  418. } else {
  419. buf->cur = buf->mem;
  420. }
  421. check();
  422. }
  423. /** Make sure that the memory in buf ends with a zero byte. */
  424. static INLINE int
  425. buf_nul_terminate(buf_t *buf)
  426. {
  427. if (buf_ensure_capacity(buf,buf->datalen+1)<0)
  428. return -1;
  429. *_buf_end(buf) = '\0';
  430. return 0;
  431. }
  432. /** Create and return a new buf with capacity <b>size</b>.
  433. * (Used for testing). */
  434. buf_t *
  435. buf_new_with_capacity(size_t size)
  436. {
  437. buf_t *buf;
  438. buf = tor_malloc_zero(sizeof(buf_t));
  439. buf->magic = BUFFER_MAGIC;
  440. if (IS_FREELIST_SIZE(size)) {
  441. buf_get_initial_mem(buf, size);
  442. } else {
  443. buf->cur = buf->mem = GUARDED_MEM(tor_malloc(ALLOC_LEN(size)));
  444. SET_GUARDS(buf->mem, size);
  445. buf->len = size;
  446. buf->memsize = ALLOC_LEN(size);
  447. }
  448. assert_buf_ok(buf);
  449. return buf;
  450. }
  451. /** Allocate and return a new buffer with default capacity. */
  452. buf_t *
  453. buf_new(void)
  454. {
  455. return buf_new_with_capacity(INITIAL_BUF_SIZE);
  456. }
  457. /** Remove all data from <b>buf</b>. */
  458. void
  459. buf_clear(buf_t *buf)
  460. {
  461. buf->datalen = 0;
  462. buf->cur = buf->mem;
  463. /* buf->len = buf->memsize; bad. */
  464. }
  465. /** Return the number of bytes stored in <b>buf</b> */
  466. size_t
  467. buf_datalen(const buf_t *buf)
  468. {
  469. return buf->datalen;
  470. }
  471. /** Return the maximum bytes that can be stored in <b>buf</b> before buf
  472. * needs to resize. */
  473. size_t
  474. buf_capacity(const buf_t *buf)
  475. {
  476. return buf->len;
  477. }
  478. /** For testing only: Return a pointer to the raw memory stored in
  479. * <b>buf</b>. */
  480. const char *
  481. _buf_peek_raw_buffer(const buf_t *buf)
  482. {
  483. return buf->cur;
  484. }
  485. /** Release storage held by <b>buf</b>. */
  486. void
  487. buf_free(buf_t *buf)
  488. {
  489. char *oldmem;
  490. assert_buf_ok(buf);
  491. buf->magic = 0xDEADBEEF;
  492. if (IS_FREELIST_SIZE(buf->len)) {
  493. buf->datalen = 0; /* Avoid assert in add_buf_mem_to_freelist. */
  494. add_buf_mem_to_freelist(buf);
  495. }
  496. if (buf->mem) {
  497. /* The freelist didn't want the RAM. */
  498. oldmem = RAW_MEM(buf->mem);
  499. tor_free(oldmem);
  500. }
  501. tor_free(buf);
  502. }
  503. /** Helper for read_to_buf(): read no more than at_most bytes from
  504. * socket s into buffer buf, starting at the position pos. (Does not
  505. * check for overflow.) Set *reached_eof to true on EOF. Return
  506. * number of bytes read on success, 0 if the read would block, -1 on
  507. * failure.
  508. */
  509. static INLINE int
  510. read_to_buf_impl(int s, size_t at_most, buf_t *buf,
  511. char *pos, int *reached_eof)
  512. {
  513. int read_result;
  514. // log_fn(LOG_DEBUG,"reading at most %d bytes.",at_most);
  515. read_result = tor_socket_recv(s, pos, at_most, 0);
  516. if (read_result < 0) {
  517. int e = tor_socket_errno(s);
  518. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  519. #ifdef MS_WINDOWS
  520. if (e == WSAENOBUFS)
  521. log_warn(LD_NET,"recv() failed: WSAENOBUFS. Not enough ram?");
  522. #endif
  523. return -1;
  524. }
  525. return 0; /* would block. */
  526. } else if (read_result == 0) {
  527. log_debug(LD_NET,"Encountered eof");
  528. *reached_eof = 1;
  529. return 0;
  530. } else { /* we read some bytes */
  531. buf->datalen += read_result;
  532. if (buf->datalen > buf->highwater)
  533. buf->highwater = buf->datalen;
  534. log_debug(LD_NET,"Read %d bytes. %d on inbuf.",read_result,
  535. (int)buf->datalen);
  536. return read_result;
  537. }
  538. }
  539. /** Read from socket <b>s</b>, writing onto end of <b>buf</b>. Read at most
  540. * <b>at_most</b> bytes, resizing the buffer as necessary. If recv()
  541. * returns 0, set *<b>reached_eof</b> to 1 and return 0. Return -1 on error;
  542. * else return the number of bytes read. Return 0 if recv() would
  543. * block.
  544. */
  545. int
  546. read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof)
  547. {
  548. int r;
  549. char *next;
  550. size_t at_start;
  551. /* assert_buf_ok(buf); */
  552. tor_assert(reached_eof);
  553. tor_assert(s>=0);
  554. if (buf_ensure_capacity(buf,buf->datalen+at_most))
  555. return -1;
  556. if (at_most + buf->datalen > buf->len)
  557. at_most = buf->len - buf->datalen; /* take the min of the two */
  558. if (at_most == 0)
  559. return 0; /* we shouldn't read anything */
  560. next = _buf_end(buf);
  561. _split_range(buf, next, &at_most, &at_start);
  562. r = read_to_buf_impl(s, at_most, buf, next, reached_eof);
  563. check();
  564. if (r < 0 || (size_t)r < at_most) {
  565. return r; /* Either error, eof, block, or no more to read. */
  566. }
  567. if (at_start) {
  568. int r2;
  569. tor_assert(_buf_end(buf) == buf->mem);
  570. r2 = read_to_buf_impl(s, at_start, buf, buf->mem, reached_eof);
  571. check();
  572. if (r2 < 0) {
  573. return r2;
  574. } else {
  575. r += r2;
  576. }
  577. }
  578. return r;
  579. }
  580. /** Helper for read_to_buf_tls(): read no more than <b>at_most</b>
  581. * bytes from the TLS connection <b>tls</b> into buffer <b>buf</b>,
  582. * starting at the position <b>next</b>. (Does not check for overflow.)
  583. * Return number of bytes read on success, 0 if the read would block,
  584. * -1 on failure.
  585. */
  586. static INLINE int
  587. read_to_buf_tls_impl(tor_tls_t *tls, size_t at_most, buf_t *buf, char *next)
  588. {
  589. int r;
  590. log_debug(LD_NET,"before: %d on buf, %d pending, at_most %d.",
  591. (int)buf_datalen(buf), (int)tor_tls_get_pending_bytes(tls),
  592. (int)at_most);
  593. r = tor_tls_read(tls, next, at_most);
  594. if (r<0)
  595. return r;
  596. buf->datalen += r;
  597. if (buf->datalen > buf->highwater)
  598. buf->highwater = buf->datalen;
  599. log_debug(LD_NET,"Read %d bytes. %d on inbuf; %d pending",r,
  600. (int)buf->datalen,(int)tor_tls_get_pending_bytes(tls));
  601. return r;
  602. }
  603. /** As read_to_buf, but reads from a TLS connection.
  604. *
  605. * Using TLS on OR connections complicates matters in two ways.
  606. *
  607. * First, a TLS stream has its own read buffer independent of the
  608. * connection's read buffer. (TLS needs to read an entire frame from
  609. * the network before it can decrypt any data. Thus, trying to read 1
  610. * byte from TLS can require that several KB be read from the network
  611. * and decrypted. The extra data is stored in TLS's decrypt buffer.)
  612. * Because the data hasn't been read by Tor (it's still inside the TLS),
  613. * this means that sometimes a connection "has stuff to read" even when
  614. * poll() didn't return POLLIN. The tor_tls_get_pending_bytes function is
  615. * used in connection.c to detect TLS objects with non-empty internal
  616. * buffers and read from them again.
  617. *
  618. * Second, the TLS stream's events do not correspond directly to network
  619. * events: sometimes, before a TLS stream can read, the network must be
  620. * ready to write -- or vice versa.
  621. */
  622. int
  623. read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf)
  624. {
  625. int r;
  626. char *next;
  627. size_t at_start;
  628. tor_assert(tls);
  629. assert_buf_ok(buf);
  630. log_debug(LD_NET,"start: %d on buf, %d pending, at_most %d.",
  631. (int)buf_datalen(buf), (int)tor_tls_get_pending_bytes(tls),
  632. (int)at_most);
  633. if (buf_ensure_capacity(buf, at_most+buf->datalen))
  634. return TOR_TLS_ERROR_MISC;
  635. if (at_most + buf->datalen > buf->len)
  636. at_most = buf->len - buf->datalen;
  637. if (at_most == 0)
  638. return 0;
  639. next = _buf_end(buf);
  640. _split_range(buf, next, &at_most, &at_start);
  641. r = read_to_buf_tls_impl(tls, at_most, buf, next);
  642. check();
  643. if (r < 0 || (size_t)r < at_most)
  644. return r; /* Either error, eof, block, or no more to read. */
  645. if (at_start) {
  646. int r2;
  647. tor_assert(_buf_end(buf) == buf->mem);
  648. r2 = read_to_buf_tls_impl(tls, at_start, buf, buf->mem);
  649. check();
  650. if (r2 < 0)
  651. return r2;
  652. else
  653. r += r2;
  654. }
  655. return r;
  656. }
  657. /** Helper for flush_buf(): try to write <b>sz</b> bytes from buffer
  658. * <b>buf</b> onto socket <b>s</b>. On success, deduct the bytes written
  659. * from *<b>buf_flushlen</b>.
  660. * Return the number of bytes written on success, -1 on failure.
  661. */
  662. static INLINE int
  663. flush_buf_impl(int s, buf_t *buf, size_t sz, size_t *buf_flushlen)
  664. {
  665. int write_result;
  666. write_result = tor_socket_send(s, buf->cur, sz, 0);
  667. if (write_result < 0) {
  668. int e = tor_socket_errno(s);
  669. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  670. #ifdef MS_WINDOWS
  671. if (e == WSAENOBUFS)
  672. log_warn(LD_NET,"write() failed: WSAENOBUFS. Not enough ram?");
  673. #endif
  674. return -1;
  675. }
  676. log_debug(LD_NET,"write() would block, returning.");
  677. return 0;
  678. } else {
  679. *buf_flushlen -= write_result;
  680. buf_remove_from_front(buf, write_result);
  681. return write_result;
  682. }
  683. }
  684. /** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
  685. * <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by
  686. * the number of bytes actually written, and remove the written bytes
  687. * from the buffer. Return the number of bytes written on success,
  688. * -1 on failure. Return 0 if write() would block.
  689. */
  690. int
  691. flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen)
  692. {
  693. int r;
  694. size_t flushed = 0;
  695. size_t flushlen0, flushlen1;
  696. /* assert_buf_ok(buf); */
  697. tor_assert(buf_flushlen);
  698. tor_assert(s>=0);
  699. tor_assert(*buf_flushlen <= buf->datalen);
  700. tor_assert(sz <= *buf_flushlen);
  701. if (sz == 0) /* nothing to flush */
  702. return 0;
  703. flushlen0 = sz;
  704. _split_range(buf, buf->cur, &flushlen0, &flushlen1);
  705. r = flush_buf_impl(s, buf, flushlen0, buf_flushlen);
  706. check();
  707. log_debug(LD_NET,"%d: flushed %d bytes, %d ready to flush, %d remain.",
  708. s,r,(int)*buf_flushlen,(int)buf->datalen);
  709. if (r < 0 || (size_t)r < flushlen0)
  710. return r; /* Error, or can't flush any more now. */
  711. flushed = r;
  712. if (flushlen1) {
  713. tor_assert(buf->cur == buf->mem);
  714. r = flush_buf_impl(s, buf, flushlen1, buf_flushlen);
  715. check();
  716. log_debug(LD_NET,"%d: flushed %d bytes, %d ready to flush, %d remain.",
  717. s,r,(int)*buf_flushlen,(int)buf->datalen);
  718. if (r<0)
  719. return r;
  720. flushed += r;
  721. }
  722. return flushed;
  723. }
  724. /** Helper for flush_buf_tls(): try to write <b>sz</b> bytes (or more if
  725. * required by a previous write) from buffer <b>buf</b> onto TLS object
  726. * <b>tls</b>. On success, deduct the bytes written from
  727. * *<b>buf_flushlen</b>. Return the number of bytes written on success, -1 on
  728. * failure.
  729. */
  730. static INLINE int
  731. flush_buf_tls_impl(tor_tls_t *tls, buf_t *buf, size_t sz, size_t *buf_flushlen)
  732. {
  733. int r;
  734. size_t forced;
  735. forced = tor_tls_get_forced_write_size(tls);
  736. if (forced > sz)
  737. sz = forced;
  738. r = tor_tls_write(tls, buf->cur, sz);
  739. if (r < 0) {
  740. return r;
  741. }
  742. *buf_flushlen -= r;
  743. buf_remove_from_front(buf, r);
  744. log_debug(LD_NET,"flushed %d bytes, %d ready to flush, %d remain.",
  745. r,(int)*buf_flushlen,(int)buf->datalen);
  746. return r;
  747. }
  748. /** As flush_buf(), but writes data to a TLS connection.
  749. */
  750. int
  751. flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t sz, size_t *buf_flushlen)
  752. {
  753. int r;
  754. size_t flushed=0;
  755. size_t flushlen0, flushlen1;
  756. /* assert_buf_ok(buf); */
  757. tor_assert(tls);
  758. tor_assert(buf_flushlen);
  759. tor_assert(*buf_flushlen <= buf->datalen);
  760. tor_assert(sz <= *buf_flushlen);
  761. /* we want to let tls write even if flushlen is zero, because it might
  762. * have a partial record pending */
  763. check_no_tls_errors();
  764. flushlen0 = sz;
  765. _split_range(buf, buf->cur, &flushlen0, &flushlen1);
  766. if (flushlen1) {
  767. size_t forced = tor_tls_get_forced_write_size(tls);
  768. tor_assert(forced <= flushlen0);
  769. }
  770. r = flush_buf_tls_impl(tls, buf, flushlen0, buf_flushlen);
  771. check();
  772. if (r < 0 || (size_t)r < flushlen0)
  773. return r; /* Error, or can't flush any more now. */
  774. flushed = r;
  775. if (flushlen1) {
  776. tor_assert(buf->cur == buf->mem);
  777. r = flush_buf_tls_impl(tls, buf, flushlen1, buf_flushlen);
  778. check();
  779. if (r<0)
  780. return r;
  781. flushed += r;
  782. }
  783. return flushed;
  784. }
  785. /** Append <b>string_len</b> bytes from <b>string</b> to the end of
  786. * <b>buf</b>.
  787. *
  788. * Return the new length of the buffer on success, -1 on failure.
  789. */
  790. int
  791. write_to_buf(const char *string, size_t string_len, buf_t *buf)
  792. {
  793. char *next;
  794. size_t len2;
  795. /* append string to buf (growing as needed, return -1 if "too big")
  796. * return total number of bytes on the buf
  797. */
  798. tor_assert(string);
  799. /* assert_buf_ok(buf); */
  800. if (buf_ensure_capacity(buf, buf->datalen+string_len)) {
  801. log_warn(LD_MM, "buflen too small, can't hold %d bytes.",
  802. (int)(buf->datalen+string_len));
  803. return -1;
  804. }
  805. next = _buf_end(buf);
  806. _split_range(buf, next, &string_len, &len2);
  807. memcpy(next, string, string_len);
  808. buf->datalen += string_len;
  809. if (len2) {
  810. tor_assert(_buf_end(buf) == buf->mem);
  811. memcpy(buf->mem, string+string_len, len2);
  812. buf->datalen += len2;
  813. }
  814. if (buf->datalen > buf->highwater)
  815. buf->highwater = buf->datalen;
  816. log_debug(LD_NET,"added %d bytes to buf (now %d total).",
  817. (int)string_len, (int)buf->datalen);
  818. check();
  819. return buf->datalen;
  820. }
  821. /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
  822. * onto <b>string</b>.
  823. */
  824. static INLINE void
  825. peek_from_buf(char *string, size_t string_len, buf_t *buf)
  826. {
  827. size_t len2;
  828. /* There must be string_len bytes in buf; write them onto string,
  829. * then memmove buf back (that is, remove them from buf).
  830. *
  831. * Return the number of bytes still on the buffer. */
  832. tor_assert(string);
  833. /* make sure we don't ask for too much */
  834. tor_assert(string_len <= buf->datalen);
  835. /* assert_buf_ok(buf); */
  836. _split_range(buf, buf->cur, &string_len, &len2);
  837. memcpy(string, buf->cur, string_len);
  838. if (len2) {
  839. memcpy(string+string_len,buf->mem,len2);
  840. }
  841. }
  842. /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
  843. * them into <b>string</b>. Return the new buffer size. <b>string_len</b>
  844. * must be \<= the number of bytes on the buffer.
  845. */
  846. int
  847. fetch_from_buf(char *string, size_t string_len, buf_t *buf)
  848. {
  849. /* There must be string_len bytes in buf; write them onto string,
  850. * then memmove buf back (that is, remove them from buf).
  851. *
  852. * Return the number of bytes still on the buffer. */
  853. check();
  854. peek_from_buf(string, string_len, buf);
  855. buf_remove_from_front(buf, string_len);
  856. check();
  857. return buf->datalen;
  858. }
  859. /** Move up to *<b>buf_flushlen</b> bytes from <b>buf_in</b> to
  860. * <b>buf_out</b>, and modify *<b>buf_flushlen</b> appropriately.
  861. * Return the number of bytes actually copied.
  862. */
  863. int
  864. move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen)
  865. {
  866. char b[4096];
  867. size_t cp, len;
  868. len = *buf_flushlen;
  869. if (len > buf_in->datalen)
  870. len = buf_in->datalen;
  871. cp = len; /* Remember the number of bytes we intend to copy. */
  872. while (len) {
  873. /* This isn't the most efficient implementation one could imagine, since
  874. * it does two copies instead of 1, but I kinda doubt that this will be
  875. * critical path. */
  876. size_t n = len > sizeof(b) ? sizeof(b) : len;
  877. fetch_from_buf(b, n, buf_in);
  878. write_to_buf(b, n, buf_out);
  879. len -= n;
  880. }
  881. *buf_flushlen -= cp;
  882. return cp;
  883. }
  884. /** There is a (possibly incomplete) http statement on <b>buf</b>, of the
  885. * form "\%s\\r\\n\\r\\n\%s", headers, body. (body may contain nuls.)
  886. * If a) the headers include a Content-Length field and all bytes in
  887. * the body are present, or b) there's no Content-Length field and
  888. * all headers are present, then:
  889. *
  890. * - strdup headers into <b>*headers_out</b>, and nul-terminate it.
  891. * - memdup body into <b>*body_out</b>, and nul-terminate it.
  892. * - Then remove them from <b>buf</b>, and return 1.
  893. *
  894. * - If headers or body is NULL, discard that part of the buf.
  895. * - If a headers or body doesn't fit in the arg, return -1.
  896. * (We ensure that the headers or body don't exceed max len,
  897. * _even if_ we're planning to discard them.)
  898. * - If force_complete is true, then succeed even if not all of the
  899. * content has arrived.
  900. *
  901. * Else, change nothing and return 0.
  902. */
  903. int
  904. fetch_from_buf_http(buf_t *buf,
  905. char **headers_out, size_t max_headerlen,
  906. char **body_out, size_t *body_used, size_t max_bodylen,
  907. int force_complete)
  908. {
  909. char *headers, *body, *p;
  910. size_t headerlen, bodylen, contentlen;
  911. /* assert_buf_ok(buf); */
  912. buf_normalize(buf);
  913. if (buf_nul_terminate(buf)<0) {
  914. log_warn(LD_BUG,"Couldn't nul-terminate buffer");
  915. return -1;
  916. }
  917. headers = buf->cur;
  918. body = strstr(headers,"\r\n\r\n");
  919. if (!body) {
  920. log_debug(LD_HTTP,"headers not all here yet.");
  921. return 0;
  922. }
  923. body += 4; /* Skip the the CRLFCRLF */
  924. headerlen = body-headers; /* includes the CRLFCRLF */
  925. bodylen = buf->datalen - headerlen;
  926. log_debug(LD_HTTP,"headerlen %d, bodylen %d.", (int)headerlen, (int)bodylen);
  927. if (max_headerlen <= headerlen) {
  928. log_warn(LD_HTTP,"headerlen %d larger than %d. Failing.",
  929. (int)headerlen, (int)max_headerlen-1);
  930. return -1;
  931. }
  932. if (max_bodylen <= bodylen) {
  933. log_warn(LD_HTTP,"bodylen %d larger than %d. Failing.",
  934. (int)bodylen, (int)max_bodylen-1);
  935. return -1;
  936. }
  937. #define CONTENT_LENGTH "\r\nContent-Length: "
  938. p = strstr(headers, CONTENT_LENGTH);
  939. if (p) {
  940. int i;
  941. i = atoi(p+strlen(CONTENT_LENGTH));
  942. if (i < 0) {
  943. log_warn(LD_PROTOCOL, "Content-Length is less than zero; it looks like "
  944. "someone is trying to crash us.");
  945. return -1;
  946. }
  947. contentlen = i;
  948. /* if content-length is malformed, then our body length is 0. fine. */
  949. log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
  950. if (bodylen < contentlen) {
  951. if (!force_complete) {
  952. log_debug(LD_HTTP,"body not all here yet.");
  953. return 0; /* not all there yet */
  954. }
  955. }
  956. if (bodylen > contentlen) {
  957. bodylen = contentlen;
  958. log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
  959. }
  960. }
  961. /* all happy. copy into the appropriate places, and return 1 */
  962. if (headers_out) {
  963. *headers_out = tor_malloc(headerlen+1);
  964. memcpy(*headers_out,buf->cur,headerlen);
  965. (*headers_out)[headerlen] = 0; /* nul terminate it */
  966. }
  967. if (body_out) {
  968. tor_assert(body_used);
  969. *body_used = bodylen;
  970. *body_out = tor_malloc(bodylen+1);
  971. memcpy(*body_out,buf->cur+headerlen,bodylen);
  972. (*body_out)[bodylen] = 0; /* nul terminate it */
  973. }
  974. buf_remove_from_front(buf, headerlen+bodylen);
  975. return 1;
  976. }
  977. /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
  978. * of the forms
  979. * - socks4: "socksheader username\\0"
  980. * - socks4a: "socksheader username\\0 destaddr\\0"
  981. * - socks5 phase one: "version #methods methods"
  982. * - socks5 phase two: "version command 0 addresstype..."
  983. * If it's a complete and valid handshake, and destaddr fits in
  984. * MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
  985. * assign to <b>req</b>, and return 1.
  986. *
  987. * If it's invalid or too big, return -1.
  988. *
  989. * Else it's not all there yet, leave buf alone and return 0.
  990. *
  991. * If you want to specify the socks reply, write it into <b>req->reply</b>
  992. * and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
  993. *
  994. * If <b>log_sockstype</b> is non-zero, then do a notice-level log of whether
  995. * the connection is possibly leaking DNS requests locally or not.
  996. *
  997. * If <b>safe_socks</b> is true, then reject unsafe socks protocols.
  998. *
  999. * If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are
  1000. * undefined.
  1001. */
  1002. int
  1003. fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
  1004. int log_sockstype, int safe_socks)
  1005. {
  1006. unsigned int len;
  1007. char tmpbuf[INET_NTOA_BUF_LEN];
  1008. uint32_t destip;
  1009. enum {socks4, socks4a} socks4_prot = socks4a;
  1010. char *next, *startaddr;
  1011. struct in_addr in;
  1012. /* If the user connects with socks4 or the wrong variant of socks5,
  1013. * then log a warning to let him know that it might be unwise. */
  1014. static int have_warned_about_unsafe_socks = 0;
  1015. if (buf->datalen < 2) /* version and another byte */
  1016. return 0;
  1017. buf_normalize(buf);
  1018. switch (*(buf->cur)) { /* which version of socks? */
  1019. case 5: /* socks5 */
  1020. if (req->socks_version != 5) { /* we need to negotiate a method */
  1021. unsigned char nummethods = (unsigned char)*(buf->cur+1);
  1022. tor_assert(!req->socks_version);
  1023. if (buf->datalen < 2u+nummethods)
  1024. return 0;
  1025. if (!nummethods || !memchr(buf->cur+2, 0, nummethods)) {
  1026. log_warn(LD_APP,
  1027. "socks5: offered methods don't include 'no auth'. "
  1028. "Rejecting.");
  1029. req->replylen = 2; /* 2 bytes of response */
  1030. req->reply[0] = 5;
  1031. req->reply[1] = '\xFF'; /* reject all methods */
  1032. return -1;
  1033. }
  1034. /* remove packet from buf. also remove any other extraneous
  1035. * bytes, to support broken socks clients. */
  1036. buf_clear(buf);
  1037. req->replylen = 2; /* 2 bytes of response */
  1038. req->reply[0] = 5; /* socks5 reply */
  1039. req->reply[1] = SOCKS5_SUCCEEDED;
  1040. req->socks_version = 5; /* remember we've already negotiated auth */
  1041. log_debug(LD_APP,"socks5: accepted method 0");
  1042. return 0;
  1043. }
  1044. /* we know the method; read in the request */
  1045. log_debug(LD_APP,"socks5: checking request");
  1046. if (buf->datalen < 8) /* basic info plus >=2 for addr plus 2 for port */
  1047. return 0; /* not yet */
  1048. req->command = (unsigned char) *(buf->cur+1);
  1049. if (req->command != SOCKS_COMMAND_CONNECT &&
  1050. req->command != SOCKS_COMMAND_CONNECT_DIR &&
  1051. req->command != SOCKS_COMMAND_RESOLVE &&
  1052. req->command != SOCKS_COMMAND_RESOLVE_PTR) {
  1053. /* not a connect or resolve or a resolve_ptr? we don't support it. */
  1054. log_warn(LD_APP,"socks5: command %d not recognized. Rejecting.",
  1055. req->command);
  1056. return -1;
  1057. }
  1058. switch (*(buf->cur+3)) { /* address type */
  1059. case 1: /* IPv4 address */
  1060. log_debug(LD_APP,"socks5: ipv4 address type");
  1061. if (buf->datalen < 10) /* ip/port there? */
  1062. return 0; /* not yet */
  1063. destip = ntohl(*(uint32_t*)(buf->cur+4));
  1064. in.s_addr = htonl(destip);
  1065. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1066. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1067. log_warn(LD_APP,
  1068. "socks5 IP takes %d bytes, which doesn't fit in %d. "
  1069. "Rejecting.",
  1070. (int)strlen(tmpbuf)+1,(int)MAX_SOCKS_ADDR_LEN);
  1071. return -1;
  1072. }
  1073. strlcpy(req->address,tmpbuf,sizeof(req->address));
  1074. req->port = ntohs(*(uint16_t*)(buf->cur+8));
  1075. buf_remove_from_front(buf, 10);
  1076. if (req->command != SOCKS_COMMAND_RESOLVE_PTR &&
  1077. !addressmap_have_mapping(req->address) &&
  1078. !have_warned_about_unsafe_socks) {
  1079. log_warn(LD_APP,
  1080. "Your application (using socks5 on port %d) is giving "
  1081. "Tor only an IP address. Applications that do DNS resolves "
  1082. "themselves may leak information. Consider using Socks4A "
  1083. "(e.g. via privoxy or socat) instead. For more information, "
  1084. "please see http://wiki.noreply.org/noreply/TheOnionRouter/"
  1085. "TorFAQ#SOCKSAndDNS.%s", req->port,
  1086. safe_socks ? " Rejecting." : "");
  1087. // have_warned_about_unsafe_socks = 1; // (for now, warn every time)
  1088. control_event_client_status(LOG_WARN,
  1089. "DANGEROUS_SOCKS PROTOCOL=SOCKS5 ADDRESS=%s:%d",
  1090. req->address, req->port);
  1091. if (safe_socks)
  1092. return -1;
  1093. }
  1094. return 1;
  1095. case 3: /* fqdn */
  1096. log_debug(LD_APP,"socks5: fqdn address type");
  1097. if (req->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1098. log_warn(LD_APP, "socks5 received RESOLVE_PTR command with "
  1099. "hostname type. Rejecting.");
  1100. return -1;
  1101. }
  1102. len = (unsigned char)*(buf->cur+4);
  1103. if (buf->datalen < 7+len) /* addr/port there? */
  1104. return 0; /* not yet */
  1105. if (len+1 > MAX_SOCKS_ADDR_LEN) {
  1106. log_warn(LD_APP,
  1107. "socks5 hostname is %d bytes, which doesn't fit in "
  1108. "%d. Rejecting.", len+1,MAX_SOCKS_ADDR_LEN);
  1109. return -1;
  1110. }
  1111. memcpy(req->address,buf->cur+5,len);
  1112. req->address[len] = 0;
  1113. req->port = ntohs(get_uint16(buf->cur+5+len));
  1114. buf_remove_from_front(buf, 5+len+2);
  1115. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1116. log_warn(LD_PROTOCOL,
  1117. "Your application (using socks5 on port %d) gave Tor "
  1118. "a malformed hostname: %s. Rejecting the connection.",
  1119. req->port, escaped(req->address));
  1120. return -1;
  1121. }
  1122. if (log_sockstype)
  1123. log_notice(LD_APP,
  1124. "Your application (using socks5 on port %d) gave "
  1125. "Tor a hostname, which means Tor will do the DNS resolve "
  1126. "for you. This is good.", req->port);
  1127. return 1;
  1128. default: /* unsupported */
  1129. log_warn(LD_APP,"socks5: unsupported address type %d. Rejecting.",
  1130. *(buf->cur+3));
  1131. return -1;
  1132. }
  1133. tor_assert(0);
  1134. case 4: /* socks4 */
  1135. /* http://archive.socks.permeo.com/protocol/socks4.protocol */
  1136. /* http://archive.socks.permeo.com/protocol/socks4a.protocol */
  1137. req->socks_version = 4;
  1138. if (buf->datalen < SOCKS4_NETWORK_LEN) /* basic info available? */
  1139. return 0; /* not yet */
  1140. req->command = (unsigned char) *(buf->cur+1);
  1141. if (req->command != SOCKS_COMMAND_CONNECT &&
  1142. req->command != SOCKS_COMMAND_CONNECT_DIR &&
  1143. req->command != SOCKS_COMMAND_RESOLVE) {
  1144. /* not a connect or resolve? we don't support it. (No resolve_ptr with
  1145. * socks4.) */
  1146. log_warn(LD_APP,"socks4: command %d not recognized. Rejecting.",
  1147. req->command);
  1148. return -1;
  1149. }
  1150. req->port = ntohs(*(uint16_t*)(buf->cur+2));
  1151. destip = ntohl(*(uint32_t*)(buf->mem+4));
  1152. if ((!req->port && req->command!=SOCKS_COMMAND_RESOLVE) || !destip) {
  1153. log_warn(LD_APP,"socks4: Port or DestIP is zero. Rejecting.");
  1154. return -1;
  1155. }
  1156. if (destip >> 8) {
  1157. log_debug(LD_APP,"socks4: destip not in form 0.0.0.x.");
  1158. in.s_addr = htonl(destip);
  1159. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1160. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1161. log_debug(LD_APP,"socks4 addr (%d bytes) too long. Rejecting.",
  1162. (int)strlen(tmpbuf));
  1163. return -1;
  1164. }
  1165. log_debug(LD_APP,
  1166. "socks4: successfully read destip (%s)", safe_str(tmpbuf));
  1167. socks4_prot = socks4;
  1168. }
  1169. next = memchr(buf->cur+SOCKS4_NETWORK_LEN, 0,
  1170. buf->datalen-SOCKS4_NETWORK_LEN);
  1171. if (!next) {
  1172. log_debug(LD_APP,"socks4: Username not here yet.");
  1173. return 0;
  1174. }
  1175. tor_assert(next < buf->cur+buf->datalen);
  1176. startaddr = NULL;
  1177. if (socks4_prot != socks4a &&
  1178. !addressmap_have_mapping(tmpbuf) &&
  1179. !have_warned_about_unsafe_socks) {
  1180. log_warn(LD_APP,
  1181. "Your application (using socks4 on port %d) is giving Tor "
  1182. "only an IP address. Applications that do DNS resolves "
  1183. "themselves may leak information. Consider using Socks4A "
  1184. "(e.g. via privoxy or socat) instead. For more information, "
  1185. "please see http://wiki.noreply.org/noreply/TheOnionRouter/"
  1186. "TorFAQ#SOCKSAndDNS.%s", req->port,
  1187. safe_socks ? " Rejecting." : "");
  1188. // have_warned_about_unsafe_socks = 1; // (for now, warn every time)
  1189. control_event_client_status(LOG_WARN,
  1190. "DANGEROUS_SOCKS PROTOCOL=SOCKS4 ADDRESS=%s:%d",
  1191. tmpbuf, req->port);
  1192. if (safe_socks)
  1193. return -1;
  1194. }
  1195. if (socks4_prot == socks4a) {
  1196. if (next+1 == buf->cur+buf->datalen) {
  1197. log_debug(LD_APP,"socks4: No part of destaddr here yet.");
  1198. return 0;
  1199. }
  1200. startaddr = next+1;
  1201. next = memchr(startaddr, 0, buf->cur+buf->datalen-startaddr);
  1202. if (!next) {
  1203. log_debug(LD_APP,"socks4: Destaddr not all here yet.");
  1204. return 0;
  1205. }
  1206. if (MAX_SOCKS_ADDR_LEN <= next-startaddr) {
  1207. log_warn(LD_APP,"socks4: Destaddr too long. Rejecting.");
  1208. return -1;
  1209. }
  1210. tor_assert(next < buf->cur+buf->datalen);
  1211. if (log_sockstype)
  1212. log_notice(LD_APP,
  1213. "Your application (using socks4a on port %d) gave "
  1214. "Tor a hostname, which means Tor will do the DNS resolve "
  1215. "for you. This is good.", req->port);
  1216. }
  1217. log_debug(LD_APP,"socks4: Everything is here. Success.");
  1218. strlcpy(req->address, startaddr ? startaddr : tmpbuf,
  1219. sizeof(req->address));
  1220. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1221. log_warn(LD_PROTOCOL,
  1222. "Your application (using socks4 on port %d) gave Tor "
  1223. "a malformed hostname: %s. Rejecting the connection.",
  1224. req->port, escaped(req->address));
  1225. return -1;
  1226. }
  1227. /* next points to the final \0 on inbuf */
  1228. buf_remove_from_front(buf, next-buf->cur+1);
  1229. return 1;
  1230. case 'G': /* get */
  1231. case 'H': /* head */
  1232. case 'P': /* put/post */
  1233. case 'C': /* connect */
  1234. strlcpy(req->reply,
  1235. "HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
  1236. "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
  1237. "<html>\n"
  1238. "<head>\n"
  1239. "<title>Tor is not an HTTP Proxy</title>\n"
  1240. "</head>\n"
  1241. "<body>\n"
  1242. "<h1>Tor is not an HTTP Proxy</h1>\n"
  1243. "<p>\n"
  1244. "It appears you have configured your web browser to use Tor as an HTTP proxy."
  1245. "\n"
  1246. "This is not correct: Tor is a SOCKS proxy, not an HTTP proxy.\n"
  1247. "Please configure your client accordingly.\n"
  1248. "</p>\n"
  1249. "<p>\n"
  1250. "See <a href=\"http://tor.eff.org/documentation.html\">"
  1251. "http://tor.eff.org/documentation.html</a> for more information.\n"
  1252. "<!-- Plus this comment, to make the body response more than 512 bytes, so "
  1253. " IE will be willing to display it. Comment comment comment comment "
  1254. " comment comment comment comment comment comment comment comment.-->\n"
  1255. "</p>\n"
  1256. "</body>\n"
  1257. "</html>\n"
  1258. , MAX_SOCKS_REPLY_LEN);
  1259. req->replylen = strlen(req->reply)+1;
  1260. /* fall through */
  1261. default: /* version is not socks4 or socks5 */
  1262. log_warn(LD_APP,
  1263. "Socks version %d not recognized. (Tor is not an http proxy.)",
  1264. *(buf->cur));
  1265. {
  1266. char *tmp = tor_strndup(buf->cur, 8);
  1267. control_event_client_status(LOG_WARN,
  1268. "SOCKS_UNKNOWN_PROTOCOL DATA=\"%s\"",
  1269. escaped(tmp));
  1270. tor_free(tmp);
  1271. }
  1272. return -1;
  1273. }
  1274. }
  1275. /** Return 1 iff buf looks more like it has an (obsolete) v0 controller
  1276. * command on it than any valid v1 controller command. */
  1277. int
  1278. peek_buf_has_control0_command(buf_t *buf)
  1279. {
  1280. if (buf->datalen >= 4) {
  1281. char header[4];
  1282. uint16_t cmd;
  1283. peek_from_buf(header, sizeof(header), buf);
  1284. cmd = ntohs(get_uint16(header+2));
  1285. if (cmd <= 0x14)
  1286. return 1; /* This is definitely not a v1 control command. */
  1287. }
  1288. return 0;
  1289. }
  1290. /** Helper: return a pointer to the first instance of <b>c</b> in the
  1291. * <b>len</b>characters after <b>start</b> on <b>buf</b>. Return NULL if the
  1292. * character isn't found. */
  1293. static char *
  1294. find_char_on_buf(buf_t *buf, char *start, size_t len, char c)
  1295. {
  1296. size_t len_rest;
  1297. char *cp;
  1298. _split_range(buf, start, &len, &len_rest);
  1299. cp = memchr(start, c, len);
  1300. if (cp || !len_rest)
  1301. return cp;
  1302. return memchr(buf->mem, c, len_rest);
  1303. }
  1304. /** Helper: return a pointer to the first CRLF after cp on <b>buf</b>. Return
  1305. * NULL if no CRLF is found. */
  1306. static char *
  1307. find_crlf_on_buf(buf_t *buf, char *cp)
  1308. {
  1309. char *next;
  1310. while (1) {
  1311. size_t remaining = buf->datalen - _buf_offset(buf,cp);
  1312. cp = find_char_on_buf(buf, cp, remaining, '\r');
  1313. if (!cp)
  1314. return NULL;
  1315. next = _wrap_ptr(buf, cp+1);
  1316. if (next == _buf_end(buf))
  1317. return NULL;
  1318. if (*next == '\n')
  1319. return cp;
  1320. cp = next;
  1321. }
  1322. }
  1323. /** Try to read a single CRLF-terminated line from <b>buf</b>, and write it,
  1324. * NUL-terminated, into the *<b>data_len</b> byte buffer at <b>data_out</b>.
  1325. * Set *<b>data_len</b> to the number of bytes in the line, not counting the
  1326. * terminating NUL. Return 1 if we read a whole line, return 0 if we don't
  1327. * have a whole line yet, and return -1 if we we need to grow the buffer.
  1328. */
  1329. int
  1330. fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
  1331. {
  1332. char *eol;
  1333. size_t sz;
  1334. /* Look for a CRLF. */
  1335. if (!(eol = find_crlf_on_buf(buf, buf->cur))) {
  1336. return 0;
  1337. }
  1338. sz = _buf_offset(buf, eol);
  1339. if (sz+3 > *data_len) {
  1340. *data_len = sz+3;
  1341. return -1;
  1342. }
  1343. fetch_from_buf(data_out, sz+2, buf);
  1344. data_out[sz+2] = '\0';
  1345. *data_len = sz+2;
  1346. return 1;
  1347. }
  1348. /** Try to read a single LF-terminated line from <b>buf</b>, and write it,
  1349. * NUL-terminated, into the *<b>data_len</b> byte buffer at <b>data_out</b>.
  1350. * Set *<b>data_len</b> to the number of bytes in the line, not counting the
  1351. * terminating NUL. Return 1 if we read a whole line, return 0 if we don't
  1352. * have a whole line yet, and return -1 if the line length exceeds
  1353. *<b>data_len</b>.
  1354. */
  1355. int
  1356. fetch_from_buf_line_lf(buf_t *buf, char *data_out, size_t *data_len)
  1357. {
  1358. char *cp;
  1359. size_t sz;
  1360. size_t remaining = buf->datalen - _buf_offset(buf,buf->cur);
  1361. cp = find_char_on_buf(buf, buf->cur, remaining, '\n');
  1362. if (!cp)
  1363. return 0;
  1364. sz = _buf_offset(buf, cp);
  1365. if (sz+2 > *data_len) {
  1366. *data_len = sz+2;
  1367. return -1;
  1368. }
  1369. fetch_from_buf(data_out, sz+1, buf);
  1370. data_out[sz+1] = '\0';
  1371. *data_len = sz+1;
  1372. return 1;
  1373. }
  1374. /** Compress on uncompress the <b>data_len</b> bytes in <b>data</b> using the
  1375. * zlib state <b>state</b>, appending the result to <b>buf</b>. If
  1376. * <b>done</b> is true, flush the data in the state and finish the
  1377. * compression/uncompression. Return -1 on failure, 0 on success. */
  1378. int
  1379. write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
  1380. const char *data, size_t data_len,
  1381. int done)
  1382. {
  1383. char *next;
  1384. size_t old_avail, avail;
  1385. int over = 0;
  1386. do {
  1387. buf_ensure_capacity(buf, buf->datalen + 1024);
  1388. next = _buf_end(buf);
  1389. if (next < buf->cur)
  1390. old_avail = avail = buf->cur - next;
  1391. else
  1392. old_avail = avail = (buf->mem + buf->len) - next;
  1393. switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
  1394. case TOR_ZLIB_DONE:
  1395. over = 1;
  1396. break;
  1397. case TOR_ZLIB_ERR:
  1398. return -1;
  1399. case TOR_ZLIB_OK:
  1400. if (data_len == 0)
  1401. over = 1;
  1402. break;
  1403. case TOR_ZLIB_BUF_FULL:
  1404. if (avail && buf->len >= 1024 + buf->datalen) {
  1405. /* Zlib says we need more room (ZLIB_BUF_FULL), and we're not about
  1406. * to wrap around (avail != 0), and resizing won't actually make us
  1407. * un-full: we're at the end of the buffer, and zlib refuses to
  1408. * append more here, but there's a pile of free space at the start
  1409. * of the buffer (about 1K). So chop a few characters off the
  1410. * end of the buffer. This feels silly; anybody got a better hack?
  1411. *
  1412. * (We don't just want to expand the buffer nevertheless. Consider a
  1413. * 1/3 full buffer with a single byte free at the end. zlib will
  1414. * often refuse to append to that, and so we want to use the
  1415. * beginning, not double the buffer to be just 1/6 full.)
  1416. */
  1417. tor_assert(next >= buf->cur);
  1418. buf->len -= avail;
  1419. }
  1420. break;
  1421. }
  1422. buf->datalen += old_avail - avail;
  1423. if (buf->datalen > buf->highwater)
  1424. buf->highwater = buf->datalen;
  1425. } while (!over);
  1426. return 0;
  1427. }
  1428. /** Log an error and exit if <b>buf</b> is corrupted.
  1429. */
  1430. void
  1431. assert_buf_ok(buf_t *buf)
  1432. {
  1433. tor_assert(buf);
  1434. tor_assert(buf->magic == BUFFER_MAGIC);
  1435. tor_assert(buf->highwater <= buf->len);
  1436. tor_assert(buf->datalen <= buf->highwater);
  1437. if (buf->mem) {
  1438. tor_assert(buf->cur >= buf->mem);
  1439. tor_assert(buf->cur < buf->mem+buf->len);
  1440. tor_assert(buf->memsize == ALLOC_LEN(buf->len));
  1441. } else {
  1442. tor_assert(!buf->cur);
  1443. tor_assert(!buf->len);
  1444. tor_assert(!buf->memsize);
  1445. }
  1446. #ifdef SENTINELS
  1447. if (buf->mem) {
  1448. uint32_t u32 = get_uint32(buf->mem - 4);
  1449. tor_assert(u32 == START_MAGIC);
  1450. u32 = get_uint32(buf->mem + buf->memsize - 8);
  1451. tor_assert(u32 == END_MAGIC);
  1452. }
  1453. #endif
  1454. }