buffers.c 77 KB

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