buffers.c 77 KB

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