buffers.c 80 KB

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