buffers.c 74 KB

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