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