buffers.c 59 KB

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