buffers.c 74 KB

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