buffers.c 59 KB

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