buffers.c 78 KB

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