buffers.c 49 KB

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