buffers.c 59 KB

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