buffers.c 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521
  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-2013, 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 "addressmap.h"
  15. #include "buffers.h"
  16. #include "config.h"
  17. #include "connection_edge.h"
  18. #include "connection_or.h"
  19. #include "control.h"
  20. #include "reasons.h"
  21. #include "../common/util.h"
  22. #include "../common/torlog.h"
  23. #ifdef HAVE_UNISTD_H
  24. #include <unistd.h>
  25. #endif
  26. //#define PARANOIA
  27. #ifdef PARANOIA
  28. /** Helper: If PARANOIA is defined, assert that the buffer in local variable
  29. * <b>buf</b> is well-formed. */
  30. #define check() STMT_BEGIN assert_buf_ok(buf); STMT_END
  31. #else
  32. #define check() STMT_NIL
  33. #endif
  34. /* Implementation notes:
  35. *
  36. * After flirting with memmove, and dallying with ring-buffers, we're finally
  37. * getting up to speed with the 1970s and implementing buffers as a linked
  38. * list of small chunks. Each buffer has such a list; data is removed from
  39. * the head of the list, and added at the tail. The list is singly linked,
  40. * and the buffer keeps a pointer to the head and the tail.
  41. *
  42. * Every chunk, except the tail, contains at least one byte of data. Data in
  43. * each chunk is contiguous.
  44. *
  45. * When you need to treat the first N characters on a buffer as a contiguous
  46. * string, use the buf_pullup function to make them so. Don't do this more
  47. * than necessary.
  48. *
  49. * The major free Unix kernels have handled buffers like this since, like,
  50. * forever.
  51. */
  52. static int parse_socks(const char *data, size_t datalen, socks_request_t *req,
  53. int log_sockstype, int safe_socks, ssize_t *drain_out,
  54. size_t *want_length_out);
  55. static int parse_socks_client(const uint8_t *data, size_t datalen,
  56. int state, char **reason,
  57. ssize_t *drain_out);
  58. /* Chunk manipulation functions */
  59. /** A single chunk on a buffer or in a freelist. */
  60. typedef struct chunk_t {
  61. struct chunk_t *next; /**< The next chunk on the buffer or freelist. */
  62. size_t datalen; /**< The number of bytes stored in this chunk */
  63. size_t memlen; /**< The number of usable bytes of storage in <b>mem</b>. */
  64. char *data; /**< A pointer to the first byte of data stored in <b>mem</b>. */
  65. char mem[FLEXIBLE_ARRAY_MEMBER]; /**< The actual memory used for storage in
  66. * this chunk. */
  67. } chunk_t;
  68. #define CHUNK_HEADER_LEN STRUCT_OFFSET(chunk_t, mem[0])
  69. /** Return the number of bytes needed to allocate a chunk to hold
  70. * <b>memlen</b> bytes. */
  71. #define CHUNK_ALLOC_SIZE(memlen) (CHUNK_HEADER_LEN + (memlen))
  72. /** Return the number of usable bytes in a chunk allocated with
  73. * malloc(<b>memlen</b>). */
  74. #define CHUNK_SIZE_WITH_ALLOC(memlen) ((memlen) - CHUNK_HEADER_LEN)
  75. /** Return the next character in <b>chunk</b> onto which data can be appended.
  76. * If the chunk is full, this might be off the end of chunk->mem. */
  77. static INLINE char *
  78. CHUNK_WRITE_PTR(chunk_t *chunk)
  79. {
  80. return chunk->data + chunk->datalen;
  81. }
  82. /** Return the number of bytes that can be written onto <b>chunk</b> without
  83. * running out of space. */
  84. static INLINE size_t
  85. CHUNK_REMAINING_CAPACITY(const chunk_t *chunk)
  86. {
  87. return (chunk->mem + chunk->memlen) - (chunk->data + chunk->datalen);
  88. }
  89. /** Move all bytes stored in <b>chunk</b> to the front of <b>chunk</b>->mem,
  90. * to free up space at the end. */
  91. static INLINE void
  92. chunk_repack(chunk_t *chunk)
  93. {
  94. if (chunk->datalen && chunk->data != &chunk->mem[0]) {
  95. memmove(chunk->mem, chunk->data, chunk->datalen);
  96. }
  97. chunk->data = &chunk->mem[0];
  98. }
  99. #if defined(ENABLE_BUF_FREELISTS) || defined(RUNNING_DOXYGEN)
  100. /** A freelist of chunks. */
  101. typedef struct chunk_freelist_t {
  102. size_t alloc_size; /**< What size chunks does this freelist hold? */
  103. int max_length; /**< Never allow more than this number of chunks in the
  104. * freelist. */
  105. int slack; /**< When trimming the freelist, leave this number of extra
  106. * chunks beyond lowest_length.*/
  107. int cur_length; /**< How many chunks on the freelist now? */
  108. int lowest_length; /**< What's the smallest value of cur_length since the
  109. * last time we cleaned this freelist? */
  110. uint64_t n_alloc;
  111. uint64_t n_free;
  112. uint64_t n_hit;
  113. chunk_t *head; /**< First chunk on the freelist. */
  114. } chunk_freelist_t;
  115. /** Macro to help define freelists. */
  116. #define FL(a,m,s) { a, m, s, 0, 0, 0, 0, 0, NULL }
  117. /** Static array of freelists, sorted by alloc_len, terminated by an entry
  118. * with alloc_size of 0. */
  119. static chunk_freelist_t freelists[] = {
  120. FL(4096, 256, 8), FL(8192, 128, 4), FL(16384, 64, 4), FL(32768, 32, 2),
  121. FL(0, 0, 0)
  122. };
  123. #undef FL
  124. /** How many times have we looked for a chunk of a size that no freelist
  125. * could help with? */
  126. static uint64_t n_freelist_miss = 0;
  127. static void assert_freelist_ok(chunk_freelist_t *fl);
  128. /** Return the freelist to hold chunks of size <b>alloc</b>, or NULL if
  129. * no freelist exists for that size. */
  130. static INLINE chunk_freelist_t *
  131. get_freelist(size_t alloc)
  132. {
  133. int i;
  134. for (i=0; freelists[i].alloc_size <= alloc; ++i) {
  135. if (freelists[i].alloc_size == alloc) {
  136. return &freelists[i];
  137. }
  138. }
  139. return NULL;
  140. }
  141. /** Deallocate a chunk or put it on a freelist */
  142. static void
  143. chunk_free_unchecked(chunk_t *chunk)
  144. {
  145. size_t alloc;
  146. chunk_freelist_t *freelist;
  147. alloc = CHUNK_ALLOC_SIZE(chunk->memlen);
  148. freelist = get_freelist(alloc);
  149. if (freelist && freelist->cur_length < freelist->max_length) {
  150. chunk->next = freelist->head;
  151. freelist->head = chunk;
  152. ++freelist->cur_length;
  153. } else {
  154. if (freelist)
  155. ++freelist->n_free;
  156. tor_free(chunk);
  157. }
  158. }
  159. /** Allocate a new chunk with a given allocation size, or get one from the
  160. * freelist. Note that a chunk with allocation size A can actually hold only
  161. * CHUNK_SIZE_WITH_ALLOC(A) bytes in its mem field. */
  162. static INLINE chunk_t *
  163. chunk_new_with_alloc_size(size_t alloc)
  164. {
  165. chunk_t *ch;
  166. chunk_freelist_t *freelist;
  167. tor_assert(alloc >= sizeof(chunk_t));
  168. freelist = get_freelist(alloc);
  169. if (freelist && freelist->head) {
  170. ch = freelist->head;
  171. freelist->head = ch->next;
  172. if (--freelist->cur_length < freelist->lowest_length)
  173. freelist->lowest_length = freelist->cur_length;
  174. ++freelist->n_hit;
  175. } else {
  176. if (freelist)
  177. ++freelist->n_alloc;
  178. else
  179. ++n_freelist_miss;
  180. ch = tor_malloc(alloc);
  181. }
  182. ch->next = NULL;
  183. ch->datalen = 0;
  184. ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
  185. ch->data = &ch->mem[0];
  186. return ch;
  187. }
  188. #else
  189. static void
  190. chunk_free_unchecked(chunk_t *chunk)
  191. {
  192. tor_free(chunk);
  193. }
  194. static INLINE chunk_t *
  195. chunk_new_with_alloc_size(size_t alloc)
  196. {
  197. chunk_t *ch;
  198. ch = tor_malloc(alloc);
  199. ch->next = NULL;
  200. ch->datalen = 0;
  201. ch->memlen = CHUNK_SIZE_WITH_ALLOC(alloc);
  202. ch->data = &ch->mem[0];
  203. return ch;
  204. }
  205. #endif
  206. /** Expand <b>chunk</b> until it can hold <b>sz</b> bytes, and return a
  207. * new pointer to <b>chunk</b>. Old pointers are no longer valid. */
  208. static INLINE chunk_t *
  209. chunk_grow(chunk_t *chunk, size_t sz)
  210. {
  211. off_t offset;
  212. tor_assert(sz > chunk->memlen);
  213. offset = chunk->data - chunk->mem;
  214. chunk = tor_realloc(chunk, CHUNK_ALLOC_SIZE(sz));
  215. chunk->memlen = sz;
  216. chunk->data = chunk->mem + offset;
  217. return chunk;
  218. }
  219. /** If a read onto the end of a chunk would be smaller than this number, then
  220. * just start a new chunk. */
  221. #define MIN_READ_LEN 8
  222. /** Every chunk should take up at least this many bytes. */
  223. #define MIN_CHUNK_ALLOC 256
  224. /** No chunk should take up more than this many bytes. */
  225. #define MAX_CHUNK_ALLOC 65536
  226. /** Return the allocation size we'd like to use to hold <b>target</b>
  227. * bytes. */
  228. static INLINE size_t
  229. preferred_chunk_size(size_t target)
  230. {
  231. size_t sz = MIN_CHUNK_ALLOC;
  232. while (CHUNK_SIZE_WITH_ALLOC(sz) < target) {
  233. sz <<= 1;
  234. }
  235. return sz;
  236. }
  237. /** Remove from the freelists most chunks that have not been used since the
  238. * last call to buf_shrink_freelists(). */
  239. void
  240. buf_shrink_freelists(int free_all)
  241. {
  242. #ifdef ENABLE_BUF_FREELISTS
  243. int i;
  244. disable_control_logging();
  245. for (i = 0; freelists[i].alloc_size; ++i) {
  246. int slack = freelists[i].slack;
  247. assert_freelist_ok(&freelists[i]);
  248. if (free_all || freelists[i].lowest_length > slack) {
  249. int n_to_free = free_all ? freelists[i].cur_length :
  250. (freelists[i].lowest_length - slack);
  251. int n_to_skip = freelists[i].cur_length - n_to_free;
  252. int orig_length = freelists[i].cur_length;
  253. int orig_n_to_free = n_to_free, n_freed=0;
  254. int orig_n_to_skip = n_to_skip;
  255. int new_length = n_to_skip;
  256. chunk_t **chp = &freelists[i].head;
  257. chunk_t *chunk;
  258. while (n_to_skip) {
  259. if (! (*chp)->next) {
  260. log_warn(LD_BUG, "I wanted to skip %d chunks in the freelist for "
  261. "%d-byte chunks, but only found %d. (Length %d)",
  262. orig_n_to_skip, (int)freelists[i].alloc_size,
  263. orig_n_to_skip-n_to_skip, freelists[i].cur_length);
  264. assert_freelist_ok(&freelists[i]);
  265. goto done;
  266. }
  267. // tor_assert((*chp)->next);
  268. chp = &(*chp)->next;
  269. --n_to_skip;
  270. }
  271. chunk = *chp;
  272. *chp = NULL;
  273. while (chunk) {
  274. chunk_t *next = chunk->next;
  275. tor_free(chunk);
  276. chunk = next;
  277. --n_to_free;
  278. ++n_freed;
  279. ++freelists[i].n_free;
  280. }
  281. if (n_to_free) {
  282. log_warn(LD_BUG, "Freelist length for %d-byte chunks may have been "
  283. "messed up somehow.", (int)freelists[i].alloc_size);
  284. log_warn(LD_BUG, "There were %d chunks at the start. I decided to "
  285. "keep %d. I wanted to free %d. I freed %d. I somehow think "
  286. "I have %d left to free.",
  287. freelists[i].cur_length, n_to_skip, orig_n_to_free,
  288. n_freed, n_to_free);
  289. }
  290. // tor_assert(!n_to_free);
  291. freelists[i].cur_length = new_length;
  292. log_info(LD_MM, "Cleaned freelist for %d-byte chunks: original "
  293. "length %d, kept %d, dropped %d.",
  294. (int)freelists[i].alloc_size, orig_length,
  295. orig_n_to_skip, orig_n_to_free);
  296. }
  297. freelists[i].lowest_length = freelists[i].cur_length;
  298. assert_freelist_ok(&freelists[i]);
  299. }
  300. done:
  301. enable_control_logging();
  302. #else
  303. (void) free_all;
  304. #endif
  305. }
  306. /** Describe the current status of the freelists at log level <b>severity</b>.
  307. */
  308. void
  309. buf_dump_freelist_sizes(int severity)
  310. {
  311. #ifdef ENABLE_BUF_FREELISTS
  312. int i;
  313. tor_log(severity, LD_MM, "====== Buffer freelists:");
  314. for (i = 0; freelists[i].alloc_size; ++i) {
  315. uint64_t total = ((uint64_t)freelists[i].cur_length) *
  316. freelists[i].alloc_size;
  317. tor_log(severity, LD_MM,
  318. U64_FORMAT" bytes in %d %d-byte chunks ["U64_FORMAT
  319. " misses; "U64_FORMAT" frees; "U64_FORMAT" hits]",
  320. U64_PRINTF_ARG(total),
  321. freelists[i].cur_length, (int)freelists[i].alloc_size,
  322. U64_PRINTF_ARG(freelists[i].n_alloc),
  323. U64_PRINTF_ARG(freelists[i].n_free),
  324. U64_PRINTF_ARG(freelists[i].n_hit));
  325. }
  326. tor_log(severity, LD_MM, U64_FORMAT" allocations in non-freelist sizes",
  327. U64_PRINTF_ARG(n_freelist_miss));
  328. #else
  329. (void)severity;
  330. #endif
  331. }
  332. /** Magic value for buf_t.magic, to catch pointer errors. */
  333. #define BUFFER_MAGIC 0xB0FFF312u
  334. /** A resizeable buffer, optimized for reading and writing. */
  335. struct buf_t {
  336. uint32_t magic; /**< Magic cookie for debugging: Must be set to
  337. * BUFFER_MAGIC. */
  338. size_t datalen; /**< How many bytes is this buffer holding right now? */
  339. size_t default_chunk_size; /**< Don't allocate any chunks smaller than
  340. * this for this buffer. */
  341. chunk_t *head; /**< First chunk in the list, or NULL for none. */
  342. chunk_t *tail; /**< Last chunk in the list, or NULL for none. */
  343. };
  344. /** Collapse data from the first N chunks from <b>buf</b> into buf->head,
  345. * growing it as necessary, until buf->head has the first <b>bytes</b> bytes
  346. * of data from the buffer, or until buf->head has all the data in <b>buf</b>.
  347. *
  348. * If <b>nulterminate</b> is true, ensure that there is a 0 byte in
  349. * buf->head->mem right after all the data. */
  350. static void
  351. buf_pullup(buf_t *buf, size_t bytes, int nulterminate)
  352. {
  353. chunk_t *dest, *src;
  354. size_t capacity;
  355. if (!buf->head)
  356. return;
  357. check();
  358. if (buf->datalen < bytes)
  359. bytes = buf->datalen;
  360. if (nulterminate) {
  361. capacity = bytes + 1;
  362. if (buf->head->datalen >= bytes && CHUNK_REMAINING_CAPACITY(buf->head)) {
  363. *CHUNK_WRITE_PTR(buf->head) = '\0';
  364. return;
  365. }
  366. } else {
  367. capacity = bytes;
  368. if (buf->head->datalen >= bytes)
  369. return;
  370. }
  371. if (buf->head->memlen >= capacity) {
  372. /* We don't need to grow the first chunk, but we might need to repack it.*/
  373. size_t needed = capacity - buf->head->datalen;
  374. if (CHUNK_REMAINING_CAPACITY(buf->head) < needed)
  375. chunk_repack(buf->head);
  376. tor_assert(CHUNK_REMAINING_CAPACITY(buf->head) >= needed);
  377. } else {
  378. chunk_t *newhead;
  379. size_t newsize;
  380. /* We need to grow the chunk. */
  381. chunk_repack(buf->head);
  382. newsize = CHUNK_SIZE_WITH_ALLOC(preferred_chunk_size(capacity));
  383. newhead = chunk_grow(buf->head, newsize);
  384. tor_assert(newhead->memlen >= capacity);
  385. if (newhead != buf->head) {
  386. if (buf->tail == buf->head)
  387. buf->tail = newhead;
  388. buf->head = newhead;
  389. }
  390. }
  391. dest = buf->head;
  392. while (dest->datalen < bytes) {
  393. size_t n = bytes - dest->datalen;
  394. src = dest->next;
  395. tor_assert(src);
  396. if (n > src->datalen) {
  397. memcpy(CHUNK_WRITE_PTR(dest), src->data, src->datalen);
  398. dest->datalen += src->datalen;
  399. dest->next = src->next;
  400. if (buf->tail == src)
  401. buf->tail = dest;
  402. chunk_free_unchecked(src);
  403. } else {
  404. memcpy(CHUNK_WRITE_PTR(dest), src->data, n);
  405. dest->datalen += n;
  406. src->data += n;
  407. src->datalen -= n;
  408. tor_assert(dest->datalen == bytes);
  409. }
  410. }
  411. if (nulterminate) {
  412. tor_assert(CHUNK_REMAINING_CAPACITY(buf->head));
  413. *CHUNK_WRITE_PTR(buf->head) = '\0';
  414. }
  415. check();
  416. }
  417. /** Resize buf so it won't hold extra memory that we haven't been
  418. * using lately.
  419. */
  420. void
  421. buf_shrink(buf_t *buf)
  422. {
  423. (void)buf;
  424. }
  425. /** Remove the first <b>n</b> bytes from buf. */
  426. static INLINE void
  427. buf_remove_from_front(buf_t *buf, size_t n)
  428. {
  429. tor_assert(buf->datalen >= n);
  430. while (n) {
  431. tor_assert(buf->head);
  432. if (buf->head->datalen > n) {
  433. buf->head->datalen -= n;
  434. buf->head->data += n;
  435. buf->datalen -= n;
  436. return;
  437. } else {
  438. chunk_t *victim = buf->head;
  439. n -= victim->datalen;
  440. buf->datalen -= victim->datalen;
  441. buf->head = victim->next;
  442. if (buf->tail == victim)
  443. buf->tail = NULL;
  444. chunk_free_unchecked(victim);
  445. }
  446. }
  447. check();
  448. }
  449. /** Create and return a new buf with default chunk capacity <b>size</b>.
  450. */
  451. buf_t *
  452. buf_new_with_capacity(size_t size)
  453. {
  454. buf_t *b = buf_new();
  455. b->default_chunk_size = preferred_chunk_size(size);
  456. return b;
  457. }
  458. /** Allocate and return a new buffer with default capacity. */
  459. buf_t *
  460. buf_new(void)
  461. {
  462. buf_t *buf = tor_malloc_zero(sizeof(buf_t));
  463. buf->magic = BUFFER_MAGIC;
  464. buf->default_chunk_size = 4096;
  465. return buf;
  466. }
  467. /** Remove all data from <b>buf</b>. */
  468. void
  469. buf_clear(buf_t *buf)
  470. {
  471. chunk_t *chunk, *next;
  472. buf->datalen = 0;
  473. for (chunk = buf->head; chunk; chunk = next) {
  474. next = chunk->next;
  475. chunk_free_unchecked(chunk);
  476. }
  477. buf->head = buf->tail = NULL;
  478. }
  479. /** Return the number of bytes stored in <b>buf</b> */
  480. size_t
  481. buf_datalen(const buf_t *buf)
  482. {
  483. return buf->datalen;
  484. }
  485. /** Return the total length of all chunks used in <b>buf</b>. */
  486. size_t
  487. buf_allocation(const buf_t *buf)
  488. {
  489. size_t total = 0;
  490. const chunk_t *chunk;
  491. for (chunk = buf->head; chunk; chunk = chunk->next) {
  492. total += chunk->memlen;
  493. }
  494. return total;
  495. }
  496. /** Return the number of bytes that can be added to <b>buf</b> without
  497. * performing any additional allocation. */
  498. size_t
  499. buf_slack(const buf_t *buf)
  500. {
  501. if (!buf->tail)
  502. return 0;
  503. else
  504. return CHUNK_REMAINING_CAPACITY(buf->tail);
  505. }
  506. /** Release storage held by <b>buf</b>. */
  507. void
  508. buf_free(buf_t *buf)
  509. {
  510. if (!buf)
  511. return;
  512. buf_clear(buf);
  513. buf->magic = 0xdeadbeef;
  514. tor_free(buf);
  515. }
  516. /** Return a new copy of <b>in_chunk</b> */
  517. static chunk_t *
  518. chunk_copy(const chunk_t *in_chunk)
  519. {
  520. chunk_t *newch = tor_memdup(in_chunk, CHUNK_ALLOC_SIZE(in_chunk->memlen));
  521. newch->next = NULL;
  522. if (in_chunk->data) {
  523. off_t offset = in_chunk->data - in_chunk->mem;
  524. newch->data = newch->mem + offset;
  525. }
  526. return newch;
  527. }
  528. /** Return a new copy of <b>buf</b> */
  529. buf_t *
  530. buf_copy(const buf_t *buf)
  531. {
  532. chunk_t *ch;
  533. buf_t *out = buf_new();
  534. out->default_chunk_size = buf->default_chunk_size;
  535. for (ch = buf->head; ch; ch = ch->next) {
  536. chunk_t *newch = chunk_copy(ch);
  537. if (out->tail) {
  538. out->tail->next = newch;
  539. out->tail = newch;
  540. } else {
  541. out->head = out->tail = newch;
  542. }
  543. }
  544. out->datalen = buf->datalen;
  545. return out;
  546. }
  547. /** Append a new chunk with enough capacity to hold <b>capacity</b> bytes to
  548. * the tail of <b>buf</b>. If <b>capped</b>, don't allocate a chunk bigger
  549. * than MAX_CHUNK_ALLOC. */
  550. static chunk_t *
  551. buf_add_chunk_with_capacity(buf_t *buf, size_t capacity, int capped)
  552. {
  553. chunk_t *chunk;
  554. if (CHUNK_ALLOC_SIZE(capacity) < buf->default_chunk_size) {
  555. chunk = chunk_new_with_alloc_size(buf->default_chunk_size);
  556. } else if (capped && CHUNK_ALLOC_SIZE(capacity) > MAX_CHUNK_ALLOC) {
  557. chunk = chunk_new_with_alloc_size(MAX_CHUNK_ALLOC);
  558. } else {
  559. chunk = chunk_new_with_alloc_size(preferred_chunk_size(capacity));
  560. }
  561. if (buf->tail) {
  562. tor_assert(buf->head);
  563. buf->tail->next = chunk;
  564. buf->tail = chunk;
  565. } else {
  566. tor_assert(!buf->head);
  567. buf->head = buf->tail = chunk;
  568. }
  569. check();
  570. return chunk;
  571. }
  572. /** Read up to <b>at_most</b> bytes from the socket <b>fd</b> into
  573. * <b>chunk</b> (which must be on <b>buf</b>). If we get an EOF, set
  574. * *<b>reached_eof</b> to 1. Return -1 on error, 0 on eof or blocking,
  575. * and the number of bytes read otherwise. */
  576. static INLINE int
  577. read_to_chunk(buf_t *buf, chunk_t *chunk, tor_socket_t fd, size_t at_most,
  578. int *reached_eof, int *socket_error)
  579. {
  580. ssize_t read_result;
  581. if (at_most > CHUNK_REMAINING_CAPACITY(chunk))
  582. at_most = CHUNK_REMAINING_CAPACITY(chunk);
  583. read_result = tor_socket_recv(fd, CHUNK_WRITE_PTR(chunk), at_most, 0);
  584. if (read_result < 0) {
  585. int e = tor_socket_errno(fd);
  586. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  587. #ifdef _WIN32
  588. if (e == WSAENOBUFS)
  589. log_warn(LD_NET,"recv() failed: WSAENOBUFS. Not enough ram?");
  590. #endif
  591. *socket_error = e;
  592. return -1;
  593. }
  594. return 0; /* would block. */
  595. } else if (read_result == 0) {
  596. log_debug(LD_NET,"Encountered eof on fd %d", (int)fd);
  597. *reached_eof = 1;
  598. return 0;
  599. } else { /* actually got bytes. */
  600. buf->datalen += read_result;
  601. chunk->datalen += read_result;
  602. log_debug(LD_NET,"Read %ld bytes. %d on inbuf.", (long)read_result,
  603. (int)buf->datalen);
  604. tor_assert(read_result < INT_MAX);
  605. return (int)read_result;
  606. }
  607. }
  608. /** As read_to_chunk(), but return (negative) error code on error, blocking,
  609. * or TLS, and the number of bytes read otherwise. */
  610. static INLINE int
  611. read_to_chunk_tls(buf_t *buf, chunk_t *chunk, tor_tls_t *tls,
  612. size_t at_most)
  613. {
  614. int read_result;
  615. tor_assert(CHUNK_REMAINING_CAPACITY(chunk) >= at_most);
  616. read_result = tor_tls_read(tls, CHUNK_WRITE_PTR(chunk), at_most);
  617. if (read_result < 0)
  618. return read_result;
  619. buf->datalen += read_result;
  620. chunk->datalen += read_result;
  621. return read_result;
  622. }
  623. /** Read from socket <b>s</b>, writing onto end of <b>buf</b>. Read at most
  624. * <b>at_most</b> bytes, growing the buffer as necessary. If recv() returns 0
  625. * (because of EOF), set *<b>reached_eof</b> to 1 and return 0. Return -1 on
  626. * error; else return the number of bytes read.
  627. */
  628. /* XXXX024 indicate "read blocked" somehow? */
  629. int
  630. read_to_buf(tor_socket_t s, size_t at_most, buf_t *buf, int *reached_eof,
  631. int *socket_error)
  632. {
  633. /* XXXX024 It's stupid to overload the return values for these functions:
  634. * "error status" and "number of bytes read" are not mutually exclusive.
  635. */
  636. int r = 0;
  637. size_t total_read = 0;
  638. check();
  639. tor_assert(reached_eof);
  640. tor_assert(SOCKET_OK(s));
  641. while (at_most > total_read) {
  642. size_t readlen = at_most - total_read;
  643. chunk_t *chunk;
  644. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  645. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  646. if (readlen > chunk->memlen)
  647. readlen = chunk->memlen;
  648. } else {
  649. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  650. chunk = buf->tail;
  651. if (cap < readlen)
  652. readlen = cap;
  653. }
  654. r = read_to_chunk(buf, chunk, s, readlen, reached_eof, socket_error);
  655. check();
  656. if (r < 0)
  657. return r; /* Error */
  658. tor_assert(total_read+r < INT_MAX);
  659. total_read += r;
  660. if ((size_t)r < readlen) { /* eof, block, or no more to read. */
  661. break;
  662. }
  663. }
  664. return (int)total_read;
  665. }
  666. /** As read_to_buf, but reads from a TLS connection, and returns a TLS
  667. * status value rather than the number of bytes read.
  668. *
  669. * Using TLS on OR connections complicates matters in two ways.
  670. *
  671. * First, a TLS stream has its own read buffer independent of the
  672. * connection's read buffer. (TLS needs to read an entire frame from
  673. * the network before it can decrypt any data. Thus, trying to read 1
  674. * byte from TLS can require that several KB be read from the network
  675. * and decrypted. The extra data is stored in TLS's decrypt buffer.)
  676. * Because the data hasn't been read by Tor (it's still inside the TLS),
  677. * this means that sometimes a connection "has stuff to read" even when
  678. * poll() didn't return POLLIN. The tor_tls_get_pending_bytes function is
  679. * used in connection.c to detect TLS objects with non-empty internal
  680. * buffers and read from them again.
  681. *
  682. * Second, the TLS stream's events do not correspond directly to network
  683. * events: sometimes, before a TLS stream can read, the network must be
  684. * ready to write -- or vice versa.
  685. */
  686. int
  687. read_to_buf_tls(tor_tls_t *tls, size_t at_most, buf_t *buf)
  688. {
  689. int r = 0;
  690. size_t total_read = 0;
  691. check_no_tls_errors();
  692. check();
  693. while (at_most > total_read) {
  694. size_t readlen = at_most - total_read;
  695. chunk_t *chunk;
  696. if (!buf->tail || CHUNK_REMAINING_CAPACITY(buf->tail) < MIN_READ_LEN) {
  697. chunk = buf_add_chunk_with_capacity(buf, at_most, 1);
  698. if (readlen > chunk->memlen)
  699. readlen = chunk->memlen;
  700. } else {
  701. size_t cap = CHUNK_REMAINING_CAPACITY(buf->tail);
  702. chunk = buf->tail;
  703. if (cap < readlen)
  704. readlen = cap;
  705. }
  706. r = read_to_chunk_tls(buf, chunk, tls, readlen);
  707. check();
  708. if (r < 0)
  709. return r; /* Error */
  710. tor_assert(total_read+r < INT_MAX);
  711. total_read += r;
  712. if ((size_t)r < readlen) /* eof, block, or no more to read. */
  713. break;
  714. }
  715. return (int)total_read;
  716. }
  717. /** Helper for flush_buf(): try to write <b>sz</b> bytes from chunk
  718. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. On success, deduct
  719. * the bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  720. * written on success, 0 on blocking, -1 on failure.
  721. */
  722. static INLINE int
  723. flush_chunk(tor_socket_t s, buf_t *buf, chunk_t *chunk, size_t sz,
  724. size_t *buf_flushlen)
  725. {
  726. ssize_t write_result;
  727. if (sz > chunk->datalen)
  728. sz = chunk->datalen;
  729. write_result = tor_socket_send(s, chunk->data, sz, 0);
  730. if (write_result < 0) {
  731. int e = tor_socket_errno(s);
  732. if (!ERRNO_IS_EAGAIN(e)) { /* it's a real error */
  733. #ifdef _WIN32
  734. if (e == WSAENOBUFS)
  735. log_warn(LD_NET,"write() failed: WSAENOBUFS. Not enough ram?");
  736. #endif
  737. return -1;
  738. }
  739. log_debug(LD_NET,"write() would block, returning.");
  740. return 0;
  741. } else {
  742. *buf_flushlen -= write_result;
  743. buf_remove_from_front(buf, write_result);
  744. tor_assert(write_result < INT_MAX);
  745. return (int)write_result;
  746. }
  747. }
  748. /** Helper for flush_buf_tls(): try to write <b>sz</b> bytes from chunk
  749. * <b>chunk</b> of buffer <b>buf</b> onto socket <b>s</b>. (Tries to write
  750. * more if there is a forced pending write size.) On success, deduct the
  751. * bytes written from *<b>buf_flushlen</b>. Return the number of bytes
  752. * written on success, and a TOR_TLS error code on failure or blocking.
  753. */
  754. static INLINE int
  755. flush_chunk_tls(tor_tls_t *tls, buf_t *buf, chunk_t *chunk,
  756. size_t sz, size_t *buf_flushlen)
  757. {
  758. int r;
  759. size_t forced;
  760. char *data;
  761. forced = tor_tls_get_forced_write_size(tls);
  762. if (forced > sz)
  763. sz = forced;
  764. if (chunk) {
  765. data = chunk->data;
  766. tor_assert(sz <= chunk->datalen);
  767. } else {
  768. data = NULL;
  769. tor_assert(sz == 0);
  770. }
  771. r = tor_tls_write(tls, data, sz);
  772. if (r < 0)
  773. return r;
  774. if (*buf_flushlen > (size_t)r)
  775. *buf_flushlen -= r;
  776. else
  777. *buf_flushlen = 0;
  778. buf_remove_from_front(buf, r);
  779. log_debug(LD_NET,"flushed %d bytes, %d ready to flush, %d remain.",
  780. r,(int)*buf_flushlen,(int)buf->datalen);
  781. return r;
  782. }
  783. /** Write data from <b>buf</b> to the socket <b>s</b>. Write at most
  784. * <b>sz</b> bytes, decrement *<b>buf_flushlen</b> by
  785. * the number of bytes actually written, and remove the written bytes
  786. * from the buffer. Return the number of bytes written on success,
  787. * -1 on failure. Return 0 if write() would block.
  788. */
  789. int
  790. flush_buf(tor_socket_t s, buf_t *buf, size_t sz, size_t *buf_flushlen)
  791. {
  792. /* XXXX024 It's stupid to overload the return values for these functions:
  793. * "error status" and "number of bytes flushed" are not mutually exclusive.
  794. */
  795. int r;
  796. size_t flushed = 0;
  797. tor_assert(buf_flushlen);
  798. tor_assert(SOCKET_OK(s));
  799. tor_assert(*buf_flushlen <= buf->datalen);
  800. tor_assert(sz <= *buf_flushlen);
  801. check();
  802. while (sz) {
  803. size_t flushlen0;
  804. tor_assert(buf->head);
  805. if (buf->head->datalen >= sz)
  806. flushlen0 = sz;
  807. else
  808. flushlen0 = buf->head->datalen;
  809. r = flush_chunk(s, buf, buf->head, flushlen0, buf_flushlen);
  810. check();
  811. if (r < 0)
  812. return r;
  813. flushed += r;
  814. sz -= r;
  815. if (r == 0 || (size_t)r < flushlen0) /* can't flush any more now. */
  816. break;
  817. }
  818. tor_assert(flushed < INT_MAX);
  819. return (int)flushed;
  820. }
  821. /** As flush_buf(), but writes data to a TLS connection. Can write more than
  822. * <b>flushlen</b> bytes.
  823. */
  824. int
  825. flush_buf_tls(tor_tls_t *tls, buf_t *buf, size_t flushlen,
  826. size_t *buf_flushlen)
  827. {
  828. int r;
  829. size_t flushed = 0;
  830. ssize_t sz;
  831. tor_assert(buf_flushlen);
  832. tor_assert(*buf_flushlen <= buf->datalen);
  833. tor_assert(flushlen <= *buf_flushlen);
  834. sz = (ssize_t) flushlen;
  835. /* we want to let tls write even if flushlen is zero, because it might
  836. * have a partial record pending */
  837. check_no_tls_errors();
  838. check();
  839. do {
  840. size_t flushlen0;
  841. if (buf->head) {
  842. if ((ssize_t)buf->head->datalen >= sz)
  843. flushlen0 = sz;
  844. else
  845. flushlen0 = buf->head->datalen;
  846. } else {
  847. flushlen0 = 0;
  848. }
  849. r = flush_chunk_tls(tls, buf, buf->head, flushlen0, buf_flushlen);
  850. check();
  851. if (r < 0)
  852. return r;
  853. flushed += r;
  854. sz -= r;
  855. if (r == 0) /* Can't flush any more now. */
  856. break;
  857. } while (sz > 0);
  858. tor_assert(flushed < INT_MAX);
  859. return (int)flushed;
  860. }
  861. /** Append <b>string_len</b> bytes from <b>string</b> to the end of
  862. * <b>buf</b>.
  863. *
  864. * Return the new length of the buffer on success, -1 on failure.
  865. */
  866. int
  867. write_to_buf(const char *string, size_t string_len, buf_t *buf)
  868. {
  869. if (!string_len)
  870. return (int)buf->datalen;
  871. check();
  872. while (string_len) {
  873. size_t copy;
  874. if (!buf->tail || !CHUNK_REMAINING_CAPACITY(buf->tail))
  875. buf_add_chunk_with_capacity(buf, string_len, 1);
  876. copy = CHUNK_REMAINING_CAPACITY(buf->tail);
  877. if (copy > string_len)
  878. copy = string_len;
  879. memcpy(CHUNK_WRITE_PTR(buf->tail), string, copy);
  880. string_len -= copy;
  881. string += copy;
  882. buf->datalen += copy;
  883. buf->tail->datalen += copy;
  884. }
  885. check();
  886. tor_assert(buf->datalen < INT_MAX);
  887. return (int)buf->datalen;
  888. }
  889. /** Helper: copy the first <b>string_len</b> bytes from <b>buf</b>
  890. * onto <b>string</b>.
  891. */
  892. static INLINE void
  893. peek_from_buf(char *string, size_t string_len, const buf_t *buf)
  894. {
  895. chunk_t *chunk;
  896. tor_assert(string);
  897. /* make sure we don't ask for too much */
  898. tor_assert(string_len <= buf->datalen);
  899. /* assert_buf_ok(buf); */
  900. chunk = buf->head;
  901. while (string_len) {
  902. size_t copy = string_len;
  903. tor_assert(chunk);
  904. if (chunk->datalen < copy)
  905. copy = chunk->datalen;
  906. memcpy(string, chunk->data, copy);
  907. string_len -= copy;
  908. string += copy;
  909. chunk = chunk->next;
  910. }
  911. }
  912. /** Remove <b>string_len</b> bytes from the front of <b>buf</b>, and store
  913. * them into <b>string</b>. Return the new buffer size. <b>string_len</b>
  914. * must be \<= the number of bytes on the buffer.
  915. */
  916. int
  917. fetch_from_buf(char *string, size_t string_len, buf_t *buf)
  918. {
  919. /* There must be string_len bytes in buf; write them onto string,
  920. * then memmove buf back (that is, remove them from buf).
  921. *
  922. * Return the number of bytes still on the buffer. */
  923. check();
  924. peek_from_buf(string, string_len, buf);
  925. buf_remove_from_front(buf, string_len);
  926. check();
  927. tor_assert(buf->datalen < INT_MAX);
  928. return (int)buf->datalen;
  929. }
  930. /** True iff the cell command <b>command</b> is one that implies a
  931. * variable-length cell in Tor link protocol <b>linkproto</b>. */
  932. static INLINE int
  933. cell_command_is_var_length(uint8_t command, int linkproto)
  934. {
  935. /* If linkproto is v2 (2), CELL_VERSIONS is the only variable-length cells
  936. * work as implemented here. If it's 1, there are no variable-length cells.
  937. * Tor does not support other versions right now, and so can't negotiate
  938. * them.
  939. */
  940. switch (linkproto) {
  941. case 1:
  942. /* Link protocol version 1 has no variable-length cells. */
  943. return 0;
  944. case 2:
  945. /* In link protocol version 2, VERSIONS is the only variable-length cell */
  946. return command == CELL_VERSIONS;
  947. case 0:
  948. case 3:
  949. default:
  950. /* In link protocol version 3 and later, and in version "unknown",
  951. * commands 128 and higher indicate variable-length. VERSIONS is
  952. * grandfathered in. */
  953. return command == CELL_VERSIONS || command >= 128;
  954. }
  955. }
  956. /** Check <b>buf</b> for a variable-length cell according to the rules of link
  957. * protocol version <b>linkproto</b>. If one is found, pull it off the buffer
  958. * and assign a newly allocated var_cell_t to *<b>out</b>, and return 1.
  959. * Return 0 if whatever is on the start of buf_t is not a variable-length
  960. * cell. Return 1 and set *<b>out</b> to NULL if there seems to be the start
  961. * of a variable-length cell on <b>buf</b>, but the whole thing isn't there
  962. * yet. */
  963. int
  964. fetch_var_cell_from_buf(buf_t *buf, var_cell_t **out, int linkproto)
  965. {
  966. char hdr[VAR_CELL_MAX_HEADER_SIZE];
  967. var_cell_t *result;
  968. uint8_t command;
  969. uint16_t length;
  970. const int wide_circ_ids = linkproto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
  971. const int circ_id_len = get_circ_id_size(wide_circ_ids);
  972. const unsigned header_len = get_var_cell_header_size(wide_circ_ids);
  973. check();
  974. *out = NULL;
  975. if (buf->datalen < header_len)
  976. return 0;
  977. peek_from_buf(hdr, sizeof(hdr), buf);
  978. command = get_uint8(hdr + circ_id_len);
  979. if (!(cell_command_is_var_length(command, linkproto)))
  980. return 0;
  981. length = ntohs(get_uint16(hdr + circ_id_len + 1));
  982. if (buf->datalen < (size_t)(header_len+length))
  983. return 1;
  984. result = var_cell_new(length);
  985. result->command = command;
  986. if (wide_circ_ids)
  987. result->circ_id = ntohl(get_uint32(hdr));
  988. else
  989. result->circ_id = ntohs(get_uint16(hdr));
  990. buf_remove_from_front(buf, header_len);
  991. peek_from_buf((char*) result->payload, length, buf);
  992. buf_remove_from_front(buf, length);
  993. check();
  994. *out = result;
  995. return 1;
  996. }
  997. #ifdef USE_BUFFEREVENTS
  998. /** Try to read <b>n</b> bytes from <b>buf</b> at <b>pos</b> (which may be
  999. * NULL for the start of the buffer), copying the data only if necessary. Set
  1000. * *<b>data_out</b> to a pointer to the desired bytes. Set <b>free_out</b>
  1001. * to 1 if we needed to malloc *<b>data</b> because the original bytes were
  1002. * noncontiguous; 0 otherwise. Return the number of bytes actually available
  1003. * at *<b>data_out</b>.
  1004. */
  1005. static ssize_t
  1006. inspect_evbuffer(struct evbuffer *buf, char **data_out, size_t n,
  1007. int *free_out, struct evbuffer_ptr *pos)
  1008. {
  1009. int n_vecs, i;
  1010. if (evbuffer_get_length(buf) < n)
  1011. n = evbuffer_get_length(buf);
  1012. if (n == 0)
  1013. return 0;
  1014. n_vecs = evbuffer_peek(buf, n, pos, NULL, 0);
  1015. tor_assert(n_vecs > 0);
  1016. if (n_vecs == 1) {
  1017. struct evbuffer_iovec v;
  1018. i = evbuffer_peek(buf, n, pos, &v, 1);
  1019. tor_assert(i == 1);
  1020. *data_out = v.iov_base;
  1021. *free_out = 0;
  1022. return v.iov_len;
  1023. } else {
  1024. ev_ssize_t copied;
  1025. *data_out = tor_malloc(n);
  1026. *free_out = 1;
  1027. copied = evbuffer_copyout(buf, *data_out, n);
  1028. tor_assert(copied >= 0 && (size_t)copied == n);
  1029. return copied;
  1030. }
  1031. }
  1032. /** As fetch_var_cell_from_buf, buf works on an evbuffer. */
  1033. int
  1034. fetch_var_cell_from_evbuffer(struct evbuffer *buf, var_cell_t **out,
  1035. int linkproto)
  1036. {
  1037. char *hdr = NULL;
  1038. int free_hdr = 0;
  1039. size_t n;
  1040. size_t buf_len;
  1041. uint8_t command;
  1042. uint16_t cell_length;
  1043. var_cell_t *cell;
  1044. int result = 0;
  1045. const int wide_circ_ids = linkproto >= MIN_LINK_PROTO_FOR_WIDE_CIRC_IDS;
  1046. const int circ_id_len = get_circ_id_size(wide_circ_ids);
  1047. const unsigned header_len = get_var_cell_header_size(wide_circ_ids);
  1048. *out = NULL;
  1049. buf_len = evbuffer_get_length(buf);
  1050. if (buf_len < header_len)
  1051. return 0;
  1052. n = inspect_evbuffer(buf, &hdr, header_len, &free_hdr, NULL);
  1053. tor_assert(n >= header_len);
  1054. command = get_uint8(hdr + circ_id_len);
  1055. if (!(cell_command_is_var_length(command, linkproto))) {
  1056. goto done;
  1057. }
  1058. cell_length = ntohs(get_uint16(hdr + circ_id_len + 1));
  1059. if (buf_len < (size_t)(header_len+cell_length)) {
  1060. result = 1; /* Not all here yet. */
  1061. goto done;
  1062. }
  1063. cell = var_cell_new(cell_length);
  1064. cell->command = command;
  1065. if (wide_circ_ids)
  1066. cell->circ_id = ntohl(get_uint32(hdr));
  1067. else
  1068. cell->circ_id = ntohs(get_uint16(hdr));
  1069. evbuffer_drain(buf, header_len);
  1070. evbuffer_remove(buf, cell->payload, cell_length);
  1071. *out = cell;
  1072. result = 1;
  1073. done:
  1074. if (free_hdr && hdr)
  1075. tor_free(hdr);
  1076. return result;
  1077. }
  1078. #endif
  1079. /** Move up to *<b>buf_flushlen</b> bytes from <b>buf_in</b> to
  1080. * <b>buf_out</b>, and modify *<b>buf_flushlen</b> appropriately.
  1081. * Return the number of bytes actually copied.
  1082. */
  1083. int
  1084. move_buf_to_buf(buf_t *buf_out, buf_t *buf_in, size_t *buf_flushlen)
  1085. {
  1086. /* We can do way better here, but this doesn't turn up in any profiles. */
  1087. char b[4096];
  1088. size_t cp, len;
  1089. len = *buf_flushlen;
  1090. if (len > buf_in->datalen)
  1091. len = buf_in->datalen;
  1092. cp = len; /* Remember the number of bytes we intend to copy. */
  1093. tor_assert(cp < INT_MAX);
  1094. while (len) {
  1095. /* This isn't the most efficient implementation one could imagine, since
  1096. * it does two copies instead of 1, but I kinda doubt that this will be
  1097. * critical path. */
  1098. size_t n = len > sizeof(b) ? sizeof(b) : len;
  1099. fetch_from_buf(b, n, buf_in);
  1100. write_to_buf(b, n, buf_out);
  1101. len -= n;
  1102. }
  1103. *buf_flushlen -= cp;
  1104. return (int)cp;
  1105. }
  1106. /** Internal structure: represents a position in a buffer. */
  1107. typedef struct buf_pos_t {
  1108. const chunk_t *chunk; /**< Which chunk are we pointing to? */
  1109. int pos;/**< Which character inside the chunk's data are we pointing to? */
  1110. size_t chunk_pos; /**< Total length of all previous chunks. */
  1111. } buf_pos_t;
  1112. /** Initialize <b>out</b> to point to the first character of <b>buf</b>.*/
  1113. static void
  1114. buf_pos_init(const buf_t *buf, buf_pos_t *out)
  1115. {
  1116. out->chunk = buf->head;
  1117. out->pos = 0;
  1118. out->chunk_pos = 0;
  1119. }
  1120. /** Advance <b>out</b> to the first appearance of <b>ch</b> at the current
  1121. * position of <b>out</b>, or later. Return -1 if no instances are found;
  1122. * otherwise returns the absolute position of the character. */
  1123. static off_t
  1124. buf_find_pos_of_char(char ch, buf_pos_t *out)
  1125. {
  1126. const chunk_t *chunk;
  1127. int pos;
  1128. tor_assert(out);
  1129. if (out->chunk) {
  1130. if (out->chunk->datalen) {
  1131. tor_assert(out->pos < (off_t)out->chunk->datalen);
  1132. } else {
  1133. tor_assert(out->pos == 0);
  1134. }
  1135. }
  1136. pos = out->pos;
  1137. for (chunk = out->chunk; chunk; chunk = chunk->next) {
  1138. char *cp = memchr(chunk->data+pos, ch, chunk->datalen - pos);
  1139. if (cp) {
  1140. out->chunk = chunk;
  1141. tor_assert(cp - chunk->data < INT_MAX);
  1142. out->pos = (int)(cp - chunk->data);
  1143. return out->chunk_pos + out->pos;
  1144. } else {
  1145. out->chunk_pos += chunk->datalen;
  1146. pos = 0;
  1147. }
  1148. }
  1149. return -1;
  1150. }
  1151. /** Advance <b>pos</b> by a single character, if there are any more characters
  1152. * in the buffer. Returns 0 on success, -1 on failure. */
  1153. static INLINE int
  1154. buf_pos_inc(buf_pos_t *pos)
  1155. {
  1156. ++pos->pos;
  1157. if (pos->pos == (off_t)pos->chunk->datalen) {
  1158. if (!pos->chunk->next)
  1159. return -1;
  1160. pos->chunk_pos += pos->chunk->datalen;
  1161. pos->chunk = pos->chunk->next;
  1162. pos->pos = 0;
  1163. }
  1164. return 0;
  1165. }
  1166. /** Return true iff the <b>n</b>-character string in <b>s</b> appears
  1167. * (verbatim) at <b>pos</b>. */
  1168. static int
  1169. buf_matches_at_pos(const buf_pos_t *pos, const char *s, size_t n)
  1170. {
  1171. buf_pos_t p;
  1172. if (!n)
  1173. return 1;
  1174. memcpy(&p, pos, sizeof(p));
  1175. while (1) {
  1176. char ch = p.chunk->data[p.pos];
  1177. if (ch != *s)
  1178. return 0;
  1179. ++s;
  1180. /* If we're out of characters that don't match, we match. Check this
  1181. * _before_ we test incrementing pos, in case we're at the end of the
  1182. * string. */
  1183. if (--n == 0)
  1184. return 1;
  1185. if (buf_pos_inc(&p)<0)
  1186. return 0;
  1187. }
  1188. }
  1189. /** Return the first position in <b>buf</b> at which the <b>n</b>-character
  1190. * string <b>s</b> occurs, or -1 if it does not occur. */
  1191. /*private*/ int
  1192. buf_find_string_offset(const buf_t *buf, const char *s, size_t n)
  1193. {
  1194. buf_pos_t pos;
  1195. buf_pos_init(buf, &pos);
  1196. while (buf_find_pos_of_char(*s, &pos) >= 0) {
  1197. if (buf_matches_at_pos(&pos, s, n)) {
  1198. tor_assert(pos.chunk_pos + pos.pos < INT_MAX);
  1199. return (int)(pos.chunk_pos + pos.pos);
  1200. } else {
  1201. if (buf_pos_inc(&pos)<0)
  1202. return -1;
  1203. }
  1204. }
  1205. return -1;
  1206. }
  1207. /** There is a (possibly incomplete) http statement on <b>buf</b>, of the
  1208. * form "\%s\\r\\n\\r\\n\%s", headers, body. (body may contain NULs.)
  1209. * If a) the headers include a Content-Length field and all bytes in
  1210. * the body are present, or b) there's no Content-Length field and
  1211. * all headers are present, then:
  1212. *
  1213. * - strdup headers into <b>*headers_out</b>, and NUL-terminate it.
  1214. * - memdup body into <b>*body_out</b>, and NUL-terminate it.
  1215. * - Then remove them from <b>buf</b>, and return 1.
  1216. *
  1217. * - If headers or body is NULL, discard that part of the buf.
  1218. * - If a headers or body doesn't fit in the arg, return -1.
  1219. * (We ensure that the headers or body don't exceed max len,
  1220. * _even if_ we're planning to discard them.)
  1221. * - If force_complete is true, then succeed even if not all of the
  1222. * content has arrived.
  1223. *
  1224. * Else, change nothing and return 0.
  1225. */
  1226. int
  1227. fetch_from_buf_http(buf_t *buf,
  1228. char **headers_out, size_t max_headerlen,
  1229. char **body_out, size_t *body_used, size_t max_bodylen,
  1230. int force_complete)
  1231. {
  1232. char *headers, *p;
  1233. size_t headerlen, bodylen, contentlen;
  1234. int crlf_offset;
  1235. check();
  1236. if (!buf->head)
  1237. return 0;
  1238. crlf_offset = buf_find_string_offset(buf, "\r\n\r\n", 4);
  1239. if (crlf_offset > (int)max_headerlen ||
  1240. (crlf_offset < 0 && buf->datalen > max_headerlen)) {
  1241. log_debug(LD_HTTP,"headers too long.");
  1242. return -1;
  1243. } else if (crlf_offset < 0) {
  1244. log_debug(LD_HTTP,"headers not all here yet.");
  1245. return 0;
  1246. }
  1247. /* Okay, we have a full header. Make sure it all appears in the first
  1248. * chunk. */
  1249. if ((int)buf->head->datalen < crlf_offset + 4)
  1250. buf_pullup(buf, crlf_offset+4, 0);
  1251. headerlen = crlf_offset + 4;
  1252. headers = buf->head->data;
  1253. bodylen = buf->datalen - headerlen;
  1254. log_debug(LD_HTTP,"headerlen %d, bodylen %d.", (int)headerlen, (int)bodylen);
  1255. if (max_headerlen <= headerlen) {
  1256. log_warn(LD_HTTP,"headerlen %d larger than %d. Failing.",
  1257. (int)headerlen, (int)max_headerlen-1);
  1258. return -1;
  1259. }
  1260. if (max_bodylen <= bodylen) {
  1261. log_warn(LD_HTTP,"bodylen %d larger than %d. Failing.",
  1262. (int)bodylen, (int)max_bodylen-1);
  1263. return -1;
  1264. }
  1265. #define CONTENT_LENGTH "\r\nContent-Length: "
  1266. p = (char*) tor_memstr(headers, headerlen, CONTENT_LENGTH);
  1267. if (p) {
  1268. int i;
  1269. i = atoi(p+strlen(CONTENT_LENGTH));
  1270. if (i < 0) {
  1271. log_warn(LD_PROTOCOL, "Content-Length is less than zero; it looks like "
  1272. "someone is trying to crash us.");
  1273. return -1;
  1274. }
  1275. contentlen = i;
  1276. /* if content-length is malformed, then our body length is 0. fine. */
  1277. log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
  1278. if (bodylen < contentlen) {
  1279. if (!force_complete) {
  1280. log_debug(LD_HTTP,"body not all here yet.");
  1281. return 0; /* not all there yet */
  1282. }
  1283. }
  1284. if (bodylen > contentlen) {
  1285. bodylen = contentlen;
  1286. log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
  1287. }
  1288. }
  1289. /* all happy. copy into the appropriate places, and return 1 */
  1290. if (headers_out) {
  1291. *headers_out = tor_malloc(headerlen+1);
  1292. fetch_from_buf(*headers_out, headerlen, buf);
  1293. (*headers_out)[headerlen] = 0; /* NUL terminate it */
  1294. }
  1295. if (body_out) {
  1296. tor_assert(body_used);
  1297. *body_used = bodylen;
  1298. *body_out = tor_malloc(bodylen+1);
  1299. fetch_from_buf(*body_out, bodylen, buf);
  1300. (*body_out)[bodylen] = 0; /* NUL terminate it */
  1301. }
  1302. check();
  1303. return 1;
  1304. }
  1305. #ifdef USE_BUFFEREVENTS
  1306. /** As fetch_from_buf_http, buf works on an evbuffer. */
  1307. int
  1308. fetch_from_evbuffer_http(struct evbuffer *buf,
  1309. char **headers_out, size_t max_headerlen,
  1310. char **body_out, size_t *body_used, size_t max_bodylen,
  1311. int force_complete)
  1312. {
  1313. struct evbuffer_ptr crlf, content_length;
  1314. size_t headerlen, bodylen, contentlen;
  1315. /* Find the first \r\n\r\n in the buffer */
  1316. crlf = evbuffer_search(buf, "\r\n\r\n", 4, NULL);
  1317. if (crlf.pos < 0) {
  1318. /* We didn't find one. */
  1319. if (evbuffer_get_length(buf) > max_headerlen)
  1320. return -1; /* Headers too long. */
  1321. return 0; /* Headers not here yet. */
  1322. } else if (crlf.pos > (int)max_headerlen) {
  1323. return -1; /* Headers too long. */
  1324. }
  1325. headerlen = crlf.pos + 4; /* Skip over the \r\n\r\n */
  1326. bodylen = evbuffer_get_length(buf) - headerlen;
  1327. if (bodylen > max_bodylen)
  1328. return -1; /* body too long */
  1329. /* Look for the first occurrence of CONTENT_LENGTH insize buf before the
  1330. * crlfcrlf */
  1331. content_length = evbuffer_search_range(buf, CONTENT_LENGTH,
  1332. strlen(CONTENT_LENGTH), NULL, &crlf);
  1333. if (content_length.pos >= 0) {
  1334. /* We found a content_length: parse it and figure out if the body is here
  1335. * yet. */
  1336. struct evbuffer_ptr eol;
  1337. char *data = NULL;
  1338. int free_data = 0;
  1339. int n, i;
  1340. n = evbuffer_ptr_set(buf, &content_length, strlen(CONTENT_LENGTH),
  1341. EVBUFFER_PTR_ADD);
  1342. tor_assert(n == 0);
  1343. eol = evbuffer_search_eol(buf, &content_length, NULL, EVBUFFER_EOL_CRLF);
  1344. tor_assert(eol.pos > content_length.pos);
  1345. tor_assert(eol.pos <= crlf.pos);
  1346. inspect_evbuffer(buf, &data, eol.pos - content_length.pos, &free_data,
  1347. &content_length);
  1348. i = atoi(data);
  1349. if (free_data)
  1350. tor_free(data);
  1351. if (i < 0) {
  1352. log_warn(LD_PROTOCOL, "Content-Length is less than zero; it looks like "
  1353. "someone is trying to crash us.");
  1354. return -1;
  1355. }
  1356. contentlen = i;
  1357. /* if content-length is malformed, then our body length is 0. fine. */
  1358. log_debug(LD_HTTP,"Got a contentlen of %d.",(int)contentlen);
  1359. if (bodylen < contentlen) {
  1360. if (!force_complete) {
  1361. log_debug(LD_HTTP,"body not all here yet.");
  1362. return 0; /* not all there yet */
  1363. }
  1364. }
  1365. if (bodylen > contentlen) {
  1366. bodylen = contentlen;
  1367. log_debug(LD_HTTP,"bodylen reduced to %d.",(int)bodylen);
  1368. }
  1369. }
  1370. if (headers_out) {
  1371. *headers_out = tor_malloc(headerlen+1);
  1372. evbuffer_remove(buf, *headers_out, headerlen);
  1373. (*headers_out)[headerlen] = '\0';
  1374. }
  1375. if (body_out) {
  1376. tor_assert(headers_out);
  1377. tor_assert(body_used);
  1378. *body_used = bodylen;
  1379. *body_out = tor_malloc(bodylen+1);
  1380. evbuffer_remove(buf, *body_out, bodylen);
  1381. (*body_out)[bodylen] = '\0';
  1382. }
  1383. return 1;
  1384. }
  1385. #endif
  1386. /**
  1387. * Wait this many seconds before warning the user about using SOCKS unsafely
  1388. * again (requires that WarnUnsafeSocks is turned on). */
  1389. #define SOCKS_WARN_INTERVAL 5
  1390. /** Warn that the user application has made an unsafe socks request using
  1391. * protocol <b>socks_protocol</b> on port <b>port</b>. Don't warn more than
  1392. * once per SOCKS_WARN_INTERVAL, unless <b>safe_socks</b> is set. */
  1393. static void
  1394. log_unsafe_socks_warning(int socks_protocol, const char *address,
  1395. uint16_t port, int safe_socks)
  1396. {
  1397. static ratelim_t socks_ratelim = RATELIM_INIT(SOCKS_WARN_INTERVAL);
  1398. const or_options_t *options = get_options();
  1399. if (! options->WarnUnsafeSocks)
  1400. return;
  1401. if (safe_socks) {
  1402. log_fn_ratelim(&socks_ratelim, LOG_WARN, LD_APP,
  1403. "Your application (using socks%d to port %d) is giving "
  1404. "Tor only an IP address. Applications that do DNS resolves "
  1405. "themselves may leak information. Consider using Socks4A "
  1406. "(e.g. via privoxy or socat) instead. For more information, "
  1407. "please see https://wiki.torproject.org/TheOnionRouter/"
  1408. "TorFAQ#SOCKSAndDNS.%s",
  1409. socks_protocol,
  1410. (int)port,
  1411. safe_socks ? " Rejecting." : "");
  1412. }
  1413. control_event_client_status(LOG_WARN,
  1414. "DANGEROUS_SOCKS PROTOCOL=SOCKS%d ADDRESS=%s:%d",
  1415. socks_protocol, address, (int)port);
  1416. }
  1417. /** Do not attempt to parse socks messages longer than this. This value is
  1418. * actually significantly higher than the longest possible socks message. */
  1419. #define MAX_SOCKS_MESSAGE_LEN 512
  1420. /** Return a new socks_request_t. */
  1421. socks_request_t *
  1422. socks_request_new(void)
  1423. {
  1424. return tor_malloc_zero(sizeof(socks_request_t));
  1425. }
  1426. /** Free all storage held in the socks_request_t <b>req</b>. */
  1427. void
  1428. socks_request_free(socks_request_t *req)
  1429. {
  1430. if (!req)
  1431. return;
  1432. if (req->username) {
  1433. memwipe(req->username, 0x10, req->usernamelen);
  1434. tor_free(req->username);
  1435. }
  1436. if (req->password) {
  1437. memwipe(req->password, 0x04, req->passwordlen);
  1438. tor_free(req->password);
  1439. }
  1440. memwipe(req, 0xCC, sizeof(socks_request_t));
  1441. tor_free(req);
  1442. }
  1443. /** There is a (possibly incomplete) socks handshake on <b>buf</b>, of one
  1444. * of the forms
  1445. * - socks4: "socksheader username\\0"
  1446. * - socks4a: "socksheader username\\0 destaddr\\0"
  1447. * - socks5 phase one: "version #methods methods"
  1448. * - socks5 phase two: "version command 0 addresstype..."
  1449. * If it's a complete and valid handshake, and destaddr fits in
  1450. * MAX_SOCKS_ADDR_LEN bytes, then pull the handshake off the buf,
  1451. * assign to <b>req</b>, and return 1.
  1452. *
  1453. * If it's invalid or too big, return -1.
  1454. *
  1455. * Else it's not all there yet, leave buf alone and return 0.
  1456. *
  1457. * If you want to specify the socks reply, write it into <b>req->reply</b>
  1458. * and set <b>req->replylen</b>, else leave <b>req->replylen</b> alone.
  1459. *
  1460. * If <b>log_sockstype</b> is non-zero, then do a notice-level log of whether
  1461. * the connection is possibly leaking DNS requests locally or not.
  1462. *
  1463. * If <b>safe_socks</b> is true, then reject unsafe socks protocols.
  1464. *
  1465. * If returning 0 or -1, <b>req->address</b> and <b>req->port</b> are
  1466. * undefined.
  1467. */
  1468. int
  1469. fetch_from_buf_socks(buf_t *buf, socks_request_t *req,
  1470. int log_sockstype, int safe_socks)
  1471. {
  1472. int res;
  1473. ssize_t n_drain;
  1474. size_t want_length = 128;
  1475. if (buf->datalen < 2) /* version and another byte */
  1476. return 0;
  1477. do {
  1478. n_drain = 0;
  1479. buf_pullup(buf, want_length, 0);
  1480. tor_assert(buf->head && buf->head->datalen >= 2);
  1481. want_length = 0;
  1482. res = parse_socks(buf->head->data, buf->head->datalen, req, log_sockstype,
  1483. safe_socks, &n_drain, &want_length);
  1484. if (n_drain < 0)
  1485. buf_clear(buf);
  1486. else if (n_drain > 0)
  1487. buf_remove_from_front(buf, n_drain);
  1488. } while (res == 0 && buf->head && want_length < buf->datalen &&
  1489. buf->datalen >= 2);
  1490. return res;
  1491. }
  1492. #ifdef USE_BUFFEREVENTS
  1493. /* As fetch_from_buf_socks(), but targets an evbuffer instead. */
  1494. int
  1495. fetch_from_evbuffer_socks(struct evbuffer *buf, socks_request_t *req,
  1496. int log_sockstype, int safe_socks)
  1497. {
  1498. char *data;
  1499. ssize_t n_drain;
  1500. size_t datalen, buflen, want_length;
  1501. int res;
  1502. buflen = evbuffer_get_length(buf);
  1503. if (buflen < 2)
  1504. return 0;
  1505. {
  1506. /* See if we can find the socks request in the first chunk of the buffer.
  1507. */
  1508. struct evbuffer_iovec v;
  1509. int i;
  1510. n_drain = 0;
  1511. i = evbuffer_peek(buf, -1, NULL, &v, 1);
  1512. tor_assert(i == 1);
  1513. data = v.iov_base;
  1514. datalen = v.iov_len;
  1515. want_length = 0;
  1516. res = parse_socks(data, datalen, req, log_sockstype,
  1517. safe_socks, &n_drain, &want_length);
  1518. if (n_drain < 0)
  1519. evbuffer_drain(buf, evbuffer_get_length(buf));
  1520. else if (n_drain > 0)
  1521. evbuffer_drain(buf, n_drain);
  1522. if (res)
  1523. return res;
  1524. }
  1525. /* Okay, the first chunk of the buffer didn't have a complete socks request.
  1526. * That means that either we don't have a whole socks request at all, or
  1527. * it's gotten split up. We're going to try passing parse_socks() bigger
  1528. * and bigger chunks until either it says "Okay, I got it", or it says it
  1529. * will need more data than we currently have. */
  1530. /* Loop while we have more data that we haven't given parse_socks() yet. */
  1531. do {
  1532. int free_data = 0;
  1533. const size_t last_wanted = want_length;
  1534. n_drain = 0;
  1535. data = NULL;
  1536. datalen = inspect_evbuffer(buf, &data, want_length, &free_data, NULL);
  1537. want_length = 0;
  1538. res = parse_socks(data, datalen, req, log_sockstype,
  1539. safe_socks, &n_drain, &want_length);
  1540. if (free_data)
  1541. tor_free(data);
  1542. if (n_drain < 0)
  1543. evbuffer_drain(buf, evbuffer_get_length(buf));
  1544. else if (n_drain > 0)
  1545. evbuffer_drain(buf, n_drain);
  1546. if (res == 0 && n_drain == 0 && want_length <= last_wanted) {
  1547. /* If we drained nothing, and we didn't ask for more than last time,
  1548. * then we probably wanted more data than the buffer actually had,
  1549. * and we're finding out that we're not satisified with it. It's
  1550. * time to break until we have more data. */
  1551. break;
  1552. }
  1553. buflen = evbuffer_get_length(buf);
  1554. } while (res == 0 && want_length <= buflen && buflen >= 2);
  1555. return res;
  1556. }
  1557. #endif
  1558. /** Implementation helper to implement fetch_from_*_socks. Instead of looking
  1559. * at a buffer's contents, we look at the <b>datalen</b> bytes of data in
  1560. * <b>data</b>. Instead of removing data from the buffer, we set
  1561. * <b>drain_out</b> to the amount of data that should be removed (or -1 if the
  1562. * buffer should be cleared). Instead of pulling more data into the first
  1563. * chunk of the buffer, we set *<b>want_length_out</b> to the number of bytes
  1564. * we'd like to see in the input buffer, if they're available. */
  1565. static int
  1566. parse_socks(const char *data, size_t datalen, socks_request_t *req,
  1567. int log_sockstype, int safe_socks, ssize_t *drain_out,
  1568. size_t *want_length_out)
  1569. {
  1570. unsigned int len;
  1571. char tmpbuf[TOR_ADDR_BUF_LEN+1];
  1572. tor_addr_t destaddr;
  1573. uint32_t destip;
  1574. uint8_t socksver;
  1575. char *next, *startaddr;
  1576. unsigned char usernamelen, passlen;
  1577. struct in_addr in;
  1578. if (datalen < 2) {
  1579. /* We always need at least 2 bytes. */
  1580. *want_length_out = 2;
  1581. return 0;
  1582. }
  1583. if (req->socks_version == 5 && !req->got_auth) {
  1584. /* See if we have received authentication. Strictly speaking, we should
  1585. also check whether we actually negotiated username/password
  1586. authentication. But some broken clients will send us authentication
  1587. even if we negotiated SOCKS_NO_AUTH. */
  1588. if (*data == 1) { /* username/pass version 1 */
  1589. /* Format is: authversion [1 byte] == 1
  1590. usernamelen [1 byte]
  1591. username [usernamelen bytes]
  1592. passlen [1 byte]
  1593. password [passlen bytes] */
  1594. usernamelen = (unsigned char)*(data + 1);
  1595. if (datalen < 2u + usernamelen + 1u) {
  1596. *want_length_out = 2u + usernamelen + 1u;
  1597. return 0;
  1598. }
  1599. passlen = (unsigned char)*(data + 2u + usernamelen);
  1600. if (datalen < 2u + usernamelen + 1u + passlen) {
  1601. *want_length_out = 2u + usernamelen + 1u + passlen;
  1602. return 0;
  1603. }
  1604. req->replylen = 2; /* 2 bytes of response */
  1605. req->reply[0] = 5;
  1606. req->reply[1] = 0; /* authentication successful */
  1607. log_debug(LD_APP,
  1608. "socks5: Accepted username/password without checking.");
  1609. if (usernamelen) {
  1610. req->username = tor_memdup(data+2u, usernamelen);
  1611. req->usernamelen = usernamelen;
  1612. }
  1613. if (passlen) {
  1614. req->password = tor_memdup(data+3u+usernamelen, passlen);
  1615. req->passwordlen = passlen;
  1616. }
  1617. *drain_out = 2u + usernamelen + 1u + passlen;
  1618. req->got_auth = 1;
  1619. *want_length_out = 7; /* Minimal socks5 sommand. */
  1620. return 0;
  1621. } else if (req->auth_type == SOCKS_USER_PASS) {
  1622. /* unknown version byte */
  1623. log_warn(LD_APP, "Socks5 username/password version %d not recognized; "
  1624. "rejecting.", (int)*data);
  1625. return -1;
  1626. }
  1627. }
  1628. socksver = *data;
  1629. switch (socksver) { /* which version of socks? */
  1630. case 5: /* socks5 */
  1631. if (req->socks_version != 5) { /* we need to negotiate a method */
  1632. unsigned char nummethods = (unsigned char)*(data+1);
  1633. int r=0;
  1634. tor_assert(!req->socks_version);
  1635. if (datalen < 2u+nummethods) {
  1636. *want_length_out = 2u+nummethods;
  1637. return 0;
  1638. }
  1639. if (!nummethods)
  1640. return -1;
  1641. req->replylen = 2; /* 2 bytes of response */
  1642. req->reply[0] = 5; /* socks5 reply */
  1643. if (memchr(data+2, SOCKS_NO_AUTH, nummethods)) {
  1644. req->reply[1] = SOCKS_NO_AUTH; /* tell client to use "none" auth
  1645. method */
  1646. req->socks_version = 5; /* remember we've already negotiated auth */
  1647. log_debug(LD_APP,"socks5: accepted method 0 (no authentication)");
  1648. r=0;
  1649. } else if (memchr(data+2, SOCKS_USER_PASS, nummethods)) {
  1650. req->auth_type = SOCKS_USER_PASS;
  1651. req->reply[1] = SOCKS_USER_PASS; /* tell client to use "user/pass"
  1652. auth method */
  1653. req->socks_version = 5; /* remember we've already negotiated auth */
  1654. log_debug(LD_APP,"socks5: accepted method 2 (username/password)");
  1655. r=0;
  1656. } else {
  1657. log_warn(LD_APP,
  1658. "socks5: offered methods don't include 'no auth' or "
  1659. "username/password. Rejecting.");
  1660. req->reply[1] = '\xFF'; /* reject all methods */
  1661. r=-1;
  1662. }
  1663. /* Remove packet from buf. Some SOCKS clients will have sent extra
  1664. * junk at this point; let's hope it's an authentication message. */
  1665. *drain_out = 2u + nummethods;
  1666. return r;
  1667. }
  1668. if (req->auth_type != SOCKS_NO_AUTH && !req->got_auth) {
  1669. log_warn(LD_APP,
  1670. "socks5: negotiated authentication, but none provided");
  1671. return -1;
  1672. }
  1673. /* we know the method; read in the request */
  1674. log_debug(LD_APP,"socks5: checking request");
  1675. if (datalen < 7) {/* basic info plus >=1 for addr plus 2 for port */
  1676. *want_length_out = 7;
  1677. return 0; /* not yet */
  1678. }
  1679. req->command = (unsigned char) *(data+1);
  1680. if (req->command != SOCKS_COMMAND_CONNECT &&
  1681. req->command != SOCKS_COMMAND_RESOLVE &&
  1682. req->command != SOCKS_COMMAND_RESOLVE_PTR) {
  1683. /* not a connect or resolve or a resolve_ptr? we don't support it. */
  1684. log_warn(LD_APP,"socks5: command %d not recognized. Rejecting.",
  1685. req->command);
  1686. return -1;
  1687. }
  1688. switch (*(data+3)) { /* address type */
  1689. case 1: /* IPv4 address */
  1690. case 4: /* IPv6 address */ {
  1691. const int is_v6 = *(data+3) == 4;
  1692. const unsigned addrlen = is_v6 ? 16 : 4;
  1693. log_debug(LD_APP,"socks5: ipv4 address type");
  1694. if (datalen < 6+addrlen) {/* ip/port there? */
  1695. *want_length_out = 6+addrlen;
  1696. return 0; /* not yet */
  1697. }
  1698. if (is_v6)
  1699. tor_addr_from_ipv6_bytes(&destaddr, data+4);
  1700. else
  1701. tor_addr_from_ipv4n(&destaddr, get_uint32(data+4));
  1702. tor_addr_to_str(tmpbuf, &destaddr, sizeof(tmpbuf), 1);
  1703. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1704. log_warn(LD_APP,
  1705. "socks5 IP takes %d bytes, which doesn't fit in %d. "
  1706. "Rejecting.",
  1707. (int)strlen(tmpbuf)+1,(int)MAX_SOCKS_ADDR_LEN);
  1708. return -1;
  1709. }
  1710. strlcpy(req->address,tmpbuf,sizeof(req->address));
  1711. req->port = ntohs(get_uint16(data+4+addrlen));
  1712. *drain_out = 6+addrlen;
  1713. if (req->command != SOCKS_COMMAND_RESOLVE_PTR &&
  1714. !addressmap_have_mapping(req->address,0)) {
  1715. log_unsafe_socks_warning(5, req->address, req->port, safe_socks);
  1716. if (safe_socks)
  1717. return -1;
  1718. }
  1719. return 1;
  1720. }
  1721. case 3: /* fqdn */
  1722. log_debug(LD_APP,"socks5: fqdn address type");
  1723. if (req->command == SOCKS_COMMAND_RESOLVE_PTR) {
  1724. log_warn(LD_APP, "socks5 received RESOLVE_PTR command with "
  1725. "hostname type. Rejecting.");
  1726. return -1;
  1727. }
  1728. len = (unsigned char)*(data+4);
  1729. if (datalen < 7+len) { /* addr/port there? */
  1730. *want_length_out = 7+len;
  1731. return 0; /* not yet */
  1732. }
  1733. if (len+1 > MAX_SOCKS_ADDR_LEN) {
  1734. log_warn(LD_APP,
  1735. "socks5 hostname is %d bytes, which doesn't fit in "
  1736. "%d. Rejecting.", len+1,MAX_SOCKS_ADDR_LEN);
  1737. return -1;
  1738. }
  1739. memcpy(req->address,data+5,len);
  1740. req->address[len] = 0;
  1741. req->port = ntohs(get_uint16(data+5+len));
  1742. *drain_out = 5+len+2;
  1743. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1744. log_warn(LD_PROTOCOL,
  1745. "Your application (using socks5 to port %d) gave Tor "
  1746. "a malformed hostname: %s. Rejecting the connection.",
  1747. req->port, escaped(req->address));
  1748. return -1;
  1749. }
  1750. if (log_sockstype)
  1751. log_notice(LD_APP,
  1752. "Your application (using socks5 to port %d) instructed "
  1753. "Tor to take care of the DNS resolution itself if "
  1754. "necessary. This is good.", req->port);
  1755. return 1;
  1756. default: /* unsupported */
  1757. log_warn(LD_APP,"socks5: unsupported address type %d. Rejecting.",
  1758. (int) *(data+3));
  1759. return -1;
  1760. }
  1761. tor_assert(0);
  1762. case 4: { /* socks4 */
  1763. enum {socks4, socks4a} socks4_prot = socks4a;
  1764. const char *authstart, *authend;
  1765. /* http://ss5.sourceforge.net/socks4.protocol.txt */
  1766. /* http://ss5.sourceforge.net/socks4A.protocol.txt */
  1767. req->socks_version = 4;
  1768. if (datalen < SOCKS4_NETWORK_LEN) {/* basic info available? */
  1769. *want_length_out = SOCKS4_NETWORK_LEN;
  1770. return 0; /* not yet */
  1771. }
  1772. // buf_pullup(buf, 1280, 0);
  1773. req->command = (unsigned char) *(data+1);
  1774. if (req->command != SOCKS_COMMAND_CONNECT &&
  1775. req->command != SOCKS_COMMAND_RESOLVE) {
  1776. /* not a connect or resolve? we don't support it. (No resolve_ptr with
  1777. * socks4.) */
  1778. log_warn(LD_APP,"socks4: command %d not recognized. Rejecting.",
  1779. req->command);
  1780. return -1;
  1781. }
  1782. req->port = ntohs(get_uint16(data+2));
  1783. destip = ntohl(get_uint32(data+4));
  1784. if ((!req->port && req->command!=SOCKS_COMMAND_RESOLVE) || !destip) {
  1785. log_warn(LD_APP,"socks4: Port or DestIP is zero. Rejecting.");
  1786. return -1;
  1787. }
  1788. if (destip >> 8) {
  1789. log_debug(LD_APP,"socks4: destip not in form 0.0.0.x.");
  1790. in.s_addr = htonl(destip);
  1791. tor_inet_ntoa(&in,tmpbuf,sizeof(tmpbuf));
  1792. if (strlen(tmpbuf)+1 > MAX_SOCKS_ADDR_LEN) {
  1793. log_debug(LD_APP,"socks4 addr (%d bytes) too long. Rejecting.",
  1794. (int)strlen(tmpbuf));
  1795. return -1;
  1796. }
  1797. log_debug(LD_APP,
  1798. "socks4: successfully read destip (%s)",
  1799. safe_str_client(tmpbuf));
  1800. socks4_prot = socks4;
  1801. }
  1802. authstart = data + SOCKS4_NETWORK_LEN;
  1803. next = memchr(authstart, 0,
  1804. datalen-SOCKS4_NETWORK_LEN);
  1805. if (!next) {
  1806. if (datalen >= 1024) {
  1807. log_debug(LD_APP, "Socks4 user name too long; rejecting.");
  1808. return -1;
  1809. }
  1810. log_debug(LD_APP,"socks4: Username not here yet.");
  1811. *want_length_out = datalen+1024; /* More than we need, but safe */
  1812. return 0;
  1813. }
  1814. authend = next;
  1815. tor_assert(next < data+datalen);
  1816. startaddr = NULL;
  1817. if (socks4_prot != socks4a &&
  1818. !addressmap_have_mapping(tmpbuf,0)) {
  1819. log_unsafe_socks_warning(4, tmpbuf, req->port, safe_socks);
  1820. if (safe_socks)
  1821. return -1;
  1822. }
  1823. if (socks4_prot == socks4a) {
  1824. if (next+1 == data+datalen) {
  1825. log_debug(LD_APP,"socks4: No part of destaddr here yet.");
  1826. *want_length_out = datalen + 1024; /* More than we need, but safe */
  1827. return 0;
  1828. }
  1829. startaddr = next+1;
  1830. next = memchr(startaddr, 0, data + datalen - startaddr);
  1831. if (!next) {
  1832. if (datalen >= 1024) {
  1833. log_debug(LD_APP,"socks4: Destaddr too long.");
  1834. return -1;
  1835. }
  1836. log_debug(LD_APP,"socks4: Destaddr not all here yet.");
  1837. *want_length_out = datalen + 1024; /* More than we need, but safe */
  1838. return 0;
  1839. }
  1840. if (MAX_SOCKS_ADDR_LEN <= next-startaddr) {
  1841. log_warn(LD_APP,"socks4: Destaddr too long. Rejecting.");
  1842. return -1;
  1843. }
  1844. // tor_assert(next < buf->cur+buf->datalen);
  1845. if (log_sockstype)
  1846. log_notice(LD_APP,
  1847. "Your application (using socks4a to port %d) instructed "
  1848. "Tor to take care of the DNS resolution itself if "
  1849. "necessary. This is good.", req->port);
  1850. }
  1851. log_debug(LD_APP,"socks4: Everything is here. Success.");
  1852. strlcpy(req->address, startaddr ? startaddr : tmpbuf,
  1853. sizeof(req->address));
  1854. if (!tor_strisprint(req->address) || strchr(req->address,'\"')) {
  1855. log_warn(LD_PROTOCOL,
  1856. "Your application (using socks4 to port %d) gave Tor "
  1857. "a malformed hostname: %s. Rejecting the connection.",
  1858. req->port, escaped(req->address));
  1859. return -1;
  1860. }
  1861. if (authend != authstart) {
  1862. req->got_auth = 1;
  1863. req->usernamelen = authend - authstart;
  1864. req->username = tor_memdup(authstart, authend - authstart);
  1865. }
  1866. /* next points to the final \0 on inbuf */
  1867. *drain_out = next - data + 1;
  1868. return 1;
  1869. }
  1870. case 'G': /* get */
  1871. case 'H': /* head */
  1872. case 'P': /* put/post */
  1873. case 'C': /* connect */
  1874. strlcpy((char*)req->reply,
  1875. "HTTP/1.0 501 Tor is not an HTTP Proxy\r\n"
  1876. "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
  1877. "<html>\n"
  1878. "<head>\n"
  1879. "<title>Tor is not an HTTP Proxy</title>\n"
  1880. "</head>\n"
  1881. "<body>\n"
  1882. "<h1>Tor is not an HTTP Proxy</h1>\n"
  1883. "<p>\n"
  1884. "It appears you have configured your web browser to use Tor as an HTTP proxy."
  1885. "\n"
  1886. "This is not correct: Tor is a SOCKS proxy, not an HTTP proxy.\n"
  1887. "Please configure your client accordingly.\n"
  1888. "</p>\n"
  1889. "<p>\n"
  1890. "See <a href=\"https://www.torproject.org/documentation.html\">"
  1891. "https://www.torproject.org/documentation.html</a> for more "
  1892. "information.\n"
  1893. "<!-- Plus this comment, to make the body response more than 512 bytes, so "
  1894. " IE will be willing to display it. Comment comment comment comment "
  1895. " comment comment comment comment comment comment comment comment.-->\n"
  1896. "</p>\n"
  1897. "</body>\n"
  1898. "</html>\n"
  1899. , MAX_SOCKS_REPLY_LEN);
  1900. req->replylen = strlen((char*)req->reply)+1;
  1901. /* fall through */
  1902. default: /* version is not socks4 or socks5 */
  1903. log_warn(LD_APP,
  1904. "Socks version %d not recognized. (Tor is not an http proxy.)",
  1905. *(data));
  1906. {
  1907. /* Tell the controller the first 8 bytes. */
  1908. char *tmp = tor_strndup(data, datalen < 8 ? datalen : 8);
  1909. control_event_client_status(LOG_WARN,
  1910. "SOCKS_UNKNOWN_PROTOCOL DATA=\"%s\"",
  1911. escaped(tmp));
  1912. tor_free(tmp);
  1913. }
  1914. return -1;
  1915. }
  1916. }
  1917. /** Inspect a reply from SOCKS server stored in <b>buf</b> according
  1918. * to <b>state</b>, removing the protocol data upon success. Return 0 on
  1919. * incomplete response, 1 on success and -1 on error, in which case
  1920. * <b>reason</b> is set to a descriptive message (free() when finished
  1921. * with it).
  1922. *
  1923. * As a special case, 2 is returned when user/pass is required
  1924. * during SOCKS5 handshake and user/pass is configured.
  1925. */
  1926. int
  1927. fetch_from_buf_socks_client(buf_t *buf, int state, char **reason)
  1928. {
  1929. ssize_t drain = 0;
  1930. int r;
  1931. if (buf->datalen < 2)
  1932. return 0;
  1933. buf_pullup(buf, MAX_SOCKS_MESSAGE_LEN, 0);
  1934. tor_assert(buf->head && buf->head->datalen >= 2);
  1935. r = parse_socks_client((uint8_t*)buf->head->data, buf->head->datalen,
  1936. state, reason, &drain);
  1937. if (drain > 0)
  1938. buf_remove_from_front(buf, drain);
  1939. else if (drain < 0)
  1940. buf_clear(buf);
  1941. return r;
  1942. }
  1943. #ifdef USE_BUFFEREVENTS
  1944. /** As fetch_from_buf_socks_client, buf works on an evbuffer */
  1945. int
  1946. fetch_from_evbuffer_socks_client(struct evbuffer *buf, int state,
  1947. char **reason)
  1948. {
  1949. ssize_t drain = 0;
  1950. uint8_t *data;
  1951. size_t datalen;
  1952. int r;
  1953. /* Linearize the SOCKS response in the buffer, up to 128 bytes.
  1954. * (parse_socks_client shouldn't need to see anything beyond that.) */
  1955. datalen = evbuffer_get_length(buf);
  1956. if (datalen > MAX_SOCKS_MESSAGE_LEN)
  1957. datalen = MAX_SOCKS_MESSAGE_LEN;
  1958. data = evbuffer_pullup(buf, datalen);
  1959. r = parse_socks_client(data, datalen, state, reason, &drain);
  1960. if (drain > 0)
  1961. evbuffer_drain(buf, drain);
  1962. else if (drain < 0)
  1963. evbuffer_drain(buf, evbuffer_get_length(buf));
  1964. return r;
  1965. }
  1966. #endif
  1967. /** Implementation logic for fetch_from_*_socks_client. */
  1968. static int
  1969. parse_socks_client(const uint8_t *data, size_t datalen,
  1970. int state, char **reason,
  1971. ssize_t *drain_out)
  1972. {
  1973. unsigned int addrlen;
  1974. *drain_out = 0;
  1975. if (datalen < 2)
  1976. return 0;
  1977. switch (state) {
  1978. case PROXY_SOCKS4_WANT_CONNECT_OK:
  1979. /* Wait for the complete response */
  1980. if (datalen < 8)
  1981. return 0;
  1982. if (data[1] != 0x5a) {
  1983. *reason = tor_strdup(socks4_response_code_to_string(data[1]));
  1984. return -1;
  1985. }
  1986. /* Success */
  1987. *drain_out = 8;
  1988. return 1;
  1989. case PROXY_SOCKS5_WANT_AUTH_METHOD_NONE:
  1990. /* we don't have any credentials */
  1991. if (data[1] != 0x00) {
  1992. *reason = tor_strdup("server doesn't support any of our "
  1993. "available authentication methods");
  1994. return -1;
  1995. }
  1996. log_info(LD_NET, "SOCKS 5 client: continuing without authentication");
  1997. *drain_out = -1;
  1998. return 1;
  1999. case PROXY_SOCKS5_WANT_AUTH_METHOD_RFC1929:
  2000. /* we have a username and password. return 1 if we can proceed without
  2001. * providing authentication, or 2 otherwise. */
  2002. switch (data[1]) {
  2003. case 0x00:
  2004. log_info(LD_NET, "SOCKS 5 client: we have auth details but server "
  2005. "doesn't require authentication.");
  2006. *drain_out = -1;
  2007. return 1;
  2008. case 0x02:
  2009. log_info(LD_NET, "SOCKS 5 client: need authentication.");
  2010. *drain_out = -1;
  2011. return 2;
  2012. /* fall through */
  2013. }
  2014. *reason = tor_strdup("server doesn't support any of our available "
  2015. "authentication methods");
  2016. return -1;
  2017. case PROXY_SOCKS5_WANT_AUTH_RFC1929_OK:
  2018. /* handle server reply to rfc1929 authentication */
  2019. if (data[1] != 0x00) {
  2020. *reason = tor_strdup("authentication failed");
  2021. return -1;
  2022. }
  2023. log_info(LD_NET, "SOCKS 5 client: authentication successful.");
  2024. *drain_out = -1;
  2025. return 1;
  2026. case PROXY_SOCKS5_WANT_CONNECT_OK:
  2027. /* response is variable length. BND.ADDR, etc, isn't needed
  2028. * (don't bother with buf_pullup()), but make sure to eat all
  2029. * the data used */
  2030. /* wait for address type field to arrive */
  2031. if (datalen < 4)
  2032. return 0;
  2033. switch (data[3]) {
  2034. case 0x01: /* ip4 */
  2035. addrlen = 4;
  2036. break;
  2037. case 0x04: /* ip6 */
  2038. addrlen = 16;
  2039. break;
  2040. case 0x03: /* fqdn (can this happen here?) */
  2041. if (datalen < 5)
  2042. return 0;
  2043. addrlen = 1 + data[4];
  2044. break;
  2045. default:
  2046. *reason = tor_strdup("invalid response to connect request");
  2047. return -1;
  2048. }
  2049. /* wait for address and port */
  2050. if (datalen < 6 + addrlen)
  2051. return 0;
  2052. if (data[1] != 0x00) {
  2053. *reason = tor_strdup(socks5_response_code_to_string(data[1]));
  2054. return -1;
  2055. }
  2056. *drain_out = 6 + addrlen;
  2057. return 1;
  2058. }
  2059. /* shouldn't get here... */
  2060. tor_assert(0);
  2061. return -1;
  2062. }
  2063. /** Return 1 iff buf looks more like it has an (obsolete) v0 controller
  2064. * command on it than any valid v1 controller command. */
  2065. int
  2066. peek_buf_has_control0_command(buf_t *buf)
  2067. {
  2068. if (buf->datalen >= 4) {
  2069. char header[4];
  2070. uint16_t cmd;
  2071. peek_from_buf(header, sizeof(header), buf);
  2072. cmd = ntohs(get_uint16(header+2));
  2073. if (cmd <= 0x14)
  2074. return 1; /* This is definitely not a v1 control command. */
  2075. }
  2076. return 0;
  2077. }
  2078. #ifdef USE_BUFFEREVENTS
  2079. int
  2080. peek_evbuffer_has_control0_command(struct evbuffer *buf)
  2081. {
  2082. int result = 0;
  2083. if (evbuffer_get_length(buf) >= 4) {
  2084. int free_out = 0;
  2085. char *data = NULL;
  2086. size_t n = inspect_evbuffer(buf, &data, 4, &free_out, NULL);
  2087. uint16_t cmd;
  2088. tor_assert(n >= 4);
  2089. cmd = ntohs(get_uint16(data+2));
  2090. if (cmd <= 0x14)
  2091. result = 1;
  2092. if (free_out)
  2093. tor_free(data);
  2094. }
  2095. return result;
  2096. }
  2097. #endif
  2098. /** Return the index within <b>buf</b> at which <b>ch</b> first appears,
  2099. * or -1 if <b>ch</b> does not appear on buf. */
  2100. static off_t
  2101. buf_find_offset_of_char(buf_t *buf, char ch)
  2102. {
  2103. chunk_t *chunk;
  2104. off_t offset = 0;
  2105. for (chunk = buf->head; chunk; chunk = chunk->next) {
  2106. char *cp = memchr(chunk->data, ch, chunk->datalen);
  2107. if (cp)
  2108. return offset + (cp - chunk->data);
  2109. else
  2110. offset += chunk->datalen;
  2111. }
  2112. return -1;
  2113. }
  2114. /** Try to read a single LF-terminated line from <b>buf</b>, and write it
  2115. * (including the LF), NUL-terminated, into the *<b>data_len</b> byte buffer
  2116. * at <b>data_out</b>. Set *<b>data_len</b> to the number of bytes in the
  2117. * line, not counting the terminating NUL. Return 1 if we read a whole line,
  2118. * return 0 if we don't have a whole line yet, and return -1 if the line
  2119. * length exceeds *<b>data_len</b>.
  2120. */
  2121. int
  2122. fetch_from_buf_line(buf_t *buf, char *data_out, size_t *data_len)
  2123. {
  2124. size_t sz;
  2125. off_t offset;
  2126. if (!buf->head)
  2127. return 0;
  2128. offset = buf_find_offset_of_char(buf, '\n');
  2129. if (offset < 0)
  2130. return 0;
  2131. sz = (size_t) offset;
  2132. if (sz+2 > *data_len) {
  2133. *data_len = sz + 2;
  2134. return -1;
  2135. }
  2136. fetch_from_buf(data_out, sz+1, buf);
  2137. data_out[sz+1] = '\0';
  2138. *data_len = sz+1;
  2139. return 1;
  2140. }
  2141. /** Compress on uncompress the <b>data_len</b> bytes in <b>data</b> using the
  2142. * zlib state <b>state</b>, appending the result to <b>buf</b>. If
  2143. * <b>done</b> is true, flush the data in the state and finish the
  2144. * compression/uncompression. Return -1 on failure, 0 on success. */
  2145. int
  2146. write_to_buf_zlib(buf_t *buf, tor_zlib_state_t *state,
  2147. const char *data, size_t data_len,
  2148. int done)
  2149. {
  2150. char *next;
  2151. size_t old_avail, avail;
  2152. int over = 0;
  2153. do {
  2154. int need_new_chunk = 0;
  2155. if (!buf->tail || ! CHUNK_REMAINING_CAPACITY(buf->tail)) {
  2156. size_t cap = data_len / 4;
  2157. buf_add_chunk_with_capacity(buf, cap, 1);
  2158. }
  2159. next = CHUNK_WRITE_PTR(buf->tail);
  2160. avail = old_avail = CHUNK_REMAINING_CAPACITY(buf->tail);
  2161. switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
  2162. case TOR_ZLIB_DONE:
  2163. over = 1;
  2164. break;
  2165. case TOR_ZLIB_ERR:
  2166. return -1;
  2167. case TOR_ZLIB_OK:
  2168. if (data_len == 0)
  2169. over = 1;
  2170. break;
  2171. case TOR_ZLIB_BUF_FULL:
  2172. if (avail) {
  2173. /* Zlib says we need more room (ZLIB_BUF_FULL). Start a new chunk
  2174. * automatically, whether were going to or not. */
  2175. need_new_chunk = 1;
  2176. }
  2177. break;
  2178. }
  2179. buf->datalen += old_avail - avail;
  2180. buf->tail->datalen += old_avail - avail;
  2181. if (need_new_chunk) {
  2182. buf_add_chunk_with_capacity(buf, data_len/4, 1);
  2183. }
  2184. } while (!over);
  2185. check();
  2186. return 0;
  2187. }
  2188. #ifdef USE_BUFFEREVENTS
  2189. int
  2190. write_to_evbuffer_zlib(struct evbuffer *buf, tor_zlib_state_t *state,
  2191. const char *data, size_t data_len,
  2192. int done)
  2193. {
  2194. char *next;
  2195. size_t old_avail, avail;
  2196. int over = 0, n;
  2197. struct evbuffer_iovec vec[1];
  2198. do {
  2199. {
  2200. size_t cap = data_len / 4;
  2201. if (cap < 128)
  2202. cap = 128;
  2203. /* XXXX NM this strategy is fragmentation-prone. We should really have
  2204. * two iovecs, and write first into the one, and then into the
  2205. * second if the first gets full. */
  2206. n = evbuffer_reserve_space(buf, cap, vec, 1);
  2207. tor_assert(n == 1);
  2208. }
  2209. next = vec[0].iov_base;
  2210. avail = old_avail = vec[0].iov_len;
  2211. switch (tor_zlib_process(state, &next, &avail, &data, &data_len, done)) {
  2212. case TOR_ZLIB_DONE:
  2213. over = 1;
  2214. break;
  2215. case TOR_ZLIB_ERR:
  2216. return -1;
  2217. case TOR_ZLIB_OK:
  2218. if (data_len == 0)
  2219. over = 1;
  2220. break;
  2221. case TOR_ZLIB_BUF_FULL:
  2222. if (avail) {
  2223. /* Zlib says we need more room (ZLIB_BUF_FULL). Start a new chunk
  2224. * automatically, whether were going to or not. */
  2225. }
  2226. break;
  2227. }
  2228. /* XXXX possible infinite loop on BUF_FULL. */
  2229. vec[0].iov_len = old_avail - avail;
  2230. evbuffer_commit_space(buf, vec, 1);
  2231. } while (!over);
  2232. check();
  2233. return 0;
  2234. }
  2235. #endif
  2236. /** Set *<b>output</b> to contain a copy of the data in *<b>input</b> */
  2237. int
  2238. generic_buffer_set_to_copy(generic_buffer_t **output,
  2239. const generic_buffer_t *input)
  2240. {
  2241. #ifdef USE_BUFFEREVENTS
  2242. struct evbuffer_ptr ptr;
  2243. size_t remaining = evbuffer_get_length(input);
  2244. if (*output) {
  2245. evbuffer_drain(*output, evbuffer_get_length(*output));
  2246. } else {
  2247. if (!(*output = evbuffer_new()))
  2248. return -1;
  2249. }
  2250. evbuffer_ptr_set((struct evbuffer*)input, &ptr, 0, EVBUFFER_PTR_SET);
  2251. while (remaining) {
  2252. struct evbuffer_iovec v[4];
  2253. int n_used, i;
  2254. n_used = evbuffer_peek((struct evbuffer*)input, -1, &ptr, v, 4);
  2255. if (n_used < 0)
  2256. return -1;
  2257. for (i=0;i<n_used;++i) {
  2258. evbuffer_add(*output, v[i].iov_base, v[i].iov_len);
  2259. tor_assert(v[i].iov_len <= remaining);
  2260. remaining -= v[i].iov_len;
  2261. evbuffer_ptr_set((struct evbuffer*)input,
  2262. &ptr, v[i].iov_len, EVBUFFER_PTR_ADD);
  2263. }
  2264. }
  2265. #else
  2266. if (*output)
  2267. buf_free(*output);
  2268. *output = buf_copy(input);
  2269. #endif
  2270. return 0;
  2271. }
  2272. /** Log an error and exit if <b>buf</b> is corrupted.
  2273. */
  2274. void
  2275. assert_buf_ok(buf_t *buf)
  2276. {
  2277. tor_assert(buf);
  2278. tor_assert(buf->magic == BUFFER_MAGIC);
  2279. if (! buf->head) {
  2280. tor_assert(!buf->tail);
  2281. tor_assert(buf->datalen == 0);
  2282. } else {
  2283. chunk_t *ch;
  2284. size_t total = 0;
  2285. tor_assert(buf->tail);
  2286. for (ch = buf->head; ch; ch = ch->next) {
  2287. total += ch->datalen;
  2288. tor_assert(ch->datalen <= ch->memlen);
  2289. tor_assert(ch->data >= &ch->mem[0]);
  2290. tor_assert(ch->data < &ch->mem[0]+ch->memlen);
  2291. tor_assert(ch->data+ch->datalen <= &ch->mem[0] + ch->memlen);
  2292. if (!ch->next)
  2293. tor_assert(ch == buf->tail);
  2294. }
  2295. tor_assert(buf->datalen == total);
  2296. }
  2297. }
  2298. #ifdef ENABLE_BUF_FREELISTS
  2299. /** Log an error and exit if <b>fl</b> is corrupted.
  2300. */
  2301. static void
  2302. assert_freelist_ok(chunk_freelist_t *fl)
  2303. {
  2304. chunk_t *ch;
  2305. int n;
  2306. tor_assert(fl->alloc_size > 0);
  2307. n = 0;
  2308. for (ch = fl->head; ch; ch = ch->next) {
  2309. tor_assert(CHUNK_ALLOC_SIZE(ch->memlen) == fl->alloc_size);
  2310. ++n;
  2311. }
  2312. tor_assert(n == fl->cur_length);
  2313. tor_assert(n >= fl->lowest_length);
  2314. tor_assert(n <= fl->max_length);
  2315. }
  2316. #endif