buffer.c 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467
  1. /*
  2. * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
  3. * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  17. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  18. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  19. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  20. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  21. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  22. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  23. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  25. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "event2/event-config.h"
  28. #include "evconfig-private.h"
  29. #ifdef _WIN32
  30. #include <winsock2.h>
  31. #include <windows.h>
  32. #include <io.h>
  33. #endif
  34. #ifdef EVENT__HAVE_VASPRINTF
  35. /* If we have vasprintf, we need to define _GNU_SOURCE before we include
  36. * stdio.h. This comes from evconfig-private.h.
  37. */
  38. #endif
  39. #include <sys/types.h>
  40. #ifdef EVENT__HAVE_SYS_TIME_H
  41. #include <sys/time.h>
  42. #endif
  43. #ifdef EVENT__HAVE_SYS_SOCKET_H
  44. #include <sys/socket.h>
  45. #endif
  46. #ifdef EVENT__HAVE_SYS_UIO_H
  47. #include <sys/uio.h>
  48. #endif
  49. #ifdef EVENT__HAVE_SYS_IOCTL_H
  50. #include <sys/ioctl.h>
  51. #endif
  52. #ifdef EVENT__HAVE_SYS_MMAN_H
  53. #include <sys/mman.h>
  54. #endif
  55. #ifdef EVENT__HAVE_SYS_SENDFILE_H
  56. #include <sys/sendfile.h>
  57. #endif
  58. #ifdef EVENT__HAVE_SYS_STAT_H
  59. #include <sys/stat.h>
  60. #endif
  61. #include <errno.h>
  62. #include <stdio.h>
  63. #include <stdlib.h>
  64. #include <string.h>
  65. #ifdef EVENT__HAVE_STDARG_H
  66. #include <stdarg.h>
  67. #endif
  68. #ifdef EVENT__HAVE_UNISTD_H
  69. #include <unistd.h>
  70. #endif
  71. #include <limits.h>
  72. #include "event2/event.h"
  73. #include "event2/buffer.h"
  74. #include "event2/buffer_compat.h"
  75. #include "event2/bufferevent.h"
  76. #include "event2/bufferevent_compat.h"
  77. #include "event2/bufferevent_struct.h"
  78. #include "event2/thread.h"
  79. #include "log-internal.h"
  80. #include "mm-internal.h"
  81. #include "util-internal.h"
  82. #include "evthread-internal.h"
  83. #include "evbuffer-internal.h"
  84. #include "bufferevent-internal.h"
  85. #include "event-internal.h"
  86. /* some systems do not have MAP_FAILED */
  87. #ifndef MAP_FAILED
  88. #define MAP_FAILED ((void *)-1)
  89. #endif
  90. /* send file support */
  91. #if defined(EVENT__HAVE_SYS_SENDFILE_H) && defined(EVENT__HAVE_SENDFILE) && defined(__linux__)
  92. #define USE_SENDFILE 1
  93. #define SENDFILE_IS_LINUX 1
  94. #elif defined(EVENT__HAVE_SENDFILE) && defined(__FreeBSD__)
  95. #define USE_SENDFILE 1
  96. #define SENDFILE_IS_FREEBSD 1
  97. #elif defined(EVENT__HAVE_SENDFILE) && defined(__APPLE__)
  98. #define USE_SENDFILE 1
  99. #define SENDFILE_IS_MACOSX 1
  100. #elif defined(EVENT__HAVE_SENDFILE) && defined(__sun__) && defined(__svr4__)
  101. #define USE_SENDFILE 1
  102. #define SENDFILE_IS_SOLARIS 1
  103. #endif
  104. /* Mask of user-selectable callback flags. */
  105. #define EVBUFFER_CB_USER_FLAGS 0xffff
  106. /* Mask of all internal-use-only flags. */
  107. #define EVBUFFER_CB_INTERNAL_FLAGS 0xffff0000
  108. /* Flag set if the callback is using the cb_obsolete function pointer */
  109. #define EVBUFFER_CB_OBSOLETE 0x00040000
  110. /* evbuffer_chain support */
  111. #define CHAIN_SPACE_PTR(ch) ((ch)->buffer + (ch)->misalign + (ch)->off)
  112. #define CHAIN_SPACE_LEN(ch) ((ch)->flags & EVBUFFER_IMMUTABLE ? \
  113. 0 : (ch)->buffer_len - ((ch)->misalign + (ch)->off))
  114. #define CHAIN_PINNED(ch) (((ch)->flags & EVBUFFER_MEM_PINNED_ANY) != 0)
  115. #define CHAIN_PINNED_R(ch) (((ch)->flags & EVBUFFER_MEM_PINNED_R) != 0)
  116. /* evbuffer_ptr support */
  117. #define PTR_NOT_FOUND(ptr) do { \
  118. (ptr)->pos = -1; \
  119. (ptr)->internal_.chain = NULL; \
  120. (ptr)->internal_.pos_in_chain = 0; \
  121. } while (0)
  122. static void evbuffer_chain_align(struct evbuffer_chain *chain);
  123. static int evbuffer_chain_should_realign(struct evbuffer_chain *chain,
  124. size_t datalen);
  125. static void evbuffer_deferred_callback(struct event_callback *cb, void *arg);
  126. static int evbuffer_ptr_memcmp(const struct evbuffer *buf,
  127. const struct evbuffer_ptr *pos, const char *mem, size_t len);
  128. static struct evbuffer_chain *evbuffer_expand_singlechain(struct evbuffer *buf,
  129. size_t datlen);
  130. static int evbuffer_ptr_subtract(struct evbuffer *buf, struct evbuffer_ptr *pos,
  131. size_t howfar);
  132. static int evbuffer_file_segment_materialize(struct evbuffer_file_segment *seg);
  133. static inline void evbuffer_chain_incref(struct evbuffer_chain *chain);
  134. static struct evbuffer_chain *
  135. evbuffer_chain_new(size_t size)
  136. {
  137. struct evbuffer_chain *chain;
  138. size_t to_alloc;
  139. if (size > EVBUFFER_CHAIN_MAX - EVBUFFER_CHAIN_SIZE)
  140. return (NULL);
  141. size += EVBUFFER_CHAIN_SIZE;
  142. /* get the next largest memory that can hold the buffer */
  143. if (size < EVBUFFER_CHAIN_MAX / 2) {
  144. to_alloc = MIN_BUFFER_SIZE;
  145. while (to_alloc < size) {
  146. to_alloc <<= 1;
  147. }
  148. } else {
  149. to_alloc = size;
  150. }
  151. /* we get everything in one chunk */
  152. if ((chain = mm_malloc(to_alloc)) == NULL)
  153. return (NULL);
  154. memset(chain, 0, EVBUFFER_CHAIN_SIZE);
  155. chain->buffer_len = to_alloc - EVBUFFER_CHAIN_SIZE;
  156. /* this way we can manipulate the buffer to different addresses,
  157. * which is required for mmap for example.
  158. */
  159. chain->buffer = EVBUFFER_CHAIN_EXTRA(unsigned char, chain);
  160. chain->refcnt = 1;
  161. return (chain);
  162. }
  163. static inline void
  164. evbuffer_chain_free(struct evbuffer_chain *chain)
  165. {
  166. EVUTIL_ASSERT(chain->refcnt > 0);
  167. if (--chain->refcnt > 0) {
  168. /* chain is still referenced by other chains */
  169. return;
  170. }
  171. if (CHAIN_PINNED(chain)) {
  172. /* will get freed once no longer dangling */
  173. chain->refcnt++;
  174. chain->flags |= EVBUFFER_DANGLING;
  175. return;
  176. }
  177. /* safe to release chain, it's either a referencing
  178. * chain or all references to it have been freed */
  179. if (chain->flags & EVBUFFER_REFERENCE) {
  180. struct evbuffer_chain_reference *info =
  181. EVBUFFER_CHAIN_EXTRA(
  182. struct evbuffer_chain_reference,
  183. chain);
  184. if (info->cleanupfn)
  185. (*info->cleanupfn)(chain->buffer,
  186. chain->buffer_len,
  187. info->extra);
  188. }
  189. if (chain->flags & EVBUFFER_FILESEGMENT) {
  190. struct evbuffer_chain_file_segment *info =
  191. EVBUFFER_CHAIN_EXTRA(
  192. struct evbuffer_chain_file_segment,
  193. chain);
  194. if (info->segment) {
  195. #ifdef _WIN32
  196. if (info->segment->is_mapping)
  197. UnmapViewOfFile(chain->buffer);
  198. #endif
  199. evbuffer_file_segment_free(info->segment);
  200. }
  201. }
  202. if (chain->flags & EVBUFFER_MULTICAST) {
  203. struct evbuffer_multicast_parent *info =
  204. EVBUFFER_CHAIN_EXTRA(
  205. struct evbuffer_multicast_parent,
  206. chain);
  207. /* referencing chain is being freed, decrease
  208. * refcounts of source chain and associated
  209. * evbuffer (which get freed once both reach
  210. * zero) */
  211. EVUTIL_ASSERT(info->source != NULL);
  212. EVUTIL_ASSERT(info->parent != NULL);
  213. EVBUFFER_LOCK(info->source);
  214. evbuffer_chain_free(info->parent);
  215. evbuffer_decref_and_unlock_(info->source);
  216. }
  217. mm_free(chain);
  218. }
  219. static void
  220. evbuffer_free_all_chains(struct evbuffer_chain *chain)
  221. {
  222. struct evbuffer_chain *next;
  223. for (; chain; chain = next) {
  224. next = chain->next;
  225. evbuffer_chain_free(chain);
  226. }
  227. }
  228. #ifndef NDEBUG
  229. static int
  230. evbuffer_chains_all_empty(struct evbuffer_chain *chain)
  231. {
  232. for (; chain; chain = chain->next) {
  233. if (chain->off)
  234. return 0;
  235. }
  236. return 1;
  237. }
  238. #else
  239. /* The definition is needed for EVUTIL_ASSERT, which uses sizeof to avoid
  240. "unused variable" warnings. */
  241. static inline int evbuffer_chains_all_empty(struct evbuffer_chain *chain) {
  242. return 1;
  243. }
  244. #endif
  245. /* Free all trailing chains in 'buf' that are neither pinned nor empty, prior
  246. * to replacing them all with a new chain. Return a pointer to the place
  247. * where the new chain will go.
  248. *
  249. * Internal; requires lock. The caller must fix up buf->last and buf->first
  250. * as needed; they might have been freed.
  251. */
  252. static struct evbuffer_chain **
  253. evbuffer_free_trailing_empty_chains(struct evbuffer *buf)
  254. {
  255. struct evbuffer_chain **ch = buf->last_with_datap;
  256. /* Find the first victim chain. It might be *last_with_datap */
  257. while ((*ch) && ((*ch)->off != 0 || CHAIN_PINNED(*ch)))
  258. ch = &(*ch)->next;
  259. if (*ch) {
  260. EVUTIL_ASSERT(evbuffer_chains_all_empty(*ch));
  261. evbuffer_free_all_chains(*ch);
  262. *ch = NULL;
  263. }
  264. return ch;
  265. }
  266. /* Add a single chain 'chain' to the end of 'buf', freeing trailing empty
  267. * chains as necessary. Requires lock. Does not schedule callbacks.
  268. */
  269. static void
  270. evbuffer_chain_insert(struct evbuffer *buf,
  271. struct evbuffer_chain *chain)
  272. {
  273. ASSERT_EVBUFFER_LOCKED(buf);
  274. if (*buf->last_with_datap == NULL) {
  275. /* There are no chains data on the buffer at all. */
  276. EVUTIL_ASSERT(buf->last_with_datap == &buf->first);
  277. EVUTIL_ASSERT(buf->first == NULL);
  278. buf->first = buf->last = chain;
  279. } else {
  280. struct evbuffer_chain **chp;
  281. chp = evbuffer_free_trailing_empty_chains(buf);
  282. *chp = chain;
  283. if (chain->off)
  284. buf->last_with_datap = chp;
  285. buf->last = chain;
  286. }
  287. buf->total_len += chain->off;
  288. }
  289. static inline struct evbuffer_chain *
  290. evbuffer_chain_insert_new(struct evbuffer *buf, size_t datlen)
  291. {
  292. struct evbuffer_chain *chain;
  293. if ((chain = evbuffer_chain_new(datlen)) == NULL)
  294. return NULL;
  295. evbuffer_chain_insert(buf, chain);
  296. return chain;
  297. }
  298. void
  299. evbuffer_chain_pin_(struct evbuffer_chain *chain, unsigned flag)
  300. {
  301. EVUTIL_ASSERT((chain->flags & flag) == 0);
  302. chain->flags |= flag;
  303. }
  304. void
  305. evbuffer_chain_unpin_(struct evbuffer_chain *chain, unsigned flag)
  306. {
  307. EVUTIL_ASSERT((chain->flags & flag) != 0);
  308. chain->flags &= ~flag;
  309. if (chain->flags & EVBUFFER_DANGLING)
  310. evbuffer_chain_free(chain);
  311. }
  312. static inline void
  313. evbuffer_chain_incref(struct evbuffer_chain *chain)
  314. {
  315. ++chain->refcnt;
  316. }
  317. struct evbuffer *
  318. evbuffer_new(void)
  319. {
  320. struct evbuffer *buffer;
  321. buffer = mm_calloc(1, sizeof(struct evbuffer));
  322. if (buffer == NULL)
  323. return (NULL);
  324. LIST_INIT(&buffer->callbacks);
  325. buffer->refcnt = 1;
  326. buffer->last_with_datap = &buffer->first;
  327. return (buffer);
  328. }
  329. int
  330. evbuffer_set_flags(struct evbuffer *buf, ev_uint64_t flags)
  331. {
  332. EVBUFFER_LOCK(buf);
  333. buf->flags |= (ev_uint32_t)flags;
  334. EVBUFFER_UNLOCK(buf);
  335. return 0;
  336. }
  337. int
  338. evbuffer_clear_flags(struct evbuffer *buf, ev_uint64_t flags)
  339. {
  340. EVBUFFER_LOCK(buf);
  341. buf->flags &= ~(ev_uint32_t)flags;
  342. EVBUFFER_UNLOCK(buf);
  343. return 0;
  344. }
  345. void
  346. evbuffer_incref_(struct evbuffer *buf)
  347. {
  348. EVBUFFER_LOCK(buf);
  349. ++buf->refcnt;
  350. EVBUFFER_UNLOCK(buf);
  351. }
  352. void
  353. evbuffer_incref_and_lock_(struct evbuffer *buf)
  354. {
  355. EVBUFFER_LOCK(buf);
  356. ++buf->refcnt;
  357. }
  358. int
  359. evbuffer_defer_callbacks(struct evbuffer *buffer, struct event_base *base)
  360. {
  361. EVBUFFER_LOCK(buffer);
  362. buffer->cb_queue = base;
  363. buffer->deferred_cbs = 1;
  364. event_deferred_cb_init_(&buffer->deferred,
  365. event_base_get_npriorities(base) / 2,
  366. evbuffer_deferred_callback, buffer);
  367. EVBUFFER_UNLOCK(buffer);
  368. return 0;
  369. }
  370. int
  371. evbuffer_enable_locking(struct evbuffer *buf, void *lock)
  372. {
  373. #ifdef EVENT__DISABLE_THREAD_SUPPORT
  374. return -1;
  375. #else
  376. if (buf->lock)
  377. return -1;
  378. if (!lock) {
  379. EVTHREAD_ALLOC_LOCK(lock, EVTHREAD_LOCKTYPE_RECURSIVE);
  380. if (!lock)
  381. return -1;
  382. buf->lock = lock;
  383. buf->own_lock = 1;
  384. } else {
  385. buf->lock = lock;
  386. buf->own_lock = 0;
  387. }
  388. return 0;
  389. #endif
  390. }
  391. void
  392. evbuffer_set_parent_(struct evbuffer *buf, struct bufferevent *bev)
  393. {
  394. EVBUFFER_LOCK(buf);
  395. buf->parent = bev;
  396. EVBUFFER_UNLOCK(buf);
  397. }
  398. static void
  399. evbuffer_run_callbacks(struct evbuffer *buffer, int running_deferred)
  400. {
  401. struct evbuffer_cb_entry *cbent, *next;
  402. struct evbuffer_cb_info info;
  403. size_t new_size;
  404. ev_uint32_t mask, masked_val;
  405. int clear = 1;
  406. if (running_deferred) {
  407. mask = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
  408. masked_val = EVBUFFER_CB_ENABLED;
  409. } else if (buffer->deferred_cbs) {
  410. mask = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
  411. masked_val = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
  412. /* Don't zero-out n_add/n_del, since the deferred callbacks
  413. will want to see them. */
  414. clear = 0;
  415. } else {
  416. mask = EVBUFFER_CB_ENABLED;
  417. masked_val = EVBUFFER_CB_ENABLED;
  418. }
  419. ASSERT_EVBUFFER_LOCKED(buffer);
  420. if (LIST_EMPTY(&buffer->callbacks)) {
  421. buffer->n_add_for_cb = buffer->n_del_for_cb = 0;
  422. return;
  423. }
  424. if (buffer->n_add_for_cb == 0 && buffer->n_del_for_cb == 0)
  425. return;
  426. new_size = buffer->total_len;
  427. info.orig_size = new_size + buffer->n_del_for_cb - buffer->n_add_for_cb;
  428. info.n_added = buffer->n_add_for_cb;
  429. info.n_deleted = buffer->n_del_for_cb;
  430. if (clear) {
  431. buffer->n_add_for_cb = 0;
  432. buffer->n_del_for_cb = 0;
  433. }
  434. for (cbent = LIST_FIRST(&buffer->callbacks);
  435. cbent != LIST_END(&buffer->callbacks);
  436. cbent = next) {
  437. /* Get the 'next' pointer now in case this callback decides
  438. * to remove itself or something. */
  439. next = LIST_NEXT(cbent, next);
  440. if ((cbent->flags & mask) != masked_val)
  441. continue;
  442. if ((cbent->flags & EVBUFFER_CB_OBSOLETE))
  443. cbent->cb.cb_obsolete(buffer,
  444. info.orig_size, new_size, cbent->cbarg);
  445. else
  446. cbent->cb.cb_func(buffer, &info, cbent->cbarg);
  447. }
  448. }
  449. void
  450. evbuffer_invoke_callbacks_(struct evbuffer *buffer)
  451. {
  452. if (LIST_EMPTY(&buffer->callbacks)) {
  453. buffer->n_add_for_cb = buffer->n_del_for_cb = 0;
  454. return;
  455. }
  456. if (buffer->deferred_cbs) {
  457. if (event_deferred_cb_schedule_(buffer->cb_queue, &buffer->deferred)) {
  458. evbuffer_incref_and_lock_(buffer);
  459. if (buffer->parent)
  460. bufferevent_incref_(buffer->parent);
  461. EVBUFFER_UNLOCK(buffer);
  462. }
  463. }
  464. evbuffer_run_callbacks(buffer, 0);
  465. }
  466. static void
  467. evbuffer_deferred_callback(struct event_callback *cb, void *arg)
  468. {
  469. struct bufferevent *parent = NULL;
  470. struct evbuffer *buffer = arg;
  471. /* XXXX It would be better to run these callbacks without holding the
  472. * lock */
  473. EVBUFFER_LOCK(buffer);
  474. parent = buffer->parent;
  475. evbuffer_run_callbacks(buffer, 1);
  476. evbuffer_decref_and_unlock_(buffer);
  477. if (parent)
  478. bufferevent_decref_(parent);
  479. }
  480. static void
  481. evbuffer_remove_all_callbacks(struct evbuffer *buffer)
  482. {
  483. struct evbuffer_cb_entry *cbent;
  484. while ((cbent = LIST_FIRST(&buffer->callbacks))) {
  485. LIST_REMOVE(cbent, next);
  486. mm_free(cbent);
  487. }
  488. }
  489. void
  490. evbuffer_decref_and_unlock_(struct evbuffer *buffer)
  491. {
  492. struct evbuffer_chain *chain, *next;
  493. ASSERT_EVBUFFER_LOCKED(buffer);
  494. EVUTIL_ASSERT(buffer->refcnt > 0);
  495. if (--buffer->refcnt > 0) {
  496. EVBUFFER_UNLOCK(buffer);
  497. return;
  498. }
  499. for (chain = buffer->first; chain != NULL; chain = next) {
  500. next = chain->next;
  501. evbuffer_chain_free(chain);
  502. }
  503. evbuffer_remove_all_callbacks(buffer);
  504. if (buffer->deferred_cbs)
  505. event_deferred_cb_cancel_(buffer->cb_queue, &buffer->deferred);
  506. EVBUFFER_UNLOCK(buffer);
  507. if (buffer->own_lock)
  508. EVTHREAD_FREE_LOCK(buffer->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
  509. mm_free(buffer);
  510. }
  511. void
  512. evbuffer_free(struct evbuffer *buffer)
  513. {
  514. EVBUFFER_LOCK(buffer);
  515. evbuffer_decref_and_unlock_(buffer);
  516. }
  517. void
  518. evbuffer_lock(struct evbuffer *buf)
  519. {
  520. EVBUFFER_LOCK(buf);
  521. }
  522. void
  523. evbuffer_unlock(struct evbuffer *buf)
  524. {
  525. EVBUFFER_UNLOCK(buf);
  526. }
  527. size_t
  528. evbuffer_get_length(const struct evbuffer *buffer)
  529. {
  530. size_t result;
  531. EVBUFFER_LOCK(buffer);
  532. result = (buffer->total_len);
  533. EVBUFFER_UNLOCK(buffer);
  534. return result;
  535. }
  536. size_t
  537. evbuffer_get_contiguous_space(const struct evbuffer *buf)
  538. {
  539. struct evbuffer_chain *chain;
  540. size_t result;
  541. EVBUFFER_LOCK(buf);
  542. chain = buf->first;
  543. result = (chain != NULL ? chain->off : 0);
  544. EVBUFFER_UNLOCK(buf);
  545. return result;
  546. }
  547. size_t
  548. evbuffer_add_iovec(struct evbuffer * buf, struct evbuffer_iovec * vec, int n_vec) {
  549. int n;
  550. size_t res;
  551. size_t to_alloc;
  552. EVBUFFER_LOCK(buf);
  553. res = to_alloc = 0;
  554. for (n = 0; n < n_vec; n++) {
  555. to_alloc += vec[n].iov_len;
  556. }
  557. if (evbuffer_expand_fast_(buf, to_alloc, 2) < 0) {
  558. goto done;
  559. }
  560. for (n = 0; n < n_vec; n++) {
  561. /* XXX each 'add' call here does a bunch of setup that's
  562. * obviated by evbuffer_expand_fast_, and some cleanup that we
  563. * would like to do only once. Instead we should just extract
  564. * the part of the code that's needed. */
  565. if (evbuffer_add(buf, vec[n].iov_base, vec[n].iov_len) < 0) {
  566. goto done;
  567. }
  568. res += vec[n].iov_len;
  569. }
  570. done:
  571. EVBUFFER_UNLOCK(buf);
  572. return res;
  573. }
  574. int
  575. evbuffer_reserve_space(struct evbuffer *buf, ev_ssize_t size,
  576. struct evbuffer_iovec *vec, int n_vecs)
  577. {
  578. struct evbuffer_chain *chain, **chainp;
  579. int n = -1;
  580. EVBUFFER_LOCK(buf);
  581. if (buf->freeze_end)
  582. goto done;
  583. if (n_vecs < 1)
  584. goto done;
  585. if (n_vecs == 1) {
  586. if ((chain = evbuffer_expand_singlechain(buf, size)) == NULL)
  587. goto done;
  588. vec[0].iov_base = (void *)CHAIN_SPACE_PTR(chain);
  589. vec[0].iov_len = (size_t)CHAIN_SPACE_LEN(chain);
  590. EVUTIL_ASSERT(size<0 || (size_t)vec[0].iov_len >= (size_t)size);
  591. n = 1;
  592. } else {
  593. if (evbuffer_expand_fast_(buf, size, n_vecs)<0)
  594. goto done;
  595. n = evbuffer_read_setup_vecs_(buf, size, vec, n_vecs,
  596. &chainp, 0);
  597. }
  598. done:
  599. EVBUFFER_UNLOCK(buf);
  600. return n;
  601. }
  602. static int
  603. advance_last_with_data(struct evbuffer *buf)
  604. {
  605. int n = 0;
  606. struct evbuffer_chain **chainp = buf->last_with_datap;
  607. ASSERT_EVBUFFER_LOCKED(buf);
  608. if (!*chainp)
  609. return 0;
  610. while ((*chainp)->next) {
  611. chainp = &(*chainp)->next;
  612. if ((*chainp)->off)
  613. buf->last_with_datap = chainp;
  614. ++n;
  615. }
  616. return n;
  617. }
  618. int
  619. evbuffer_commit_space(struct evbuffer *buf,
  620. struct evbuffer_iovec *vec, int n_vecs)
  621. {
  622. struct evbuffer_chain *chain, **firstchainp, **chainp;
  623. int result = -1;
  624. size_t added = 0;
  625. int i;
  626. EVBUFFER_LOCK(buf);
  627. if (buf->freeze_end)
  628. goto done;
  629. if (n_vecs == 0) {
  630. result = 0;
  631. goto done;
  632. } else if (n_vecs == 1 &&
  633. (buf->last && vec[0].iov_base == (void *)CHAIN_SPACE_PTR(buf->last))) {
  634. /* The user only got or used one chain; it might not
  635. * be the first one with space in it. */
  636. if ((size_t)vec[0].iov_len > (size_t)CHAIN_SPACE_LEN(buf->last))
  637. goto done;
  638. buf->last->off += vec[0].iov_len;
  639. added = vec[0].iov_len;
  640. if (added)
  641. advance_last_with_data(buf);
  642. goto okay;
  643. }
  644. /* Advance 'firstchain' to the first chain with space in it. */
  645. firstchainp = buf->last_with_datap;
  646. if (!*firstchainp)
  647. goto done;
  648. if (CHAIN_SPACE_LEN(*firstchainp) == 0) {
  649. firstchainp = &(*firstchainp)->next;
  650. }
  651. chain = *firstchainp;
  652. /* pass 1: make sure that the pointers and lengths of vecs[] are in
  653. * bounds before we try to commit anything. */
  654. for (i=0; i<n_vecs; ++i) {
  655. if (!chain)
  656. goto done;
  657. if (vec[i].iov_base != (void *)CHAIN_SPACE_PTR(chain) ||
  658. (size_t)vec[i].iov_len > CHAIN_SPACE_LEN(chain))
  659. goto done;
  660. chain = chain->next;
  661. }
  662. /* pass 2: actually adjust all the chains. */
  663. chainp = firstchainp;
  664. for (i=0; i<n_vecs; ++i) {
  665. (*chainp)->off += vec[i].iov_len;
  666. added += vec[i].iov_len;
  667. if (vec[i].iov_len) {
  668. buf->last_with_datap = chainp;
  669. }
  670. chainp = &(*chainp)->next;
  671. }
  672. okay:
  673. buf->total_len += added;
  674. buf->n_add_for_cb += added;
  675. result = 0;
  676. evbuffer_invoke_callbacks_(buf);
  677. done:
  678. EVBUFFER_UNLOCK(buf);
  679. return result;
  680. }
  681. static inline int
  682. HAS_PINNED_R(struct evbuffer *buf)
  683. {
  684. return (buf->last && CHAIN_PINNED_R(buf->last));
  685. }
  686. static inline void
  687. ZERO_CHAIN(struct evbuffer *dst)
  688. {
  689. ASSERT_EVBUFFER_LOCKED(dst);
  690. dst->first = NULL;
  691. dst->last = NULL;
  692. dst->last_with_datap = &(dst)->first;
  693. dst->total_len = 0;
  694. }
  695. /* Prepares the contents of src to be moved to another buffer by removing
  696. * read-pinned chains. The first pinned chain is saved in first, and the
  697. * last in last. If src has no read-pinned chains, first and last are set
  698. * to NULL. */
  699. static int
  700. PRESERVE_PINNED(struct evbuffer *src, struct evbuffer_chain **first,
  701. struct evbuffer_chain **last)
  702. {
  703. struct evbuffer_chain *chain, **pinned;
  704. ASSERT_EVBUFFER_LOCKED(src);
  705. if (!HAS_PINNED_R(src)) {
  706. *first = *last = NULL;
  707. return 0;
  708. }
  709. pinned = src->last_with_datap;
  710. if (!CHAIN_PINNED_R(*pinned))
  711. pinned = &(*pinned)->next;
  712. EVUTIL_ASSERT(CHAIN_PINNED_R(*pinned));
  713. chain = *first = *pinned;
  714. *last = src->last;
  715. /* If there's data in the first pinned chain, we need to allocate
  716. * a new chain and copy the data over. */
  717. if (chain->off) {
  718. struct evbuffer_chain *tmp;
  719. EVUTIL_ASSERT(pinned == src->last_with_datap);
  720. tmp = evbuffer_chain_new(chain->off);
  721. if (!tmp)
  722. return -1;
  723. memcpy(tmp->buffer, chain->buffer + chain->misalign,
  724. chain->off);
  725. tmp->off = chain->off;
  726. *src->last_with_datap = tmp;
  727. src->last = tmp;
  728. chain->misalign += chain->off;
  729. chain->off = 0;
  730. } else {
  731. src->last = *src->last_with_datap;
  732. *pinned = NULL;
  733. }
  734. return 0;
  735. }
  736. static inline void
  737. RESTORE_PINNED(struct evbuffer *src, struct evbuffer_chain *pinned,
  738. struct evbuffer_chain *last)
  739. {
  740. ASSERT_EVBUFFER_LOCKED(src);
  741. if (!pinned) {
  742. ZERO_CHAIN(src);
  743. return;
  744. }
  745. src->first = pinned;
  746. src->last = last;
  747. src->last_with_datap = &src->first;
  748. src->total_len = 0;
  749. }
  750. static inline void
  751. COPY_CHAIN(struct evbuffer *dst, struct evbuffer *src)
  752. {
  753. ASSERT_EVBUFFER_LOCKED(dst);
  754. ASSERT_EVBUFFER_LOCKED(src);
  755. dst->first = src->first;
  756. if (src->last_with_datap == &src->first)
  757. dst->last_with_datap = &dst->first;
  758. else
  759. dst->last_with_datap = src->last_with_datap;
  760. dst->last = src->last;
  761. dst->total_len = src->total_len;
  762. }
  763. static void
  764. APPEND_CHAIN(struct evbuffer *dst, struct evbuffer *src)
  765. {
  766. struct evbuffer_chain **chp;
  767. ASSERT_EVBUFFER_LOCKED(dst);
  768. ASSERT_EVBUFFER_LOCKED(src);
  769. chp = evbuffer_free_trailing_empty_chains(dst);
  770. *chp = src->first;
  771. if (src->last_with_datap == &src->first)
  772. dst->last_with_datap = chp;
  773. else
  774. dst->last_with_datap = src->last_with_datap;
  775. dst->last = src->last;
  776. dst->total_len += src->total_len;
  777. }
  778. static inline void
  779. APPEND_CHAIN_MULTICAST(struct evbuffer *dst, struct evbuffer *src)
  780. {
  781. struct evbuffer_chain *tmp;
  782. struct evbuffer_chain *chain = src->first;
  783. struct evbuffer_multicast_parent *extra;
  784. ASSERT_EVBUFFER_LOCKED(dst);
  785. ASSERT_EVBUFFER_LOCKED(src);
  786. for (; chain; chain = chain->next) {
  787. if (!chain->off || chain->flags & EVBUFFER_DANGLING) {
  788. /* skip empty chains */
  789. continue;
  790. }
  791. tmp = evbuffer_chain_new(sizeof(struct evbuffer_multicast_parent));
  792. if (!tmp) {
  793. event_warn("%s: out of memory", __func__);
  794. return;
  795. }
  796. extra = EVBUFFER_CHAIN_EXTRA(struct evbuffer_multicast_parent, tmp);
  797. /* reference evbuffer containing source chain so it
  798. * doesn't get released while the chain is still
  799. * being referenced to */
  800. evbuffer_incref_(src);
  801. extra->source = src;
  802. /* reference source chain which now becomes immutable */
  803. evbuffer_chain_incref(chain);
  804. extra->parent = chain;
  805. chain->flags |= EVBUFFER_IMMUTABLE;
  806. tmp->buffer_len = chain->buffer_len;
  807. tmp->misalign = chain->misalign;
  808. tmp->off = chain->off;
  809. tmp->flags |= EVBUFFER_MULTICAST|EVBUFFER_IMMUTABLE;
  810. tmp->buffer = chain->buffer;
  811. evbuffer_chain_insert(dst, tmp);
  812. }
  813. }
  814. static void
  815. PREPEND_CHAIN(struct evbuffer *dst, struct evbuffer *src)
  816. {
  817. ASSERT_EVBUFFER_LOCKED(dst);
  818. ASSERT_EVBUFFER_LOCKED(src);
  819. src->last->next = dst->first;
  820. dst->first = src->first;
  821. dst->total_len += src->total_len;
  822. if (*dst->last_with_datap == NULL) {
  823. if (src->last_with_datap == &(src)->first)
  824. dst->last_with_datap = &dst->first;
  825. else
  826. dst->last_with_datap = src->last_with_datap;
  827. } else if (dst->last_with_datap == &dst->first) {
  828. dst->last_with_datap = &src->last->next;
  829. }
  830. }
  831. int
  832. evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
  833. {
  834. struct evbuffer_chain *pinned, *last;
  835. size_t in_total_len, out_total_len;
  836. int result = 0;
  837. EVBUFFER_LOCK2(inbuf, outbuf);
  838. in_total_len = inbuf->total_len;
  839. out_total_len = outbuf->total_len;
  840. if (in_total_len == 0 || outbuf == inbuf)
  841. goto done;
  842. if (outbuf->freeze_end || inbuf->freeze_start) {
  843. result = -1;
  844. goto done;
  845. }
  846. if (PRESERVE_PINNED(inbuf, &pinned, &last) < 0) {
  847. result = -1;
  848. goto done;
  849. }
  850. if (out_total_len == 0) {
  851. /* There might be an empty chain at the start of outbuf; free
  852. * it. */
  853. evbuffer_free_all_chains(outbuf->first);
  854. COPY_CHAIN(outbuf, inbuf);
  855. } else {
  856. APPEND_CHAIN(outbuf, inbuf);
  857. }
  858. RESTORE_PINNED(inbuf, pinned, last);
  859. inbuf->n_del_for_cb += in_total_len;
  860. outbuf->n_add_for_cb += in_total_len;
  861. evbuffer_invoke_callbacks_(inbuf);
  862. evbuffer_invoke_callbacks_(outbuf);
  863. done:
  864. EVBUFFER_UNLOCK2(inbuf, outbuf);
  865. return result;
  866. }
  867. int
  868. evbuffer_add_buffer_reference(struct evbuffer *outbuf, struct evbuffer *inbuf)
  869. {
  870. size_t in_total_len, out_total_len;
  871. struct evbuffer_chain *chain;
  872. int result = 0;
  873. EVBUFFER_LOCK2(inbuf, outbuf);
  874. in_total_len = inbuf->total_len;
  875. out_total_len = outbuf->total_len;
  876. chain = inbuf->first;
  877. if (in_total_len == 0)
  878. goto done;
  879. if (outbuf->freeze_end || outbuf == inbuf) {
  880. result = -1;
  881. goto done;
  882. }
  883. for (; chain; chain = chain->next) {
  884. if ((chain->flags & (EVBUFFER_FILESEGMENT|EVBUFFER_SENDFILE|EVBUFFER_MULTICAST)) != 0) {
  885. /* chain type can not be referenced */
  886. result = -1;
  887. goto done;
  888. }
  889. }
  890. if (out_total_len == 0) {
  891. /* There might be an empty chain at the start of outbuf; free
  892. * it. */
  893. evbuffer_free_all_chains(outbuf->first);
  894. }
  895. APPEND_CHAIN_MULTICAST(outbuf, inbuf);
  896. outbuf->n_add_for_cb += in_total_len;
  897. evbuffer_invoke_callbacks_(outbuf);
  898. done:
  899. EVBUFFER_UNLOCK2(inbuf, outbuf);
  900. return result;
  901. }
  902. int
  903. evbuffer_prepend_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
  904. {
  905. struct evbuffer_chain *pinned, *last;
  906. size_t in_total_len, out_total_len;
  907. int result = 0;
  908. EVBUFFER_LOCK2(inbuf, outbuf);
  909. in_total_len = inbuf->total_len;
  910. out_total_len = outbuf->total_len;
  911. if (!in_total_len || inbuf == outbuf)
  912. goto done;
  913. if (outbuf->freeze_start || inbuf->freeze_start) {
  914. result = -1;
  915. goto done;
  916. }
  917. if (PRESERVE_PINNED(inbuf, &pinned, &last) < 0) {
  918. result = -1;
  919. goto done;
  920. }
  921. if (out_total_len == 0) {
  922. /* There might be an empty chain at the start of outbuf; free
  923. * it. */
  924. evbuffer_free_all_chains(outbuf->first);
  925. COPY_CHAIN(outbuf, inbuf);
  926. } else {
  927. PREPEND_CHAIN(outbuf, inbuf);
  928. }
  929. RESTORE_PINNED(inbuf, pinned, last);
  930. inbuf->n_del_for_cb += in_total_len;
  931. outbuf->n_add_for_cb += in_total_len;
  932. evbuffer_invoke_callbacks_(inbuf);
  933. evbuffer_invoke_callbacks_(outbuf);
  934. done:
  935. EVBUFFER_UNLOCK2(inbuf, outbuf);
  936. return result;
  937. }
  938. int
  939. evbuffer_drain(struct evbuffer *buf, size_t len)
  940. {
  941. struct evbuffer_chain *chain, *next;
  942. size_t remaining, old_len;
  943. int result = 0;
  944. EVBUFFER_LOCK(buf);
  945. old_len = buf->total_len;
  946. if (old_len == 0)
  947. goto done;
  948. if (buf->freeze_start) {
  949. result = -1;
  950. goto done;
  951. }
  952. if (len >= old_len && !HAS_PINNED_R(buf)) {
  953. len = old_len;
  954. for (chain = buf->first; chain != NULL; chain = next) {
  955. next = chain->next;
  956. evbuffer_chain_free(chain);
  957. }
  958. ZERO_CHAIN(buf);
  959. } else {
  960. if (len >= old_len)
  961. len = old_len;
  962. buf->total_len -= len;
  963. remaining = len;
  964. for (chain = buf->first;
  965. remaining >= chain->off;
  966. chain = next) {
  967. next = chain->next;
  968. remaining -= chain->off;
  969. if (chain == *buf->last_with_datap) {
  970. buf->last_with_datap = &buf->first;
  971. }
  972. if (&chain->next == buf->last_with_datap)
  973. buf->last_with_datap = &buf->first;
  974. if (CHAIN_PINNED_R(chain)) {
  975. EVUTIL_ASSERT(remaining == 0);
  976. chain->misalign += chain->off;
  977. chain->off = 0;
  978. break;
  979. } else
  980. evbuffer_chain_free(chain);
  981. }
  982. buf->first = chain;
  983. EVUTIL_ASSERT(remaining <= chain->off);
  984. chain->misalign += remaining;
  985. chain->off -= remaining;
  986. }
  987. buf->n_del_for_cb += len;
  988. /* Tell someone about changes in this buffer */
  989. evbuffer_invoke_callbacks_(buf);
  990. done:
  991. EVBUFFER_UNLOCK(buf);
  992. return result;
  993. }
  994. /* Reads data from an event buffer and drains the bytes read */
  995. int
  996. evbuffer_remove(struct evbuffer *buf, void *data_out, size_t datlen)
  997. {
  998. ev_ssize_t n;
  999. EVBUFFER_LOCK(buf);
  1000. n = evbuffer_copyout_from(buf, NULL, data_out, datlen);
  1001. if (n > 0) {
  1002. if (evbuffer_drain(buf, n)<0)
  1003. n = -1;
  1004. }
  1005. EVBUFFER_UNLOCK(buf);
  1006. return (int)n;
  1007. }
  1008. ev_ssize_t
  1009. evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen)
  1010. {
  1011. return evbuffer_copyout_from(buf, NULL, data_out, datlen);
  1012. }
  1013. ev_ssize_t
  1014. evbuffer_copyout_from(struct evbuffer *buf, const struct evbuffer_ptr *pos,
  1015. void *data_out, size_t datlen)
  1016. {
  1017. /*XXX fails badly on sendfile case. */
  1018. struct evbuffer_chain *chain;
  1019. char *data = data_out;
  1020. size_t nread;
  1021. ev_ssize_t result = 0;
  1022. size_t pos_in_chain;
  1023. EVBUFFER_LOCK(buf);
  1024. if (pos) {
  1025. if (datlen > (size_t)(EV_SSIZE_MAX - pos->pos)) {
  1026. result = -1;
  1027. goto done;
  1028. }
  1029. chain = pos->internal_.chain;
  1030. pos_in_chain = pos->internal_.pos_in_chain;
  1031. if (datlen + pos->pos > buf->total_len)
  1032. datlen = buf->total_len - pos->pos;
  1033. } else {
  1034. chain = buf->first;
  1035. pos_in_chain = 0;
  1036. if (datlen > buf->total_len)
  1037. datlen = buf->total_len;
  1038. }
  1039. if (datlen == 0)
  1040. goto done;
  1041. if (buf->freeze_start) {
  1042. result = -1;
  1043. goto done;
  1044. }
  1045. nread = datlen;
  1046. while (datlen && datlen >= chain->off - pos_in_chain) {
  1047. size_t copylen = chain->off - pos_in_chain;
  1048. memcpy(data,
  1049. chain->buffer + chain->misalign + pos_in_chain,
  1050. copylen);
  1051. data += copylen;
  1052. datlen -= copylen;
  1053. chain = chain->next;
  1054. pos_in_chain = 0;
  1055. EVUTIL_ASSERT(chain || datlen==0);
  1056. }
  1057. if (datlen) {
  1058. EVUTIL_ASSERT(chain);
  1059. EVUTIL_ASSERT(datlen+pos_in_chain <= chain->off);
  1060. memcpy(data, chain->buffer + chain->misalign + pos_in_chain,
  1061. datlen);
  1062. }
  1063. result = nread;
  1064. done:
  1065. EVBUFFER_UNLOCK(buf);
  1066. return result;
  1067. }
  1068. /* reads data from the src buffer to the dst buffer, avoids memcpy as
  1069. * possible. */
  1070. /* XXXX should return ev_ssize_t */
  1071. int
  1072. evbuffer_remove_buffer(struct evbuffer *src, struct evbuffer *dst,
  1073. size_t datlen)
  1074. {
  1075. /*XXX We should have an option to force this to be zero-copy.*/
  1076. /*XXX can fail badly on sendfile case. */
  1077. struct evbuffer_chain *chain, *previous;
  1078. size_t nread = 0;
  1079. int result;
  1080. EVBUFFER_LOCK2(src, dst);
  1081. chain = previous = src->first;
  1082. if (datlen == 0 || dst == src) {
  1083. result = 0;
  1084. goto done;
  1085. }
  1086. if (dst->freeze_end || src->freeze_start) {
  1087. result = -1;
  1088. goto done;
  1089. }
  1090. /* short-cut if there is no more data buffered */
  1091. if (datlen >= src->total_len) {
  1092. datlen = src->total_len;
  1093. evbuffer_add_buffer(dst, src);
  1094. result = (int)datlen; /*XXXX should return ev_ssize_t*/
  1095. goto done;
  1096. }
  1097. /* removes chains if possible */
  1098. while (chain->off <= datlen) {
  1099. /* We can't remove the last with data from src unless we
  1100. * remove all chains, in which case we would have done the if
  1101. * block above */
  1102. EVUTIL_ASSERT(chain != *src->last_with_datap);
  1103. nread += chain->off;
  1104. datlen -= chain->off;
  1105. previous = chain;
  1106. if (src->last_with_datap == &chain->next)
  1107. src->last_with_datap = &src->first;
  1108. chain = chain->next;
  1109. }
  1110. if (chain != src->first) {
  1111. /* we can remove the chain */
  1112. struct evbuffer_chain **chp;
  1113. chp = evbuffer_free_trailing_empty_chains(dst);
  1114. if (dst->first == NULL) {
  1115. dst->first = src->first;
  1116. } else {
  1117. *chp = src->first;
  1118. }
  1119. dst->last = previous;
  1120. previous->next = NULL;
  1121. src->first = chain;
  1122. advance_last_with_data(dst);
  1123. dst->total_len += nread;
  1124. dst->n_add_for_cb += nread;
  1125. }
  1126. /* we know that there is more data in the src buffer than
  1127. * we want to read, so we manually drain the chain */
  1128. evbuffer_add(dst, chain->buffer + chain->misalign, datlen);
  1129. chain->misalign += datlen;
  1130. chain->off -= datlen;
  1131. nread += datlen;
  1132. /* You might think we would want to increment dst->n_add_for_cb
  1133. * here too. But evbuffer_add above already took care of that.
  1134. */
  1135. src->total_len -= nread;
  1136. src->n_del_for_cb += nread;
  1137. if (nread) {
  1138. evbuffer_invoke_callbacks_(dst);
  1139. evbuffer_invoke_callbacks_(src);
  1140. }
  1141. result = (int)nread;/*XXXX should change return type */
  1142. done:
  1143. EVBUFFER_UNLOCK2(src, dst);
  1144. return result;
  1145. }
  1146. unsigned char *
  1147. evbuffer_pullup(struct evbuffer *buf, ev_ssize_t size)
  1148. {
  1149. struct evbuffer_chain *chain, *next, *tmp, *last_with_data;
  1150. unsigned char *buffer, *result = NULL;
  1151. ev_ssize_t remaining;
  1152. int removed_last_with_data = 0;
  1153. int removed_last_with_datap = 0;
  1154. EVBUFFER_LOCK(buf);
  1155. chain = buf->first;
  1156. if (size < 0)
  1157. size = buf->total_len;
  1158. /* if size > buf->total_len, we cannot guarantee to the user that she
  1159. * is going to have a long enough buffer afterwards; so we return
  1160. * NULL */
  1161. if (size == 0 || (size_t)size > buf->total_len)
  1162. goto done;
  1163. /* No need to pull up anything; the first size bytes are
  1164. * already here. */
  1165. if (chain->off >= (size_t)size) {
  1166. result = chain->buffer + chain->misalign;
  1167. goto done;
  1168. }
  1169. /* Make sure that none of the chains we need to copy from is pinned. */
  1170. remaining = size - chain->off;
  1171. EVUTIL_ASSERT(remaining >= 0);
  1172. for (tmp=chain->next; tmp; tmp=tmp->next) {
  1173. if (CHAIN_PINNED(tmp))
  1174. goto done;
  1175. if (tmp->off >= (size_t)remaining)
  1176. break;
  1177. remaining -= tmp->off;
  1178. }
  1179. if (CHAIN_PINNED(chain)) {
  1180. size_t old_off = chain->off;
  1181. if (CHAIN_SPACE_LEN(chain) < size - chain->off) {
  1182. /* not enough room at end of chunk. */
  1183. goto done;
  1184. }
  1185. buffer = CHAIN_SPACE_PTR(chain);
  1186. tmp = chain;
  1187. tmp->off = size;
  1188. size -= old_off;
  1189. chain = chain->next;
  1190. } else if (chain->buffer_len - chain->misalign >= (size_t)size) {
  1191. /* already have enough space in the first chain */
  1192. size_t old_off = chain->off;
  1193. buffer = chain->buffer + chain->misalign + chain->off;
  1194. tmp = chain;
  1195. tmp->off = size;
  1196. size -= old_off;
  1197. chain = chain->next;
  1198. } else {
  1199. if ((tmp = evbuffer_chain_new(size)) == NULL) {
  1200. event_warn("%s: out of memory", __func__);
  1201. goto done;
  1202. }
  1203. buffer = tmp->buffer;
  1204. tmp->off = size;
  1205. buf->first = tmp;
  1206. }
  1207. /* TODO(niels): deal with buffers that point to NULL like sendfile */
  1208. /* Copy and free every chunk that will be entirely pulled into tmp */
  1209. last_with_data = *buf->last_with_datap;
  1210. for (; chain != NULL && (size_t)size >= chain->off; chain = next) {
  1211. next = chain->next;
  1212. if (chain->buffer) {
  1213. memcpy(buffer, chain->buffer + chain->misalign, chain->off);
  1214. size -= chain->off;
  1215. buffer += chain->off;
  1216. }
  1217. if (chain == last_with_data)
  1218. removed_last_with_data = 1;
  1219. if (&chain->next == buf->last_with_datap)
  1220. removed_last_with_datap = 1;
  1221. evbuffer_chain_free(chain);
  1222. }
  1223. if (chain != NULL) {
  1224. memcpy(buffer, chain->buffer + chain->misalign, size);
  1225. chain->misalign += size;
  1226. chain->off -= size;
  1227. } else {
  1228. buf->last = tmp;
  1229. }
  1230. tmp->next = chain;
  1231. if (removed_last_with_data) {
  1232. buf->last_with_datap = &buf->first;
  1233. } else if (removed_last_with_datap) {
  1234. if (buf->first->next && buf->first->next->off)
  1235. buf->last_with_datap = &buf->first->next;
  1236. else
  1237. buf->last_with_datap = &buf->first;
  1238. }
  1239. result = (tmp->buffer + tmp->misalign);
  1240. done:
  1241. EVBUFFER_UNLOCK(buf);
  1242. return result;
  1243. }
  1244. /*
  1245. * Reads a line terminated by either '\r\n', '\n\r' or '\r' or '\n'.
  1246. * The returned buffer needs to be freed by the called.
  1247. */
  1248. char *
  1249. evbuffer_readline(struct evbuffer *buffer)
  1250. {
  1251. return evbuffer_readln(buffer, NULL, EVBUFFER_EOL_ANY);
  1252. }
  1253. static inline ev_ssize_t
  1254. evbuffer_strchr(struct evbuffer_ptr *it, const char chr)
  1255. {
  1256. struct evbuffer_chain *chain = it->internal_.chain;
  1257. size_t i = it->internal_.pos_in_chain;
  1258. while (chain != NULL) {
  1259. char *buffer = (char *)chain->buffer + chain->misalign;
  1260. char *cp = memchr(buffer+i, chr, chain->off-i);
  1261. if (cp) {
  1262. it->internal_.chain = chain;
  1263. it->internal_.pos_in_chain = cp - buffer;
  1264. it->pos += (cp - buffer - i);
  1265. return it->pos;
  1266. }
  1267. it->pos += chain->off - i;
  1268. i = 0;
  1269. chain = chain->next;
  1270. }
  1271. return (-1);
  1272. }
  1273. static inline char *
  1274. find_eol_char(char *s, size_t len)
  1275. {
  1276. #define CHUNK_SZ 128
  1277. /* Lots of benchmarking found this approach to be faster in practice
  1278. * than doing two memchrs over the whole buffer, doin a memchr on each
  1279. * char of the buffer, or trying to emulate memchr by hand. */
  1280. char *s_end, *cr, *lf;
  1281. s_end = s+len;
  1282. while (s < s_end) {
  1283. size_t chunk = (s + CHUNK_SZ < s_end) ? CHUNK_SZ : (s_end - s);
  1284. cr = memchr(s, '\r', chunk);
  1285. lf = memchr(s, '\n', chunk);
  1286. if (cr) {
  1287. if (lf && lf < cr)
  1288. return lf;
  1289. return cr;
  1290. } else if (lf) {
  1291. return lf;
  1292. }
  1293. s += CHUNK_SZ;
  1294. }
  1295. return NULL;
  1296. #undef CHUNK_SZ
  1297. }
  1298. static ev_ssize_t
  1299. evbuffer_find_eol_char(struct evbuffer_ptr *it)
  1300. {
  1301. struct evbuffer_chain *chain = it->internal_.chain;
  1302. size_t i = it->internal_.pos_in_chain;
  1303. while (chain != NULL) {
  1304. char *buffer = (char *)chain->buffer + chain->misalign;
  1305. char *cp = find_eol_char(buffer+i, chain->off-i);
  1306. if (cp) {
  1307. it->internal_.chain = chain;
  1308. it->internal_.pos_in_chain = cp - buffer;
  1309. it->pos += (cp - buffer) - i;
  1310. return it->pos;
  1311. }
  1312. it->pos += chain->off - i;
  1313. i = 0;
  1314. chain = chain->next;
  1315. }
  1316. return (-1);
  1317. }
  1318. static inline size_t
  1319. evbuffer_strspn(
  1320. struct evbuffer_ptr *ptr, const char *chrset)
  1321. {
  1322. size_t count = 0;
  1323. struct evbuffer_chain *chain = ptr->internal_.chain;
  1324. size_t i = ptr->internal_.pos_in_chain;
  1325. if (!chain)
  1326. return 0;
  1327. while (1) {
  1328. char *buffer = (char *)chain->buffer + chain->misalign;
  1329. for (; i < chain->off; ++i) {
  1330. const char *p = chrset;
  1331. while (*p) {
  1332. if (buffer[i] == *p++)
  1333. goto next;
  1334. }
  1335. ptr->internal_.chain = chain;
  1336. ptr->internal_.pos_in_chain = i;
  1337. ptr->pos += count;
  1338. return count;
  1339. next:
  1340. ++count;
  1341. }
  1342. i = 0;
  1343. if (! chain->next) {
  1344. ptr->internal_.chain = chain;
  1345. ptr->internal_.pos_in_chain = i;
  1346. ptr->pos += count;
  1347. return count;
  1348. }
  1349. chain = chain->next;
  1350. }
  1351. }
  1352. static inline int
  1353. evbuffer_getchr(struct evbuffer_ptr *it)
  1354. {
  1355. struct evbuffer_chain *chain = it->internal_.chain;
  1356. size_t off = it->internal_.pos_in_chain;
  1357. if (chain == NULL)
  1358. return -1;
  1359. return (unsigned char)chain->buffer[chain->misalign + off];
  1360. }
  1361. struct evbuffer_ptr
  1362. evbuffer_search_eol(struct evbuffer *buffer,
  1363. struct evbuffer_ptr *start, size_t *eol_len_out,
  1364. enum evbuffer_eol_style eol_style)
  1365. {
  1366. struct evbuffer_ptr it, it2;
  1367. size_t extra_drain = 0;
  1368. int ok = 0;
  1369. /* Avoid locking in trivial edge cases */
  1370. if (start && start->internal_.chain == NULL) {
  1371. PTR_NOT_FOUND(&it);
  1372. if (eol_len_out)
  1373. *eol_len_out = extra_drain;
  1374. return it;
  1375. }
  1376. EVBUFFER_LOCK(buffer);
  1377. if (start) {
  1378. memcpy(&it, start, sizeof(it));
  1379. } else {
  1380. it.pos = 0;
  1381. it.internal_.chain = buffer->first;
  1382. it.internal_.pos_in_chain = 0;
  1383. }
  1384. /* the eol_style determines our first stop character and how many
  1385. * characters we are going to drain afterwards. */
  1386. switch (eol_style) {
  1387. case EVBUFFER_EOL_ANY:
  1388. if (evbuffer_find_eol_char(&it) < 0)
  1389. goto done;
  1390. memcpy(&it2, &it, sizeof(it));
  1391. extra_drain = evbuffer_strspn(&it2, "\r\n");
  1392. break;
  1393. case EVBUFFER_EOL_CRLF_STRICT: {
  1394. it = evbuffer_search(buffer, "\r\n", 2, &it);
  1395. if (it.pos < 0)
  1396. goto done;
  1397. extra_drain = 2;
  1398. break;
  1399. }
  1400. case EVBUFFER_EOL_CRLF: {
  1401. ev_ssize_t start_pos = it.pos;
  1402. /* Look for a LF ... */
  1403. if (evbuffer_strchr(&it, '\n') < 0)
  1404. goto done;
  1405. extra_drain = 1;
  1406. /* ... optionally preceeded by a CR. */
  1407. if (it.pos == start_pos)
  1408. break; /* If the first character is \n, don't back up */
  1409. /* This potentially does an extra linear walk over the first
  1410. * few chains. Probably, that's not too expensive unless you
  1411. * have a really pathological setup. */
  1412. memcpy(&it2, &it, sizeof(it));
  1413. if (evbuffer_ptr_subtract(buffer, &it2, 1)<0)
  1414. break;
  1415. if (evbuffer_getchr(&it2) == '\r') {
  1416. memcpy(&it, &it2, sizeof(it));
  1417. extra_drain = 2;
  1418. }
  1419. break;
  1420. }
  1421. case EVBUFFER_EOL_LF:
  1422. if (evbuffer_strchr(&it, '\n') < 0)
  1423. goto done;
  1424. extra_drain = 1;
  1425. break;
  1426. case EVBUFFER_EOL_NUL:
  1427. if (evbuffer_strchr(&it, '\0') < 0)
  1428. goto done;
  1429. extra_drain = 1;
  1430. break;
  1431. default:
  1432. goto done;
  1433. }
  1434. ok = 1;
  1435. done:
  1436. EVBUFFER_UNLOCK(buffer);
  1437. if (!ok)
  1438. PTR_NOT_FOUND(&it);
  1439. if (eol_len_out)
  1440. *eol_len_out = extra_drain;
  1441. return it;
  1442. }
  1443. char *
  1444. evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
  1445. enum evbuffer_eol_style eol_style)
  1446. {
  1447. struct evbuffer_ptr it;
  1448. char *line;
  1449. size_t n_to_copy=0, extra_drain=0;
  1450. char *result = NULL;
  1451. EVBUFFER_LOCK(buffer);
  1452. if (buffer->freeze_start) {
  1453. goto done;
  1454. }
  1455. it = evbuffer_search_eol(buffer, NULL, &extra_drain, eol_style);
  1456. if (it.pos < 0)
  1457. goto done;
  1458. n_to_copy = it.pos;
  1459. if ((line = mm_malloc(n_to_copy+1)) == NULL) {
  1460. event_warn("%s: out of memory", __func__);
  1461. goto done;
  1462. }
  1463. evbuffer_remove(buffer, line, n_to_copy);
  1464. line[n_to_copy] = '\0';
  1465. evbuffer_drain(buffer, extra_drain);
  1466. result = line;
  1467. done:
  1468. EVBUFFER_UNLOCK(buffer);
  1469. if (n_read_out)
  1470. *n_read_out = result ? n_to_copy : 0;
  1471. return result;
  1472. }
  1473. #define EVBUFFER_CHAIN_MAX_AUTO_SIZE 4096
  1474. /* Adds data to an event buffer */
  1475. int
  1476. evbuffer_add(struct evbuffer *buf, const void *data_in, size_t datlen)
  1477. {
  1478. struct evbuffer_chain *chain, *tmp;
  1479. const unsigned char *data = data_in;
  1480. size_t remain, to_alloc;
  1481. int result = -1;
  1482. EVBUFFER_LOCK(buf);
  1483. if (buf->freeze_end) {
  1484. goto done;
  1485. }
  1486. /* Prevent buf->total_len overflow */
  1487. if (datlen > EV_SIZE_MAX - buf->total_len) {
  1488. goto done;
  1489. }
  1490. if (*buf->last_with_datap == NULL) {
  1491. chain = buf->last;
  1492. } else {
  1493. chain = *buf->last_with_datap;
  1494. }
  1495. /* If there are no chains allocated for this buffer, allocate one
  1496. * big enough to hold all the data. */
  1497. if (chain == NULL) {
  1498. chain = evbuffer_chain_new(datlen);
  1499. if (!chain)
  1500. goto done;
  1501. evbuffer_chain_insert(buf, chain);
  1502. }
  1503. if ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {
  1504. /* Always true for mutable buffers */
  1505. EVUTIL_ASSERT(chain->misalign >= 0 &&
  1506. (ev_uint64_t)chain->misalign <= EVBUFFER_CHAIN_MAX);
  1507. remain = chain->buffer_len - (size_t)chain->misalign - chain->off;
  1508. if (remain >= datlen) {
  1509. /* there's enough space to hold all the data in the
  1510. * current last chain */
  1511. memcpy(chain->buffer + chain->misalign + chain->off,
  1512. data, datlen);
  1513. chain->off += datlen;
  1514. buf->total_len += datlen;
  1515. buf->n_add_for_cb += datlen;
  1516. goto out;
  1517. } else if (!CHAIN_PINNED(chain) &&
  1518. evbuffer_chain_should_realign(chain, datlen)) {
  1519. /* we can fit the data into the misalignment */
  1520. evbuffer_chain_align(chain);
  1521. memcpy(chain->buffer + chain->off, data, datlen);
  1522. chain->off += datlen;
  1523. buf->total_len += datlen;
  1524. buf->n_add_for_cb += datlen;
  1525. goto out;
  1526. }
  1527. } else {
  1528. /* we cannot write any data to the last chain */
  1529. remain = 0;
  1530. }
  1531. /* we need to add another chain */
  1532. to_alloc = chain->buffer_len;
  1533. if (to_alloc <= EVBUFFER_CHAIN_MAX_AUTO_SIZE/2)
  1534. to_alloc <<= 1;
  1535. if (datlen > to_alloc)
  1536. to_alloc = datlen;
  1537. tmp = evbuffer_chain_new(to_alloc);
  1538. if (tmp == NULL)
  1539. goto done;
  1540. if (remain) {
  1541. memcpy(chain->buffer + chain->misalign + chain->off,
  1542. data, remain);
  1543. chain->off += remain;
  1544. buf->total_len += remain;
  1545. buf->n_add_for_cb += remain;
  1546. }
  1547. data += remain;
  1548. datlen -= remain;
  1549. memcpy(tmp->buffer, data, datlen);
  1550. tmp->off = datlen;
  1551. evbuffer_chain_insert(buf, tmp);
  1552. buf->n_add_for_cb += datlen;
  1553. out:
  1554. evbuffer_invoke_callbacks_(buf);
  1555. result = 0;
  1556. done:
  1557. EVBUFFER_UNLOCK(buf);
  1558. return result;
  1559. }
  1560. int
  1561. evbuffer_prepend(struct evbuffer *buf, const void *data, size_t datlen)
  1562. {
  1563. struct evbuffer_chain *chain, *tmp;
  1564. int result = -1;
  1565. EVBUFFER_LOCK(buf);
  1566. if (datlen == 0) {
  1567. result = 0;
  1568. goto done;
  1569. }
  1570. if (buf->freeze_start) {
  1571. goto done;
  1572. }
  1573. if (datlen > EV_SIZE_MAX - buf->total_len) {
  1574. goto done;
  1575. }
  1576. chain = buf->first;
  1577. if (chain == NULL) {
  1578. chain = evbuffer_chain_new(datlen);
  1579. if (!chain)
  1580. goto done;
  1581. evbuffer_chain_insert(buf, chain);
  1582. }
  1583. /* we cannot touch immutable buffers */
  1584. if ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {
  1585. /* Always true for mutable buffers */
  1586. EVUTIL_ASSERT(chain->misalign >= 0 &&
  1587. (ev_uint64_t)chain->misalign <= EVBUFFER_CHAIN_MAX);
  1588. /* If this chain is empty, we can treat it as
  1589. * 'empty at the beginning' rather than 'empty at the end' */
  1590. if (chain->off == 0)
  1591. chain->misalign = chain->buffer_len;
  1592. if ((size_t)chain->misalign >= datlen) {
  1593. /* we have enough space to fit everything */
  1594. memcpy(chain->buffer + chain->misalign - datlen,
  1595. data, datlen);
  1596. chain->off += datlen;
  1597. chain->misalign -= datlen;
  1598. buf->total_len += datlen;
  1599. buf->n_add_for_cb += datlen;
  1600. goto out;
  1601. } else if (chain->misalign) {
  1602. /* we can only fit some of the data. */
  1603. memcpy(chain->buffer,
  1604. (char*)data + datlen - chain->misalign,
  1605. (size_t)chain->misalign);
  1606. chain->off += (size_t)chain->misalign;
  1607. buf->total_len += (size_t)chain->misalign;
  1608. buf->n_add_for_cb += (size_t)chain->misalign;
  1609. datlen -= (size_t)chain->misalign;
  1610. chain->misalign = 0;
  1611. }
  1612. }
  1613. /* we need to add another chain */
  1614. if ((tmp = evbuffer_chain_new(datlen)) == NULL)
  1615. goto done;
  1616. buf->first = tmp;
  1617. if (buf->last_with_datap == &buf->first && chain->off)
  1618. buf->last_with_datap = &tmp->next;
  1619. tmp->next = chain;
  1620. tmp->off = datlen;
  1621. EVUTIL_ASSERT(datlen <= tmp->buffer_len);
  1622. tmp->misalign = tmp->buffer_len - datlen;
  1623. memcpy(tmp->buffer + tmp->misalign, data, datlen);
  1624. buf->total_len += datlen;
  1625. buf->n_add_for_cb += datlen;
  1626. out:
  1627. evbuffer_invoke_callbacks_(buf);
  1628. result = 0;
  1629. done:
  1630. EVBUFFER_UNLOCK(buf);
  1631. return result;
  1632. }
  1633. /** Helper: realigns the memory in chain->buffer so that misalign is 0. */
  1634. static void
  1635. evbuffer_chain_align(struct evbuffer_chain *chain)
  1636. {
  1637. EVUTIL_ASSERT(!(chain->flags & EVBUFFER_IMMUTABLE));
  1638. EVUTIL_ASSERT(!(chain->flags & EVBUFFER_MEM_PINNED_ANY));
  1639. memmove(chain->buffer, chain->buffer + chain->misalign, chain->off);
  1640. chain->misalign = 0;
  1641. }
  1642. #define MAX_TO_COPY_IN_EXPAND 4096
  1643. #define MAX_TO_REALIGN_IN_EXPAND 2048
  1644. /** Helper: return true iff we should realign chain to fit datalen bytes of
  1645. data in it. */
  1646. static int
  1647. evbuffer_chain_should_realign(struct evbuffer_chain *chain,
  1648. size_t datlen)
  1649. {
  1650. return chain->buffer_len - chain->off >= datlen &&
  1651. (chain->off < chain->buffer_len / 2) &&
  1652. (chain->off <= MAX_TO_REALIGN_IN_EXPAND);
  1653. }
  1654. /* Expands the available space in the event buffer to at least datlen, all in
  1655. * a single chunk. Return that chunk. */
  1656. static struct evbuffer_chain *
  1657. evbuffer_expand_singlechain(struct evbuffer *buf, size_t datlen)
  1658. {
  1659. struct evbuffer_chain *chain, **chainp;
  1660. struct evbuffer_chain *result = NULL;
  1661. ASSERT_EVBUFFER_LOCKED(buf);
  1662. chainp = buf->last_with_datap;
  1663. /* XXX If *chainp is no longer writeable, but has enough space in its
  1664. * misalign, this might be a bad idea: we could still use *chainp, not
  1665. * (*chainp)->next. */
  1666. if (*chainp && CHAIN_SPACE_LEN(*chainp) == 0)
  1667. chainp = &(*chainp)->next;
  1668. /* 'chain' now points to the first chain with writable space (if any)
  1669. * We will either use it, realign it, replace it, or resize it. */
  1670. chain = *chainp;
  1671. if (chain == NULL ||
  1672. (chain->flags & (EVBUFFER_IMMUTABLE|EVBUFFER_MEM_PINNED_ANY))) {
  1673. /* We can't use the last_with_data chain at all. Just add a
  1674. * new one that's big enough. */
  1675. goto insert_new;
  1676. }
  1677. /* If we can fit all the data, then we don't have to do anything */
  1678. if (CHAIN_SPACE_LEN(chain) >= datlen) {
  1679. result = chain;
  1680. goto ok;
  1681. }
  1682. /* If the chain is completely empty, just replace it by adding a new
  1683. * empty chain. */
  1684. if (chain->off == 0) {
  1685. goto insert_new;
  1686. }
  1687. /* If the misalignment plus the remaining space fulfills our data
  1688. * needs, we could just force an alignment to happen. Afterwards, we
  1689. * have enough space. But only do this if we're saving a lot of space
  1690. * and not moving too much data. Otherwise the space savings are
  1691. * probably offset by the time lost in copying.
  1692. */
  1693. if (evbuffer_chain_should_realign(chain, datlen)) {
  1694. evbuffer_chain_align(chain);
  1695. result = chain;
  1696. goto ok;
  1697. }
  1698. /* At this point, we can either resize the last chunk with space in
  1699. * it, use the next chunk after it, or If we add a new chunk, we waste
  1700. * CHAIN_SPACE_LEN(chain) bytes in the former last chunk. If we
  1701. * resize, we have to copy chain->off bytes.
  1702. */
  1703. /* Would expanding this chunk be affordable and worthwhile? */
  1704. if (CHAIN_SPACE_LEN(chain) < chain->buffer_len / 8 ||
  1705. chain->off > MAX_TO_COPY_IN_EXPAND ||
  1706. datlen >= (EVBUFFER_CHAIN_MAX - chain->off)) {
  1707. /* It's not worth resizing this chain. Can the next one be
  1708. * used? */
  1709. if (chain->next && CHAIN_SPACE_LEN(chain->next) >= datlen) {
  1710. /* Yes, we can just use the next chain (which should
  1711. * be empty. */
  1712. result = chain->next;
  1713. goto ok;
  1714. } else {
  1715. /* No; append a new chain (which will free all
  1716. * terminal empty chains.) */
  1717. goto insert_new;
  1718. }
  1719. } else {
  1720. /* Okay, we're going to try to resize this chain: Not doing so
  1721. * would waste at least 1/8 of its current allocation, and we
  1722. * can do so without having to copy more than
  1723. * MAX_TO_COPY_IN_EXPAND bytes. */
  1724. /* figure out how much space we need */
  1725. size_t length = chain->off + datlen;
  1726. struct evbuffer_chain *tmp = evbuffer_chain_new(length);
  1727. if (tmp == NULL)
  1728. goto err;
  1729. /* copy the data over that we had so far */
  1730. tmp->off = chain->off;
  1731. memcpy(tmp->buffer, chain->buffer + chain->misalign,
  1732. chain->off);
  1733. /* fix up the list */
  1734. EVUTIL_ASSERT(*chainp == chain);
  1735. result = *chainp = tmp;
  1736. if (buf->last == chain)
  1737. buf->last = tmp;
  1738. tmp->next = chain->next;
  1739. evbuffer_chain_free(chain);
  1740. goto ok;
  1741. }
  1742. insert_new:
  1743. result = evbuffer_chain_insert_new(buf, datlen);
  1744. if (!result)
  1745. goto err;
  1746. ok:
  1747. EVUTIL_ASSERT(result);
  1748. EVUTIL_ASSERT(CHAIN_SPACE_LEN(result) >= datlen);
  1749. err:
  1750. return result;
  1751. }
  1752. /* Make sure that datlen bytes are available for writing in the last n
  1753. * chains. Never copies or moves data. */
  1754. int
  1755. evbuffer_expand_fast_(struct evbuffer *buf, size_t datlen, int n)
  1756. {
  1757. struct evbuffer_chain *chain = buf->last, *tmp, *next;
  1758. size_t avail;
  1759. int used;
  1760. ASSERT_EVBUFFER_LOCKED(buf);
  1761. EVUTIL_ASSERT(n >= 2);
  1762. if (chain == NULL || (chain->flags & EVBUFFER_IMMUTABLE)) {
  1763. /* There is no last chunk, or we can't touch the last chunk.
  1764. * Just add a new chunk. */
  1765. chain = evbuffer_chain_new(datlen);
  1766. if (chain == NULL)
  1767. return (-1);
  1768. evbuffer_chain_insert(buf, chain);
  1769. return (0);
  1770. }
  1771. used = 0; /* number of chains we're using space in. */
  1772. avail = 0; /* how much space they have. */
  1773. /* How many bytes can we stick at the end of buffer as it is? Iterate
  1774. * over the chains at the end of the buffer, tring to see how much
  1775. * space we have in the first n. */
  1776. for (chain = *buf->last_with_datap; chain; chain = chain->next) {
  1777. if (chain->off) {
  1778. size_t space = (size_t) CHAIN_SPACE_LEN(chain);
  1779. EVUTIL_ASSERT(chain == *buf->last_with_datap);
  1780. if (space) {
  1781. avail += space;
  1782. ++used;
  1783. }
  1784. } else {
  1785. /* No data in chain; realign it. */
  1786. chain->misalign = 0;
  1787. avail += chain->buffer_len;
  1788. ++used;
  1789. }
  1790. if (avail >= datlen) {
  1791. /* There is already enough space. Just return */
  1792. return (0);
  1793. }
  1794. if (used == n)
  1795. break;
  1796. }
  1797. /* There wasn't enough space in the first n chains with space in
  1798. * them. Either add a new chain with enough space, or replace all
  1799. * empty chains with one that has enough space, depending on n. */
  1800. if (used < n) {
  1801. /* The loop ran off the end of the chains before it hit n
  1802. * chains; we can add another. */
  1803. EVUTIL_ASSERT(chain == NULL);
  1804. tmp = evbuffer_chain_new(datlen - avail);
  1805. if (tmp == NULL)
  1806. return (-1);
  1807. buf->last->next = tmp;
  1808. buf->last = tmp;
  1809. /* (we would only set last_with_data if we added the first
  1810. * chain. But if the buffer had no chains, we would have
  1811. * just allocated a new chain earlier) */
  1812. return (0);
  1813. } else {
  1814. /* Nuke _all_ the empty chains. */
  1815. int rmv_all = 0; /* True iff we removed last_with_data. */
  1816. chain = *buf->last_with_datap;
  1817. if (!chain->off) {
  1818. EVUTIL_ASSERT(chain == buf->first);
  1819. rmv_all = 1;
  1820. avail = 0;
  1821. } else {
  1822. /* can't overflow, since only mutable chains have
  1823. * huge misaligns. */
  1824. avail = (size_t) CHAIN_SPACE_LEN(chain);
  1825. chain = chain->next;
  1826. }
  1827. for (; chain; chain = next) {
  1828. next = chain->next;
  1829. EVUTIL_ASSERT(chain->off == 0);
  1830. evbuffer_chain_free(chain);
  1831. }
  1832. EVUTIL_ASSERT(datlen >= avail);
  1833. tmp = evbuffer_chain_new(datlen - avail);
  1834. if (tmp == NULL) {
  1835. if (rmv_all) {
  1836. ZERO_CHAIN(buf);
  1837. } else {
  1838. buf->last = *buf->last_with_datap;
  1839. (*buf->last_with_datap)->next = NULL;
  1840. }
  1841. return (-1);
  1842. }
  1843. if (rmv_all) {
  1844. buf->first = buf->last = tmp;
  1845. buf->last_with_datap = &buf->first;
  1846. } else {
  1847. (*buf->last_with_datap)->next = tmp;
  1848. buf->last = tmp;
  1849. }
  1850. return (0);
  1851. }
  1852. }
  1853. int
  1854. evbuffer_expand(struct evbuffer *buf, size_t datlen)
  1855. {
  1856. struct evbuffer_chain *chain;
  1857. EVBUFFER_LOCK(buf);
  1858. chain = evbuffer_expand_singlechain(buf, datlen);
  1859. EVBUFFER_UNLOCK(buf);
  1860. return chain ? 0 : -1;
  1861. }
  1862. /*
  1863. * Reads data from a file descriptor into a buffer.
  1864. */
  1865. #if defined(EVENT__HAVE_SYS_UIO_H) || defined(_WIN32)
  1866. #define USE_IOVEC_IMPL
  1867. #endif
  1868. #ifdef USE_IOVEC_IMPL
  1869. #ifdef EVENT__HAVE_SYS_UIO_H
  1870. /* number of iovec we use for writev, fragmentation is going to determine
  1871. * how much we end up writing */
  1872. #define DEFAULT_WRITE_IOVEC 128
  1873. #if defined(UIO_MAXIOV) && UIO_MAXIOV < DEFAULT_WRITE_IOVEC
  1874. #define NUM_WRITE_IOVEC UIO_MAXIOV
  1875. #elif defined(IOV_MAX) && IOV_MAX < DEFAULT_WRITE_IOVEC
  1876. #define NUM_WRITE_IOVEC IOV_MAX
  1877. #else
  1878. #define NUM_WRITE_IOVEC DEFAULT_WRITE_IOVEC
  1879. #endif
  1880. #define IOV_TYPE struct iovec
  1881. #define IOV_PTR_FIELD iov_base
  1882. #define IOV_LEN_FIELD iov_len
  1883. #define IOV_LEN_TYPE size_t
  1884. #else
  1885. #define NUM_WRITE_IOVEC 16
  1886. #define IOV_TYPE WSABUF
  1887. #define IOV_PTR_FIELD buf
  1888. #define IOV_LEN_FIELD len
  1889. #define IOV_LEN_TYPE unsigned long
  1890. #endif
  1891. #endif
  1892. #define NUM_READ_IOVEC 4
  1893. #define EVBUFFER_MAX_READ 4096
  1894. /** Helper function to figure out which space to use for reading data into
  1895. an evbuffer. Internal use only.
  1896. @param buf The buffer to read into
  1897. @param howmuch How much we want to read.
  1898. @param vecs An array of two or more iovecs or WSABUFs.
  1899. @param n_vecs_avail The length of vecs
  1900. @param chainp A pointer to a variable to hold the first chain we're
  1901. reading into.
  1902. @param exact Boolean: if true, we do not provide more than 'howmuch'
  1903. space in the vectors, even if more space is available.
  1904. @return The number of buffers we're using.
  1905. */
  1906. int
  1907. evbuffer_read_setup_vecs_(struct evbuffer *buf, ev_ssize_t howmuch,
  1908. struct evbuffer_iovec *vecs, int n_vecs_avail,
  1909. struct evbuffer_chain ***chainp, int exact)
  1910. {
  1911. struct evbuffer_chain *chain;
  1912. struct evbuffer_chain **firstchainp;
  1913. size_t so_far;
  1914. int i;
  1915. ASSERT_EVBUFFER_LOCKED(buf);
  1916. if (howmuch < 0)
  1917. return -1;
  1918. so_far = 0;
  1919. /* Let firstchain be the first chain with any space on it */
  1920. firstchainp = buf->last_with_datap;
  1921. EVUTIL_ASSERT(*firstchainp);
  1922. if (CHAIN_SPACE_LEN(*firstchainp) == 0) {
  1923. firstchainp = &(*firstchainp)->next;
  1924. }
  1925. chain = *firstchainp;
  1926. EVUTIL_ASSERT(chain);
  1927. for (i = 0; i < n_vecs_avail && so_far < (size_t)howmuch; ++i) {
  1928. size_t avail = (size_t) CHAIN_SPACE_LEN(chain);
  1929. if (avail > (howmuch - so_far) && exact)
  1930. avail = howmuch - so_far;
  1931. vecs[i].iov_base = (void *)CHAIN_SPACE_PTR(chain);
  1932. vecs[i].iov_len = avail;
  1933. so_far += avail;
  1934. chain = chain->next;
  1935. }
  1936. *chainp = firstchainp;
  1937. return i;
  1938. }
  1939. static int
  1940. get_n_bytes_readable_on_socket(evutil_socket_t fd)
  1941. {
  1942. #if defined(FIONREAD) && defined(_WIN32)
  1943. unsigned long lng = EVBUFFER_MAX_READ;
  1944. if (ioctlsocket(fd, FIONREAD, &lng) < 0)
  1945. return -1;
  1946. /* Can overflow, but mostly harmlessly. XXXX */
  1947. return (int)lng;
  1948. #elif defined(FIONREAD)
  1949. int n = EVBUFFER_MAX_READ;
  1950. if (ioctl(fd, FIONREAD, &n) < 0)
  1951. return -1;
  1952. return n;
  1953. #else
  1954. return EVBUFFER_MAX_READ;
  1955. #endif
  1956. }
  1957. /* TODO(niels): should this function return ev_ssize_t and take ev_ssize_t
  1958. * as howmuch? */
  1959. int
  1960. evbuffer_read(struct evbuffer *buf, evutil_socket_t fd, int howmuch)
  1961. {
  1962. struct evbuffer_chain **chainp;
  1963. int n;
  1964. int result;
  1965. #ifdef USE_IOVEC_IMPL
  1966. int nvecs, i, remaining;
  1967. #else
  1968. struct evbuffer_chain *chain;
  1969. unsigned char *p;
  1970. #endif
  1971. EVBUFFER_LOCK(buf);
  1972. if (buf->freeze_end) {
  1973. result = -1;
  1974. goto done;
  1975. }
  1976. n = get_n_bytes_readable_on_socket(fd);
  1977. if (n <= 0 || n > EVBUFFER_MAX_READ)
  1978. n = EVBUFFER_MAX_READ;
  1979. if (howmuch < 0 || howmuch > n)
  1980. howmuch = n;
  1981. #ifdef USE_IOVEC_IMPL
  1982. /* Since we can use iovecs, we're willing to use the last
  1983. * NUM_READ_IOVEC chains. */
  1984. if (evbuffer_expand_fast_(buf, howmuch, NUM_READ_IOVEC) == -1) {
  1985. result = -1;
  1986. goto done;
  1987. } else {
  1988. IOV_TYPE vecs[NUM_READ_IOVEC];
  1989. #ifdef EVBUFFER_IOVEC_IS_NATIVE_
  1990. nvecs = evbuffer_read_setup_vecs_(buf, howmuch, vecs,
  1991. NUM_READ_IOVEC, &chainp, 1);
  1992. #else
  1993. /* We aren't using the native struct iovec. Therefore,
  1994. we are on win32. */
  1995. struct evbuffer_iovec ev_vecs[NUM_READ_IOVEC];
  1996. nvecs = evbuffer_read_setup_vecs_(buf, howmuch, ev_vecs, 2,
  1997. &chainp, 1);
  1998. for (i=0; i < nvecs; ++i)
  1999. WSABUF_FROM_EVBUFFER_IOV(&vecs[i], &ev_vecs[i]);
  2000. #endif
  2001. #ifdef _WIN32
  2002. {
  2003. DWORD bytesRead;
  2004. DWORD flags=0;
  2005. if (WSARecv(fd, vecs, nvecs, &bytesRead, &flags, NULL, NULL)) {
  2006. /* The read failed. It might be a close,
  2007. * or it might be an error. */
  2008. if (WSAGetLastError() == WSAECONNABORTED)
  2009. n = 0;
  2010. else
  2011. n = -1;
  2012. } else
  2013. n = bytesRead;
  2014. }
  2015. #else
  2016. n = readv(fd, vecs, nvecs);
  2017. #endif
  2018. }
  2019. #else /*!USE_IOVEC_IMPL*/
  2020. /* If we don't have FIONREAD, we might waste some space here */
  2021. /* XXX we _will_ waste some space here if there is any space left
  2022. * over on buf->last. */
  2023. if ((chain = evbuffer_expand_singlechain(buf, howmuch)) == NULL) {
  2024. result = -1;
  2025. goto done;
  2026. }
  2027. /* We can append new data at this point */
  2028. p = chain->buffer + chain->misalign + chain->off;
  2029. #ifndef _WIN32
  2030. n = read(fd, p, howmuch);
  2031. #else
  2032. n = recv(fd, p, howmuch, 0);
  2033. #endif
  2034. #endif /* USE_IOVEC_IMPL */
  2035. if (n == -1) {
  2036. result = -1;
  2037. goto done;
  2038. }
  2039. if (n == 0) {
  2040. result = 0;
  2041. goto done;
  2042. }
  2043. #ifdef USE_IOVEC_IMPL
  2044. remaining = n;
  2045. for (i=0; i < nvecs; ++i) {
  2046. /* can't overflow, since only mutable chains have
  2047. * huge misaligns. */
  2048. size_t space = (size_t) CHAIN_SPACE_LEN(*chainp);
  2049. /* XXXX This is a kludge that can waste space in perverse
  2050. * situations. */
  2051. if (space > EVBUFFER_CHAIN_MAX)
  2052. space = EVBUFFER_CHAIN_MAX;
  2053. if ((ev_ssize_t)space < remaining) {
  2054. (*chainp)->off += space;
  2055. remaining -= (int)space;
  2056. } else {
  2057. (*chainp)->off += remaining;
  2058. buf->last_with_datap = chainp;
  2059. break;
  2060. }
  2061. chainp = &(*chainp)->next;
  2062. }
  2063. #else
  2064. chain->off += n;
  2065. advance_last_with_data(buf);
  2066. #endif
  2067. buf->total_len += n;
  2068. buf->n_add_for_cb += n;
  2069. /* Tell someone about changes in this buffer */
  2070. evbuffer_invoke_callbacks_(buf);
  2071. result = n;
  2072. done:
  2073. EVBUFFER_UNLOCK(buf);
  2074. return result;
  2075. }
  2076. #ifdef USE_IOVEC_IMPL
  2077. static inline int
  2078. evbuffer_write_iovec(struct evbuffer *buffer, evutil_socket_t fd,
  2079. ev_ssize_t howmuch)
  2080. {
  2081. IOV_TYPE iov[NUM_WRITE_IOVEC];
  2082. struct evbuffer_chain *chain = buffer->first;
  2083. int n, i = 0;
  2084. if (howmuch < 0)
  2085. return -1;
  2086. ASSERT_EVBUFFER_LOCKED(buffer);
  2087. /* XXX make this top out at some maximal data length? if the
  2088. * buffer has (say) 1MB in it, split over 128 chains, there's
  2089. * no way it all gets written in one go. */
  2090. while (chain != NULL && i < NUM_WRITE_IOVEC && howmuch) {
  2091. #ifdef USE_SENDFILE
  2092. /* we cannot write the file info via writev */
  2093. if (chain->flags & EVBUFFER_SENDFILE)
  2094. break;
  2095. #endif
  2096. iov[i].IOV_PTR_FIELD = (void *) (chain->buffer + chain->misalign);
  2097. if ((size_t)howmuch >= chain->off) {
  2098. /* XXXcould be problematic when windows supports mmap*/
  2099. iov[i++].IOV_LEN_FIELD = (IOV_LEN_TYPE)chain->off;
  2100. howmuch -= chain->off;
  2101. } else {
  2102. /* XXXcould be problematic when windows supports mmap*/
  2103. iov[i++].IOV_LEN_FIELD = (IOV_LEN_TYPE)howmuch;
  2104. break;
  2105. }
  2106. chain = chain->next;
  2107. }
  2108. if (! i)
  2109. return 0;
  2110. #ifdef _WIN32
  2111. {
  2112. DWORD bytesSent;
  2113. if (WSASend(fd, iov, i, &bytesSent, 0, NULL, NULL))
  2114. n = -1;
  2115. else
  2116. n = bytesSent;
  2117. }
  2118. #else
  2119. n = writev(fd, iov, i);
  2120. #endif
  2121. return (n);
  2122. }
  2123. #endif
  2124. #ifdef USE_SENDFILE
  2125. static inline int
  2126. evbuffer_write_sendfile(struct evbuffer *buffer, evutil_socket_t dest_fd,
  2127. ev_ssize_t howmuch)
  2128. {
  2129. struct evbuffer_chain *chain = buffer->first;
  2130. struct evbuffer_chain_file_segment *info =
  2131. EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_file_segment,
  2132. chain);
  2133. const int source_fd = info->segment->fd;
  2134. #if defined(SENDFILE_IS_MACOSX) || defined(SENDFILE_IS_FREEBSD)
  2135. int res;
  2136. ev_off_t len = chain->off;
  2137. #elif defined(SENDFILE_IS_LINUX) || defined(SENDFILE_IS_SOLARIS)
  2138. ev_ssize_t res;
  2139. off_t offset = chain->misalign;
  2140. #endif
  2141. ASSERT_EVBUFFER_LOCKED(buffer);
  2142. #if defined(SENDFILE_IS_MACOSX)
  2143. res = sendfile(source_fd, dest_fd, chain->misalign, &len, NULL, 0);
  2144. if (res == -1 && !EVUTIL_ERR_RW_RETRIABLE(errno))
  2145. return (-1);
  2146. return (len);
  2147. #elif defined(SENDFILE_IS_FREEBSD)
  2148. res = sendfile(source_fd, dest_fd, chain->misalign, chain->off, NULL, &len, 0);
  2149. if (res == -1 && !EVUTIL_ERR_RW_RETRIABLE(errno))
  2150. return (-1);
  2151. return (len);
  2152. #elif defined(SENDFILE_IS_LINUX)
  2153. /* TODO(niels): implement splice */
  2154. res = sendfile(dest_fd, source_fd, &offset, chain->off);
  2155. if (res == -1 && EVUTIL_ERR_RW_RETRIABLE(errno)) {
  2156. /* if this is EAGAIN or EINTR return 0; otherwise, -1 */
  2157. return (0);
  2158. }
  2159. return (res);
  2160. #elif defined(SENDFILE_IS_SOLARIS)
  2161. {
  2162. const off_t offset_orig = offset;
  2163. res = sendfile(dest_fd, source_fd, &offset, chain->off);
  2164. if (res == -1 && EVUTIL_ERR_RW_RETRIABLE(errno)) {
  2165. if (offset - offset_orig)
  2166. return offset - offset_orig;
  2167. /* if this is EAGAIN or EINTR and no bytes were
  2168. * written, return 0 */
  2169. return (0);
  2170. }
  2171. return (res);
  2172. }
  2173. #endif
  2174. }
  2175. #endif
  2176. int
  2177. evbuffer_write_atmost(struct evbuffer *buffer, evutil_socket_t fd,
  2178. ev_ssize_t howmuch)
  2179. {
  2180. int n = -1;
  2181. EVBUFFER_LOCK(buffer);
  2182. if (buffer->freeze_start) {
  2183. goto done;
  2184. }
  2185. if (howmuch < 0 || (size_t)howmuch > buffer->total_len)
  2186. howmuch = buffer->total_len;
  2187. if (howmuch > 0) {
  2188. #ifdef USE_SENDFILE
  2189. struct evbuffer_chain *chain = buffer->first;
  2190. if (chain != NULL && (chain->flags & EVBUFFER_SENDFILE))
  2191. n = evbuffer_write_sendfile(buffer, fd, howmuch);
  2192. else {
  2193. #endif
  2194. #ifdef USE_IOVEC_IMPL
  2195. n = evbuffer_write_iovec(buffer, fd, howmuch);
  2196. #elif defined(_WIN32)
  2197. /* XXX(nickm) Don't disable this code until we know if
  2198. * the WSARecv code above works. */
  2199. void *p = evbuffer_pullup(buffer, howmuch);
  2200. EVUTIL_ASSERT(p || !howmuch);
  2201. n = send(fd, p, howmuch, 0);
  2202. #else
  2203. void *p = evbuffer_pullup(buffer, howmuch);
  2204. EVUTIL_ASSERT(p || !howmuch);
  2205. n = write(fd, p, howmuch);
  2206. #endif
  2207. #ifdef USE_SENDFILE
  2208. }
  2209. #endif
  2210. }
  2211. if (n > 0)
  2212. evbuffer_drain(buffer, n);
  2213. done:
  2214. EVBUFFER_UNLOCK(buffer);
  2215. return (n);
  2216. }
  2217. int
  2218. evbuffer_write(struct evbuffer *buffer, evutil_socket_t fd)
  2219. {
  2220. return evbuffer_write_atmost(buffer, fd, -1);
  2221. }
  2222. unsigned char *
  2223. evbuffer_find(struct evbuffer *buffer, const unsigned char *what, size_t len)
  2224. {
  2225. unsigned char *search;
  2226. struct evbuffer_ptr ptr;
  2227. EVBUFFER_LOCK(buffer);
  2228. ptr = evbuffer_search(buffer, (const char *)what, len, NULL);
  2229. if (ptr.pos < 0) {
  2230. search = NULL;
  2231. } else {
  2232. search = evbuffer_pullup(buffer, ptr.pos + len);
  2233. if (search)
  2234. search += ptr.pos;
  2235. }
  2236. EVBUFFER_UNLOCK(buffer);
  2237. return search;
  2238. }
  2239. /* Subract <b>howfar</b> from the position of <b>pos</b> within
  2240. * <b>buf</b>. Returns 0 on success, -1 on failure.
  2241. *
  2242. * This isn't exposed yet, because of potential inefficiency issues.
  2243. * Maybe it should be. */
  2244. static int
  2245. evbuffer_ptr_subtract(struct evbuffer *buf, struct evbuffer_ptr *pos,
  2246. size_t howfar)
  2247. {
  2248. if (pos->pos < 0)
  2249. return -1;
  2250. if (howfar > (size_t)pos->pos)
  2251. return -1;
  2252. if (pos->internal_.chain && howfar <= pos->internal_.pos_in_chain) {
  2253. pos->internal_.pos_in_chain -= howfar;
  2254. pos->pos -= howfar;
  2255. return 0;
  2256. } else {
  2257. const size_t newpos = pos->pos - howfar;
  2258. /* Here's the inefficient part: it walks over the
  2259. * chains until we hit newpos. */
  2260. return evbuffer_ptr_set(buf, pos, newpos, EVBUFFER_PTR_SET);
  2261. }
  2262. }
  2263. int
  2264. evbuffer_ptr_set(struct evbuffer *buf, struct evbuffer_ptr *pos,
  2265. size_t position, enum evbuffer_ptr_how how)
  2266. {
  2267. size_t left = position;
  2268. struct evbuffer_chain *chain = NULL;
  2269. int result = 0;
  2270. EVBUFFER_LOCK(buf);
  2271. switch (how) {
  2272. case EVBUFFER_PTR_SET:
  2273. chain = buf->first;
  2274. pos->pos = position;
  2275. position = 0;
  2276. break;
  2277. case EVBUFFER_PTR_ADD:
  2278. /* this avoids iterating over all previous chains if
  2279. we just want to advance the position */
  2280. if (pos->pos < 0 || EV_SIZE_MAX - position < (size_t)pos->pos) {
  2281. EVBUFFER_UNLOCK(buf);
  2282. return -1;
  2283. }
  2284. chain = pos->internal_.chain;
  2285. pos->pos += position;
  2286. position = pos->internal_.pos_in_chain;
  2287. break;
  2288. }
  2289. EVUTIL_ASSERT(EV_SIZE_MAX - left >= position);
  2290. while (chain && position + left >= chain->off) {
  2291. left -= chain->off - position;
  2292. chain = chain->next;
  2293. position = 0;
  2294. }
  2295. if (chain) {
  2296. pos->internal_.chain = chain;
  2297. pos->internal_.pos_in_chain = position + left;
  2298. } else if (left == 0) {
  2299. /* The first byte in the (nonexistent) chain after the last chain */
  2300. pos->internal_.chain = NULL;
  2301. pos->internal_.pos_in_chain = 0;
  2302. } else {
  2303. PTR_NOT_FOUND(pos);
  2304. result = -1;
  2305. }
  2306. EVBUFFER_UNLOCK(buf);
  2307. return result;
  2308. }
  2309. /**
  2310. Compare the bytes in buf at position pos to the len bytes in mem. Return
  2311. less than 0, 0, or greater than 0 as memcmp.
  2312. */
  2313. static int
  2314. evbuffer_ptr_memcmp(const struct evbuffer *buf, const struct evbuffer_ptr *pos,
  2315. const char *mem, size_t len)
  2316. {
  2317. struct evbuffer_chain *chain;
  2318. size_t position;
  2319. int r;
  2320. ASSERT_EVBUFFER_LOCKED(buf);
  2321. if (pos->pos < 0 ||
  2322. EV_SIZE_MAX - len < (size_t)pos->pos ||
  2323. pos->pos + len > buf->total_len)
  2324. return -1;
  2325. chain = pos->internal_.chain;
  2326. position = pos->internal_.pos_in_chain;
  2327. while (len && chain) {
  2328. size_t n_comparable;
  2329. if (len + position > chain->off)
  2330. n_comparable = chain->off - position;
  2331. else
  2332. n_comparable = len;
  2333. r = memcmp(chain->buffer + chain->misalign + position, mem,
  2334. n_comparable);
  2335. if (r)
  2336. return r;
  2337. mem += n_comparable;
  2338. len -= n_comparable;
  2339. position = 0;
  2340. chain = chain->next;
  2341. }
  2342. return 0;
  2343. }
  2344. struct evbuffer_ptr
  2345. evbuffer_search(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start)
  2346. {
  2347. return evbuffer_search_range(buffer, what, len, start, NULL);
  2348. }
  2349. struct evbuffer_ptr
  2350. evbuffer_search_range(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start, const struct evbuffer_ptr *end)
  2351. {
  2352. struct evbuffer_ptr pos;
  2353. struct evbuffer_chain *chain, *last_chain = NULL;
  2354. const unsigned char *p;
  2355. char first;
  2356. EVBUFFER_LOCK(buffer);
  2357. if (start) {
  2358. memcpy(&pos, start, sizeof(pos));
  2359. chain = pos.internal_.chain;
  2360. } else {
  2361. pos.pos = 0;
  2362. chain = pos.internal_.chain = buffer->first;
  2363. pos.internal_.pos_in_chain = 0;
  2364. }
  2365. if (end)
  2366. last_chain = end->internal_.chain;
  2367. if (!len || len > EV_SSIZE_MAX)
  2368. goto done;
  2369. first = what[0];
  2370. while (chain) {
  2371. const unsigned char *start_at =
  2372. chain->buffer + chain->misalign +
  2373. pos.internal_.pos_in_chain;
  2374. p = memchr(start_at, first,
  2375. chain->off - pos.internal_.pos_in_chain);
  2376. if (p) {
  2377. pos.pos += p - start_at;
  2378. pos.internal_.pos_in_chain += p - start_at;
  2379. if (!evbuffer_ptr_memcmp(buffer, &pos, what, len)) {
  2380. if (end && pos.pos + (ev_ssize_t)len > end->pos)
  2381. goto not_found;
  2382. else
  2383. goto done;
  2384. }
  2385. ++pos.pos;
  2386. ++pos.internal_.pos_in_chain;
  2387. if (pos.internal_.pos_in_chain == chain->off) {
  2388. chain = pos.internal_.chain = chain->next;
  2389. pos.internal_.pos_in_chain = 0;
  2390. }
  2391. } else {
  2392. if (chain == last_chain)
  2393. goto not_found;
  2394. pos.pos += chain->off - pos.internal_.pos_in_chain;
  2395. chain = pos.internal_.chain = chain->next;
  2396. pos.internal_.pos_in_chain = 0;
  2397. }
  2398. }
  2399. not_found:
  2400. PTR_NOT_FOUND(&pos);
  2401. done:
  2402. EVBUFFER_UNLOCK(buffer);
  2403. return pos;
  2404. }
  2405. int
  2406. evbuffer_peek(struct evbuffer *buffer, ev_ssize_t len,
  2407. struct evbuffer_ptr *start_at,
  2408. struct evbuffer_iovec *vec, int n_vec)
  2409. {
  2410. struct evbuffer_chain *chain;
  2411. int idx = 0;
  2412. ev_ssize_t len_so_far = 0;
  2413. /* Avoid locking in trivial edge cases */
  2414. if (start_at && start_at->internal_.chain == NULL)
  2415. return 0;
  2416. EVBUFFER_LOCK(buffer);
  2417. if (start_at) {
  2418. chain = start_at->internal_.chain;
  2419. len_so_far = chain->off
  2420. - start_at->internal_.pos_in_chain;
  2421. idx = 1;
  2422. if (n_vec > 0) {
  2423. vec[0].iov_base = (void *)(chain->buffer + chain->misalign
  2424. + start_at->internal_.pos_in_chain);
  2425. vec[0].iov_len = len_so_far;
  2426. }
  2427. chain = chain->next;
  2428. } else {
  2429. chain = buffer->first;
  2430. }
  2431. if (n_vec == 0 && len < 0) {
  2432. /* If no vectors are provided and they asked for "everything",
  2433. * pretend they asked for the actual available amount. */
  2434. len = buffer->total_len;
  2435. if (start_at) {
  2436. len -= start_at->pos;
  2437. }
  2438. }
  2439. while (chain) {
  2440. if (len >= 0 && len_so_far >= len)
  2441. break;
  2442. if (idx<n_vec) {
  2443. vec[idx].iov_base = (void *)(chain->buffer + chain->misalign);
  2444. vec[idx].iov_len = chain->off;
  2445. } else if (len<0) {
  2446. break;
  2447. }
  2448. ++idx;
  2449. len_so_far += chain->off;
  2450. chain = chain->next;
  2451. }
  2452. EVBUFFER_UNLOCK(buffer);
  2453. return idx;
  2454. }
  2455. int
  2456. evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap)
  2457. {
  2458. char *buffer;
  2459. size_t space;
  2460. int sz, result = -1;
  2461. va_list aq;
  2462. struct evbuffer_chain *chain;
  2463. EVBUFFER_LOCK(buf);
  2464. if (buf->freeze_end) {
  2465. goto done;
  2466. }
  2467. /* make sure that at least some space is available */
  2468. if ((chain = evbuffer_expand_singlechain(buf, 64)) == NULL)
  2469. goto done;
  2470. for (;;) {
  2471. #if 0
  2472. size_t used = chain->misalign + chain->off;
  2473. buffer = (char *)chain->buffer + chain->misalign + chain->off;
  2474. EVUTIL_ASSERT(chain->buffer_len >= used);
  2475. space = chain->buffer_len - used;
  2476. #endif
  2477. buffer = (char*) CHAIN_SPACE_PTR(chain);
  2478. space = (size_t) CHAIN_SPACE_LEN(chain);
  2479. #ifndef va_copy
  2480. #define va_copy(dst, src) memcpy(&(dst), &(src), sizeof(va_list))
  2481. #endif
  2482. va_copy(aq, ap);
  2483. sz = evutil_vsnprintf(buffer, space, fmt, aq);
  2484. va_end(aq);
  2485. if (sz < 0)
  2486. goto done;
  2487. if (INT_MAX >= EVBUFFER_CHAIN_MAX &&
  2488. (size_t)sz >= EVBUFFER_CHAIN_MAX)
  2489. goto done;
  2490. if ((size_t)sz < space) {
  2491. chain->off += sz;
  2492. buf->total_len += sz;
  2493. buf->n_add_for_cb += sz;
  2494. advance_last_with_data(buf);
  2495. evbuffer_invoke_callbacks_(buf);
  2496. result = sz;
  2497. goto done;
  2498. }
  2499. if ((chain = evbuffer_expand_singlechain(buf, sz + 1)) == NULL)
  2500. goto done;
  2501. }
  2502. /* NOTREACHED */
  2503. done:
  2504. EVBUFFER_UNLOCK(buf);
  2505. return result;
  2506. }
  2507. int
  2508. evbuffer_add_printf(struct evbuffer *buf, const char *fmt, ...)
  2509. {
  2510. int res = -1;
  2511. va_list ap;
  2512. va_start(ap, fmt);
  2513. res = evbuffer_add_vprintf(buf, fmt, ap);
  2514. va_end(ap);
  2515. return (res);
  2516. }
  2517. int
  2518. evbuffer_add_reference(struct evbuffer *outbuf,
  2519. const void *data, size_t datlen,
  2520. evbuffer_ref_cleanup_cb cleanupfn, void *extra)
  2521. {
  2522. struct evbuffer_chain *chain;
  2523. struct evbuffer_chain_reference *info;
  2524. int result = -1;
  2525. chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_reference));
  2526. if (!chain)
  2527. return (-1);
  2528. chain->flags |= EVBUFFER_REFERENCE | EVBUFFER_IMMUTABLE;
  2529. chain->buffer = (unsigned char *)data;
  2530. chain->buffer_len = datlen;
  2531. chain->off = datlen;
  2532. info = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_reference, chain);
  2533. info->cleanupfn = cleanupfn;
  2534. info->extra = extra;
  2535. EVBUFFER_LOCK(outbuf);
  2536. if (outbuf->freeze_end) {
  2537. /* don't call chain_free; we do not want to actually invoke
  2538. * the cleanup function */
  2539. mm_free(chain);
  2540. goto done;
  2541. }
  2542. evbuffer_chain_insert(outbuf, chain);
  2543. outbuf->n_add_for_cb += datlen;
  2544. evbuffer_invoke_callbacks_(outbuf);
  2545. result = 0;
  2546. done:
  2547. EVBUFFER_UNLOCK(outbuf);
  2548. return result;
  2549. }
  2550. /* TODO(niels): we may want to add to automagically convert to mmap, in
  2551. * case evbuffer_remove() or evbuffer_pullup() are being used.
  2552. */
  2553. struct evbuffer_file_segment *
  2554. evbuffer_file_segment_new(
  2555. int fd, ev_off_t offset, ev_off_t length, unsigned flags)
  2556. {
  2557. struct evbuffer_file_segment *seg =
  2558. mm_calloc(sizeof(struct evbuffer_file_segment), 1);
  2559. if (!seg)
  2560. return NULL;
  2561. seg->refcnt = 1;
  2562. seg->fd = fd;
  2563. seg->flags = flags;
  2564. seg->file_offset = offset;
  2565. seg->cleanup_cb = NULL;
  2566. seg->cleanup_cb_arg = NULL;
  2567. #ifdef _WIN32
  2568. #ifndef lseek
  2569. #define lseek _lseeki64
  2570. #endif
  2571. #ifndef fstat
  2572. #define fstat _fstat
  2573. #endif
  2574. #ifndef stat
  2575. #define stat _stat
  2576. #endif
  2577. #endif
  2578. if (length == -1) {
  2579. struct stat st;
  2580. if (fstat(fd, &st) < 0)
  2581. goto err;
  2582. length = st.st_size;
  2583. }
  2584. seg->length = length;
  2585. if (offset < 0 || length < 0 ||
  2586. ((ev_uint64_t)length > EVBUFFER_CHAIN_MAX) ||
  2587. (ev_uint64_t)offset > (ev_uint64_t)(EVBUFFER_CHAIN_MAX - length))
  2588. goto err;
  2589. #if defined(USE_SENDFILE)
  2590. if (!(flags & EVBUF_FS_DISABLE_SENDFILE)) {
  2591. seg->can_sendfile = 1;
  2592. goto done;
  2593. }
  2594. #endif
  2595. if (evbuffer_file_segment_materialize(seg)<0)
  2596. goto err;
  2597. #if defined(USE_SENDFILE)
  2598. done:
  2599. #endif
  2600. if (!(flags & EVBUF_FS_DISABLE_LOCKING)) {
  2601. EVTHREAD_ALLOC_LOCK(seg->lock, 0);
  2602. }
  2603. return seg;
  2604. err:
  2605. mm_free(seg);
  2606. return NULL;
  2607. }
  2608. #ifdef EVENT__HAVE_MMAP
  2609. static long
  2610. get_page_size(void)
  2611. {
  2612. #ifdef SC_PAGE_SIZE
  2613. return sysconf(SC_PAGE_SIZE);
  2614. #elif defined(_SC_PAGE_SIZE)
  2615. return sysconf(_SC_PAGE_SIZE);
  2616. #else
  2617. return 1;
  2618. #endif
  2619. }
  2620. #endif
  2621. /* DOCDOC */
  2622. /* Requires lock */
  2623. static int
  2624. evbuffer_file_segment_materialize(struct evbuffer_file_segment *seg)
  2625. {
  2626. const unsigned flags = seg->flags;
  2627. const int fd = seg->fd;
  2628. const ev_off_t length = seg->length;
  2629. const ev_off_t offset = seg->file_offset;
  2630. if (seg->contents)
  2631. return 0; /* already materialized */
  2632. #if defined(EVENT__HAVE_MMAP)
  2633. if (!(flags & EVBUF_FS_DISABLE_MMAP)) {
  2634. off_t offset_rounded = 0, offset_leftover = 0;
  2635. void *mapped;
  2636. if (offset) {
  2637. /* mmap implementations don't generally like us
  2638. * to have an offset that isn't a round */
  2639. long page_size = get_page_size();
  2640. if (page_size == -1)
  2641. goto err;
  2642. offset_leftover = offset % page_size;
  2643. offset_rounded = offset - offset_leftover;
  2644. }
  2645. mapped = mmap(NULL, length + offset_leftover,
  2646. PROT_READ,
  2647. #ifdef MAP_NOCACHE
  2648. MAP_NOCACHE | /* ??? */
  2649. #endif
  2650. #ifdef MAP_FILE
  2651. MAP_FILE |
  2652. #endif
  2653. MAP_PRIVATE,
  2654. fd, offset_rounded);
  2655. if (mapped == MAP_FAILED) {
  2656. event_warn("%s: mmap(%d, %d, %zu) failed",
  2657. __func__, fd, 0, (size_t)(offset + length));
  2658. } else {
  2659. seg->mapping = mapped;
  2660. seg->contents = (char*)mapped+offset_leftover;
  2661. seg->mmap_offset = 0;
  2662. seg->is_mapping = 1;
  2663. goto done;
  2664. }
  2665. }
  2666. #endif
  2667. #ifdef _WIN32
  2668. if (!(flags & EVBUF_FS_DISABLE_MMAP)) {
  2669. intptr_t h = _get_osfhandle(fd);
  2670. HANDLE m;
  2671. ev_uint64_t total_size = length+offset;
  2672. if ((HANDLE)h == INVALID_HANDLE_VALUE)
  2673. goto err;
  2674. m = CreateFileMapping((HANDLE)h, NULL, PAGE_READONLY,
  2675. (total_size >> 32), total_size & 0xfffffffful,
  2676. NULL);
  2677. if (m != INVALID_HANDLE_VALUE) { /* Does h leak? */
  2678. seg->mapping_handle = m;
  2679. seg->mmap_offset = offset;
  2680. seg->is_mapping = 1;
  2681. goto done;
  2682. }
  2683. }
  2684. #endif
  2685. {
  2686. ev_off_t start_pos = lseek(fd, 0, SEEK_CUR), pos;
  2687. ev_off_t read_so_far = 0;
  2688. char *mem;
  2689. int e;
  2690. ev_ssize_t n = 0;
  2691. if (!(mem = mm_malloc(length)))
  2692. goto err;
  2693. if (start_pos < 0) {
  2694. mm_free(mem);
  2695. goto err;
  2696. }
  2697. if (lseek(fd, offset, SEEK_SET) < 0) {
  2698. mm_free(mem);
  2699. goto err;
  2700. }
  2701. while (read_so_far < length) {
  2702. n = read(fd, mem+read_so_far, length-read_so_far);
  2703. if (n <= 0)
  2704. break;
  2705. read_so_far += n;
  2706. }
  2707. e = errno;
  2708. pos = lseek(fd, start_pos, SEEK_SET);
  2709. if (n < 0 || (n == 0 && length > read_so_far)) {
  2710. mm_free(mem);
  2711. errno = e;
  2712. goto err;
  2713. } else if (pos < 0) {
  2714. mm_free(mem);
  2715. goto err;
  2716. }
  2717. seg->contents = mem;
  2718. }
  2719. done:
  2720. return 0;
  2721. err:
  2722. return -1;
  2723. }
  2724. void evbuffer_file_segment_add_cleanup_cb(struct evbuffer_file_segment *seg,
  2725. evbuffer_file_segment_cleanup_cb cb, void* arg)
  2726. {
  2727. EVUTIL_ASSERT(seg->refcnt > 0);
  2728. seg->cleanup_cb = cb;
  2729. seg->cleanup_cb_arg = arg;
  2730. }
  2731. void
  2732. evbuffer_file_segment_free(struct evbuffer_file_segment *seg)
  2733. {
  2734. int refcnt;
  2735. EVLOCK_LOCK(seg->lock, 0);
  2736. refcnt = --seg->refcnt;
  2737. EVLOCK_UNLOCK(seg->lock, 0);
  2738. if (refcnt > 0)
  2739. return;
  2740. EVUTIL_ASSERT(refcnt == 0);
  2741. if (seg->is_mapping) {
  2742. #ifdef _WIN32
  2743. CloseHandle(seg->mapping_handle);
  2744. #elif defined (EVENT__HAVE_MMAP)
  2745. off_t offset_leftover;
  2746. offset_leftover = seg->file_offset % get_page_size();
  2747. if (munmap(seg->mapping, seg->length + offset_leftover) == -1)
  2748. event_warn("%s: munmap failed", __func__);
  2749. #endif
  2750. } else if (seg->contents) {
  2751. mm_free(seg->contents);
  2752. }
  2753. if ((seg->flags & EVBUF_FS_CLOSE_ON_FREE) && seg->fd >= 0) {
  2754. close(seg->fd);
  2755. }
  2756. if (seg->cleanup_cb) {
  2757. (*seg->cleanup_cb)((struct evbuffer_file_segment const*)seg,
  2758. seg->flags, seg->cleanup_cb_arg);
  2759. seg->cleanup_cb = NULL;
  2760. seg->cleanup_cb_arg = NULL;
  2761. }
  2762. EVTHREAD_FREE_LOCK(seg->lock, 0);
  2763. mm_free(seg);
  2764. }
  2765. int
  2766. evbuffer_add_file_segment(struct evbuffer *buf,
  2767. struct evbuffer_file_segment *seg, ev_off_t offset, ev_off_t length)
  2768. {
  2769. struct evbuffer_chain *chain;
  2770. struct evbuffer_chain_file_segment *extra;
  2771. int can_use_sendfile = 0;
  2772. EVBUFFER_LOCK(buf);
  2773. EVLOCK_LOCK(seg->lock, 0);
  2774. if (buf->flags & EVBUFFER_FLAG_DRAINS_TO_FD) {
  2775. can_use_sendfile = 1;
  2776. } else {
  2777. if (!seg->contents) {
  2778. if (evbuffer_file_segment_materialize(seg)<0) {
  2779. EVLOCK_UNLOCK(seg->lock, 0);
  2780. EVBUFFER_UNLOCK(buf);
  2781. return -1;
  2782. }
  2783. }
  2784. }
  2785. EVLOCK_UNLOCK(seg->lock, 0);
  2786. if (buf->freeze_end)
  2787. goto err;
  2788. if (length < 0) {
  2789. if (offset > seg->length)
  2790. goto err;
  2791. length = seg->length - offset;
  2792. }
  2793. /* Can we actually add this? */
  2794. if (offset+length > seg->length)
  2795. goto err;
  2796. chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_file_segment));
  2797. if (!chain)
  2798. goto err;
  2799. extra = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_file_segment, chain);
  2800. chain->flags |= EVBUFFER_IMMUTABLE|EVBUFFER_FILESEGMENT;
  2801. if (can_use_sendfile && seg->can_sendfile) {
  2802. chain->flags |= EVBUFFER_SENDFILE;
  2803. chain->misalign = seg->file_offset + offset;
  2804. chain->off = length;
  2805. chain->buffer_len = chain->misalign + length;
  2806. } else if (seg->is_mapping) {
  2807. #ifdef _WIN32
  2808. ev_uint64_t total_offset = seg->mmap_offset+offset;
  2809. ev_uint64_t offset_rounded=0, offset_remaining=0;
  2810. LPVOID data;
  2811. if (total_offset) {
  2812. SYSTEM_INFO si;
  2813. memset(&si, 0, sizeof(si)); /* cargo cult */
  2814. GetSystemInfo(&si);
  2815. offset_remaining = total_offset % si.dwAllocationGranularity;
  2816. offset_rounded = total_offset - offset_remaining;
  2817. }
  2818. data = MapViewOfFile(
  2819. seg->mapping_handle,
  2820. FILE_MAP_READ,
  2821. offset_rounded >> 32,
  2822. offset_rounded & 0xfffffffful,
  2823. length + offset_remaining);
  2824. if (data == NULL) {
  2825. mm_free(chain);
  2826. goto err;
  2827. }
  2828. chain->buffer = (unsigned char*) data;
  2829. chain->buffer_len = length+offset_remaining;
  2830. chain->misalign = offset_remaining;
  2831. chain->off = length;
  2832. #else
  2833. chain->buffer = (unsigned char*)(seg->contents + offset);
  2834. chain->buffer_len = length;
  2835. chain->off = length;
  2836. #endif
  2837. } else {
  2838. chain->buffer = (unsigned char*)(seg->contents + offset);
  2839. chain->buffer_len = length;
  2840. chain->off = length;
  2841. }
  2842. EVLOCK_LOCK(seg->lock, 0);
  2843. ++seg->refcnt;
  2844. EVLOCK_UNLOCK(seg->lock, 0);
  2845. extra->segment = seg;
  2846. buf->n_add_for_cb += length;
  2847. evbuffer_chain_insert(buf, chain);
  2848. evbuffer_invoke_callbacks_(buf);
  2849. EVBUFFER_UNLOCK(buf);
  2850. return 0;
  2851. err:
  2852. EVBUFFER_UNLOCK(buf);
  2853. evbuffer_file_segment_free(seg); /* Lowers the refcount */
  2854. return -1;
  2855. }
  2856. int
  2857. evbuffer_add_file(struct evbuffer *buf, int fd, ev_off_t offset, ev_off_t length)
  2858. {
  2859. struct evbuffer_file_segment *seg;
  2860. unsigned flags = EVBUF_FS_CLOSE_ON_FREE;
  2861. int r;
  2862. seg = evbuffer_file_segment_new(fd, offset, length, flags);
  2863. if (!seg)
  2864. return -1;
  2865. r = evbuffer_add_file_segment(buf, seg, 0, length);
  2866. if (r == 0)
  2867. evbuffer_file_segment_free(seg);
  2868. return r;
  2869. }
  2870. int
  2871. evbuffer_setcb(struct evbuffer *buffer, evbuffer_cb cb, void *cbarg)
  2872. {
  2873. EVBUFFER_LOCK(buffer);
  2874. if (!LIST_EMPTY(&buffer->callbacks))
  2875. evbuffer_remove_all_callbacks(buffer);
  2876. if (cb) {
  2877. struct evbuffer_cb_entry *ent =
  2878. evbuffer_add_cb(buffer, NULL, cbarg);
  2879. if (!ent) {
  2880. EVBUFFER_UNLOCK(buffer);
  2881. return -1;
  2882. }
  2883. ent->cb.cb_obsolete = cb;
  2884. ent->flags |= EVBUFFER_CB_OBSOLETE;
  2885. }
  2886. EVBUFFER_UNLOCK(buffer);
  2887. return 0;
  2888. }
  2889. struct evbuffer_cb_entry *
  2890. evbuffer_add_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg)
  2891. {
  2892. struct evbuffer_cb_entry *e;
  2893. if (! (e = mm_calloc(1, sizeof(struct evbuffer_cb_entry))))
  2894. return NULL;
  2895. EVBUFFER_LOCK(buffer);
  2896. e->cb.cb_func = cb;
  2897. e->cbarg = cbarg;
  2898. e->flags = EVBUFFER_CB_ENABLED;
  2899. LIST_INSERT_HEAD(&buffer->callbacks, e, next);
  2900. EVBUFFER_UNLOCK(buffer);
  2901. return e;
  2902. }
  2903. int
  2904. evbuffer_remove_cb_entry(struct evbuffer *buffer,
  2905. struct evbuffer_cb_entry *ent)
  2906. {
  2907. EVBUFFER_LOCK(buffer);
  2908. LIST_REMOVE(ent, next);
  2909. EVBUFFER_UNLOCK(buffer);
  2910. mm_free(ent);
  2911. return 0;
  2912. }
  2913. int
  2914. evbuffer_remove_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg)
  2915. {
  2916. struct evbuffer_cb_entry *cbent;
  2917. int result = -1;
  2918. EVBUFFER_LOCK(buffer);
  2919. LIST_FOREACH(cbent, &buffer->callbacks, next) {
  2920. if (cb == cbent->cb.cb_func && cbarg == cbent->cbarg) {
  2921. result = evbuffer_remove_cb_entry(buffer, cbent);
  2922. goto done;
  2923. }
  2924. }
  2925. done:
  2926. EVBUFFER_UNLOCK(buffer);
  2927. return result;
  2928. }
  2929. int
  2930. evbuffer_cb_set_flags(struct evbuffer *buffer,
  2931. struct evbuffer_cb_entry *cb, ev_uint32_t flags)
  2932. {
  2933. /* the user isn't allowed to mess with these. */
  2934. flags &= ~EVBUFFER_CB_INTERNAL_FLAGS;
  2935. EVBUFFER_LOCK(buffer);
  2936. cb->flags |= flags;
  2937. EVBUFFER_UNLOCK(buffer);
  2938. return 0;
  2939. }
  2940. int
  2941. evbuffer_cb_clear_flags(struct evbuffer *buffer,
  2942. struct evbuffer_cb_entry *cb, ev_uint32_t flags)
  2943. {
  2944. /* the user isn't allowed to mess with these. */
  2945. flags &= ~EVBUFFER_CB_INTERNAL_FLAGS;
  2946. EVBUFFER_LOCK(buffer);
  2947. cb->flags &= ~flags;
  2948. EVBUFFER_UNLOCK(buffer);
  2949. return 0;
  2950. }
  2951. int
  2952. evbuffer_freeze(struct evbuffer *buffer, int start)
  2953. {
  2954. EVBUFFER_LOCK(buffer);
  2955. if (start)
  2956. buffer->freeze_start = 1;
  2957. else
  2958. buffer->freeze_end = 1;
  2959. EVBUFFER_UNLOCK(buffer);
  2960. return 0;
  2961. }
  2962. int
  2963. evbuffer_unfreeze(struct evbuffer *buffer, int start)
  2964. {
  2965. EVBUFFER_LOCK(buffer);
  2966. if (start)
  2967. buffer->freeze_start = 0;
  2968. else
  2969. buffer->freeze_end = 0;
  2970. EVBUFFER_UNLOCK(buffer);
  2971. return 0;
  2972. }
  2973. #if 0
  2974. void
  2975. evbuffer_cb_suspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb)
  2976. {
  2977. if (!(cb->flags & EVBUFFER_CB_SUSPENDED)) {
  2978. cb->size_before_suspend = evbuffer_get_length(buffer);
  2979. cb->flags |= EVBUFFER_CB_SUSPENDED;
  2980. }
  2981. }
  2982. void
  2983. evbuffer_cb_unsuspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb)
  2984. {
  2985. if ((cb->flags & EVBUFFER_CB_SUSPENDED)) {
  2986. unsigned call = (cb->flags & EVBUFFER_CB_CALL_ON_UNSUSPEND);
  2987. size_t sz = cb->size_before_suspend;
  2988. cb->flags &= ~(EVBUFFER_CB_SUSPENDED|
  2989. EVBUFFER_CB_CALL_ON_UNSUSPEND);
  2990. cb->size_before_suspend = 0;
  2991. if (call && (cb->flags & EVBUFFER_CB_ENABLED)) {
  2992. cb->cb(buffer, sz, evbuffer_get_length(buffer), cb->cbarg);
  2993. }
  2994. }
  2995. }
  2996. #endif
  2997. int
  2998. evbuffer_get_callbacks_(struct evbuffer *buffer, struct event_callback **cbs,
  2999. int max_cbs)
  3000. {
  3001. int r = 0;
  3002. EVBUFFER_LOCK(buffer);
  3003. if (buffer->deferred_cbs) {
  3004. if (max_cbs < 1) {
  3005. r = -1;
  3006. goto done;
  3007. }
  3008. cbs[0] = &buffer->deferred;
  3009. r = 1;
  3010. }
  3011. done:
  3012. EVBUFFER_UNLOCK(buffer);
  3013. return r;
  3014. }