buffers.c 50 KB

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