buffers.c 78 KB

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