buffers.c 74 KB

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