buffers.c 74 KB

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