buffers.c 78 KB

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