buffers.c 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901
  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-2009, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file buffers.c
  8. * \brief Implements a generic interface buffer. Buffers are
  9. * fairly opaque string holders that can read to or flush from:
  10. * memory, file descriptors, or TLS connections.
  11. **/
  12. #define BUFFERS_PRIVATE
  13. #include "or.h"
  14. #include "../common/util.h"
  15. #include "../common/log.h"
  16. #ifdef HAVE_UNISTD_H
  17. #include <unistd.h>
  18. #endif
  19. #ifdef HAVE_SYS_UIO_H
  20. #include <sys/uio.h>
  21. #endif
  22. //#define PARANOIA
  23. #ifdef PARANOIA
  24. /** Helper: If PARANOIA is defined, assert that the buffer in local variable
  25. * <b>buf</b> is well-formed. */
  26. #define check() STMT_BEGIN assert_buf_ok(buf); STMT_END
  27. #else
  28. #define check() STMT_NIL
  29. #endif
  30. /* Implementation notes:
  31. *
  32. * After flirting with memmove, and dallying with ring-buffers, we're finally
  33. * getting up to speed with the 1970s and implementing buffers as a linked
  34. * list of small chunks. Each buffer has such a list; data is removed from
  35. * the head of the list, and added at the tail. The list is singly linked,
  36. * and the buffer keeps a pointer to the head and the tail.
  37. *
  38. * Every chunk, except the tail, contains at least one byte of data. Data in
  39. * each chunk is contiguous.
  40. *
  41. * When you need to treat the first N characters on a buffer as a contiguous
  42. * string, use the buf_pullup function to make them so. Don't do this more
  43. * than necessary.
  44. *
  45. * The major free Unix kernels have handled buffers like this since, like,
  46. * forever.
  47. */
  48. /* Chunk manipulation functions */
  49. /** A single chunk on a buffer or in a freelist. */
  50. typedef struct chunk_t {
  51. struct chunk_t *next; /**< The next chunk on the buffer or freelist. */
  52. size_t datalen; /**< The number of bytes stored in this chunk */
  53. size_t memlen; /**< The number of usable bytes of storage in <b>mem</b>. */
  54. char *data; /**< A pointer to the first byte of data stored in <b>mem</b>. */
  55. char mem[1]; /**< The actual memory used for storage in this chunk. May be
  56. * more than one byte long. */
  57. } chunk_t;
  58. #define CHUNK_HEADER_LEN STRUCT_OFFSET(chunk_t, mem[0])
  59. /** Return the number of bytes needed to allocate a chunk to hold
  60. * <b>memlen</b> bytes. */
  61. #define CHUNK_ALLOC_SIZE(memlen) (CHUNK_HEADER_LEN + (memlen))
  62. /** Return the number of usable bytes in a chunk allocated with
  63. * malloc(<b>memlen</b>). */
  64. #define CHUNK_SIZE_WITH_ALLOC(memlen) ((memlen) - CHUNK_HEADER_LEN)
  65. /** Return the next character in <b>chunk</b> onto which data can be appended.
  66. * If the chunk is full, this might be off the end of chunk->mem. */
  67. static INLINE char *
  68. CHUNK_WRITE_PTR(chunk_t *chunk)
  69. {
  70. return chunk->data + chunk->datalen;
  71. }
  72. /** Return the number of bytes that can be written onto <b>chunk</b> without
  73. * running out of space. */
  74. static INLINE size_t
  75. CHUNK_REMAINING_CAPACITY(const chunk_t *chunk)
  76. {
  77. return (chunk->mem + chunk->memlen) - (chunk->data + chunk->datalen);
  78. }
  79. /** Move all bytes stored in <b>chunk</b> to the front of <b>chunk</b>->mem,
  80. * to free up space at the end. */
  81. static INLINE void
  82. chunk_repack(chunk_t *chunk)
  83. {
  84. if (chunk->datalen && chunk->data != &chunk->mem[0]) {
  85. memmove(chunk->mem, chunk->data, chunk->datalen);
  86. }
  87. chunk->data = &chunk->mem[0];
  88. }
  89. #ifdef ENABLE_BUF_FREELISTS
  90. /** A freelist of chunks. */
  91. typedef struct chunk_freelist_t {
  92. size_t alloc_size; /**< What size chunks does this freelist hold? */
  93. int max_length; /**< Never allow more than this number of chunks in the
  94. * freelist. */
  95. int slack; /**< When trimming the freelist, leave this number of extra
  96. * chunks beyond lowest_length.*/
  97. int cur_length; /**< How many chunks on the freelist now? */
  98. int lowest_length; /**< What's the smallest value of cur_length since the
  99. * last time we cleaned this freelist? */
  100. uint64_t n_alloc;
  101. uint64_t n_free;
  102. uint64_t n_hit;
  103. chunk_t *head; /**< First chunk on the freelist. */
  104. } chunk_freelist_t;
  105. /** Macro to help define freelists. */
  106. #define FL(a,m,s) { a, m, s, 0, 0, 0, 0, 0, NULL }
  107. /** Static array of freelists, sorted by alloc_len, terminated by an entry
  108. * with alloc_size of 0. */
  109. static chunk_freelist_t freelists[] = {
  110. FL(4096, 256, 8), FL(8192, 128, 4), FL(16384, 64, 4), FL(32768, 32, 2),
  111. FL(0, 0, 0)
  112. };
  113. #undef FL
  114. /** How many times have we looked for a chunk of a size that no freelist
  115. * could help with? */
  116. static uint64_t n_freelist_miss = 0;
  117. static void assert_freelist_ok(chunk_freelist_t *fl);
  118. /** Return the freelist to hold chunks of size <b>alloc</b>, or NULL if
  119. * no freelist exists for that size. */
  120. static INLINE chunk_freelist_t *
  121. get_freelist(size_t alloc)
  122. {
  123. int i;
  124. for (i=0; freelists[i].alloc_size <= alloc; ++i) {
  125. if (freelists[i].alloc_size == alloc) {
  126. return &freelists[i];
  127. }
  128. }
  129. return NULL;
  130. }
  131. /** Deallocate a chunk or put it on a freelist */
  132. static void
  133. chunk_free(chunk_t *chunk)
  134. {
  135. size_t alloc = CHUNK_ALLOC_SIZE(chunk->memlen);
  136. chunk_freelist_t *freelist = get_freelist(alloc);
  137. if (freelist && freelist->cur_length < freelist->max_length) {
  138. chunk->next = freelist->head;
  139. freelist->head = chunk;
  140. ++freelist->cur_length;
  141. } else {
  142. if (freelist)
  143. ++freelist->n_free;
  144. tor_free(chunk);
  145. }
  146. }
  147. /** Allocate a new chunk with a given allocation size, or get one from the
  148. * freelist. Note that a chunk with allocation size A can actually hold only
  149. * CHUNK_SIZE_WITH_ALLOC(A) bytes in its mem field. */
  150. static INLINE chunk_t *
  151. chunk_new_with_alloc_size(size_t alloc)
  152. {
  153. chunk_t *ch;
  154. chunk_freelist_t *freelist;
  155. tor_assert(alloc >= sizeof(chunk_t));
  156. freelist = get_freelist(alloc);
  157. if (freelist && freelist->head) {
  158. ch = freelist->head;
  159. freelist->head = ch->next;
  160. if (--freelist->cur_length < freelist->lowest_length)
  161. freelist->lowest_length = freelist->cur_length;
  162. ++freelist->n_hit;
  163. } else {
  164. /* XXXX take advantage of tor_malloc_roundup, once we know how that
  165. * affects freelists. */
  166. if (freelist)
  167. ++freelist->n_alloc;
  168. else
  169. ++n_freelist_miss;
  170. ch = tor_malloc(alloc);
  171. }
  172. ch->next = NULL;
  173. ch->datalen = 0;
  174. ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
  175. ch->data = &ch->mem[0];
  176. return ch;
  177. }
  178. #else
  179. static void
  180. chunk_free(chunk_t *chunk)
  181. {
  182. tor_free(chunk);
  183. }
  184. static INLINE chunk_t *
  185. chunk_new_with_alloc_size(size_t alloc)
  186. {
  187. chunk_t *ch;
  188. ch = tor_malloc_roundup(&alloc);
  189. ch->next = NULL;
  190. ch->datalen = 0;
  191. ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
  192. ch->data = &ch->mem[0];
  193. return ch;
  194. }
  195. #endif
  196. /** Expand <b>chunk</b> until it can hold <b>sz</b> bytes, and return a
  197. * new pointer to <b>chunk</b>. Old pointers are no longer valid. */
  198. static INLINE chunk_t *
  199. chunk_grow(chunk_t *chunk, size_t sz)
  200. {
  201. off_t offset;
  202. tor_assert(sz > chunk->memlen);
  203. offset = chunk->data - chunk->mem;
  204. chunk = tor_realloc(chunk, CHUNK_ALLOC_SIZE(sz));
  205. chunk->memlen = sz;
  206. chunk->data = chunk->mem + offset;
  207. return chunk;
  208. }
  209. /** If a read onto the end of a chunk would be smaller than this number, then
  210. * just start a new chunk. */
  211. #define MIN_READ_LEN 8
  212. /** Every chunk should take up at least this many bytes. */
  213. #define MIN_CHUNK_ALLOC 256
  214. /** No chunk should take up more than this many bytes. */
  215. #define MAX_CHUNK_ALLOC 65536
  216. /** Return the allocation size we'd like to use to hold <b>target</b>
  217. * bytes. */
  218. static INLINE size_t
  219. preferred_chunk_size(size_t target)
  220. {
  221. size_t sz = MIN_CHUNK_ALLOC;
  222. while (CHUNK_SIZE_WITH_ALLOC(sz) < target) {
  223. sz <<= 1;
  224. }
  225. return sz;
  226. }
  227. /** Remove from the freelists most chunks that have not been used since the
  228. * last call to buf_shrink_freelists(). */
  229. void
  230. buf_shrink_freelists(int free_all)
  231. {
  232. #ifdef ENABLE_BUF_FREELISTS
  233. int i;
  234. for (i = 0; freelists[i].alloc_size; ++i) {
  235. int slack = freelists[i].slack;
  236. assert_freelist_ok(&freelists[i]);
  237. if (free_all || freelists[i].lowest_length > slack) {
  238. int n_to_free = free_all ? freelists[i].cur_length :
  239. (freelists[i].lowest_length - slack);
  240. int n_to_skip = freelists[i].cur_length - n_to_free;
  241. int orig_n_to_free = n_to_free, n_freed=0;
  242. int new_length = n_to_skip;
  243. chunk_t **chp = &freelists[i].head;
  244. chunk_t *chunk;
  245. log_info(LD_MM, "Cleaning freelist for %d-byte chunks: keeping %d, "
  246. "dropping %d.",
  247. (int)freelists[i].alloc_size, n_to_skip, n_to_free);
  248. while (n_to_skip) {
  249. tor_assert((*chp)->next);
  250. chp = &(*chp)->next;
  251. --n_to_skip;
  252. }
  253. chunk = *chp;
  254. *chp = NULL;
  255. while (chunk) {
  256. chunk_t *next = chunk->next;
  257. tor_free(chunk);
  258. chunk = next;
  259. --n_to_free;
  260. ++n_freed;
  261. ++freelists[i].n_free;
  262. }
  263. if (n_to_free) {
  264. log_warn(LD_BUG, "Freelist length for %d-byte chunks may have been "
  265. "messed up somehow.", (int)freelists[i].alloc_size);
  266. log_warn(LD_BUG, "There were %d chunks at the start. I decided to "
  267. "keep %d. I wanted to free %d. I freed %d. I somehow think "
  268. "I have %d left to free.",
  269. freelists[i].cur_length, n_to_skip, orig_n_to_free,
  270. n_freed, n_to_free);
  271. }
  272. // tor_assert(!n_to_free);
  273. freelists[i].cur_length = new_length;
  274. }
  275. freelists[i].lowest_length = freelists[i].cur_length;
  276. assert_freelist_ok(&freelists[i]);
  277. }
  278. #else
  279. (void) free_all;
  280. #endif
  281. }
  282. /** Describe the current status of the freelists at log level <b>severity</b>.
  283. */
  284. void
  285. buf_dump_freelist_sizes(int severity)
  286. {
  287. #ifdef ENABLE_BUF_FREELISTS
  288. int i;
  289. log(severity, LD_MM, "====== Buffer freelists:");
  290. for (i = 0; freelists[i].alloc_size; ++i) {
  291. uint64_t total = ((uint64_t)freelists[i].cur_length) *
  292. freelists[i].alloc_size;
  293. log(severity, LD_MM,
  294. U64_FORMAT" bytes in %d %d-byte chunks ["U64_FORMAT
  295. " misses; "U64_FORMAT" frees; "U64_FORMAT" hits]",
  296. U64_PRINTF_ARG(total),
  297. freelists[i].cur_length, (int)freelists[i].alloc_size,
  298. U64_PRINTF_ARG(freelists[i].n_alloc),
  299. U64_PRINTF_ARG(freelists[i].n_free),
  300. U64_PRINTF_ARG(freelists[i].n_hit));
  301. }
  302. log(severity, LD_MM, U64_FORMAT" allocations in non-freelist sizes",
  303. U64_PRINTF_ARG(n_freelist_miss));
  304. #else
  305. (void)severity;
  306. #endif
  307. }
  308. /** Magic value for buf_t.magic, to catch pointer errors. */
  309. #define BUFFER_MAGIC 0xB0FFF312u
  310. /** A resizeable buffer, optimized for reading and writing. */
  311. struct buf_t {
  312. uint32_t magic; /**< Magic cookie for debugging: Must be set to
  313. * BUFFER_MAGIC. */
  314. size_t datalen; /**< How many bytes is this buffer holding right now? */
  315. size_t default_chunk_size; /**< Don't allocate any chunks smaller than
  316. * this for this buffer. */
  317. chunk_t *head; /**< First chunk in the list, or NULL for none. */
  318. chunk_t *tail; /**< Last chunk in the list, or NULL for none. */
  319. };
  320. /** Collapse data from the first N chunks from <b>buf</b> into buf->head,
  321. * growing it as necessary, until buf->head has the first <b>bytes</b> bytes
  322. * of data from the buffer, or until buf->head has all the data in <b>buf</b>.
  323. *
  324. * If <b>nulterminate</b> is true, ensure that there is a 0 byte in
  325. * buf->head->mem right after all the data. */
  326. static void
  327. buf_pullup(buf_t *buf, size_t bytes, int nulterminate)
  328. {
  329. chunk_t *dest, *src;
  330. size_t capacity;
  331. if (!buf->head)
  332. return;
  333. check();
  334. if (buf->datalen < bytes)
  335. bytes = buf->datalen;
  336. if (nulterminate) {
  337. capacity = bytes + 1;
  338. if (buf->head->datalen >= bytes && CHUNK_REMAINING_CAPACITY(buf->head)) {
  339. *CHUNK_WRITE_PTR(buf->head) = '\0';
  340. return;
  341. }
  342. } else {
  343. capacity = bytes;
  344. if (buf->head->datalen >= bytes)
  345. return;
  346. }
  347. if (buf->head->memlen >= capacity) {
  348. /* We don't need to grow the first chunk, but we might need to repack it.*/
  349. if (CHUNK_REMAINING_CAPACITY(buf->head) < capacity-buf->datalen)
  350. chunk_repack(buf->head);
  351. tor_assert(CHUNK_REMAINING_CAPACITY(buf->head) >= capacity-buf->datalen);
  352. } else {
  353. chunk_t *newhead;
  354. size_t newsize;
  355. /* We need to grow the chunk. */
  356. chunk_repack(buf->head);
  357. newsize = CHUNK_SIZE_WITH_ALLOC(preferred_chunk_size(capacity));
  358. newhead = chunk_grow(buf->head, newsize);
  359. tor_assert(newhead->memlen >= capacity);
  360. if (newhead != buf->head) {
  361. if (buf->tail == buf->head)
  362. buf->tail = newhead;
  363. buf->head = newhead;
  364. }
  365. }
  366. dest = buf->head;
  367. while (dest->datalen < bytes) {
  368. size_t n = bytes - dest->datalen;
  369. src = dest->next;
  370. tor_assert(src);
  371. if (n > src->datalen) {
  372. memcpy(CHUNK_WRITE_PTR(dest), src->data, src->datalen);
  373. dest->datalen += src->datalen;
  374. dest->next = src->next;
  375. if (buf->tail == src)
  376. buf->tail = dest;
  377. chunk_free(src);
  378. } else {
  379. memcpy(CHUNK_WRITE_PTR(dest), src->data, n);
  380. dest->datalen += n;
  381. src->data += n;
  382. src->datalen -= n;
  383. tor_assert(dest->datalen == bytes);
  384. }
  385. }
  386. if (nulterminate) {
  387. tor_assert(CHUNK_REMAINING_CAPACITY(buf->head));
  388. *CHUNK_WRITE_PTR(buf->head) = '\0';
  389. }
  390. check();
  391. }
  392. /** Resize buf so it won't hold extra memory that we haven't been
  393. * using lately.
  394. */
  395. void
  396. buf_shrink(buf_t *buf)
  397. {
  398. (void)buf;
  399. }
  400. /** Remove the first <b>n</b> bytes from buf. */
  401. static INLINE void
  402. buf_remove_from_front(buf_t *buf, size_t n)
  403. {
  404. tor_assert(buf->datalen >= n);
  405. while (n) {
  406. tor_assert(buf->head);
  407. if (buf->head->datalen > n) {
  408. buf->head->datalen -= n;
  409. buf->head->data += n;
  410. buf->datalen -= n;
  411. return;
  412. } else {
  413. chunk_t *victim = buf->head;
  414. n -= victim->datalen;
  415. buf->datalen -= victim->datalen;
  416. buf->head = victim->next;
  417. if (buf->tail == victim)
  418. buf->tail = NULL;
  419. chunk_free(victim);
  420. }
  421. }
  422. check();
  423. }
  424. /** Create and return a new buf with default chunk capacity <b>size</b>.
  425. */
  426. buf_t *
  427. buf_new_with_capacity(size_t size)
  428. {
  429. buf_t *b = buf_new();
  430. b->default_chunk_size = preferred_chunk_size(size);
  431. return b;
  432. }
  433. /** Allocate and return a new buffer with default capacity. */
  434. buf_t *
  435. buf_new(void)
  436. {
  437. buf_t *buf = tor_malloc_zero(sizeof(buf_t));
  438. buf->magic = BUFFER_MAGIC;
  439. buf->default_chunk_size = 4096;
  440. return buf;
  441. }
  442. /** Remove all data from <b>buf</b>. */
  443. void
  444. buf_clear(buf_t *buf)
  445. {
  446. chunk_t *chunk, *next;
  447. buf->datalen = 0;
  448. for (chunk = buf->head; chunk; chunk = next) {
  449. next = chunk->next;
  450. chunk_free(chunk);
  451. }
  452. buf->head = buf->tail = NULL;
  453. }
  454. /** Return the number of bytes stored in <b>buf</b> */
  455. size_t
  456. buf_datalen(const buf_t *buf)
  457. {
  458. return buf->datalen;
  459. }
  460. /** Return the total length of all chunks used in <b>buf</b>. */
  461. size_t
  462. buf_allocation(const buf_t *buf)
  463. {
  464. size_t total = 0;
  465. const chunk_t *chunk;
  466. for (chunk = buf->head; chunk; chunk = chunk->next) {
  467. total += chunk->memlen;
  468. }
  469. return total;
  470. }
  471. /** Return the number of bytes that can be added to <b>buf</b> without
  472. * performing any additional allocation. */
  473. size_t
  474. buf_slack(const buf_t *buf)
  475. {
  476. if (!buf->tail)
  477. return 0;
  478. else
  479. return CHUNK_REMAINING_CAPACITY(buf->tail);
  480. }
  481. /** Release storage held by <b>buf</b>. */
  482. void
  483. buf_free(buf_t *buf)
  484. {
  485. buf_clear(buf);
  486. buf->magic = 0xdeadbeef;
  487. tor_free(buf);
  488. }
  489. /** Append a new chunk with enough capacity to hold <b>capacity</b> bytes to
  490. * the tail of <b>buf</b>. If <b>capped</b>, don't allocate a chunk bigger
  491. * than MAX_CHUNK_ALLOC. */
  492. static chunk_t *
  493. buf_add_chunk_with_capacity(buf_t *buf, size_t capacity, int capped)
  494. {
  495. chunk_t *chunk;
  496. if (CHUNK_ALLOC_SIZE(capacity) < buf->default_chunk_size) {
  497. chunk = chunk_new_with_alloc_size(buf->default_chunk_size);
  498. } else if (capped && CHUNK_ALLOC_SIZE(capacity) > MAX_CHUNK_ALLOC) {
  499. chunk = chunk_new_with_alloc_size(MAX_CHUNK_ALLOC);
  500. } else {
  501. chunk = chunk_new_with_alloc_size(preferred_chunk_size(capacity));
  502. }
  503. if (buf->tail) {
  504. tor_assert(buf->head);
  505. buf->tail->next = chunk;
  506. buf->tail = chunk;
  507. } else {
  508. tor_assert(!buf->head);
  509. buf->head = buf->tail = chunk;
  510. }
  511. check();
  512. return chunk;
  513. }
  514. /** If we're using readv and writev, how many chunks are we willing to
  515. * read/write at a time? */
  516. #define N_IOV 3
  517. /** Read up to <b>at_most</b> bytes from the socket <b>fd</b> into
  518. * <b>chunk</b> (which must be on <b>buf</b>). If we get an EOF, set
  519. * *<b>reached_eof</b> to 1. Return -1 on error, 0 on eof or blocking,
  520. * and the number of bytes read otherwise. */
  521. static INLINE int
  522. read_to_chunk(buf_t *buf, chunk_t *chunk, int fd, size_t at_most,
  523. int *reached_eof, int *socket_error)
  524. {
  525. ssize_t read_result;
  526. #if 0 && defined(HAVE_READV) && !defined(WIN32)
  527. struct iovec iov[N_IOV];
  528. int i;
  529. size_t remaining = at_most;
  530. for (i=0; chunk && i < N_IOV && remaining; ++i) {
  531. iov[i].iov_base = CHUNK_WRITE_PTR(chunk);
  532. if (remaining > CHUNK_REMAINING_CAPACITY(chunk))
  533. iov[i].iov_len = CHUNK_REMAINING_CAPACITY(chunk);
  534. else
  535. iov[i].iov_len = remaining;
  536. remaining -= iov[i].iov_len;
  537. chunk = chunk->next;
  538. }
  539. read_result = readv(fd, iov, i);
  540. #else
  541. if (at_most > CHUNK_REMAINING_CAPACITY(chunk))
  542. at_most = CHUNK_REMAINING_CAPACITY(chunk);
  543. read_result = tor_socket_recv(fd, CHUNK_WRITE_PTR(chunk), at_most, 0);
  544. #endif
  545. if (read_result < 0) {
  546. int e = tor_socket_errno(fd);
  547. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  548. #ifdef MS_WINDOWS
  549. if (e == WSAENOBUFS)
  550. log_warn(LD_NET,"recv() failed: WSAENOBUFS. Not enough ram?");
  551. #endif
  552. *socket_error = e;
  553. return -1;
  554. }
  555. return 0; /* would block. */
  556. } else if (read_result == 0) {
  557. log_debug(LD_NET,"Encountered eof on fd %d", (int)fd);
  558. *reached_eof = 1;
  559. return 0;
  560. } else { /* actually got bytes. */
  561. buf->datalen += read_result;
  562. #if 0 && defined(HAVE_READV) && !defined(WIN32)
  563. while ((size_t)read_result > CHUNK_REMAINING_CAPACITY(chunk)) {
  564. chunk->datalen += CHUNK_REMAINING_CAPACITY(chunk);
  565. read_result -= CHUNK_REMAINING_CAPACITY(chunk);
  566. chunk = chunk->next;
  567. tor_assert(chunk);
  568. }
  569. #endif
  570. chunk->datalen += read_result;
  571. log_debug(LD_NET,"Read %ld bytes. %d on inbuf.", (long)read_result,
  572. (int)buf->datalen);
  573. tor_assert(read_result < INT_MAX);
  574. return (int)read_result;
  575. }
  576. }
  577. /** As read_to_chunk(), but return (negative) error code on error, blocking,
  578. * or TLS, and the number of bytes read otherwise. */
  579. static INLINE int
  580. read_to_chunk_tls(buf_t *buf, chunk_t *chunk, tor_tls_t *tls,
  581. size_t at_most)
  582. {
  583. int read_result;
  584. tor_assert(CHUNK_REMAINING_CAPACITY(chunk) >= at_most);
  585. read_result = tor_tls_read(tls, CHUNK_WRITE_PTR(chunk), at_most);
  586. if (read_result < 0)
  587. return read_result;
  588. buf->datalen += read_result;
  589. chunk->datalen += read_result;
  590. return read_result;
  591. }
  592. /** Read from socket <b>s</b>, writing onto end of <b>buf</b>. Read at most
  593. * <b>at_most</b> bytes, growing the buffer as necessary. If recv() returns 0
  594. * (because of EOF), set *<b>reached_eof</b> to 1 and return 0. Return -1 on
  595. * error; else return the number of bytes read.
  596. */
  597. /* XXXX021 indicate "read blocked" somehow? */
  598. int
  599. read_to_buf(int s, size_t at_most, buf_t *buf, int *reached_eof,
  600. int *socket_error)
  601. {
  602. /* XXXX021 It's stupid to overload the return values for these functions:
  603. * "error status" and "number of bytes read" are not mutually exclusive.
  604. */
  605. int r = 0;
  606. size_t total_read = 0;
  607. check();
  608. tor_assert(reached_eof);
  609. tor_assert(s >= 0);
  610. while (at_most > total_read) {
  611. size_t readlen = at_most - total_read;
  612. chunk_t *chunk;
  613. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  614. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  615. if (readlen > chunk->memlen)
  616. readlen = chunk->memlen;
  617. } else {
  618. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  619. chunk = buf->tail;
  620. if (cap < readlen)
  621. readlen = cap;
  622. }
  623. r = read_to_chunk(buf, chunk, s, readlen, reached_eof, socket_error);
  624. check();
  625. if (r < 0)
  626. return r; /* Error */
  627. tor_assert(total_read+r < INT_MAX);
  628. total_read += r;
  629. if ((size_t)r < readlen) { /* eof, block, or no more to read. */
  630. break;
  631. }
  632. }
  633. return (int)total_read;
  634. }
  635. /** As read_to_buf, but reads from a TLS connection, and returns a TLS
  636. * status value rather than the number of bytes read.
  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 = 0;
  659. size_t total_read = 0;
  660. check();
  661. while (at_most > total_read) {
  662. size_t readlen = at_most - total_read;
  663. chunk_t *chunk;
  664. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  665. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  666. if (readlen > chunk->memlen)
  667. readlen = chunk->memlen;
  668. } else {
  669. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  670. chunk = buf->tail;
  671. if (cap < readlen)
  672. readlen = cap;
  673. }
  674. r = read_to_chunk_tls(buf, chunk, tls, readlen);
  675. check();
  676. if (r < 0)
  677. return r; /* Error */
  678. tor_assert(total_read+r < INT_MAX);
  679. total_read += r;
  680. if ((size_t)r < readlen) /* eof, block, or no more to read. */
  681. break;
  682. }
  683. return (int)total_read;
  684. }
  685. /** Helper for flush_buf(): try to write <b>sz</b> bytes from chunk
  686. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. On success, deduct
  687. * the bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  688. * written on success, 0 on blocking, -1 on failure.
  689. */
  690. static INLINE int
  691. flush_chunk(int s, buf_t *buf, chunk_t *chunk, size_t sz,
  692. size_t *buf_flushlen)
  693. {
  694. ssize_t write_result;
  695. #if 0 && defined(HAVE_WRITEV) && !defined(WIN32)
  696. struct iovec iov[N_IOV];
  697. int i;
  698. size_t remaining = sz;
  699. for (i=0; chunk && i < N_IOV && remaining; ++i) {
  700. iov[i].iov_base = chunk->data;
  701. if (remaining > chunk->datalen)
  702. iov[i].iov_len = chunk->datalen;
  703. else
  704. iov[i].iov_len = remaining;
  705. remaining -= iov[i].iov_len;
  706. chunk = chunk->next;
  707. }
  708. write_result = writev(s, iov, i);
  709. #else
  710. if (sz > chunk->datalen)
  711. sz = chunk->datalen;
  712. write_result = tor_socket_send(s, chunk->data, sz, 0);
  713. #endif
  714. if (write_result < 0) {
  715. int e = tor_socket_errno(s);
  716. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  717. #ifdef MS_WINDOWS
  718. if (e == WSAENOBUFS)
  719. log_warn(LD_NET,"write() failed: WSAENOBUFS. Not enough ram?");
  720. #endif
  721. return -1;
  722. }
  723. log_debug(LD_NET,"write() would block, returning.");
  724. return 0;
  725. } else {
  726. *buf_flushlen -= write_result;
  727. buf_remove_from_front(buf, write_result);
  728. tor_assert(write_result < INT_MAX);
  729. return (int)write_result;
  730. }
  731. }
  732. /** Helper for flush_buf_tls(): try to write <b>sz</b> bytes from chunk
  733. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. (Tries to write
  734. * more if there is a forced pending write size.) On success, deduct the
  735. * bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  736. * written on success, and a TOR_TLS error code on failure or blocking.
  737. */
  738. static INLINE int
  739. flush_chunk_tls(tor_tls_t *tls, buf_t *buf, chunk_t *chunk,
  740. size_t sz, size_t *buf_flushlen)
  741. {
  742. int r;
  743. size_t forced;
  744. char *data;
  745. forced = tor_tls_get_forced_write_size(tls);
  746. if (forced > sz)
  747. sz = forced;
  748. if (chunk) {
  749. data = chunk->data;
  750. tor_assert(sz <= chunk->datalen);
  751. } else {
  752. data = NULL;
  753. tor_assert(sz == 0);
  754. }
  755. r = tor_tls_write(tls, data, sz);
  756. if (r < 0)
  757. return r;
  758. if (*buf_flushlen > (size_t)r)
  759. *buf_flushlen -= r;
  760. else
  761. *buf_flushlen = 0;
  762. buf_remove_from_front(buf, r);
  763. log_debug(LD_NET,"flushed %d bytes, %d ready to flush, %d remain.",
  764. r,(int)*buf_flushlen,(int)buf->datalen);
  765. return r;
  766. }
  767. /** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
  768. * <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by
  769. * the number of bytes actually written, and remove the written bytes
  770. * from the buffer. Return the number of bytes written on success,
  771. * -1 on failure. Return 0 if write() would block.
  772. */
  773. int
  774. flush_buf(int s, buf_t *buf, size_t sz, size_t *buf_flushlen)
  775. {
  776. /* XXXX021 It's stupid to overload the return values for these functions:
  777. * "error status" and "number of bytes flushed" are not mutually exclusive.
  778. */
  779. int r;
  780. size_t flushed = 0;
  781. tor_assert(buf_flushlen);
  782. tor_assert(s >= 0);
  783. tor_assert(*buf_flushlen <= buf->datalen);
  784. tor_assert(sz <= *buf_flushlen);
  785. check();
  786. while (sz) {
  787. size_t flushlen0;
  788. tor_assert(buf->head);
  789. if (buf->head->datalen >= sz)
  790. flushlen0 = sz;
  791. else
  792. flushlen0 = buf->head->datalen;
  793. r = flush_chunk(s, buf, buf->head, flushlen0, buf_flushlen);
  794. check();
  795. if (r < 0)
  796. return r;
  797. flushed += r;
  798. sz -= r;
  799. if (r == 0 || (size_t)r < flushlen0) /* can't flush any more now. */
  800. break;
  801. }
  802. tor_assert(flushed < INT_MAX);
  803. return (int)flushed;
  804. }
  805. /** As flush_buf(), but writes data to a TLS connection. Can write more than
  806. * <b>flushlen</b> bytes.
  807. */
  808. int
  809. flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t flushlen,
  810. size_t *buf_flushlen)
  811. {
  812. int r;
  813. size_t flushed = 0;
  814. ssize_t sz;
  815. tor_assert(buf_flushlen);
  816. tor_assert(*buf_flushlen <= buf->datalen);
  817. tor_assert(flushlen <= *buf_flushlen);
  818. sz = (ssize_t) flushlen;
  819. /* we want to let tls write even if flushlen is zero, because it might
  820. * have a partial record pending */
  821. check_no_tls_errors();
  822. check();
  823. do {
  824. size_t flushlen0;
  825. if (buf->head) {
  826. if ((ssize_t)buf->head->datalen >= sz)
  827. flushlen0 = sz;
  828. else
  829. flushlen0 = buf->head->datalen;
  830. } else {
  831. flushlen0 = 0;
  832. }
  833. r = flush_chunk_tls(tls, buf, buf->head, flushlen0, buf_flushlen);
  834. check();
  835. if (r < 0)
  836. return r;
  837. flushed += r;
  838. sz -= r;
  839. if (r == 0) /* Can't flush any more now. */
  840. break;
  841. } while (sz > 0);
  842. tor_assert(flushed < INT_MAX);
  843. return (int)flushed;
  844. }
  845. /** Append <b>string_len</b> bytes from <b>string</b> to the end of
  846. * <b>buf</b>.
  847. *
  848. * Return the new length of the buffer on success, -1 on failure.
  849. */
  850. int
  851. write_to_buf(const char *string, size_t string_len, buf_t *buf)
  852. {
  853. if (!string_len)
  854. return (int)buf->datalen;
  855. check();
  856. while (string_len) {
  857. size_t copy;
  858. if (!buf->tail || !CHUNK_REMAINING_CAPACITY(buf->tail))
  859. buf_add_chunk_with_capacity(buf, string_len, 1);
  860. copy = CHUNK_REMAINING_CAPACITY(buf->tail);
  861. if (copy > string_len)
  862. copy = string_len;
  863. memcpy(CHUNK_WRITE_PTR(buf->tail), string, copy);
  864. string_len -= copy;
  865. string += copy;
  866. buf->datalen += copy;
  867. buf->tail->datalen += copy;
  868. }
  869. check();
  870. tor_assert(buf->datalen < INT_MAX);
  871. return (int)buf->datalen;
  872. }
  873. /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
  874. * onto <b>string</b>.
  875. */
  876. static INLINE void
  877. peek_from_buf(char *string, size_t string_len, const buf_t *buf)
  878. {
  879. chunk_t *chunk;
  880. tor_assert(string);
  881. /* make sure we don't ask for too much */
  882. tor_assert(string_len <= buf->datalen);
  883. /* assert_buf_ok(buf); */
  884. chunk = buf->head;
  885. while (string_len) {
  886. size_t copy = string_len;
  887. tor_assert(chunk);
  888. if (chunk->datalen < copy)
  889. copy = chunk->datalen;
  890. memcpy(string, chunk->data, copy);
  891. string_len -= copy;
  892. string += copy;
  893. chunk = chunk->next;
  894. }
  895. }
  896. /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
  897. * them into <b>string</b>. Return the new buffer size. <b>string_len</b>
  898. * must be \<= the number of bytes on the buffer.
  899. */
  900. int
  901. fetch_from_buf(char *string, size_t string_len, buf_t *buf)
  902. {
  903. /* There must be string_len bytes in buf; write them onto string,
  904. * then memmove buf back (that is, remove them from buf).
  905. *
  906. * Return the number of bytes still on the buffer. */
  907. check();
  908. peek_from_buf(string, string_len, buf);
  909. buf_remove_from_front(buf, string_len);
  910. check();
  911. tor_assert(buf->datalen < INT_MAX);
  912. return (int)buf->datalen;
  913. }
  914. /** Check <b>buf</b> for a variable-length cell according to the rules of link
  915. * protocol version <b>linkproto</b>. If one is found, pull it off the buffer
  916. * and assign a newly allocated var_cell_t to *<b>out</b>, and return 1.
  917. * Return 0 if whatever is on the start of buf_t is not a variable-length
  918. * cell. Return 1 and set *<b>out</b> to NULL if there seems to be the start
  919. * of a variable-length cell on <b>buf</b>, but the whole thing isn't there
  920. * yet. */
  921. int
  922. fetch_var_cell_from_buf(buf_t *buf, var_cell_t **out, int linkproto)
  923. {
  924. char hdr[VAR_CELL_HEADER_SIZE];
  925. var_cell_t *result;
  926. uint8_t command;
  927. uint16_t length;
  928. /* If linkproto is unknown (0) or v2 (2), variable-length cells work as
  929. * implemented here. If it's 1, there are no variable-length cells. Tor
  930. * does not support other versions right now, and so can't negotiate them.
  931. */
  932. if (linkproto == 1)
  933. return 0;
  934. check();
  935. *out = NULL;
  936. if (buf->datalen < VAR_CELL_HEADER_SIZE)
  937. return 0;
  938. peek_from_buf(hdr, sizeof(hdr), buf);
  939. command = get_uint8(hdr+2);
  940. if (!(CELL_COMMAND_IS_VAR_LENGTH(command)))
  941. return 0;
  942. length = ntohs(get_uint16(hdr+3));
  943. if (buf->datalen < (size_t)(VAR_CELL_HEADER_SIZE+length))
  944. return 1;
  945. result = var_cell_new(length);
  946. result->command = command;
  947. result->circ_id = ntohs(get_uint16(hdr));
  948. buf_remove_from_front(buf, VAR_CELL_HEADER_SIZE);
  949. peek_from_buf(result->payload, length, buf);
  950. buf_remove_from_front(buf, length);
  951. check();
  952. *out = result;
  953. return 1;
  954. }
  955. /** Move up to *<b>buf_flushlen</b> bytes from <b>buf_in</b> to
  956. * <b>buf_out</b>, and modify *<b>buf_flushlen</b> appropriately.
  957. * Return the number of bytes actually copied.
  958. */
  959. int
  960. move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen)
  961. {
  962. /* XXXX we can do way better here, but this doesn't turn up in any
  963. * profiles. */
  964. char b[4096];
  965. size_t cp, len;
  966. len = *buf_flushlen;
  967. if (len > buf_in->datalen)
  968. len = buf_in->datalen;
  969. cp = len; /* Remember the number of bytes we intend to copy. */
  970. tor_assert(cp < INT_MAX);
  971. while (len) {
  972. /* This isn't the most efficient implementation one could imagine, since
  973. * it does two copies instead of 1, but I kinda doubt that this will be
  974. * critical path. */
  975. size_t n = len > sizeof(b) ? sizeof(b) : len;
  976. fetch_from_buf(b, n, buf_in);
  977. write_to_buf(b, n, buf_out);
  978. len -= n;
  979. }
  980. *buf_flushlen -= cp;
  981. return (int)cp;
  982. }
  983. /** Internal structure: represents a position in a buffer. */
  984. typedef struct buf_pos_t {
  985. const chunk_t *chunk; /**< Which chunk are we pointing to? */
  986. int pos;/**< Which character inside the chunk's data are we pointing to? */
  987. size_t chunk_pos; /**< Total length of all previous chunks. */
  988. } buf_pos_t;
  989. /** Initialize <b>out</b> to point to the first character of <b>buf</b>.*/
  990. static void
  991. buf_pos_init(const buf_t *buf, buf_pos_t *out)
  992. {
  993. out->chunk = buf->head;
  994. out->pos = 0;
  995. out->chunk_pos = 0;
  996. }
  997. /** Advance <b>out</b> to the first appearance of <b>ch</b> at the current
  998. * position of <b>out</b>, or later. Return -1 if no instances are found;
  999. * otherwise returns the absolute position of the character. */
  1000. static off_t
  1001. buf_find_pos_of_char(char ch, buf_pos_t *out)
  1002. {
  1003. const chunk_t *chunk;
  1004. int pos;
  1005. tor_assert(out);
  1006. if (out->chunk) {
  1007. if (out->chunk->datalen) {
  1008. tor_assert(out->pos < (off_t)out->chunk->datalen);
  1009. } else {
  1010. tor_assert(out->pos == 0);
  1011. }
  1012. }
  1013. pos = out->pos;
  1014. for (chunk = out->chunk; chunk; chunk = chunk->next) {
  1015. char *cp = memchr(chunk->data+pos, ch, chunk->datalen - pos);
  1016. if (cp) {
  1017. out->chunk = chunk;
  1018. tor_assert(cp - chunk->data < INT_MAX);
  1019. out->pos = (int)(cp - chunk->data);
  1020. return out->chunk_pos + out->pos;
  1021. } else {
  1022. out->chunk_pos += chunk->datalen;
  1023. pos = 0;
  1024. }
  1025. }
  1026. return -1;
  1027. }
  1028. /** Advance <b>pos</b> by a single character, if there are any more characters
  1029. * in the buffer. Returns 0 on success, -1 on failure. */
  1030. static INLINE int
  1031. buf_pos_inc(buf_pos_t *pos)
  1032. {
  1033. ++pos->pos;
  1034. if (pos->pos == (off_t)pos->chunk->datalen) {
  1035. if (!pos->chunk->next)
  1036. return -1;
  1037. pos->chunk_pos += pos->chunk->datalen;
  1038. pos->chunk = pos->chunk->next;
  1039. pos->pos = 0;
  1040. }
  1041. return 0;
  1042. }
  1043. /** Return true iff the <b>n</b>-character string in <b>s</b> appears
  1044. * (verbatim) at <b>pos</b>. */
  1045. static int
  1046. buf_matches_at_pos(const buf_pos_t *pos, const char *s, size_t n)
  1047. {
  1048. buf_pos_t p;
  1049. if (!n)
  1050. return 1;
  1051. memcpy(&p, pos, sizeof(p));
  1052. while (1) {
  1053. char ch = p.chunk->data[p.pos];
  1054. if (ch != *s)
  1055. return 0;
  1056. ++s;
  1057. /* If we're out of characters that don't match, we match. Check this
  1058. * _before_ we test incrementing pos, in case we're at the end of the
  1059. * string. */
  1060. if (--n == 0)
  1061. return 1;
  1062. if (buf_pos_inc(&p)<0)
  1063. return 0;
  1064. }
  1065. }
  1066. /** Return the first position in <b>buf</b> at which the <b>n</b>-character
  1067. * string <b>s</b> occurs, or -1 if it does not occur. */
  1068. /*private*/ int
  1069. buf_find_string_offset(const buf_t *buf, const char *s, size_t n)
  1070. {
  1071. buf_pos_t pos;
  1072. buf_pos_init(buf, &pos);
  1073. while (buf_find_pos_of_char(*s, &pos) >= 0) {
  1074. if (buf_matches_at_pos(&pos, s, n)) {
  1075. tor_assert(pos.chunk_pos + pos.pos < INT_MAX);
  1076. return (int)(pos.chunk_pos + pos.pos);
  1077. } else {
  1078. if (buf_pos_inc(&pos)<0)
  1079. return -1;
  1080. }
  1081. }
  1082. return -1;
  1083. }
  1084. /** There is a (possibly incomplete) http statement on <b>buf</b>, of the
  1085. * form "\%s\\r\\n\\r\\n\%s", headers, body. (body may contain NULs.)
  1086. * If a) the headers include a Content-Length field and all bytes in
  1087. * the body are present, or b) there's no Content-Length field and
  1088. * all headers are present, then:
  1089. *
  1090. * - strdup headers into <b>*headers_out</b>, and NUL-terminate it.
  1091. * - memdup body into <b>*body_out</b>, and NUL-terminate it.
  1092. * - Then remove them from <b>buf</b>, and return 1.
  1093. *
  1094. * - If headers or body is NULL, discard that part of the buf.
  1095. * - If a headers or body doesn't fit in the arg, return -1.
  1096. * (We ensure that the headers or body don't exceed max len,
  1097. * _even if_ we're planning to discard them.)
  1098. * - If force_complete is true, then succeed even if not all of the
  1099. * content has arrived.
  1100. *
  1101. * Else, change nothing and return 0.
  1102. */
  1103. int
  1104. fetch_from_buf_http(buf_t *buf,
  1105. char **headers_out, size_t max_headerlen,
  1106. char **body_out, size_t *body_used, size_t max_bodylen,
  1107. int force_complete)
  1108. {
  1109. char *headers, *p;
  1110. size_t headerlen, bodylen, contentlen;
  1111. int crlf_offset;
  1112. check();
  1113. if (!buf->head)
  1114. return 0;
  1115. crlf_offset = buf_find_string_offset(buf, "\r\n\r\n", 4);
  1116. if (crlf_offset > (int)max_headerlen ||
  1117. (crlf_offset < 0 && buf->datalen > max_headerlen)) {
  1118. log_debug(LD_HTTP,"headers too long.");
  1119. return -1;
  1120. } else if (crlf_offset < 0) {
  1121. log_debug(LD_HTTP,"headers not all here yet.");
  1122. return 0;
  1123. }
  1124. /* Okay, we have a full header. Make sure it all appears in the first
  1125. * chunk. */
  1126. if ((int)buf->head->datalen < crlf_offset + 4)
  1127. buf_pullup(buf, crlf_offset+4, 0);
  1128. headerlen = crlf_offset + 4;
  1129. headers = buf->head->data;
  1130. bodylen = buf->datalen - headerlen;
  1131. log_debug(LD_HTTP,"headerlen %d, bodylen %d.", (int)headerlen, (int)bodylen);
  1132. if (max_headerlen <= headerlen) {
  1133. log_warn(LD_HTTP,"headerlen %d larger than %d. Failing.",
  1134. (int)headerlen, (int)max_headerlen-1);
  1135. return -1;
  1136. }
  1137. if (max_bodylen <= bodylen) {
  1138. log_warn(LD_HTTP,"bodylen %d larger than %d. Failing.",
  1139. (int)bodylen, (int)max_bodylen-1);
  1140. return -1;
  1141. }
  1142. #define CONTENT_LENGTH "\r\nContent-Length: "
  1143. p = (char*) tor_memstr(headers, headerlen, CONTENT_LENGTH);
  1144. if (p) {
  1145. int i;
  1146. i = atoi(p+strlen(CONTENT_LENGTH));
  1147. if (i < 0) {
  1148. log_warn(LD_PROTOCOL, "Content-Length is less than zero; it looks like "
  1149. "someone is trying to crash us.");
  1150. return -1;
  1151. }
  1152. contentlen = i;
  1153. /* if content-length is malformed, then our body length is 0. fine. */
  1154. log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
  1155. if (bodylen < contentlen) {
  1156. if (!force_complete) {
  1157. log_debug(LD_HTTP,"body not all here yet.");
  1158. return 0; /* not all there yet */
  1159. }
  1160. }
  1161. if (bodylen > contentlen) {
  1162. bodylen = contentlen;
  1163. log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
  1164. }
  1165. }
  1166. /* all happy. copy into the appropriate places, and return 1 */
  1167. if (headers_out) {
  1168. *headers_out = tor_malloc(headerlen+1);
  1169. fetch_from_buf(*headers_out, headerlen, buf);
  1170. (*headers_out)[headerlen] = 0; /* NUL terminate it */
  1171. }
  1172. if (body_out) {
  1173. tor_assert(body_used);
  1174. *body_used = bodylen;
  1175. *body_out = tor_malloc(bodylen+1);
  1176. fetch_from_buf(*body_out, bodylen, buf);
  1177. (*body_out)[bodylen] = 0; /* NUL terminate it */
  1178. }
  1179. check();
  1180. return 1;
  1181. }
  1182. /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
  1183. * of the forms
  1184. * - socks4: "socksheader username\\0"
  1185. * - socks4a: "socksheader username\\0 destaddr\\0"
  1186. * - socks5 phase one: "version #methods methods"
  1187. * - socks5 phase two: "version command 0 addresstype..."
  1188. * If it's a complete and valid handshake, and destaddr fits in
  1189. * MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
  1190. * assign to <b>req</b>, and return 1.
  1191. *
  1192. * If it's invalid or too big, return -1.
  1193. *
  1194. * Else it's not all there yet, leave buf alone and return 0.
  1195. *
  1196. * If you want to specify the socks reply, write it into <b>req->reply</b>
  1197. * and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
  1198. *
  1199. * If <b>log_sockstype</b> is non-zero, then do a notice-level log of whether
  1200. * the connection is possibly leaking DNS requests locally or not.
  1201. *
  1202. * If <b>safe_socks</b> is true, then reject unsafe socks protocols.
  1203. *
  1204. * If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are
  1205. * undefined.
  1206. */
  1207. int
  1208. fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
  1209. int log_sockstype, int safe_socks)
  1210. {
  1211. unsigned int len;
  1212. char tmpbuf[TOR_ADDR_BUF_LEN+1];
  1213. tor_addr_t destaddr;
  1214. uint32_t destip;
  1215. uint8_t socksver;
  1216. enum {socks4, socks4a} socks4_prot = socks4a;
  1217. char *next, *startaddr;
  1218. struct in_addr in;
  1219. /* If the user connects with socks4 or the wrong variant of socks5,
  1220. * then log a warning to let him know that it might be unwise. */
  1221. static int have_warned_about_unsafe_socks = 0;
  1222. if (buf->datalen < 2) /* version and another byte */
  1223. return 0;
  1224. buf_pullup(buf, 128, 0);
  1225. tor_assert(buf->head && buf->head->datalen >= 2);
  1226. socksver = *buf->head->data;
  1227. switch (socksver) { /* which version of socks? */
  1228. case 5: /* socks5 */
  1229. if (req->socks_version != 5) { /* we need to negotiate a method */
  1230. unsigned char nummethods = (unsigned char)*(buf->head->data+1);
  1231. tor_assert(!req->socks_version);
  1232. if (buf->datalen < 2u+nummethods)
  1233. return 0;
  1234. buf_pullup(buf, 2u+nummethods, 0);
  1235. if (!nummethods || !memchr(buf->head->data+2, 0, nummethods)) {
  1236. log_warn(LD_APP,
  1237. "socks5: offered methods don't include 'no auth'. "
  1238. "Rejecting.");
  1239. req->replylen = 2; /* 2 bytes of response */
  1240. req->reply[0] = 5;
  1241. req->reply[1] = '\xFF'; /* reject all methods */
  1242. return -1;
  1243. }
  1244. /* remove packet from buf. also remove any other extraneous
  1245. * bytes, to support broken socks clients. */
  1246. buf_clear(buf);
  1247. req->replylen = 2; /* 2 bytes of response */
  1248. req->reply[0] = 5; /* socks5 reply */
  1249. req->reply[1] = 0; /* tell client to use "none" auth method */
  1250. req->socks_version = 5; /* remember we've already negotiated auth */
  1251. log_debug(LD_APP,"socks5: accepted method 0");
  1252. return 0;
  1253. }
  1254. /* we know the method; read in the request */
  1255. log_debug(LD_APP,"socks5: checking request");
  1256. if (buf->datalen < 8) /* basic info plus >=2 for addr plus 2 for port */
  1257. return 0; /* not yet */
  1258. tor_assert(buf->head->datalen >= 8);
  1259. req->command = (unsigned char) *(buf->head->data+1);
  1260. if (req->command != SOCKS_COMMAND_CONNECT &&
  1261. req->command != SOCKS_COMMAND_RESOLVE &&
  1262. req->command != SOCKS_COMMAND_RESOLVE_PTR) {
  1263. /* not a connect or resolve or a resolve_ptr? we don't support it. */
  1264. log_warn(LD_APP,"socks5: command %d not recognized. Rejecting.",
  1265. req->command);
  1266. return -1;
  1267. }
  1268. switch (*(buf->head->data+3)) { /* address type */
  1269. case 1: /* IPv4 address */
  1270. case 4: /* IPv6 address */ {
  1271. const int is_v6 = *(buf->head->data+3) == 4;
  1272. const unsigned addrlen = is_v6 ? 16 : 4;
  1273. log_debug(LD_APP,"socks5: ipv4 address type");
  1274. if (buf->datalen < 6+addrlen) /* ip/port there? */
  1275. return 0; /* not yet */
  1276. if (is_v6)
  1277. tor_addr_from_ipv6_bytes(&destaddr, buf->head->data+4);
  1278. else
  1279. tor_addr_from_ipv4n(&destaddr, get_uint32(buf->head->data+4));
  1280. tor_addr_to_str(tmpbuf, &destaddr, sizeof(tmpbuf), 1);
  1281. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1282. log_warn(LD_APP,
  1283. "socks5 IP takes %d bytes, which doesn't fit in %d. "
  1284. "Rejecting.",
  1285. (int)strlen(tmpbuf)+1,(int)MAX_SOCKS_ADDR_LEN);
  1286. return -1;
  1287. }
  1288. strlcpy(req->address,tmpbuf,sizeof(req->address));
  1289. req->port = ntohs(get_uint16(buf->head->data+4+addrlen));
  1290. buf_remove_from_front(buf, 6+addrlen);
  1291. if (req->command != SOCKS_COMMAND_RESOLVE_PTR &&
  1292. !addressmap_have_mapping(req->address,0) &&
  1293. !have_warned_about_unsafe_socks) {
  1294. log_warn(LD_APP,
  1295. "Your application (using socks5 to port %d) is giving "
  1296. "Tor only an IP address. Applications that do DNS resolves "
  1297. "themselves may leak information. Consider using Socks4A "
  1298. "(e.g. via privoxy or socat) instead. For more information, "
  1299. "please see https://wiki.torproject.org/TheOnionRouter/"
  1300. "TorFAQ#SOCKSAndDNS.%s", req->port,
  1301. safe_socks ? " Rejecting." : "");
  1302. /*have_warned_about_unsafe_socks = 1;*/
  1303. /*(for now, warn every time)*/
  1304. control_event_client_status(LOG_WARN,
  1305. "DANGEROUS_SOCKS PROTOCOL=SOCKS5 ADDRESS=%s:%d",
  1306. req->address, req->port);
  1307. if (safe_socks)
  1308. return -1;
  1309. }
  1310. return 1;
  1311. }
  1312. case 3: /* fqdn */
  1313. log_debug(LD_APP,"socks5: fqdn address type");
  1314. if (req->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1315. log_warn(LD_APP, "socks5 received RESOLVE_PTR command with "
  1316. "hostname type. Rejecting.");
  1317. return -1;
  1318. }
  1319. len = (unsigned char)*(buf->head->data+4);
  1320. if (buf->datalen < 7+len) /* addr/port there? */
  1321. return 0; /* not yet */
  1322. buf_pullup(buf, 7+len, 0);
  1323. tor_assert(buf->head->datalen >= 7+len);
  1324. if (len+1 > MAX_SOCKS_ADDR_LEN) {
  1325. log_warn(LD_APP,
  1326. "socks5 hostname is %d bytes, which doesn't fit in "
  1327. "%d. Rejecting.", len+1,MAX_SOCKS_ADDR_LEN);
  1328. return -1;
  1329. }
  1330. memcpy(req->address,buf->head->data+5,len);
  1331. req->address[len] = 0;
  1332. req->port = ntohs(get_uint16(buf->head->data+5+len));
  1333. buf_remove_from_front(buf, 5+len+2);
  1334. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1335. log_warn(LD_PROTOCOL,
  1336. "Your application (using socks5 to port %d) gave Tor "
  1337. "a malformed hostname: %s. Rejecting the connection.",
  1338. req->port, escaped(req->address));
  1339. return -1;
  1340. }
  1341. if (log_sockstype)
  1342. log_notice(LD_APP,
  1343. "Your application (using socks5 to port %d) gave "
  1344. "Tor a hostname, which means Tor will do the DNS resolve "
  1345. "for you. This is good.", req->port);
  1346. return 1;
  1347. default: /* unsupported */
  1348. log_warn(LD_APP,"socks5: unsupported address type %d. Rejecting.",
  1349. (int) *(buf->head->data+3));
  1350. return -1;
  1351. }
  1352. tor_assert(0);
  1353. case 4: /* socks4 */
  1354. /* http://archive.socks.permeo.com/protocol/socks4.protocol */
  1355. /* http://archive.socks.permeo.com/protocol/socks4a.protocol */
  1356. req->socks_version = 4;
  1357. if (buf->datalen < SOCKS4_NETWORK_LEN) /* basic info available? */
  1358. return 0; /* not yet */
  1359. buf_pullup(buf, 1280, 0);
  1360. req->command = (unsigned char) *(buf->head->data+1);
  1361. if (req->command != SOCKS_COMMAND_CONNECT &&
  1362. req->command != SOCKS_COMMAND_RESOLVE) {
  1363. /* not a connect or resolve? we don't support it. (No resolve_ptr with
  1364. * socks4.) */
  1365. log_warn(LD_APP,"socks4: command %d not recognized. Rejecting.",
  1366. req->command);
  1367. return -1;
  1368. }
  1369. req->port = ntohs(*(uint16_t*)(buf->head->data+2));
  1370. destip = ntohl(*(uint32_t*)(buf->head->data+4));
  1371. if ((!req->port && req->command!=SOCKS_COMMAND_RESOLVE) || !destip) {
  1372. log_warn(LD_APP,"socks4: Port or DestIP is zero. Rejecting.");
  1373. return -1;
  1374. }
  1375. if (destip >> 8) {
  1376. log_debug(LD_APP,"socks4: destip not in form 0.0.0.x.");
  1377. in.s_addr = htonl(destip);
  1378. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1379. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1380. log_debug(LD_APP,"socks4 addr (%d bytes) too long. Rejecting.",
  1381. (int)strlen(tmpbuf));
  1382. return -1;
  1383. }
  1384. log_debug(LD_APP,
  1385. "socks4: successfully read destip (%s)", safe_str(tmpbuf));
  1386. socks4_prot = socks4;
  1387. }
  1388. next = memchr(buf->head->data+SOCKS4_NETWORK_LEN, 0,
  1389. buf->head->datalen-SOCKS4_NETWORK_LEN);
  1390. if (!next) {
  1391. if (buf->head->datalen >= 1024) {
  1392. log_debug(LD_APP, "Socks4 user name too long; rejecting.");
  1393. return -1;
  1394. }
  1395. log_debug(LD_APP,"socks4: Username not here yet.");
  1396. return 0;
  1397. }
  1398. tor_assert(next < CHUNK_WRITE_PTR(buf->head));
  1399. startaddr = NULL;
  1400. if (socks4_prot != socks4a &&
  1401. !addressmap_have_mapping(tmpbuf,0) &&
  1402. !have_warned_about_unsafe_socks) {
  1403. log_warn(LD_APP,
  1404. "Your application (using socks4 to port %d) is giving Tor "
  1405. "only an IP address. Applications that do DNS resolves "
  1406. "themselves may leak information. Consider using Socks4A "
  1407. "(e.g. via privoxy or socat) instead. For more information, "
  1408. "please see https://wiki.torproject.org/TheOnionRouter/"
  1409. "TorFAQ#SOCKSAndDNS.%s", req->port,
  1410. safe_socks ? " Rejecting." : "");
  1411. /*have_warned_about_unsafe_socks = 1;*/ /*(for now, warn every time)*/
  1412. control_event_client_status(LOG_WARN,
  1413. "DANGEROUS_SOCKS PROTOCOL=SOCKS4 ADDRESS=%s:%d",
  1414. tmpbuf, req->port);
  1415. if (safe_socks)
  1416. return -1;
  1417. }
  1418. if (socks4_prot == socks4a) {
  1419. if (next+1 == CHUNK_WRITE_PTR(buf->head)) {
  1420. log_debug(LD_APP,"socks4: No part of destaddr here yet.");
  1421. return 0;
  1422. }
  1423. startaddr = next+1;
  1424. next = memchr(startaddr, 0, CHUNK_WRITE_PTR(buf->head)-startaddr);
  1425. if (!next) {
  1426. if (buf->head->datalen >= 1024) {
  1427. log_debug(LD_APP,"socks4: Destaddr too long.");
  1428. return -1;
  1429. }
  1430. log_debug(LD_APP,"socks4: Destaddr not all here yet.");
  1431. return 0;
  1432. }
  1433. if (MAX_SOCKS_ADDR_LEN <= next-startaddr) {
  1434. log_warn(LD_APP,"socks4: Destaddr too long. Rejecting.");
  1435. return -1;
  1436. }
  1437. // tor_assert(next < buf->cur+buf->datalen);
  1438. if (log_sockstype)
  1439. log_notice(LD_APP,
  1440. "Your application (using socks4a to port %d) gave "
  1441. "Tor a hostname, which means Tor will do the DNS resolve "
  1442. "for you. This is good.", req->port);
  1443. }
  1444. log_debug(LD_APP,"socks4: Everything is here. Success.");
  1445. strlcpy(req->address, startaddr ? startaddr : tmpbuf,
  1446. sizeof(req->address));
  1447. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1448. log_warn(LD_PROTOCOL,
  1449. "Your application (using socks4 to port %d) gave Tor "
  1450. "a malformed hostname: %s. Rejecting the connection.",
  1451. req->port, escaped(req->address));
  1452. return -1;
  1453. }
  1454. /* next points to the final \0 on inbuf */
  1455. buf_remove_from_front(buf, next - buf->head->data + 1);
  1456. return 1;
  1457. case 'G': /* get */
  1458. case 'H': /* head */
  1459. case 'P': /* put/post */
  1460. case 'C': /* connect */
  1461. strlcpy(req->reply,
  1462. "HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
  1463. "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
  1464. "<html>\n"
  1465. "<head>\n"
  1466. "<title>Tor is not an HTTP Proxy</title>\n"
  1467. "</head>\n"
  1468. "<body>\n"
  1469. "<h1>Tor is not an HTTP Proxy</h1>\n"
  1470. "<p>\n"
  1471. "It appears you have configured your web browser to use Tor as an HTTP proxy."
  1472. "\n"
  1473. "This is not correct: Tor is a SOCKS proxy, not an HTTP proxy.\n"
  1474. "Please configure your client accordingly.\n"
  1475. "</p>\n"
  1476. "<p>\n"
  1477. "See <a href=\"https://www.torproject.org/documentation.html\">"
  1478. "https://www.torproject.org/documentation.html</a> for more "
  1479. "information.\n"
  1480. "<!-- Plus this comment, to make the body response more than 512 bytes, so "
  1481. " IE will be willing to display it. Comment comment comment comment "
  1482. " comment comment comment comment comment comment comment comment.-->\n"
  1483. "</p>\n"
  1484. "</body>\n"
  1485. "</html>\n"
  1486. , MAX_SOCKS_REPLY_LEN);
  1487. req->replylen = strlen(req->reply)+1;
  1488. /* fall through */
  1489. default: /* version is not socks4 or socks5 */
  1490. log_warn(LD_APP,
  1491. "Socks version %d not recognized. (Tor is not an http proxy.)",
  1492. *(buf->head->data));
  1493. {
  1494. char *tmp = tor_strndup(buf->head->data, 8); /*XXXX what if longer?*/
  1495. control_event_client_status(LOG_WARN,
  1496. "SOCKS_UNKNOWN_PROTOCOL DATA=\"%s\"",
  1497. escaped(tmp));
  1498. tor_free(tmp);
  1499. }
  1500. return -1;
  1501. }
  1502. }
  1503. /** Inspect a reply from SOCKS server stored in <b>buf</b> according
  1504. * to <b>state</b>, removing the protocol data upon success. Return 0 on
  1505. * incomplete response, 1 on success and -1 on error, in which case
  1506. * <b>reason</b> is set to a descriptive message (free() when finished
  1507. * with it).
  1508. *
  1509. * As a special case, 2 is returned when user/pass is required
  1510. * during SOCKS5 handshake and user/pass is configured.
  1511. */
  1512. int
  1513. fetch_from_buf_socks_client(buf_t *buf, int state, char **reason)
  1514. {
  1515. unsigned char *data;
  1516. size_t addrlen;
  1517. if (buf->datalen < 2)
  1518. return 0;
  1519. buf_pullup(buf, 128, 0);
  1520. tor_assert(buf->head && buf->head->datalen >= 2);
  1521. data = (unsigned char *) buf->head->data;
  1522. switch (state) {
  1523. case PROXY_SOCKS4_WANT_CONNECT_OK:
  1524. /* Wait for the complete response */
  1525. if (buf->head->datalen < 8)
  1526. return 0;
  1527. if (data[1] != 0x5a) {
  1528. *reason = tor_strdup(socks4_response_code_to_string(data[1]));
  1529. return -1;
  1530. }
  1531. /* Success */
  1532. buf_remove_from_front(buf, 8);
  1533. return 1;
  1534. case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
  1535. /* we don't have any credentials */
  1536. if (data[1] != 0x00) {
  1537. *reason = tor_strdup("server doesn't support any of our "
  1538. "available authentication methods");
  1539. return -1;
  1540. }
  1541. log_info(LD_NET, "SOCKS 5 client: continuing without authentication");
  1542. buf_clear(buf);
  1543. return 1;
  1544. case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
  1545. /* we have a username and password. return 1 if we can proceed without
  1546. * providing authentication, or 2 otherwise. */
  1547. switch (data[1]) {
  1548. case 0x00:
  1549. log_info(LD_NET, "SOCKS 5 client: we have auth details but server "
  1550. "doesn't require authentication.");
  1551. buf_clear(buf);
  1552. return 1;
  1553. case 0x02:
  1554. log_info(LD_NET, "SOCKS 5 client: need authentication.");
  1555. buf_clear(buf);
  1556. return 2;
  1557. /* fall through */
  1558. }
  1559. *reason = tor_strdup("server doesn't support any of our available "
  1560. "authentication methods");
  1561. return -1;
  1562. case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
  1563. /* handle server reply to rfc1929 authentication */
  1564. if (data[1] != 0x00) {
  1565. *reason = tor_strdup("authentication failed");
  1566. return -1;
  1567. }
  1568. log_info(LD_NET, "SOCKS 5 client: authentication successful.");
  1569. buf_clear(buf);
  1570. return 1;
  1571. case PROXY_SOCKS5_WANT_CONNECT_OK:
  1572. /* response is variable length. BND.ADDR, etc, isn't needed
  1573. * (don't bother with buf_pullup()), but make sure to eat all
  1574. * the data used */
  1575. /* wait for address type field to arrive */
  1576. if (buf->datalen < 4)
  1577. return 0;
  1578. switch (data[3]) {
  1579. case 0x01: /* ip4 */
  1580. addrlen = 4;
  1581. break;
  1582. case 0x04: /* ip6 */
  1583. addrlen = 16;
  1584. break;
  1585. case 0x03: /* fqdn (can this happen here?) */
  1586. if (buf->datalen < 5)
  1587. return 0;
  1588. addrlen = 1 + data[4];
  1589. break;
  1590. default:
  1591. *reason = tor_strdup("invalid response to connect request");
  1592. return -1;
  1593. }
  1594. /* wait for address and port */
  1595. if (buf->datalen < 6 + addrlen)
  1596. return 0;
  1597. if (data[1] != 0x00) {
  1598. *reason = tor_strdup(socks5_response_code_to_string(data[1]));
  1599. return -1;
  1600. }
  1601. buf_remove_from_front(buf, 6 + addrlen);
  1602. return 1;
  1603. }
  1604. /* shouldn't get here... */
  1605. tor_assert(0);
  1606. return -1;
  1607. }
  1608. /** Return 1 iff buf looks more like it has an (obsolete) v0 controller
  1609. * command on it than any valid v1 controller command. */
  1610. int
  1611. peek_buf_has_control0_command(buf_t *buf)
  1612. {
  1613. if (buf->datalen >= 4) {
  1614. char header[4];
  1615. uint16_t cmd;
  1616. peek_from_buf(header, sizeof(header), buf);
  1617. cmd = ntohs(get_uint16(header+2));
  1618. if (cmd <= 0x14)
  1619. return 1; /* This is definitely not a v1 control command. */
  1620. }
  1621. return 0;
  1622. }
  1623. /** Return the index within <b>buf</b> at which <b>ch</b> first appears,
  1624. * or -1 if <b>ch</b> does not appear on buf. */
  1625. static off_t
  1626. buf_find_offset_of_char(buf_t *buf, char ch)
  1627. {
  1628. chunk_t *chunk;
  1629. off_t offset = 0;
  1630. for (chunk = buf->head; chunk; chunk = chunk->next) {
  1631. char *cp = memchr(chunk->data, ch, chunk->datalen);
  1632. if (cp)
  1633. return offset + (cp - chunk->data);
  1634. else
  1635. offset += chunk->datalen;
  1636. }
  1637. return -1;
  1638. }
  1639. /** Try to read a single LF-terminated line from <b>buf</b>, and write it,
  1640. * NUL-terminated, into the *<b>data_len</b> byte buffer at <b>data_out</b>.
  1641. * Set *<b>data_len</b> to the number of bytes in the line, not counting the
  1642. * terminating NUL. Return 1 if we read a whole line, return 0 if we don't
  1643. * have a whole line yet, and return -1 if the line length exceeds
  1644. * *<b>data_len</b>.
  1645. */
  1646. int
  1647. fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
  1648. {
  1649. size_t sz;
  1650. off_t offset;
  1651. if (!buf->head)
  1652. return 0;
  1653. offset = buf_find_offset_of_char(buf, '\n');
  1654. if (offset < 0)
  1655. return 0;
  1656. sz = (size_t) offset;
  1657. if (sz+2 > *data_len) {
  1658. *data_len = sz + 2;
  1659. return -1;
  1660. }
  1661. fetch_from_buf(data_out, sz+1, buf);
  1662. data_out[sz+1] = '\0';
  1663. *data_len = sz+1;
  1664. return 1;
  1665. }
  1666. /** Compress on uncompress the <b>data_len</b> bytes in <b>data</b> using the
  1667. * zlib state <b>state</b>, appending the result to <b>buf</b>. If
  1668. * <b>done</b> is true, flush the data in the state and finish the
  1669. * compression/uncompression. Return -1 on failure, 0 on success. */
  1670. int
  1671. write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
  1672. const char *data, size_t data_len,
  1673. int done)
  1674. {
  1675. char *next;
  1676. size_t old_avail, avail;
  1677. int over = 0;
  1678. do {
  1679. int need_new_chunk = 0;
  1680. if (!buf->tail || ! CHUNK_REMAINING_CAPACITY(buf->tail)) {
  1681. size_t cap = data_len / 4;
  1682. buf_add_chunk_with_capacity(buf, cap, 1);
  1683. }
  1684. next = CHUNK_WRITE_PTR(buf->tail);
  1685. avail = old_avail = CHUNK_REMAINING_CAPACITY(buf->tail);
  1686. switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
  1687. case TOR_ZLIB_DONE:
  1688. over = 1;
  1689. break;
  1690. case TOR_ZLIB_ERR:
  1691. return -1;
  1692. case TOR_ZLIB_OK:
  1693. if (data_len == 0)
  1694. over = 1;
  1695. break;
  1696. case TOR_ZLIB_BUF_FULL:
  1697. if (avail) {
  1698. /* Zlib says we need more room (ZLIB_BUF_FULL). Start a new chunk
  1699. * automatically, whether were going to or not. */
  1700. need_new_chunk = 1;
  1701. }
  1702. break;
  1703. }
  1704. buf->datalen += old_avail - avail;
  1705. buf->tail->datalen += old_avail - avail;
  1706. if (need_new_chunk) {
  1707. buf_add_chunk_with_capacity(buf, data_len/4, 1);
  1708. }
  1709. } while (!over);
  1710. check();
  1711. return 0;
  1712. }
  1713. /** Log an error and exit if <b>buf</b> is corrupted.
  1714. */
  1715. void
  1716. assert_buf_ok(buf_t *buf)
  1717. {
  1718. tor_assert(buf);
  1719. tor_assert(buf->magic == BUFFER_MAGIC);
  1720. if (! buf->head) {
  1721. tor_assert(!buf->tail);
  1722. tor_assert(buf->datalen == 0);
  1723. } else {
  1724. chunk_t *ch;
  1725. size_t total = 0;
  1726. tor_assert(buf->tail);
  1727. for (ch = buf->head; ch; ch = ch->next) {
  1728. total += ch->datalen;
  1729. tor_assert(ch->datalen <= ch->memlen);
  1730. tor_assert(ch->data >= &ch->mem[0]);
  1731. tor_assert(ch->data < &ch->mem[0]+ch->memlen);
  1732. tor_assert(ch->data+ch->datalen <= &ch->mem[0] + ch->memlen);
  1733. if (!ch->next)
  1734. tor_assert(ch == buf->tail);
  1735. }
  1736. tor_assert(buf->datalen == total);
  1737. }
  1738. }
  1739. #ifdef ENABLE_BUF_FREELISTS
  1740. /** Log an error and exit if <b>fl</b> is corrupted.
  1741. */
  1742. static void
  1743. assert_freelist_ok(chunk_freelist_t *fl)
  1744. {
  1745. chunk_t *ch;
  1746. int n;
  1747. tor_assert(fl->alloc_size > 0);
  1748. n = 0;
  1749. for (ch = fl->head; ch; ch = ch->next) {
  1750. tor_assert(CHUNK_ALLOC_SIZE(ch->memlen) == fl->alloc_size);
  1751. ++n;
  1752. }
  1753. tor_assert(n == fl->cur_length);
  1754. tor_assert(n >= fl->lowest_length);
  1755. tor_assert(n <= fl->max_length);
  1756. }
  1757. #endif