buffers.c 81 KB

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