httplib.h 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693
  1. //
  2. // httplib.h
  3. //
  4. // Copyright (c) 2019 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #ifndef CPPHTTPLIB_HTTPLIB_H
  8. #define CPPHTTPLIB_HTTPLIB_H
  9. /*
  10. * Configuration
  11. */
  12. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
  13. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
  14. #endif
  15. #ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND
  16. #define CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND 0
  17. #endif
  18. #ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
  19. #define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
  20. #endif
  21. #ifndef CPPHTTPLIB_READ_TIMEOUT_SECOND
  22. #define CPPHTTPLIB_READ_TIMEOUT_SECOND 5
  23. #endif
  24. #ifndef CPPHTTPLIB_READ_TIMEOUT_USECOND
  25. #define CPPHTTPLIB_READ_TIMEOUT_USECOND 0
  26. #endif
  27. #ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
  28. #define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
  29. #endif
  30. #ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
  31. #define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
  32. #endif
  33. #ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
  34. #define CPPHTTPLIB_PAYLOAD_MAX_LENGTH (std::numeric_limits<size_t>::max)()
  35. #endif
  36. #ifndef CPPHTTPLIB_RECV_BUFSIZ
  37. #define CPPHTTPLIB_RECV_BUFSIZ size_t(4096u)
  38. #endif
  39. #ifndef CPPHTTPLIB_THREAD_POOL_COUNT
  40. // if hardware_concurrency() outputs 0 we still wants to use threads for this.
  41. // -1 because we have one thread already in the main function.
  42. #define CPPHTTPLIB_THREAD_POOL_COUNT std::thread::hardware_concurrency() ? std::thread::hardware_concurrency()-1 : 2
  43. #endif
  44. /*
  45. * Headers
  46. */
  47. #ifdef _WIN32
  48. #ifndef _CRT_SECURE_NO_WARNINGS
  49. #define _CRT_SECURE_NO_WARNINGS
  50. #endif //_CRT_SECURE_NO_WARNINGS
  51. #ifndef _CRT_NONSTDC_NO_DEPRECATE
  52. #define _CRT_NONSTDC_NO_DEPRECATE
  53. #endif //_CRT_NONSTDC_NO_DEPRECATE
  54. #if defined(_MSC_VER)
  55. #ifdef _WIN64
  56. using ssize_t = __int64;
  57. #else
  58. using ssize_t = int;
  59. #endif
  60. #if _MSC_VER < 1900
  61. #define snprintf _snprintf_s
  62. #endif
  63. #endif // _MSC_VER
  64. #ifndef S_ISREG
  65. #define S_ISREG(m) (((m)&S_IFREG) == S_IFREG)
  66. #endif // S_ISREG
  67. #ifndef S_ISDIR
  68. #define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR)
  69. #endif // S_ISDIR
  70. #ifndef NOMINMAX
  71. #define NOMINMAX
  72. #endif // NOMINMAX
  73. #include <io.h>
  74. #include <winsock2.h>
  75. #include <ws2tcpip.h>
  76. #ifndef WSA_FLAG_NO_HANDLE_INHERIT
  77. #define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  78. #endif
  79. #ifdef _MSC_VER
  80. #pragma comment(lib, "ws2_32.lib")
  81. #endif
  82. #ifndef strcasecmp
  83. #define strcasecmp _stricmp
  84. #endif // strcasecmp
  85. using socket_t = SOCKET;
  86. #ifdef CPPHTTPLIB_USE_POLL
  87. #define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
  88. #endif
  89. #else // not _WIN32
  90. #include <arpa/inet.h>
  91. #include <cstring>
  92. #include <ifaddrs.h>
  93. #include <netdb.h>
  94. #include <netinet/in.h>
  95. #ifdef CPPHTTPLIB_USE_POLL
  96. #include <poll.h>
  97. #endif
  98. #include <csignal>
  99. #include <pthread.h>
  100. #include <sys/select.h>
  101. #include <sys/socket.h>
  102. #include <unistd.h>
  103. using socket_t = int;
  104. #define INVALID_SOCKET (-1)
  105. #endif //_WIN32
  106. #include <array>
  107. #include <atomic>
  108. #include <cassert>
  109. #include <condition_variable>
  110. #include <errno.h>
  111. #include <fcntl.h>
  112. #include <fstream>
  113. #include <functional>
  114. #include <list>
  115. #include <map>
  116. #include <memory>
  117. #include <mutex>
  118. #include <random>
  119. #include <regex>
  120. #include <string>
  121. #include <sys/stat.h>
  122. #include <thread>
  123. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  124. #include <openssl/err.h>
  125. #include <openssl/md5.h>
  126. #include <openssl/ssl.h>
  127. #include <openssl/x509v3.h>
  128. #include <iomanip>
  129. #include <sstream>
  130. // #if OPENSSL_VERSION_NUMBER < 0x1010100fL
  131. // #error Sorry, OpenSSL versions prior to 1.1.1 are not supported
  132. // #endif
  133. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  134. #include <openssl/crypto.h>
  135. inline const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) {
  136. return M_ASN1_STRING_data(asn1);
  137. }
  138. #endif
  139. #endif
  140. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  141. #include <zlib.h>
  142. #endif
  143. /*
  144. * Declaration
  145. */
  146. namespace httplib {
  147. namespace detail {
  148. struct ci {
  149. bool operator()(const std::string &s1, const std::string &s2) const {
  150. return std::lexicographical_compare(
  151. s1.begin(), s1.end(), s2.begin(), s2.end(),
  152. [](char c1, char c2) { return ::tolower(c1) < ::tolower(c2); });
  153. }
  154. };
  155. } // namespace detail
  156. using Headers = std::multimap<std::string, std::string, detail::ci>;
  157. using Params = std::multimap<std::string, std::string>;
  158. using Match = std::smatch;
  159. using Progress = std::function<bool(uint64_t current, uint64_t total)>;
  160. struct Response;
  161. using ResponseHandler = std::function<bool(const Response &response)>;
  162. struct MultipartFormData {
  163. std::string name;
  164. std::string content;
  165. std::string filename;
  166. std::string content_type;
  167. };
  168. using MultipartFormDataItems = std::vector<MultipartFormData>;
  169. using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
  170. class DataSink {
  171. public:
  172. DataSink() = default;
  173. DataSink(const DataSink &) = delete;
  174. DataSink &operator=(const DataSink &) = delete;
  175. DataSink(DataSink &&) = delete;
  176. DataSink &operator=(DataSink &&) = delete;
  177. std::function<void(const char *data, size_t data_len)> write;
  178. std::function<void()> done;
  179. // TODO: std::function<bool()> is_alive;
  180. };
  181. using ContentProvider =
  182. std::function<void(size_t offset, size_t length, DataSink &sink)>;
  183. using ContentReceiver =
  184. std::function<bool(const char *data, size_t data_length)>;
  185. using MultipartContentHeader =
  186. std::function<bool(const MultipartFormData &file)>;
  187. class ContentReader {
  188. public:
  189. using Reader = std::function<bool(ContentReceiver receiver)>;
  190. using MultipartReader = std::function<bool(MultipartContentHeader header,
  191. ContentReceiver receiver)>;
  192. ContentReader(Reader reader, MultipartReader muitlpart_reader)
  193. : reader_(reader), muitlpart_reader_(muitlpart_reader) {}
  194. bool operator()(MultipartContentHeader header,
  195. ContentReceiver receiver) const {
  196. return muitlpart_reader_(header, receiver);
  197. }
  198. bool operator()(ContentReceiver receiver) const { return reader_(receiver); }
  199. Reader reader_;
  200. MultipartReader muitlpart_reader_;
  201. };
  202. using Range = std::pair<ssize_t, ssize_t>;
  203. using Ranges = std::vector<Range>;
  204. struct Request {
  205. std::string method;
  206. std::string path;
  207. Headers headers;
  208. std::string body;
  209. // for server
  210. std::string version;
  211. std::string target;
  212. Params params;
  213. MultipartFormDataMap files;
  214. Ranges ranges;
  215. Match matches;
  216. // for client
  217. size_t redirect_count = CPPHTTPLIB_REDIRECT_MAX_COUNT;
  218. ResponseHandler response_handler;
  219. ContentReceiver content_receiver;
  220. Progress progress;
  221. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  222. const SSL *ssl;
  223. #endif
  224. bool has_header(const char *key) const;
  225. std::string get_header_value(const char *key, size_t id = 0) const;
  226. size_t get_header_value_count(const char *key) const;
  227. void set_header(const char *key, const char *val);
  228. void set_header(const char *key, const std::string &val);
  229. bool has_param(const char *key) const;
  230. std::string get_param_value(const char *key, size_t id = 0) const;
  231. size_t get_param_value_count(const char *key) const;
  232. bool is_multipart_form_data() const;
  233. bool has_file(const char *key) const;
  234. MultipartFormData get_file_value(const char *key) const;
  235. // private members...
  236. size_t content_length;
  237. ContentProvider content_provider;
  238. };
  239. struct Response {
  240. std::string version;
  241. int status = -1;
  242. Headers headers;
  243. std::string body;
  244. bool has_header(const char *key) const;
  245. std::string get_header_value(const char *key, size_t id = 0) const;
  246. size_t get_header_value_count(const char *key) const;
  247. void set_header(const char *key, const char *val);
  248. void set_header(const char *key, const std::string &val);
  249. void set_redirect(const char *url);
  250. void set_content(const char *s, size_t n, const char *content_type);
  251. void set_content(const std::string &s, const char *content_type);
  252. void set_content_provider(
  253. size_t length,
  254. std::function<void(size_t offset, size_t length, DataSink &sink)>
  255. provider,
  256. std::function<void()> resource_releaser = [] {});
  257. void set_chunked_content_provider(
  258. std::function<void(size_t offset, DataSink &sink)> provider,
  259. std::function<void()> resource_releaser = [] {});
  260. Response() = default;
  261. Response(const Response &) = default;
  262. Response &operator=(const Response &) = default;
  263. Response(Response &&) = default;
  264. Response &operator=(Response &&) = default;
  265. ~Response() {
  266. if (content_provider_resource_releaser) {
  267. content_provider_resource_releaser();
  268. }
  269. }
  270. // private members...
  271. size_t content_length = 0;
  272. ContentProvider content_provider;
  273. std::function<void()> content_provider_resource_releaser;
  274. };
  275. class Stream {
  276. public:
  277. virtual ~Stream() = default;
  278. virtual int read(char *ptr, size_t size) = 0;
  279. virtual int write(const char *ptr, size_t size1) = 0;
  280. virtual int write(const char *ptr) = 0;
  281. virtual int write(const std::string &s) = 0;
  282. virtual std::string get_remote_addr() const = 0;
  283. template <typename... Args>
  284. int write_format(const char *fmt, const Args &... args);
  285. };
  286. class TaskQueue {
  287. public:
  288. TaskQueue() = default;
  289. virtual ~TaskQueue() = default;
  290. virtual void enqueue(std::function<void()> fn) = 0;
  291. virtual void shutdown() = 0;
  292. };
  293. class ThreadPool : public TaskQueue {
  294. public:
  295. explicit ThreadPool(size_t n) : shutdown_(false) {
  296. while (n) {
  297. threads_.emplace_back(worker(*this));
  298. n--;
  299. }
  300. }
  301. ThreadPool(const ThreadPool &) = delete;
  302. ~ThreadPool() override = default;
  303. void enqueue(std::function<void()> fn) override {
  304. std::unique_lock<std::mutex> lock(mutex_);
  305. jobs_.push_back(fn);
  306. cond_.notify_one();
  307. }
  308. void shutdown() override {
  309. // Stop all worker threads...
  310. {
  311. std::unique_lock<std::mutex> lock(mutex_);
  312. shutdown_ = true;
  313. }
  314. cond_.notify_all();
  315. // Join...
  316. for (auto &t : threads_) {
  317. t.join();
  318. }
  319. }
  320. private:
  321. struct worker {
  322. explicit worker(ThreadPool &pool) : pool_(pool) {}
  323. void operator()() {
  324. for (;;) {
  325. std::function<void()> fn;
  326. {
  327. std::unique_lock<std::mutex> lock(pool_.mutex_);
  328. pool_.cond_.wait(
  329. lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
  330. if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
  331. fn = pool_.jobs_.front();
  332. pool_.jobs_.pop_front();
  333. }
  334. assert(true == static_cast<bool>(fn));
  335. fn();
  336. }
  337. }
  338. ThreadPool &pool_;
  339. };
  340. friend struct worker;
  341. std::vector<std::thread> threads_;
  342. std::list<std::function<void()>> jobs_;
  343. bool shutdown_;
  344. std::condition_variable cond_;
  345. std::mutex mutex_;
  346. };
  347. using Logger = std::function<void(const Request &, const Response &)>;
  348. class Server {
  349. public:
  350. using Handler = std::function<void(const Request &, Response &)>;
  351. using HandlerWithContentReader = std::function<void(
  352. const Request &, Response &, const ContentReader &content_reader)>;
  353. Server();
  354. virtual ~Server();
  355. virtual bool is_valid() const;
  356. Server &Get(const char *pattern, Handler handler);
  357. Server &Post(const char *pattern, Handler handler);
  358. Server &Post(const char *pattern, HandlerWithContentReader handler);
  359. Server &Put(const char *pattern, Handler handler);
  360. Server &Put(const char *pattern, HandlerWithContentReader handler);
  361. Server &Patch(const char *pattern, Handler handler);
  362. Server &Patch(const char *pattern, HandlerWithContentReader handler);
  363. Server &Delete(const char *pattern, Handler handler);
  364. Server &Options(const char *pattern, Handler handler);
  365. bool set_base_dir(const char *dir, const char *mount_point = nullptr);
  366. void set_file_extension_and_mimetype_mapping(const char *ext,
  367. const char *mime);
  368. void set_file_request_handler(Handler handler);
  369. void set_error_handler(Handler handler);
  370. void set_logger(Logger logger);
  371. void set_keep_alive_max_count(size_t count);
  372. void set_read_timeout(time_t sec, time_t usec);
  373. void set_payload_max_length(size_t length);
  374. bool bind_to_port(const char *host, int port, int socket_flags = 0);
  375. int bind_to_any_port(const char *host, int socket_flags = 0);
  376. bool listen_after_bind();
  377. bool listen(const char *host, int port, int socket_flags = 0);
  378. bool is_running() const;
  379. void stop();
  380. std::function<TaskQueue *(void)> new_task_queue;
  381. protected:
  382. bool process_request(Stream &strm, bool last_connection,
  383. bool &connection_close,
  384. const std::function<void(Request &)> &setup_request);
  385. size_t keep_alive_max_count_;
  386. time_t read_timeout_sec_;
  387. time_t read_timeout_usec_;
  388. size_t payload_max_length_;
  389. private:
  390. using Handlers = std::vector<std::pair<std::regex, Handler>>;
  391. using HandersForContentReader =
  392. std::vector<std::pair<std::regex, HandlerWithContentReader>>;
  393. socket_t create_server_socket(const char *host, int port,
  394. int socket_flags) const;
  395. int bind_internal(const char *host, int port, int socket_flags);
  396. bool listen_internal();
  397. bool routing(Request &req, Response &res, Stream &strm, bool last_connection);
  398. bool handle_file_request(Request &req, Response &res);
  399. bool dispatch_request(Request &req, Response &res, Handlers &handlers);
  400. bool dispatch_request_for_content_reader(Request &req, Response &res,
  401. ContentReader content_reader,
  402. HandersForContentReader &handlers);
  403. bool parse_request_line(const char *s, Request &req);
  404. bool write_response(Stream &strm, bool last_connection, const Request &req,
  405. Response &res);
  406. bool write_content_with_provider(Stream &strm, const Request &req,
  407. Response &res, const std::string &boundary,
  408. const std::string &content_type);
  409. bool read_content(Stream &strm, bool last_connection, Request &req,
  410. Response &res);
  411. bool read_content_with_content_receiver(
  412. Stream &strm, bool last_connection, Request &req, Response &res,
  413. ContentReceiver receiver, MultipartContentHeader multipart_header,
  414. ContentReceiver multipart_receiver);
  415. bool read_content_core(Stream &strm, bool last_connection, Request &req,
  416. Response &res, ContentReceiver receiver,
  417. MultipartContentHeader mulitpart_header,
  418. ContentReceiver multipart_receiver);
  419. virtual bool process_and_close_socket(socket_t sock);
  420. std::atomic<bool> is_running_;
  421. std::atomic<socket_t> svr_sock_;
  422. std::vector<std::pair<std::string, std::string>> base_dirs_;
  423. std::map<std::string, std::string> file_extension_and_mimetype_map_;
  424. Handler file_request_handler_;
  425. Handlers get_handlers_;
  426. Handlers post_handlers_;
  427. HandersForContentReader post_handlers_for_content_reader_;
  428. Handlers put_handlers_;
  429. HandersForContentReader put_handlers_for_content_reader_;
  430. Handlers patch_handlers_;
  431. HandersForContentReader patch_handlers_for_content_reader_;
  432. Handlers delete_handlers_;
  433. Handlers options_handlers_;
  434. Handler error_handler_;
  435. Logger logger_;
  436. };
  437. class Client {
  438. public:
  439. explicit Client(const std::string &host, int port = 80,
  440. const std::string &client_cert_path = std::string(),
  441. const std::string &client_key_path = std::string());
  442. virtual ~Client();
  443. virtual bool is_valid() const;
  444. std::shared_ptr<Response> Get(const char *path);
  445. std::shared_ptr<Response> Get(const char *path, const Headers &headers);
  446. std::shared_ptr<Response> Get(const char *path, Progress progress);
  447. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  448. Progress progress);
  449. std::shared_ptr<Response> Get(const char *path,
  450. ContentReceiver content_receiver);
  451. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  452. ContentReceiver content_receiver);
  453. std::shared_ptr<Response>
  454. Get(const char *path, ContentReceiver content_receiver, Progress progress);
  455. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  456. ContentReceiver content_receiver,
  457. Progress progress);
  458. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  459. ResponseHandler response_handler,
  460. ContentReceiver content_receiver);
  461. std::shared_ptr<Response> Get(const char *path, const Headers &headers,
  462. ResponseHandler response_handler,
  463. ContentReceiver content_receiver,
  464. Progress progress);
  465. std::shared_ptr<Response> Head(const char *path);
  466. std::shared_ptr<Response> Head(const char *path, const Headers &headers);
  467. std::shared_ptr<Response> Post(const char *path, const std::string &body,
  468. const char *content_type);
  469. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  470. const std::string &body,
  471. const char *content_type);
  472. std::shared_ptr<Response> Post(const char *path, size_t content_length,
  473. ContentProvider content_provider,
  474. const char *content_type);
  475. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  476. size_t content_length,
  477. ContentProvider content_provider,
  478. const char *content_type);
  479. std::shared_ptr<Response> Post(const char *path, const Params &params);
  480. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  481. const Params &params);
  482. std::shared_ptr<Response> Post(const char *path,
  483. const MultipartFormDataItems &items);
  484. std::shared_ptr<Response> Post(const char *path, const Headers &headers,
  485. const MultipartFormDataItems &items);
  486. std::shared_ptr<Response> Put(const char *path, const std::string &body,
  487. const char *content_type);
  488. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  489. const std::string &body,
  490. const char *content_type);
  491. std::shared_ptr<Response> Put(const char *path, size_t content_length,
  492. ContentProvider content_provider,
  493. const char *content_type);
  494. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  495. size_t content_length,
  496. ContentProvider content_provider,
  497. const char *content_type);
  498. std::shared_ptr<Response> Put(const char *path, const Params &params);
  499. std::shared_ptr<Response> Put(const char *path, const Headers &headers,
  500. const Params &params);
  501. std::shared_ptr<Response> Patch(const char *path, const std::string &body,
  502. const char *content_type);
  503. std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
  504. const std::string &body,
  505. const char *content_type);
  506. std::shared_ptr<Response> Patch(const char *path, size_t content_length,
  507. ContentProvider content_provider,
  508. const char *content_type);
  509. std::shared_ptr<Response> Patch(const char *path, const Headers &headers,
  510. size_t content_length,
  511. ContentProvider content_provider,
  512. const char *content_type);
  513. std::shared_ptr<Response> Delete(const char *path);
  514. std::shared_ptr<Response> Delete(const char *path, const std::string &body,
  515. const char *content_type);
  516. std::shared_ptr<Response> Delete(const char *path, const Headers &headers);
  517. std::shared_ptr<Response> Delete(const char *path, const Headers &headers,
  518. const std::string &body,
  519. const char *content_type);
  520. std::shared_ptr<Response> Options(const char *path);
  521. std::shared_ptr<Response> Options(const char *path, const Headers &headers);
  522. bool send(const Request &req, Response &res);
  523. bool send(const std::vector<Request> &requests,
  524. std::vector<Response> &responses);
  525. void set_timeout_sec(time_t timeout_sec);
  526. void set_read_timeout(time_t sec, time_t usec);
  527. void set_keep_alive_max_count(size_t count);
  528. void set_basic_auth(const char *username, const char *password);
  529. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  530. void set_digest_auth(const char *username, const char *password);
  531. #endif
  532. void set_follow_location(bool on);
  533. void set_compress(bool on);
  534. void set_interface(const char *intf);
  535. void set_proxy(const char *host, int port);
  536. void set_proxy_basic_auth(const char *username, const char *password);
  537. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  538. void set_proxy_digest_auth(const char *username, const char *password);
  539. #endif
  540. void set_logger(Logger logger);
  541. protected:
  542. bool process_request(Stream &strm, const Request &req, Response &res,
  543. bool last_connection, bool &connection_close);
  544. const std::string host_;
  545. const int port_;
  546. const std::string host_and_port_;
  547. // Settings
  548. std::string client_cert_path_;
  549. std::string client_key_path_;
  550. time_t timeout_sec_ = 300;
  551. time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
  552. time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
  553. size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
  554. std::string basic_auth_username_;
  555. std::string basic_auth_password_;
  556. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  557. std::string digest_auth_username_;
  558. std::string digest_auth_password_;
  559. #endif
  560. bool follow_location_ = false;
  561. bool compress_ = false;
  562. std::string interface_;
  563. std::string proxy_host_;
  564. int proxy_port_;
  565. std::string proxy_basic_auth_username_;
  566. std::string proxy_basic_auth_password_;
  567. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  568. std::string proxy_digest_auth_username_;
  569. std::string proxy_digest_auth_password_;
  570. #endif
  571. Logger logger_;
  572. void copy_settings(const Client &rhs) {
  573. client_cert_path_ = rhs.client_cert_path_;
  574. client_key_path_ = rhs.client_key_path_;
  575. timeout_sec_ = rhs.timeout_sec_;
  576. read_timeout_sec_ = rhs.read_timeout_sec_;
  577. read_timeout_usec_ = rhs.read_timeout_usec_;
  578. keep_alive_max_count_ = rhs.keep_alive_max_count_;
  579. basic_auth_username_ = rhs.basic_auth_username_;
  580. basic_auth_password_ = rhs.basic_auth_password_;
  581. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  582. digest_auth_username_ = rhs.digest_auth_username_;
  583. digest_auth_password_ = rhs.digest_auth_password_;
  584. #endif
  585. follow_location_ = rhs.follow_location_;
  586. compress_ = rhs.compress_;
  587. interface_ = rhs.interface_;
  588. proxy_host_ = rhs.proxy_host_;
  589. proxy_port_ = rhs.proxy_port_;
  590. proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
  591. proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
  592. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  593. proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
  594. proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
  595. #endif
  596. logger_ = rhs.logger_;
  597. }
  598. private:
  599. socket_t create_client_socket() const;
  600. bool read_response_line(Stream &strm, Response &res);
  601. bool write_request(Stream &strm, const Request &req, bool last_connection);
  602. bool redirect(const Request &req, Response &res);
  603. bool handle_request(Stream &strm, const Request &req, Response &res,
  604. bool last_connection, bool &connection_close);
  605. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  606. bool connect(socket_t sock, Response &res, bool &error);
  607. #endif
  608. std::shared_ptr<Response> send_with_content_provider(
  609. const char *method, const char *path, const Headers &headers,
  610. const std::string &body, size_t content_length,
  611. ContentProvider content_provider, const char *content_type);
  612. virtual bool process_and_close_socket(
  613. socket_t sock, size_t request_count,
  614. std::function<bool(Stream &strm, bool last_connection,
  615. bool &connection_close)>
  616. callback);
  617. virtual bool is_ssl() const;
  618. };
  619. inline void Get(std::vector<Request> &requests, const char *path,
  620. const Headers &headers) {
  621. Request req;
  622. req.method = "GET";
  623. req.path = path;
  624. req.headers = headers;
  625. requests.emplace_back(std::move(req));
  626. }
  627. inline void Get(std::vector<Request> &requests, const char *path) {
  628. Get(requests, path, Headers());
  629. }
  630. inline void Post(std::vector<Request> &requests, const char *path,
  631. const Headers &headers, const std::string &body,
  632. const char *content_type) {
  633. Request req;
  634. req.method = "POST";
  635. req.path = path;
  636. req.headers = headers;
  637. req.headers.emplace("Content-Type", content_type);
  638. req.body = body;
  639. requests.emplace_back(std::move(req));
  640. }
  641. inline void Post(std::vector<Request> &requests, const char *path,
  642. const std::string &body, const char *content_type) {
  643. Post(requests, path, Headers(), body, content_type);
  644. }
  645. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  646. class SSLServer : public Server {
  647. public:
  648. SSLServer(const char *cert_path, const char *private_key_path,
  649. const char *client_ca_cert_file_path = nullptr,
  650. const char *client_ca_cert_dir_path = nullptr);
  651. virtual ~SSLServer();
  652. virtual bool is_valid() const;
  653. private:
  654. virtual bool process_and_close_socket(socket_t sock);
  655. SSL_CTX *ctx_;
  656. std::mutex ctx_mutex_;
  657. };
  658. class SSLClient : public Client {
  659. public:
  660. SSLClient(const std::string &host, int port = 443,
  661. const std::string &client_cert_path = std::string(),
  662. const std::string &client_key_path = std::string());
  663. virtual ~SSLClient();
  664. virtual bool is_valid() const;
  665. void set_ca_cert_path(const char *ca_ceert_file_path,
  666. const char *ca_cert_dir_path = nullptr);
  667. void enable_server_certificate_verification(bool enabled);
  668. long get_openssl_verify_result() const;
  669. SSL_CTX *ssl_context() const noexcept;
  670. private:
  671. virtual bool process_and_close_socket(
  672. socket_t sock, size_t request_count,
  673. std::function<bool(Stream &strm, bool last_connection,
  674. bool &connection_close)>
  675. callback);
  676. virtual bool is_ssl() const;
  677. bool verify_host(X509 *server_cert) const;
  678. bool verify_host_with_subject_alt_name(X509 *server_cert) const;
  679. bool verify_host_with_common_name(X509 *server_cert) const;
  680. bool check_host_name(const char *pattern, size_t pattern_len) const;
  681. SSL_CTX *ctx_;
  682. std::mutex ctx_mutex_;
  683. std::vector<std::string> host_components_;
  684. std::string ca_cert_file_path_;
  685. std::string ca_cert_dir_path_;
  686. bool server_certificate_verification_ = false;
  687. long verify_result_ = 0;
  688. };
  689. #endif
  690. // ----------------------------------------------------------------------------
  691. /*
  692. * Implementation
  693. */
  694. namespace detail {
  695. inline bool is_hex(char c, int &v) {
  696. if (0x20 <= c && isdigit(c)) {
  697. v = c - '0';
  698. return true;
  699. } else if ('A' <= c && c <= 'F') {
  700. v = c - 'A' + 10;
  701. return true;
  702. } else if ('a' <= c && c <= 'f') {
  703. v = c - 'a' + 10;
  704. return true;
  705. }
  706. return false;
  707. }
  708. inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
  709. int &val) {
  710. if (i >= s.size()) { return false; }
  711. val = 0;
  712. for (; cnt; i++, cnt--) {
  713. if (!s[i]) { return false; }
  714. int v = 0;
  715. if (is_hex(s[i], v)) {
  716. val = val * 16 + v;
  717. } else {
  718. return false;
  719. }
  720. }
  721. return true;
  722. }
  723. inline std::string from_i_to_hex(size_t n) {
  724. const char *charset = "0123456789abcdef";
  725. std::string ret;
  726. do {
  727. ret = charset[n & 15] + ret;
  728. n >>= 4;
  729. } while (n > 0);
  730. return ret;
  731. }
  732. inline size_t to_utf8(int code, char *buff) {
  733. if (code < 0x0080) {
  734. buff[0] = (code & 0x7F);
  735. return 1;
  736. } else if (code < 0x0800) {
  737. buff[0] = (0xC0 | ((code >> 6) & 0x1F));
  738. buff[1] = (0x80 | (code & 0x3F));
  739. return 2;
  740. } else if (code < 0xD800) {
  741. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  742. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  743. buff[2] = (0x80 | (code & 0x3F));
  744. return 3;
  745. } else if (code < 0xE000) { // D800 - DFFF is invalid...
  746. return 0;
  747. } else if (code < 0x10000) {
  748. buff[0] = (0xE0 | ((code >> 12) & 0xF));
  749. buff[1] = (0x80 | ((code >> 6) & 0x3F));
  750. buff[2] = (0x80 | (code & 0x3F));
  751. return 3;
  752. } else if (code < 0x110000) {
  753. buff[0] = (0xF0 | ((code >> 18) & 0x7));
  754. buff[1] = (0x80 | ((code >> 12) & 0x3F));
  755. buff[2] = (0x80 | ((code >> 6) & 0x3F));
  756. buff[3] = (0x80 | (code & 0x3F));
  757. return 4;
  758. }
  759. // NOTREACHED
  760. return 0;
  761. }
  762. // NOTE: This code came up with the following stackoverflow post:
  763. // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
  764. inline std::string base64_encode(const std::string &in) {
  765. static const auto lookup =
  766. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  767. std::string out;
  768. out.reserve(in.size());
  769. int val = 0;
  770. int valb = -6;
  771. for (uint8_t c : in) {
  772. val = (val << 8) + c;
  773. valb += 8;
  774. while (valb >= 0) {
  775. out.push_back(lookup[(val >> valb) & 0x3F]);
  776. valb -= 6;
  777. }
  778. }
  779. if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
  780. while (out.size() % 4) {
  781. out.push_back('=');
  782. }
  783. return out;
  784. }
  785. inline bool is_file(const std::string &path) {
  786. struct stat st;
  787. return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
  788. }
  789. inline bool is_dir(const std::string &path) {
  790. struct stat st;
  791. return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
  792. }
  793. inline bool is_valid_path(const std::string &path) {
  794. size_t level = 0;
  795. size_t i = 0;
  796. // Skip slash
  797. while (i < path.size() && path[i] == '/') {
  798. i++;
  799. }
  800. while (i < path.size()) {
  801. // Read component
  802. auto beg = i;
  803. while (i < path.size() && path[i] != '/') {
  804. i++;
  805. }
  806. auto len = i - beg;
  807. assert(len > 0);
  808. if (!path.compare(beg, len, ".")) {
  809. ;
  810. } else if (!path.compare(beg, len, "..")) {
  811. if (level == 0) { return false; }
  812. level--;
  813. } else {
  814. level++;
  815. }
  816. // Skip slash
  817. while (i < path.size() && path[i] == '/') {
  818. i++;
  819. }
  820. }
  821. return true;
  822. }
  823. inline void read_file(const std::string &path, std::string &out) {
  824. std::ifstream fs(path, std::ios_base::binary);
  825. fs.seekg(0, std::ios_base::end);
  826. auto size = fs.tellg();
  827. fs.seekg(0);
  828. out.resize(static_cast<size_t>(size));
  829. fs.read(&out[0], size);
  830. }
  831. inline std::string file_extension(const std::string &path) {
  832. std::smatch m;
  833. static auto re = std::regex("\\.([a-zA-Z0-9]+)$");
  834. if (std::regex_search(path, m, re)) { return m[1].str(); }
  835. return std::string();
  836. }
  837. template <class Fn> void split(const char *b, const char *e, char d, Fn fn) {
  838. int i = 0;
  839. int beg = 0;
  840. while (e ? (b + i != e) : (b[i] != '\0')) {
  841. if (b[i] == d) {
  842. fn(&b[beg], &b[i]);
  843. beg = i + 1;
  844. }
  845. i++;
  846. }
  847. if (i) { fn(&b[beg], &b[i]); }
  848. }
  849. // NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
  850. // to store data. The call can set memory on stack for performance.
  851. class stream_line_reader {
  852. public:
  853. stream_line_reader(Stream &strm, char *fixed_buffer, size_t fixed_buffer_size)
  854. : strm_(strm), fixed_buffer_(fixed_buffer),
  855. fixed_buffer_size_(fixed_buffer_size) {}
  856. const char *ptr() const {
  857. if (glowable_buffer_.empty()) {
  858. return fixed_buffer_;
  859. } else {
  860. return glowable_buffer_.data();
  861. }
  862. }
  863. size_t size() const {
  864. if (glowable_buffer_.empty()) {
  865. return fixed_buffer_used_size_;
  866. } else {
  867. return glowable_buffer_.size();
  868. }
  869. }
  870. bool end_with_crlf() const {
  871. auto end = ptr() + size();
  872. return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
  873. }
  874. bool getline() {
  875. fixed_buffer_used_size_ = 0;
  876. glowable_buffer_.clear();
  877. for (size_t i = 0;; i++) {
  878. char byte;
  879. auto n = strm_.read(&byte, 1);
  880. if (n < 0) {
  881. return false;
  882. } else if (n == 0) {
  883. if (i == 0) {
  884. return false;
  885. } else {
  886. break;
  887. }
  888. }
  889. append(byte);
  890. if (byte == '\n') { break; }
  891. }
  892. return true;
  893. }
  894. private:
  895. void append(char c) {
  896. if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
  897. fixed_buffer_[fixed_buffer_used_size_++] = c;
  898. fixed_buffer_[fixed_buffer_used_size_] = '\0';
  899. } else {
  900. if (glowable_buffer_.empty()) {
  901. assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
  902. glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
  903. }
  904. glowable_buffer_ += c;
  905. }
  906. }
  907. Stream &strm_;
  908. char *fixed_buffer_;
  909. const size_t fixed_buffer_size_;
  910. size_t fixed_buffer_used_size_ = 0;
  911. std::string glowable_buffer_;
  912. };
  913. inline int close_socket(socket_t sock) {
  914. #ifdef _WIN32
  915. return closesocket(sock);
  916. #else
  917. return close(sock);
  918. #endif
  919. }
  920. inline int select_read(socket_t sock, time_t sec, time_t usec) {
  921. #ifdef CPPHTTPLIB_USE_POLL
  922. struct pollfd pfd_read;
  923. pfd_read.fd = sock;
  924. pfd_read.events = POLLIN;
  925. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  926. return poll(&pfd_read, 1, timeout);
  927. #else
  928. fd_set fds;
  929. FD_ZERO(&fds);
  930. FD_SET(sock, &fds);
  931. timeval tv;
  932. tv.tv_sec = static_cast<long>(sec);
  933. tv.tv_usec = static_cast<long>(usec);
  934. return select(static_cast<int>(sock + 1), &fds, nullptr, nullptr, &tv);
  935. #endif
  936. }
  937. inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
  938. #ifdef CPPHTTPLIB_USE_POLL
  939. struct pollfd pfd_read;
  940. pfd_read.fd = sock;
  941. pfd_read.events = POLLIN | POLLOUT;
  942. auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
  943. if (poll(&pfd_read, 1, timeout) > 0 &&
  944. pfd_read.revents & (POLLIN | POLLOUT)) {
  945. int error = 0;
  946. socklen_t len = sizeof(error);
  947. return getsockopt(sock, SOL_SOCKET, SO_ERROR,
  948. reinterpret_cast<char *>(&error), &len) >= 0 &&
  949. !error;
  950. }
  951. return false;
  952. #else
  953. fd_set fdsr;
  954. FD_ZERO(&fdsr);
  955. FD_SET(sock, &fdsr);
  956. auto fdsw = fdsr;
  957. auto fdse = fdsr;
  958. timeval tv;
  959. tv.tv_sec = static_cast<long>(sec);
  960. tv.tv_usec = static_cast<long>(usec);
  961. if (select(static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv) > 0 &&
  962. (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
  963. int error = 0;
  964. socklen_t len = sizeof(error);
  965. return getsockopt(sock, SOL_SOCKET, SO_ERROR,
  966. reinterpret_cast<char *>(&error), &len) >= 0 &&
  967. !error;
  968. }
  969. return false;
  970. #endif
  971. }
  972. class SocketStream : public Stream {
  973. public:
  974. SocketStream(socket_t sock, time_t read_timeout_sec,
  975. time_t read_timeout_usec);
  976. ~SocketStream() override;
  977. int read(char *ptr, size_t size) override;
  978. int write(const char *ptr, size_t size) override;
  979. int write(const char *ptr) override;
  980. int write(const std::string &s) override;
  981. std::string get_remote_addr() const override;
  982. private:
  983. socket_t sock_;
  984. time_t read_timeout_sec_;
  985. time_t read_timeout_usec_;
  986. };
  987. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  988. class SSLSocketStream : public Stream {
  989. public:
  990. SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec,
  991. time_t read_timeout_usec);
  992. virtual ~SSLSocketStream();
  993. virtual int read(char *ptr, size_t size);
  994. virtual int write(const char *ptr, size_t size);
  995. virtual int write(const char *ptr);
  996. virtual int write(const std::string &s);
  997. virtual std::string get_remote_addr() const;
  998. private:
  999. socket_t sock_;
  1000. SSL *ssl_;
  1001. time_t read_timeout_sec_;
  1002. time_t read_timeout_usec_;
  1003. };
  1004. #endif
  1005. class BufferStream : public Stream {
  1006. public:
  1007. BufferStream() = default;
  1008. ~BufferStream() override = default;
  1009. int read(char *ptr, size_t size) override;
  1010. int write(const char *ptr, size_t size) override;
  1011. int write(const char *ptr) override;
  1012. int write(const std::string &s) override;
  1013. std::string get_remote_addr() const override;
  1014. const std::string &get_buffer() const;
  1015. private:
  1016. std::string buffer;
  1017. int position = 0;
  1018. };
  1019. template <typename T>
  1020. inline bool process_socket(bool is_client_request, socket_t sock,
  1021. size_t keep_alive_max_count, time_t read_timeout_sec,
  1022. time_t read_timeout_usec, T callback) {
  1023. assert(keep_alive_max_count > 0);
  1024. auto ret = false;
  1025. if (keep_alive_max_count > 1) {
  1026. auto count = keep_alive_max_count;
  1027. while (count > 0 &&
  1028. (is_client_request ||
  1029. select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  1030. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) {
  1031. SocketStream strm(sock, read_timeout_sec, read_timeout_usec);
  1032. auto last_connection = count == 1;
  1033. auto connection_close = false;
  1034. ret = callback(strm, last_connection, connection_close);
  1035. if (!ret || connection_close) { break; }
  1036. count--;
  1037. }
  1038. } else { // keep_alive_max_count is 0 or 1
  1039. SocketStream strm(sock, read_timeout_sec, read_timeout_usec);
  1040. auto dummy_connection_close = false;
  1041. ret = callback(strm, true, dummy_connection_close);
  1042. }
  1043. return ret;
  1044. }
  1045. template <typename T>
  1046. inline bool process_and_close_socket(bool is_client_request, socket_t sock,
  1047. size_t keep_alive_max_count,
  1048. time_t read_timeout_sec,
  1049. time_t read_timeout_usec, T callback) {
  1050. auto ret = process_socket(is_client_request, sock, keep_alive_max_count,
  1051. read_timeout_sec, read_timeout_usec, callback);
  1052. close_socket(sock);
  1053. return ret;
  1054. }
  1055. inline int shutdown_socket(socket_t sock) {
  1056. #ifdef _WIN32
  1057. return shutdown(sock, SD_BOTH);
  1058. #else
  1059. return shutdown(sock, SHUT_RDWR);
  1060. #endif
  1061. }
  1062. template <typename Fn>
  1063. socket_t create_socket(const char *host, int port, Fn fn,
  1064. int socket_flags = 0) {
  1065. #ifdef _WIN32
  1066. #define SO_SYNCHRONOUS_NONALERT 0x20
  1067. #define SO_OPENTYPE 0x7008
  1068. int opt = SO_SYNCHRONOUS_NONALERT;
  1069. setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&opt,
  1070. sizeof(opt));
  1071. #endif
  1072. // Get address info
  1073. struct addrinfo hints;
  1074. struct addrinfo *result;
  1075. memset(&hints, 0, sizeof(struct addrinfo));
  1076. hints.ai_family = AF_UNSPEC;
  1077. hints.ai_socktype = SOCK_STREAM;
  1078. hints.ai_flags = socket_flags;
  1079. hints.ai_protocol = 0;
  1080. auto service = std::to_string(port);
  1081. if (getaddrinfo(host, service.c_str(), &hints, &result)) {
  1082. return INVALID_SOCKET;
  1083. }
  1084. for (auto rp = result; rp; rp = rp->ai_next) {
  1085. // Create a socket
  1086. #ifdef _WIN32
  1087. auto sock = WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol,
  1088. nullptr, 0, WSA_FLAG_NO_HANDLE_INHERIT);
  1089. /**
  1090. * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
  1091. * and above the socket creation fails on older Windows Systems.
  1092. *
  1093. * Let's try to create a socket the old way in this case.
  1094. *
  1095. * Reference:
  1096. * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
  1097. *
  1098. * WSA_FLAG_NO_HANDLE_INHERIT:
  1099. * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
  1100. * SP1, and later
  1101. *
  1102. */
  1103. if (sock == INVALID_SOCKET) {
  1104. sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  1105. }
  1106. #else
  1107. auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  1108. #endif
  1109. if (sock == INVALID_SOCKET) { continue; }
  1110. #ifndef _WIN32
  1111. if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { continue; }
  1112. #endif
  1113. // Make 'reuse address' option available
  1114. int yes = 1;
  1115. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&yes),
  1116. sizeof(yes));
  1117. #ifdef SO_REUSEPORT
  1118. setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<char *>(&yes),
  1119. sizeof(yes));
  1120. #endif
  1121. // bind or connect
  1122. if (fn(sock, *rp)) {
  1123. freeaddrinfo(result);
  1124. return sock;
  1125. }
  1126. close_socket(sock);
  1127. }
  1128. freeaddrinfo(result);
  1129. return INVALID_SOCKET;
  1130. }
  1131. inline void set_nonblocking(socket_t sock, bool nonblocking) {
  1132. #ifdef _WIN32
  1133. auto flags = nonblocking ? 1UL : 0UL;
  1134. ioctlsocket(sock, FIONBIO, &flags);
  1135. #else
  1136. auto flags = fcntl(sock, F_GETFL, 0);
  1137. fcntl(sock, F_SETFL,
  1138. nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
  1139. #endif
  1140. }
  1141. inline bool is_connection_error() {
  1142. #ifdef _WIN32
  1143. return WSAGetLastError() != WSAEWOULDBLOCK;
  1144. #else
  1145. return errno != EINPROGRESS;
  1146. #endif
  1147. }
  1148. inline bool bind_ip_address(socket_t sock, const char *host) {
  1149. struct addrinfo hints;
  1150. struct addrinfo *result;
  1151. memset(&hints, 0, sizeof(struct addrinfo));
  1152. hints.ai_family = AF_UNSPEC;
  1153. hints.ai_socktype = SOCK_STREAM;
  1154. hints.ai_protocol = 0;
  1155. if (getaddrinfo(host, "0", &hints, &result)) { return false; }
  1156. auto ret = false;
  1157. for (auto rp = result; rp; rp = rp->ai_next) {
  1158. const auto &ai = *rp;
  1159. if (!::bind(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen))) {
  1160. ret = true;
  1161. break;
  1162. }
  1163. }
  1164. freeaddrinfo(result);
  1165. return ret;
  1166. }
  1167. inline std::string if2ip(const std::string &ifn) {
  1168. #ifndef _WIN32
  1169. struct ifaddrs *ifap;
  1170. getifaddrs(&ifap);
  1171. for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
  1172. if (ifa->ifa_addr && ifn == ifa->ifa_name) {
  1173. if (ifa->ifa_addr->sa_family == AF_INET) {
  1174. auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
  1175. char buf[INET_ADDRSTRLEN];
  1176. if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
  1177. freeifaddrs(ifap);
  1178. return std::string(buf, INET_ADDRSTRLEN);
  1179. }
  1180. }
  1181. }
  1182. }
  1183. freeifaddrs(ifap);
  1184. #endif
  1185. return std::string();
  1186. }
  1187. inline socket_t create_client_socket(const char *host, int port,
  1188. time_t timeout_sec,
  1189. const std::string &intf) {
  1190. return create_socket(
  1191. host, port, [&](socket_t sock, struct addrinfo &ai) -> bool {
  1192. if (!intf.empty()) {
  1193. auto ip = if2ip(intf);
  1194. if (ip.empty()) { ip = intf; }
  1195. if (!bind_ip_address(sock, ip.c_str())) { return false; }
  1196. }
  1197. set_nonblocking(sock, true);
  1198. auto ret = ::connect(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen));
  1199. if (ret < 0) {
  1200. if (is_connection_error() ||
  1201. !wait_until_socket_is_ready(sock, timeout_sec, 0)) {
  1202. close_socket(sock);
  1203. return false;
  1204. }
  1205. }
  1206. set_nonblocking(sock, false);
  1207. return true;
  1208. });
  1209. }
  1210. inline std::string get_remote_addr(socket_t sock) {
  1211. struct sockaddr_storage addr;
  1212. socklen_t len = sizeof(addr);
  1213. if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr), &len)) {
  1214. std::array<char, NI_MAXHOST> ipstr{};
  1215. if (!getnameinfo(reinterpret_cast<struct sockaddr *>(&addr), len,
  1216. ipstr.data(), ipstr.size(), nullptr, 0, NI_NUMERICHOST)) {
  1217. return ipstr.data();
  1218. }
  1219. }
  1220. return std::string();
  1221. }
  1222. inline const char *
  1223. find_content_type(const std::string &path,
  1224. const std::map<std::string, std::string> &user_data) {
  1225. auto ext = file_extension(path);
  1226. auto it = user_data.find(ext);
  1227. if (it != user_data.end()) { return it->second.c_str(); }
  1228. if (ext == "txt") {
  1229. return "text/plain";
  1230. } else if (ext == "html" || ext == "htm") {
  1231. return "text/html";
  1232. } else if (ext == "css") {
  1233. return "text/css";
  1234. } else if (ext == "jpeg" || ext == "jpg") {
  1235. return "image/jpg";
  1236. } else if (ext == "png") {
  1237. return "image/png";
  1238. } else if (ext == "gif") {
  1239. return "image/gif";
  1240. } else if (ext == "svg") {
  1241. return "image/svg+xml";
  1242. } else if (ext == "ico") {
  1243. return "image/x-icon";
  1244. } else if (ext == "json") {
  1245. return "application/json";
  1246. } else if (ext == "pdf") {
  1247. return "application/pdf";
  1248. } else if (ext == "js") {
  1249. return "application/javascript";
  1250. } else if (ext == "wasm") {
  1251. return "application/wasm";
  1252. } else if (ext == "xml") {
  1253. return "application/xml";
  1254. } else if (ext == "xhtml") {
  1255. return "application/xhtml+xml";
  1256. }
  1257. return nullptr;
  1258. }
  1259. inline const char *status_message(int status) {
  1260. switch (status) {
  1261. case 200: return "OK";
  1262. case 202: return "Accepted";
  1263. case 204: return "No Content";
  1264. case 206: return "Partial Content";
  1265. case 301: return "Moved Permanently";
  1266. case 302: return "Found";
  1267. case 303: return "See Other";
  1268. case 304: return "Not Modified";
  1269. case 400: return "Bad Request";
  1270. case 401: return "Unauthorized";
  1271. case 403: return "Forbidden";
  1272. case 404: return "Not Found";
  1273. case 413: return "Payload Too Large";
  1274. case 414: return "Request-URI Too Long";
  1275. case 415: return "Unsupported Media Type";
  1276. case 416: return "Range Not Satisfiable";
  1277. default:
  1278. case 500: return "Internal Server Error";
  1279. }
  1280. }
  1281. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1282. inline bool can_compress(const std::string &content_type) {
  1283. return !content_type.find("text/") || content_type == "image/svg+xml" ||
  1284. content_type == "application/javascript" ||
  1285. content_type == "application/json" ||
  1286. content_type == "application/xml" ||
  1287. content_type == "application/xhtml+xml";
  1288. }
  1289. inline bool compress(std::string &content) {
  1290. z_stream strm;
  1291. strm.zalloc = Z_NULL;
  1292. strm.zfree = Z_NULL;
  1293. strm.opaque = Z_NULL;
  1294. auto ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
  1295. Z_DEFAULT_STRATEGY);
  1296. if (ret != Z_OK) { return false; }
  1297. strm.avail_in = content.size();
  1298. strm.next_in =
  1299. const_cast<Bytef *>(reinterpret_cast<const Bytef *>(content.data()));
  1300. std::string compressed;
  1301. std::array<char, 16384> buff{};
  1302. do {
  1303. strm.avail_out = buff.size();
  1304. strm.next_out = reinterpret_cast<Bytef *>(buff.data());
  1305. ret = deflate(&strm, Z_FINISH);
  1306. assert(ret != Z_STREAM_ERROR);
  1307. compressed.append(buff.data(), buff.size() - strm.avail_out);
  1308. } while (strm.avail_out == 0);
  1309. assert(ret == Z_STREAM_END);
  1310. assert(strm.avail_in == 0);
  1311. content.swap(compressed);
  1312. deflateEnd(&strm);
  1313. return true;
  1314. }
  1315. class decompressor {
  1316. public:
  1317. decompressor() {
  1318. strm.zalloc = Z_NULL;
  1319. strm.zfree = Z_NULL;
  1320. strm.opaque = Z_NULL;
  1321. // 15 is the value of wbits, which should be at the maximum possible value
  1322. // to ensure that any gzip stream can be decoded. The offset of 16 specifies
  1323. // that the stream to decompress will be formatted with a gzip wrapper.
  1324. is_valid_ = inflateInit2(&strm, 16 + 15) == Z_OK;
  1325. }
  1326. ~decompressor() { inflateEnd(&strm); }
  1327. bool is_valid() const { return is_valid_; }
  1328. template <typename T>
  1329. bool decompress(const char *data, size_t data_length, T callback) {
  1330. int ret = Z_OK;
  1331. strm.avail_in = data_length;
  1332. strm.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
  1333. std::array<char, 16384> buff{};
  1334. do {
  1335. strm.avail_out = buff.size();
  1336. strm.next_out = reinterpret_cast<Bytef *>(buff.data());
  1337. ret = inflate(&strm, Z_NO_FLUSH);
  1338. assert(ret != Z_STREAM_ERROR);
  1339. switch (ret) {
  1340. case Z_NEED_DICT:
  1341. case Z_DATA_ERROR:
  1342. case Z_MEM_ERROR: inflateEnd(&strm); return false;
  1343. }
  1344. if (!callback(buff.data(), buff.size() - strm.avail_out)) {
  1345. return false;
  1346. }
  1347. } while (strm.avail_out == 0);
  1348. return ret == Z_OK || ret == Z_STREAM_END;
  1349. }
  1350. private:
  1351. bool is_valid_;
  1352. z_stream strm;
  1353. };
  1354. #endif
  1355. inline bool has_header(const Headers &headers, const char *key) {
  1356. return headers.find(key) != headers.end();
  1357. }
  1358. inline const char *get_header_value(const Headers &headers, const char *key,
  1359. size_t id = 0, const char *def = nullptr) {
  1360. auto it = headers.find(key);
  1361. std::advance(it, id);
  1362. if (it != headers.end()) { return it->second.c_str(); }
  1363. return def;
  1364. }
  1365. inline uint64_t get_header_value_uint64(const Headers &headers, const char *key,
  1366. int def = 0) {
  1367. auto it = headers.find(key);
  1368. if (it != headers.end()) {
  1369. return std::strtoull(it->second.data(), nullptr, 10);
  1370. }
  1371. return def;
  1372. }
  1373. inline bool read_headers(Stream &strm, Headers &headers) {
  1374. const auto bufsiz = 2048;
  1375. char buf[bufsiz];
  1376. stream_line_reader line_reader(strm, buf, bufsiz);
  1377. for (;;) {
  1378. if (!line_reader.getline()) { return false; }
  1379. // Check if the line ends with CRLF.
  1380. if (line_reader.end_with_crlf()) {
  1381. // Blank line indicates end of headers.
  1382. if (line_reader.size() == 2) { break; }
  1383. } else {
  1384. continue; // Skip invalid line.
  1385. }
  1386. // Skip trailing spaces and tabs.
  1387. auto end = line_reader.ptr() + line_reader.size() - 2;
  1388. while (line_reader.ptr() < end && (end[-1] == ' ' || end[-1] == '\t')) {
  1389. end--;
  1390. }
  1391. // Horizontal tab and ' ' are considered whitespace and are ignored when on
  1392. // the left or right side of the header value:
  1393. // - https://stackoverflow.com/questions/50179659/
  1394. // - https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
  1395. static const std::regex re(R"((.+?):[\t ]*(.+))");
  1396. std::cmatch m;
  1397. if (std::regex_match(line_reader.ptr(), end, m, re)) {
  1398. auto key = std::string(m[1]);
  1399. auto val = std::string(m[2]);
  1400. headers.emplace(key, val);
  1401. }
  1402. }
  1403. return true;
  1404. }
  1405. inline bool read_content_with_length(Stream &strm, uint64_t len,
  1406. Progress progress, ContentReceiver out) {
  1407. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1408. uint64_t r = 0;
  1409. while (r < len) {
  1410. auto read_len = static_cast<size_t>(len - r);
  1411. auto n = strm.read(buf, std::min(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  1412. if (n <= 0) { return false; }
  1413. if (!out(buf, n)) { return false; }
  1414. r += n;
  1415. if (progress) {
  1416. if (!progress(r, len)) { return false; }
  1417. }
  1418. }
  1419. return true;
  1420. }
  1421. inline void skip_content_with_length(Stream &strm, uint64_t len) {
  1422. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1423. uint64_t r = 0;
  1424. while (r < len) {
  1425. auto read_len = static_cast<size_t>(len - r);
  1426. auto n = strm.read(buf, std::min(read_len, CPPHTTPLIB_RECV_BUFSIZ));
  1427. if (n <= 0) { return; }
  1428. r += n;
  1429. }
  1430. }
  1431. inline bool read_content_without_length(Stream &strm, ContentReceiver out) {
  1432. char buf[CPPHTTPLIB_RECV_BUFSIZ];
  1433. for (;;) {
  1434. auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
  1435. if (n < 0) {
  1436. return false;
  1437. } else if (n == 0) {
  1438. return true;
  1439. }
  1440. if (!out(buf, n)) { return false; }
  1441. }
  1442. return true;
  1443. }
  1444. inline bool read_content_chunked(Stream &strm, ContentReceiver out) {
  1445. const auto bufsiz = 16;
  1446. char buf[bufsiz];
  1447. stream_line_reader line_reader(strm, buf, bufsiz);
  1448. if (!line_reader.getline()) { return false; }
  1449. auto chunk_len = std::stoi(line_reader.ptr(), 0, 16);
  1450. while (chunk_len > 0) {
  1451. if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
  1452. return false;
  1453. }
  1454. if (!line_reader.getline()) { return false; }
  1455. if (strcmp(line_reader.ptr(), "\r\n")) { break; }
  1456. if (!line_reader.getline()) { return false; }
  1457. chunk_len = std::stoi(line_reader.ptr(), 0, 16);
  1458. }
  1459. if (chunk_len == 0) {
  1460. // Reader terminator after chunks
  1461. if (!line_reader.getline() || strcmp(line_reader.ptr(), "\r\n"))
  1462. return false;
  1463. }
  1464. return true;
  1465. }
  1466. inline bool is_chunked_transfer_encoding(const Headers &headers) {
  1467. return !strcasecmp(get_header_value(headers, "Transfer-Encoding", 0, ""),
  1468. "chunked");
  1469. }
  1470. template <typename T>
  1471. bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
  1472. Progress progress, ContentReceiver receiver) {
  1473. ContentReceiver out = [&](const char *buf, size_t n) {
  1474. return receiver(buf, n);
  1475. };
  1476. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1477. decompressor decompressor;
  1478. if (!decompressor.is_valid()) {
  1479. status = 500;
  1480. return false;
  1481. }
  1482. if (x.get_header_value("Content-Encoding") == "gzip") {
  1483. out = [&](const char *buf, size_t n) {
  1484. return decompressor.decompress(
  1485. buf, n, [&](const char *buf, size_t n) { return receiver(buf, n); });
  1486. };
  1487. }
  1488. #else
  1489. if (x.get_header_value("Content-Encoding") == "gzip") {
  1490. status = 415;
  1491. return false;
  1492. }
  1493. #endif
  1494. auto ret = true;
  1495. auto exceed_payload_max_length = false;
  1496. if (is_chunked_transfer_encoding(x.headers)) {
  1497. ret = read_content_chunked(strm, out);
  1498. } else if (!has_header(x.headers, "Content-Length")) {
  1499. ret = read_content_without_length(strm, out);
  1500. } else {
  1501. auto len = get_header_value_uint64(x.headers, "Content-Length", 0);
  1502. if (len > payload_max_length) {
  1503. exceed_payload_max_length = true;
  1504. skip_content_with_length(strm, len);
  1505. ret = false;
  1506. } else if (len > 0) {
  1507. ret = read_content_with_length(strm, len, progress, out);
  1508. }
  1509. }
  1510. if (!ret) { status = exceed_payload_max_length ? 413 : 400; }
  1511. return ret;
  1512. }
  1513. template <typename T>
  1514. inline int write_headers(Stream &strm, const T &info, const Headers &headers) {
  1515. auto write_len = 0;
  1516. for (const auto &x : info.headers) {
  1517. auto len =
  1518. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  1519. if (len < 0) { return len; }
  1520. write_len += len;
  1521. }
  1522. for (const auto &x : headers) {
  1523. auto len =
  1524. strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
  1525. if (len < 0) { return len; }
  1526. write_len += len;
  1527. }
  1528. auto len = strm.write("\r\n");
  1529. if (len < 0) { return len; }
  1530. write_len += len;
  1531. return write_len;
  1532. }
  1533. inline ssize_t write_content(Stream &strm, ContentProvider content_provider,
  1534. size_t offset, size_t length) {
  1535. size_t begin_offset = offset;
  1536. size_t end_offset = offset + length;
  1537. while (offset < end_offset) {
  1538. ssize_t written_length = 0;
  1539. DataSink data_sink;
  1540. data_sink.write = [&](const char *d, size_t l) {
  1541. offset += l;
  1542. written_length = strm.write(d, l);
  1543. };
  1544. data_sink.done = [&](void) { written_length = -1; };
  1545. content_provider(offset, end_offset - offset, data_sink);
  1546. if (written_length < 0) { return written_length; }
  1547. }
  1548. return static_cast<ssize_t>(offset - begin_offset);
  1549. }
  1550. template <typename T>
  1551. inline ssize_t write_content_chunked(Stream &strm,
  1552. ContentProvider content_provider,
  1553. T is_shutting_down) {
  1554. size_t offset = 0;
  1555. auto data_available = true;
  1556. ssize_t total_written_length = 0;
  1557. while (data_available && !is_shutting_down()) {
  1558. ssize_t written_length = 0;
  1559. DataSink data_sink;
  1560. data_sink.write = [&](const char *d, size_t l) {
  1561. data_available = l > 0;
  1562. offset += l;
  1563. // Emit chunked response header and footer for each chunk
  1564. auto chunk = from_i_to_hex(l) + "\r\n" + std::string(d, l) + "\r\n";
  1565. written_length = strm.write(chunk);
  1566. };
  1567. data_sink.done = [&](void) {
  1568. data_available = false;
  1569. written_length = strm.write("0\r\n\r\n");
  1570. };
  1571. content_provider(offset, 0, data_sink);
  1572. if (written_length < 0) { return written_length; }
  1573. total_written_length += written_length;
  1574. }
  1575. return total_written_length;
  1576. }
  1577. template <typename T>
  1578. inline bool redirect(T &cli, const Request &req, Response &res,
  1579. const std::string &path) {
  1580. Request new_req = req;
  1581. new_req.path = path;
  1582. new_req.redirect_count -= 1;
  1583. Response new_res;
  1584. auto ret = cli.send(new_req, new_res);
  1585. if (ret) { res = new_res; }
  1586. return ret;
  1587. }
  1588. inline std::string encode_url(const std::string &s) {
  1589. std::string result;
  1590. for (auto i = 0; s[i]; i++) {
  1591. switch (s[i]) {
  1592. case ' ': result += "%20"; break;
  1593. case '+': result += "%2B"; break;
  1594. case '\r': result += "%0D"; break;
  1595. case '\n': result += "%0A"; break;
  1596. case '\'': result += "%27"; break;
  1597. case ',': result += "%2C"; break;
  1598. // case ':': result += "%3A"; break; // ok? probably...
  1599. case ';': result += "%3B"; break;
  1600. default:
  1601. auto c = static_cast<uint8_t>(s[i]);
  1602. if (c >= 0x80) {
  1603. result += '%';
  1604. char hex[4];
  1605. size_t len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
  1606. assert(len == 2);
  1607. result.append(hex, len);
  1608. } else {
  1609. result += s[i];
  1610. }
  1611. break;
  1612. }
  1613. }
  1614. return result;
  1615. }
  1616. inline std::string decode_url(const std::string &s) {
  1617. std::string result;
  1618. for (size_t i = 0; i < s.size(); i++) {
  1619. if (s[i] == '%' && i + 1 < s.size()) {
  1620. if (s[i + 1] == 'u') {
  1621. int val = 0;
  1622. if (from_hex_to_i(s, i + 2, 4, val)) {
  1623. // 4 digits Unicode codes
  1624. char buff[4];
  1625. size_t len = to_utf8(val, buff);
  1626. if (len > 0) { result.append(buff, len); }
  1627. i += 5; // 'u0000'
  1628. } else {
  1629. result += s[i];
  1630. }
  1631. } else {
  1632. int val = 0;
  1633. if (from_hex_to_i(s, i + 1, 2, val)) {
  1634. // 2 digits hex codes
  1635. result += static_cast<char>(val);
  1636. i += 2; // '00'
  1637. } else {
  1638. result += s[i];
  1639. }
  1640. }
  1641. } else if (s[i] == '+') {
  1642. result += ' ';
  1643. } else {
  1644. result += s[i];
  1645. }
  1646. }
  1647. return result;
  1648. }
  1649. inline void parse_query_text(const std::string &s, Params &params) {
  1650. split(&s[0], &s[s.size()], '&', [&](const char *b, const char *e) {
  1651. std::string key;
  1652. std::string val;
  1653. split(b, e, '=', [&](const char *b, const char *e) {
  1654. if (key.empty()) {
  1655. key.assign(b, e);
  1656. } else {
  1657. val.assign(b, e);
  1658. }
  1659. });
  1660. params.emplace(key, decode_url(val));
  1661. });
  1662. }
  1663. inline bool parse_multipart_boundary(const std::string &content_type,
  1664. std::string &boundary) {
  1665. auto pos = content_type.find("boundary=");
  1666. if (pos == std::string::npos) { return false; }
  1667. boundary = content_type.substr(pos + 9);
  1668. return true;
  1669. }
  1670. inline bool parse_range_header(const std::string &s, Ranges &ranges) {
  1671. static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))");
  1672. std::smatch m;
  1673. if (std::regex_match(s, m, re_first_range)) {
  1674. auto pos = m.position(1);
  1675. auto len = m.length(1);
  1676. bool all_valid_ranges = true;
  1677. split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
  1678. if (!all_valid_ranges) return;
  1679. static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))");
  1680. std::cmatch m;
  1681. if (std::regex_match(b, e, m, re_another_range)) {
  1682. ssize_t first = -1;
  1683. if (!m.str(1).empty()) {
  1684. first = static_cast<ssize_t>(std::stoll(m.str(1)));
  1685. }
  1686. ssize_t last = -1;
  1687. if (!m.str(2).empty()) {
  1688. last = static_cast<ssize_t>(std::stoll(m.str(2)));
  1689. }
  1690. if (first != -1 && last != -1 && first > last) {
  1691. all_valid_ranges = false;
  1692. return;
  1693. }
  1694. ranges.emplace_back(std::make_pair(first, last));
  1695. }
  1696. });
  1697. return all_valid_ranges;
  1698. }
  1699. return false;
  1700. }
  1701. class MultipartFormDataParser {
  1702. public:
  1703. MultipartFormDataParser() {}
  1704. void set_boundary(const std::string &boundary) { boundary_ = boundary; }
  1705. bool is_valid() const { return is_valid_; }
  1706. template <typename T, typename U>
  1707. bool parse(const char *buf, size_t n, T content_callback, U header_callback) {
  1708. static const std::regex re_content_type(R"(^Content-Type:\s*(.*?)\s*$)",
  1709. std::regex_constants::icase);
  1710. static const std::regex re_content_disposition(
  1711. "^Content-Disposition:\\s*form-data;\\s*name=\"(.*?)\"(?:;\\s*filename="
  1712. "\"(.*?)\")?\\s*$",
  1713. std::regex_constants::icase);
  1714. buf_.append(buf, n); // TODO: performance improvement
  1715. while (!buf_.empty()) {
  1716. switch (state_) {
  1717. case 0: { // Initial boundary
  1718. auto pattern = dash_ + boundary_ + crlf_;
  1719. if (pattern.size() > buf_.size()) { return true; }
  1720. auto pos = buf_.find(pattern);
  1721. if (pos != 0) {
  1722. is_done_ = true;
  1723. return false;
  1724. }
  1725. buf_.erase(0, pattern.size());
  1726. off_ += pattern.size();
  1727. state_ = 1;
  1728. break;
  1729. }
  1730. case 1: { // New entry
  1731. clear_file_info();
  1732. state_ = 2;
  1733. break;
  1734. }
  1735. case 2: { // Headers
  1736. auto pos = buf_.find(crlf_);
  1737. while (pos != std::string::npos) {
  1738. // Empty line
  1739. if (pos == 0) {
  1740. if (!header_callback(file_)) {
  1741. is_valid_ = false;
  1742. is_done_ = false;
  1743. return false;
  1744. }
  1745. buf_.erase(0, crlf_.size());
  1746. off_ += crlf_.size();
  1747. state_ = 3;
  1748. break;
  1749. }
  1750. auto header = buf_.substr(0, pos);
  1751. {
  1752. std::smatch m;
  1753. if (std::regex_match(header, m, re_content_type)) {
  1754. file_.content_type = m[1];
  1755. } else if (std::regex_match(header, m, re_content_disposition)) {
  1756. file_.name = m[1];
  1757. file_.filename = m[2];
  1758. }
  1759. }
  1760. buf_.erase(0, pos + crlf_.size());
  1761. off_ += pos + crlf_.size();
  1762. pos = buf_.find(crlf_);
  1763. }
  1764. break;
  1765. }
  1766. case 3: { // Body
  1767. {
  1768. auto pattern = crlf_ + dash_;
  1769. if (pattern.size() > buf_.size()) { return true; }
  1770. auto pos = buf_.find(pattern);
  1771. if (pos == std::string::npos) { pos = buf_.size(); }
  1772. if (!content_callback(buf_.data(), pos)) {
  1773. is_valid_ = false;
  1774. is_done_ = false;
  1775. return false;
  1776. }
  1777. off_ += pos;
  1778. buf_.erase(0, pos);
  1779. }
  1780. {
  1781. auto pattern = crlf_ + dash_ + boundary_;
  1782. if (pattern.size() > buf_.size()) { return true; }
  1783. auto pos = buf_.find(pattern);
  1784. if (pos != std::string::npos) {
  1785. if (!content_callback(buf_.data(), pos)) {
  1786. is_valid_ = false;
  1787. is_done_ = false;
  1788. return false;
  1789. }
  1790. off_ += pos + pattern.size();
  1791. buf_.erase(0, pos + pattern.size());
  1792. state_ = 4;
  1793. } else {
  1794. if (!content_callback(buf_.data(), pattern.size())) {
  1795. is_valid_ = false;
  1796. is_done_ = false;
  1797. return false;
  1798. }
  1799. off_ += pattern.size();
  1800. buf_.erase(0, pattern.size());
  1801. }
  1802. }
  1803. break;
  1804. }
  1805. case 4: { // Boundary
  1806. if (crlf_.size() > buf_.size()) { return true; }
  1807. if (buf_.find(crlf_) == 0) {
  1808. buf_.erase(0, crlf_.size());
  1809. off_ += crlf_.size();
  1810. state_ = 1;
  1811. } else {
  1812. auto pattern = dash_ + crlf_;
  1813. if (pattern.size() > buf_.size()) { return true; }
  1814. if (buf_.find(pattern) == 0) {
  1815. buf_.erase(0, pattern.size());
  1816. off_ += pattern.size();
  1817. is_valid_ = true;
  1818. state_ = 5;
  1819. } else {
  1820. is_done_ = true;
  1821. return true;
  1822. }
  1823. }
  1824. break;
  1825. }
  1826. case 5: { // Done
  1827. is_valid_ = false;
  1828. return false;
  1829. }
  1830. }
  1831. }
  1832. return true;
  1833. }
  1834. private:
  1835. void clear_file_info() {
  1836. file_.name.clear();
  1837. file_.filename.clear();
  1838. file_.content_type.clear();
  1839. }
  1840. const std::string dash_ = "--";
  1841. const std::string crlf_ = "\r\n";
  1842. std::string boundary_;
  1843. std::string buf_;
  1844. size_t state_ = 0;
  1845. size_t is_valid_ = false;
  1846. size_t is_done_ = false;
  1847. size_t off_ = 0;
  1848. MultipartFormData file_;
  1849. };
  1850. inline std::string to_lower(const char *beg, const char *end) {
  1851. std::string out;
  1852. auto it = beg;
  1853. while (it != end) {
  1854. out += static_cast<char>(::tolower(*it));
  1855. it++;
  1856. }
  1857. return out;
  1858. }
  1859. inline std::string make_multipart_data_boundary() {
  1860. static const char data[] =
  1861. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  1862. std::random_device seed_gen;
  1863. std::mt19937 engine(seed_gen());
  1864. std::string result = "--cpp-httplib-multipart-data-";
  1865. for (auto i = 0; i < 16; i++) {
  1866. result += data[engine() % (sizeof(data) - 1)];
  1867. }
  1868. return result;
  1869. }
  1870. inline std::pair<size_t, size_t>
  1871. get_range_offset_and_length(const Request &req, size_t content_length,
  1872. size_t index) {
  1873. auto r = req.ranges[index];
  1874. if (r.first == -1 && r.second == -1) {
  1875. return std::make_pair(0, content_length);
  1876. }
  1877. if (r.first == -1) {
  1878. r.first = content_length - r.second;
  1879. r.second = content_length - 1;
  1880. }
  1881. if (r.second == -1) { r.second = content_length - 1; }
  1882. return std::make_pair(r.first, r.second - r.first + 1);
  1883. }
  1884. inline std::string make_content_range_header_field(size_t offset, size_t length,
  1885. size_t content_length) {
  1886. std::string field = "bytes ";
  1887. field += std::to_string(offset);
  1888. field += "-";
  1889. field += std::to_string(offset + length - 1);
  1890. field += "/";
  1891. field += std::to_string(content_length);
  1892. return field;
  1893. }
  1894. template <typename SToken, typename CToken, typename Content>
  1895. bool process_multipart_ranges_data(const Request &req, Response &res,
  1896. const std::string &boundary,
  1897. const std::string &content_type,
  1898. SToken stoken, CToken ctoken,
  1899. Content content) {
  1900. for (size_t i = 0; i < req.ranges.size(); i++) {
  1901. ctoken("--");
  1902. stoken(boundary);
  1903. ctoken("\r\n");
  1904. if (!content_type.empty()) {
  1905. ctoken("Content-Type: ");
  1906. stoken(content_type);
  1907. ctoken("\r\n");
  1908. }
  1909. auto offsets = get_range_offset_and_length(req, res.body.size(), i);
  1910. auto offset = offsets.first;
  1911. auto length = offsets.second;
  1912. ctoken("Content-Range: ");
  1913. stoken(make_content_range_header_field(offset, length, res.body.size()));
  1914. ctoken("\r\n");
  1915. ctoken("\r\n");
  1916. if (!content(offset, length)) { return false; }
  1917. ctoken("\r\n");
  1918. }
  1919. ctoken("--");
  1920. stoken(boundary);
  1921. ctoken("--\r\n");
  1922. return true;
  1923. }
  1924. inline std::string make_multipart_ranges_data(const Request &req, Response &res,
  1925. const std::string &boundary,
  1926. const std::string &content_type) {
  1927. std::string data;
  1928. process_multipart_ranges_data(
  1929. req, res, boundary, content_type,
  1930. [&](const std::string &token) { data += token; },
  1931. [&](const char *token) { data += token; },
  1932. [&](size_t offset, size_t length) {
  1933. data += res.body.substr(offset, length);
  1934. return true;
  1935. });
  1936. return data;
  1937. }
  1938. inline size_t
  1939. get_multipart_ranges_data_length(const Request &req, Response &res,
  1940. const std::string &boundary,
  1941. const std::string &content_type) {
  1942. size_t data_length = 0;
  1943. process_multipart_ranges_data(
  1944. req, res, boundary, content_type,
  1945. [&](const std::string &token) { data_length += token.size(); },
  1946. [&](const char *token) { data_length += strlen(token); },
  1947. [&](size_t /*offset*/, size_t length) {
  1948. data_length += length;
  1949. return true;
  1950. });
  1951. return data_length;
  1952. }
  1953. inline bool write_multipart_ranges_data(Stream &strm, const Request &req,
  1954. Response &res,
  1955. const std::string &boundary,
  1956. const std::string &content_type) {
  1957. return process_multipart_ranges_data(
  1958. req, res, boundary, content_type,
  1959. [&](const std::string &token) { strm.write(token); },
  1960. [&](const char *token) { strm.write(token); },
  1961. [&](size_t offset, size_t length) {
  1962. return write_content(strm, res.content_provider, offset, length) >= 0;
  1963. });
  1964. }
  1965. inline std::pair<size_t, size_t>
  1966. get_range_offset_and_length(const Request &req, const Response &res,
  1967. size_t index) {
  1968. auto r = req.ranges[index];
  1969. if (r.second == -1) { r.second = res.content_length - 1; }
  1970. return std::make_pair(r.first, r.second - r.first + 1);
  1971. }
  1972. inline bool expect_content(const Request &req) {
  1973. if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
  1974. req.method == "PRI") {
  1975. return true;
  1976. }
  1977. // TODO: check if Content-Length is set
  1978. return false;
  1979. }
  1980. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1981. template <typename CTX, typename Init, typename Update, typename Final>
  1982. inline std::string message_digest(const std::string &s, Init init,
  1983. Update update, Final final,
  1984. size_t digest_length) {
  1985. using namespace std;
  1986. std::vector<unsigned char> md(digest_length, 0);
  1987. CTX ctx;
  1988. init(&ctx);
  1989. update(&ctx, s.data(), s.size());
  1990. final(md.data(), &ctx);
  1991. stringstream ss;
  1992. for (auto c : md) {
  1993. ss << setfill('0') << setw(2) << hex << (unsigned int)c;
  1994. }
  1995. return ss.str();
  1996. }
  1997. inline std::string MD5(const std::string &s) {
  1998. return message_digest<MD5_CTX>(s, MD5_Init, MD5_Update, MD5_Final,
  1999. MD5_DIGEST_LENGTH);
  2000. }
  2001. inline std::string SHA_256(const std::string &s) {
  2002. return message_digest<SHA256_CTX>(s, SHA256_Init, SHA256_Update, SHA256_Final,
  2003. SHA256_DIGEST_LENGTH);
  2004. }
  2005. inline std::string SHA_512(const std::string &s) {
  2006. return message_digest<SHA512_CTX>(s, SHA512_Init, SHA512_Update, SHA512_Final,
  2007. SHA512_DIGEST_LENGTH);
  2008. }
  2009. #endif
  2010. #ifdef _WIN32
  2011. class WSInit {
  2012. public:
  2013. WSInit() {
  2014. WSADATA wsaData;
  2015. WSAStartup(0x0002, &wsaData);
  2016. }
  2017. ~WSInit() { WSACleanup(); }
  2018. };
  2019. static WSInit wsinit_;
  2020. #endif
  2021. } // namespace detail
  2022. // Header utilities
  2023. inline std::pair<std::string, std::string> make_range_header(Ranges ranges) {
  2024. std::string field = "bytes=";
  2025. auto i = 0;
  2026. for (auto r : ranges) {
  2027. if (i != 0) { field += ", "; }
  2028. if (r.first != -1) { field += std::to_string(r.first); }
  2029. field += '-';
  2030. if (r.second != -1) { field += std::to_string(r.second); }
  2031. i++;
  2032. }
  2033. return std::make_pair("Range", field);
  2034. }
  2035. inline std::pair<std::string, std::string>
  2036. make_basic_authentication_header(const std::string &username,
  2037. const std::string &password,
  2038. bool is_proxy = false) {
  2039. auto field = "Basic " + detail::base64_encode(username + ":" + password);
  2040. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2041. return std::make_pair(key, field);
  2042. }
  2043. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2044. inline std::pair<std::string, std::string> make_digest_authentication_header(
  2045. const Request &req, const std::map<std::string, std::string> &auth,
  2046. size_t cnonce_count, const std::string &cnonce, const std::string &username,
  2047. const std::string &password, bool is_proxy = false) {
  2048. using namespace std;
  2049. string nc;
  2050. {
  2051. stringstream ss;
  2052. ss << setfill('0') << setw(8) << hex << cnonce_count;
  2053. nc = ss.str();
  2054. }
  2055. auto qop = auth.at("qop");
  2056. if (qop.find("auth-int") != std::string::npos) {
  2057. qop = "auth-int";
  2058. } else {
  2059. qop = "auth";
  2060. }
  2061. std::string algo = "MD5";
  2062. if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
  2063. string response;
  2064. {
  2065. auto H = algo == "SHA-256"
  2066. ? detail::SHA_256
  2067. : algo == "SHA-512" ? detail::SHA_512 : detail::MD5;
  2068. auto A1 = username + ":" + auth.at("realm") + ":" + password;
  2069. auto A2 = req.method + ":" + req.path;
  2070. if (qop == "auth-int") { A2 += ":" + H(req.body); }
  2071. response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
  2072. ":" + qop + ":" + H(A2));
  2073. }
  2074. auto field = "Digest username=\"hello\", realm=\"" + auth.at("realm") +
  2075. "\", nonce=\"" + auth.at("nonce") + "\", uri=\"" + req.path +
  2076. "\", algorithm=" + algo + ", qop=" + qop + ", nc=\"" + nc +
  2077. "\", cnonce=\"" + cnonce + "\", response=\"" + response + "\"";
  2078. auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
  2079. return std::make_pair(key, field);
  2080. }
  2081. #endif
  2082. inline bool parse_www_authenticate(const httplib::Response &res,
  2083. std::map<std::string, std::string> &auth,
  2084. bool is_proxy) {
  2085. auto key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
  2086. if (res.has_header(key)) {
  2087. static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
  2088. auto s = res.get_header_value(key);
  2089. auto pos = s.find(' ');
  2090. if (pos != std::string::npos) {
  2091. auto type = s.substr(0, pos);
  2092. if (type == "Basic") {
  2093. return false;
  2094. } else if (type == "Digest") {
  2095. s = s.substr(pos + 1);
  2096. auto beg = std::sregex_iterator(s.begin(), s.end(), re);
  2097. for (auto i = beg; i != std::sregex_iterator(); ++i) {
  2098. auto m = *i;
  2099. auto key = s.substr(m.position(1), m.length(1));
  2100. auto val = m.length(2) > 0 ? s.substr(m.position(2), m.length(2))
  2101. : s.substr(m.position(3), m.length(3));
  2102. auth[key] = val;
  2103. }
  2104. return true;
  2105. }
  2106. }
  2107. }
  2108. return false;
  2109. }
  2110. // https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c/440240#answer-440240
  2111. inline std::string random_string(size_t length) {
  2112. auto randchar = []() -> char {
  2113. const char charset[] = "0123456789"
  2114. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  2115. "abcdefghijklmnopqrstuvwxyz";
  2116. const size_t max_index = (sizeof(charset) - 1);
  2117. return charset[rand() % max_index];
  2118. };
  2119. std::string str(length, 0);
  2120. std::generate_n(str.begin(), length, randchar);
  2121. return str;
  2122. }
  2123. // Request implementation
  2124. inline bool Request::has_header(const char *key) const {
  2125. return detail::has_header(headers, key);
  2126. }
  2127. inline std::string Request::get_header_value(const char *key, size_t id) const {
  2128. return detail::get_header_value(headers, key, id, "");
  2129. }
  2130. inline size_t Request::get_header_value_count(const char *key) const {
  2131. auto r = headers.equal_range(key);
  2132. return std::distance(r.first, r.second);
  2133. }
  2134. inline void Request::set_header(const char *key, const char *val) {
  2135. headers.emplace(key, val);
  2136. }
  2137. inline void Request::set_header(const char *key, const std::string &val) {
  2138. headers.emplace(key, val);
  2139. }
  2140. inline bool Request::has_param(const char *key) const {
  2141. return params.find(key) != params.end();
  2142. }
  2143. inline std::string Request::get_param_value(const char *key, size_t id) const {
  2144. auto it = params.find(key);
  2145. std::advance(it, id);
  2146. if (it != params.end()) { return it->second; }
  2147. return std::string();
  2148. }
  2149. inline size_t Request::get_param_value_count(const char *key) const {
  2150. auto r = params.equal_range(key);
  2151. return std::distance(r.first, r.second);
  2152. }
  2153. inline bool Request::is_multipart_form_data() const {
  2154. const auto &content_type = get_header_value("Content-Type");
  2155. return !content_type.find("multipart/form-data");
  2156. }
  2157. inline bool Request::has_file(const char *key) const {
  2158. return files.find(key) != files.end();
  2159. }
  2160. inline MultipartFormData Request::get_file_value(const char *key) const {
  2161. auto it = files.find(key);
  2162. if (it != files.end()) { return it->second; }
  2163. return MultipartFormData();
  2164. }
  2165. // Response implementation
  2166. inline bool Response::has_header(const char *key) const {
  2167. return headers.find(key) != headers.end();
  2168. }
  2169. inline std::string Response::get_header_value(const char *key,
  2170. size_t id) const {
  2171. return detail::get_header_value(headers, key, id, "");
  2172. }
  2173. inline size_t Response::get_header_value_count(const char *key) const {
  2174. auto r = headers.equal_range(key);
  2175. return std::distance(r.first, r.second);
  2176. }
  2177. inline void Response::set_header(const char *key, const char *val) {
  2178. headers.emplace(key, val);
  2179. }
  2180. inline void Response::set_header(const char *key, const std::string &val) {
  2181. headers.emplace(key, val);
  2182. }
  2183. inline void Response::set_redirect(const char *url) {
  2184. set_header("Location", url);
  2185. status = 302;
  2186. }
  2187. inline void Response::set_content(const char *s, size_t n,
  2188. const char *content_type) {
  2189. body.assign(s, n);
  2190. set_header("Content-Type", content_type);
  2191. }
  2192. inline void Response::set_content(const std::string &s,
  2193. const char *content_type) {
  2194. body = s;
  2195. set_header("Content-Type", content_type);
  2196. }
  2197. inline void Response::set_content_provider(
  2198. size_t length,
  2199. std::function<void(size_t offset, size_t length, DataSink &sink)> provider,
  2200. std::function<void()> resource_releaser) {
  2201. assert(length > 0);
  2202. content_length = length;
  2203. content_provider = [provider](size_t offset, size_t length, DataSink &sink) {
  2204. provider(offset, length, sink);
  2205. };
  2206. content_provider_resource_releaser = resource_releaser;
  2207. }
  2208. inline void Response::set_chunked_content_provider(
  2209. std::function<void(size_t offset, DataSink &sink)> provider,
  2210. std::function<void()> resource_releaser) {
  2211. content_length = 0;
  2212. content_provider = [provider](size_t offset, size_t, DataSink &sink) {
  2213. provider(offset, sink);
  2214. };
  2215. content_provider_resource_releaser = resource_releaser;
  2216. }
  2217. // Rstream implementation
  2218. template <typename... Args>
  2219. inline int Stream::write_format(const char *fmt, const Args &... args) {
  2220. std::array<char, 2048> buf;
  2221. #if defined(_MSC_VER) && _MSC_VER < 1900
  2222. auto n = _snprintf_s(buf, bufsiz, buf.size() - 1, fmt, args...);
  2223. #else
  2224. auto n = snprintf(buf.data(), buf.size() - 1, fmt, args...);
  2225. #endif
  2226. if (n <= 0) { return n; }
  2227. if (n >= static_cast<int>(buf.size()) - 1) {
  2228. std::vector<char> glowable_buf(buf.size());
  2229. while (n >= static_cast<int>(glowable_buf.size() - 1)) {
  2230. glowable_buf.resize(glowable_buf.size() * 2);
  2231. #if defined(_MSC_VER) && _MSC_VER < 1900
  2232. n = _snprintf_s(&glowable_buf[0], glowable_buf.size(),
  2233. glowable_buf.size() - 1, fmt, args...);
  2234. #else
  2235. n = snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...);
  2236. #endif
  2237. }
  2238. return write(&glowable_buf[0], n);
  2239. } else {
  2240. return write(buf.data(), n);
  2241. }
  2242. }
  2243. namespace detail {
  2244. // Socket stream implementation
  2245. inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec,
  2246. time_t read_timeout_usec)
  2247. : sock_(sock), read_timeout_sec_(read_timeout_sec),
  2248. read_timeout_usec_(read_timeout_usec) {}
  2249. inline SocketStream::~SocketStream() {}
  2250. inline int SocketStream::read(char *ptr, size_t size) {
  2251. if (detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0) {
  2252. return recv(sock_, ptr, static_cast<int>(size), 0);
  2253. }
  2254. return -1;
  2255. }
  2256. inline int SocketStream::write(const char *ptr, size_t size) {
  2257. return send(sock_, ptr, static_cast<int>(size), 0);
  2258. }
  2259. inline int SocketStream::write(const char *ptr) {
  2260. return write(ptr, strlen(ptr));
  2261. }
  2262. inline int SocketStream::write(const std::string &s) {
  2263. return write(s.data(), s.size());
  2264. }
  2265. inline std::string SocketStream::get_remote_addr() const {
  2266. return detail::get_remote_addr(sock_);
  2267. }
  2268. // Buffer stream implementation
  2269. inline int BufferStream::read(char *ptr, size_t size) {
  2270. #if defined(_MSC_VER) && _MSC_VER < 1900
  2271. int len_read = static_cast<int>(buffer._Copy_s(ptr, size, size, position));
  2272. #else
  2273. int len_read = static_cast<int>(buffer.copy(ptr, size, position));
  2274. #endif
  2275. position += len_read;
  2276. return len_read;
  2277. }
  2278. inline int BufferStream::write(const char *ptr, size_t size) {
  2279. buffer.append(ptr, size);
  2280. return static_cast<int>(size);
  2281. }
  2282. inline int BufferStream::write(const char *ptr) {
  2283. return write(ptr, strlen(ptr));
  2284. }
  2285. inline int BufferStream::write(const std::string &s) {
  2286. return write(s.data(), s.size());
  2287. }
  2288. inline std::string BufferStream::get_remote_addr() const { return ""; }
  2289. inline const std::string &BufferStream::get_buffer() const { return buffer; }
  2290. } // namespace detail
  2291. // HTTP server implementation
  2292. inline Server::Server()
  2293. : keep_alive_max_count_(CPPHTTPLIB_KEEPALIVE_MAX_COUNT),
  2294. read_timeout_sec_(CPPHTTPLIB_READ_TIMEOUT_SECOND),
  2295. read_timeout_usec_(CPPHTTPLIB_READ_TIMEOUT_USECOND),
  2296. payload_max_length_(CPPHTTPLIB_PAYLOAD_MAX_LENGTH), is_running_(false),
  2297. svr_sock_(INVALID_SOCKET) {
  2298. #ifndef _WIN32
  2299. signal(SIGPIPE, SIG_IGN);
  2300. #endif
  2301. new_task_queue = [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); };
  2302. }
  2303. inline Server::~Server() {}
  2304. inline Server &Server::Get(const char *pattern, Handler handler) {
  2305. get_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2306. return *this;
  2307. }
  2308. inline Server &Server::Post(const char *pattern, Handler handler) {
  2309. post_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2310. return *this;
  2311. }
  2312. inline Server &Server::Post(const char *pattern,
  2313. HandlerWithContentReader handler) {
  2314. post_handlers_for_content_reader_.push_back(
  2315. std::make_pair(std::regex(pattern), handler));
  2316. return *this;
  2317. }
  2318. inline Server &Server::Put(const char *pattern, Handler handler) {
  2319. put_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2320. return *this;
  2321. }
  2322. inline Server &Server::Put(const char *pattern,
  2323. HandlerWithContentReader handler) {
  2324. put_handlers_for_content_reader_.push_back(
  2325. std::make_pair(std::regex(pattern), handler));
  2326. return *this;
  2327. }
  2328. inline Server &Server::Patch(const char *pattern, Handler handler) {
  2329. patch_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2330. return *this;
  2331. }
  2332. inline Server &Server::Patch(const char *pattern,
  2333. HandlerWithContentReader handler) {
  2334. patch_handlers_for_content_reader_.push_back(
  2335. std::make_pair(std::regex(pattern), handler));
  2336. return *this;
  2337. }
  2338. inline Server &Server::Delete(const char *pattern, Handler handler) {
  2339. delete_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2340. return *this;
  2341. }
  2342. inline Server &Server::Options(const char *pattern, Handler handler) {
  2343. options_handlers_.push_back(std::make_pair(std::regex(pattern), handler));
  2344. return *this;
  2345. }
  2346. inline bool Server::set_base_dir(const char *dir, const char *mount_point) {
  2347. if (detail::is_dir(dir)) {
  2348. std::string mnt = mount_point ? mount_point : "/";
  2349. if (!mnt.empty() && mnt[0] == '/') {
  2350. base_dirs_.emplace_back(mnt, dir);
  2351. return true;
  2352. }
  2353. }
  2354. return false;
  2355. }
  2356. inline void Server::set_file_extension_and_mimetype_mapping(const char *ext,
  2357. const char *mime) {
  2358. file_extension_and_mimetype_map_[ext] = mime;
  2359. }
  2360. inline void Server::set_file_request_handler(Handler handler) {
  2361. file_request_handler_ = std::move(handler);
  2362. }
  2363. inline void Server::set_error_handler(Handler handler) {
  2364. error_handler_ = std::move(handler);
  2365. }
  2366. inline void Server::set_logger(Logger logger) { logger_ = std::move(logger); }
  2367. inline void Server::set_keep_alive_max_count(size_t count) {
  2368. keep_alive_max_count_ = count;
  2369. }
  2370. inline void Server::set_read_timeout(time_t sec, time_t usec) {
  2371. read_timeout_sec_ = sec;
  2372. read_timeout_usec_ = usec;
  2373. }
  2374. inline void Server::set_payload_max_length(size_t length) {
  2375. payload_max_length_ = length;
  2376. }
  2377. inline bool Server::bind_to_port(const char *host, int port, int socket_flags) {
  2378. if (bind_internal(host, port, socket_flags) < 0) return false;
  2379. return true;
  2380. }
  2381. inline int Server::bind_to_any_port(const char *host, int socket_flags) {
  2382. return bind_internal(host, 0, socket_flags);
  2383. }
  2384. inline bool Server::listen_after_bind() { return listen_internal(); }
  2385. inline bool Server::listen(const char *host, int port, int socket_flags) {
  2386. return bind_to_port(host, port, socket_flags) && listen_internal();
  2387. }
  2388. inline bool Server::is_running() const { return is_running_; }
  2389. inline void Server::stop() {
  2390. if (is_running_) {
  2391. assert(svr_sock_ != INVALID_SOCKET);
  2392. std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
  2393. detail::shutdown_socket(sock);
  2394. detail::close_socket(sock);
  2395. }
  2396. }
  2397. inline bool Server::parse_request_line(const char *s, Request &req) {
  2398. const static std::regex re(
  2399. "(GET|HEAD|POST|PUT|DELETE|CONNECT|OPTIONS|TRACE|PATCH|PRI) "
  2400. "(([^?]+)(?:\\?(.*?))?) (HTTP/1\\.[01])\r\n");
  2401. std::cmatch m;
  2402. if (std::regex_match(s, m, re)) {
  2403. req.version = std::string(m[5]);
  2404. req.method = std::string(m[1]);
  2405. req.target = std::string(m[2]);
  2406. req.path = detail::decode_url(m[3]);
  2407. // Parse query text
  2408. auto len = std::distance(m[4].first, m[4].second);
  2409. if (len > 0) { detail::parse_query_text(m[4], req.params); }
  2410. return true;
  2411. }
  2412. return false;
  2413. }
  2414. inline bool Server::write_response(Stream &strm, bool last_connection,
  2415. const Request &req, Response &res) {
  2416. assert(res.status != -1);
  2417. if (400 <= res.status && error_handler_) { error_handler_(req, res); }
  2418. // Response line
  2419. if (!strm.write_format("HTTP/1.1 %d %s\r\n", res.status,
  2420. detail::status_message(res.status))) {
  2421. return false;
  2422. }
  2423. // Headers
  2424. if (last_connection || req.get_header_value("Connection") == "close") {
  2425. res.set_header("Connection", "close");
  2426. }
  2427. if (!last_connection && req.get_header_value("Connection") == "Keep-Alive") {
  2428. res.set_header("Connection", "Keep-Alive");
  2429. }
  2430. if (!res.has_header("Content-Type")) {
  2431. res.set_header("Content-Type", "text/plain");
  2432. }
  2433. if (!res.has_header("Accept-Ranges")) {
  2434. res.set_header("Accept-Ranges", "bytes");
  2435. }
  2436. std::string content_type;
  2437. std::string boundary;
  2438. if (req.ranges.size() > 1) {
  2439. boundary = detail::make_multipart_data_boundary();
  2440. auto it = res.headers.find("Content-Type");
  2441. if (it != res.headers.end()) {
  2442. content_type = it->second;
  2443. res.headers.erase(it);
  2444. }
  2445. res.headers.emplace("Content-Type",
  2446. "multipart/byteranges; boundary=" + boundary);
  2447. }
  2448. if (res.body.empty()) {
  2449. if (res.content_length > 0) {
  2450. size_t length = 0;
  2451. if (req.ranges.empty()) {
  2452. length = res.content_length;
  2453. } else if (req.ranges.size() == 1) {
  2454. auto offsets =
  2455. detail::get_range_offset_and_length(req, res.content_length, 0);
  2456. auto offset = offsets.first;
  2457. length = offsets.second;
  2458. auto content_range = detail::make_content_range_header_field(
  2459. offset, length, res.content_length);
  2460. res.set_header("Content-Range", content_range);
  2461. } else {
  2462. length = detail::get_multipart_ranges_data_length(req, res, boundary,
  2463. content_type);
  2464. }
  2465. res.set_header("Content-Length", std::to_string(length));
  2466. } else {
  2467. if (res.content_provider) {
  2468. res.set_header("Transfer-Encoding", "chunked");
  2469. } else {
  2470. res.set_header("Content-Length", "0");
  2471. }
  2472. }
  2473. } else {
  2474. if (req.ranges.empty()) {
  2475. ;
  2476. } else if (req.ranges.size() == 1) {
  2477. auto offsets =
  2478. detail::get_range_offset_and_length(req, res.body.size(), 0);
  2479. auto offset = offsets.first;
  2480. auto length = offsets.second;
  2481. auto content_range = detail::make_content_range_header_field(
  2482. offset, length, res.body.size());
  2483. res.set_header("Content-Range", content_range);
  2484. res.body = res.body.substr(offset, length);
  2485. } else {
  2486. res.body =
  2487. detail::make_multipart_ranges_data(req, res, boundary, content_type);
  2488. }
  2489. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2490. // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
  2491. const auto &encodings = req.get_header_value("Accept-Encoding");
  2492. if (encodings.find("gzip") != std::string::npos &&
  2493. detail::can_compress(res.get_header_value("Content-Type"))) {
  2494. if (detail::compress(res.body)) {
  2495. res.set_header("Content-Encoding", "gzip");
  2496. }
  2497. }
  2498. #endif
  2499. auto length = std::to_string(res.body.size());
  2500. res.set_header("Content-Length", length);
  2501. }
  2502. if (!detail::write_headers(strm, res, Headers())) { return false; }
  2503. // Body
  2504. if (req.method != "HEAD") {
  2505. if (!res.body.empty()) {
  2506. if (!strm.write(res.body)) { return false; }
  2507. } else if (res.content_provider) {
  2508. if (!write_content_with_provider(strm, req, res, boundary,
  2509. content_type)) {
  2510. return false;
  2511. }
  2512. }
  2513. }
  2514. // Log
  2515. if (logger_) { logger_(req, res); }
  2516. return true;
  2517. }
  2518. inline bool
  2519. Server::write_content_with_provider(Stream &strm, const Request &req,
  2520. Response &res, const std::string &boundary,
  2521. const std::string &content_type) {
  2522. if (res.content_length) {
  2523. if (req.ranges.empty()) {
  2524. if (detail::write_content(strm, res.content_provider, 0,
  2525. res.content_length) < 0) {
  2526. return false;
  2527. }
  2528. } else if (req.ranges.size() == 1) {
  2529. auto offsets =
  2530. detail::get_range_offset_and_length(req, res.content_length, 0);
  2531. auto offset = offsets.first;
  2532. auto length = offsets.second;
  2533. if (detail::write_content(strm, res.content_provider, offset, length) <
  2534. 0) {
  2535. return false;
  2536. }
  2537. } else {
  2538. if (!detail::write_multipart_ranges_data(strm, req, res, boundary,
  2539. content_type)) {
  2540. return false;
  2541. }
  2542. }
  2543. } else {
  2544. auto is_shutting_down = [this]() {
  2545. return this->svr_sock_ == INVALID_SOCKET;
  2546. };
  2547. if (detail::write_content_chunked(strm, res.content_provider,
  2548. is_shutting_down) < 0) {
  2549. return false;
  2550. }
  2551. }
  2552. return true;
  2553. }
  2554. inline bool Server::read_content(Stream &strm, bool last_connection,
  2555. Request &req, Response &res) {
  2556. MultipartFormDataMap::iterator cur;
  2557. auto ret = read_content_core(
  2558. strm, last_connection, req, res,
  2559. // Regular
  2560. [&](const char *buf, size_t n) {
  2561. if (req.body.size() + n > req.body.max_size()) { return false; }
  2562. req.body.append(buf, n);
  2563. return true;
  2564. },
  2565. // Multipart
  2566. [&](const MultipartFormData &file) {
  2567. cur = req.files.emplace(file.name, file);
  2568. return true;
  2569. },
  2570. [&](const char *buf, size_t n) {
  2571. auto &content = cur->second.content;
  2572. if (content.size() + n > content.max_size()) { return false; }
  2573. content.append(buf, n);
  2574. return true;
  2575. });
  2576. const auto &content_type = req.get_header_value("Content-Type");
  2577. if (!content_type.find("application/x-www-form-urlencoded")) {
  2578. detail::parse_query_text(req.body, req.params);
  2579. }
  2580. return ret;
  2581. }
  2582. inline bool Server::read_content_with_content_receiver(
  2583. Stream &strm, bool last_connection, Request &req, Response &res,
  2584. ContentReceiver receiver, MultipartContentHeader multipart_header,
  2585. ContentReceiver multipart_receiver) {
  2586. return read_content_core(strm, last_connection, req, res, receiver,
  2587. multipart_header, multipart_receiver);
  2588. }
  2589. inline bool Server::read_content_core(Stream &strm, bool last_connection,
  2590. Request &req, Response &res,
  2591. ContentReceiver receiver,
  2592. MultipartContentHeader mulitpart_header,
  2593. ContentReceiver multipart_receiver) {
  2594. detail::MultipartFormDataParser multipart_form_data_parser;
  2595. ContentReceiver out;
  2596. if (req.is_multipart_form_data()) {
  2597. const auto &content_type = req.get_header_value("Content-Type");
  2598. std::string boundary;
  2599. if (!detail::parse_multipart_boundary(content_type, boundary)) {
  2600. res.status = 400;
  2601. return write_response(strm, last_connection, req, res);
  2602. }
  2603. multipart_form_data_parser.set_boundary(boundary);
  2604. out = [&](const char *buf, size_t n) {
  2605. return multipart_form_data_parser.parse(buf, n, multipart_receiver,
  2606. mulitpart_header);
  2607. };
  2608. } else {
  2609. out = receiver;
  2610. }
  2611. if (!detail::read_content(strm, req, payload_max_length_, res.status,
  2612. Progress(), out)) {
  2613. return write_response(strm, last_connection, req, res);
  2614. }
  2615. if (req.is_multipart_form_data()) {
  2616. if (!multipart_form_data_parser.is_valid()) {
  2617. res.status = 400;
  2618. return write_response(strm, last_connection, req, res);
  2619. }
  2620. }
  2621. return true;
  2622. }
  2623. inline bool Server::handle_file_request(Request &req, Response &res) {
  2624. for (const auto &kv : base_dirs_) {
  2625. const auto &mount_point = kv.first;
  2626. const auto &base_dir = kv.second;
  2627. // Prefix match
  2628. if (!req.path.find(mount_point)) {
  2629. std::string sub_path = "/" + req.path.substr(mount_point.size());
  2630. if (detail::is_valid_path(sub_path)) {
  2631. auto path = base_dir + sub_path;
  2632. if (path.back() == '/') { path += "index.html"; }
  2633. if (detail::is_file(path)) {
  2634. detail::read_file(path, res.body);
  2635. auto type =
  2636. detail::find_content_type(path, file_extension_and_mimetype_map_);
  2637. if (type) { res.set_header("Content-Type", type); }
  2638. res.status = 200;
  2639. if (file_request_handler_) { file_request_handler_(req, res); }
  2640. return true;
  2641. }
  2642. }
  2643. }
  2644. }
  2645. return false;
  2646. }
  2647. inline socket_t Server::create_server_socket(const char *host, int port,
  2648. int socket_flags) const {
  2649. return detail::create_socket(
  2650. host, port,
  2651. [](socket_t sock, struct addrinfo &ai) -> bool {
  2652. if (::bind(sock, ai.ai_addr, static_cast<int>(ai.ai_addrlen))) {
  2653. return false;
  2654. }
  2655. if (::listen(sock, 5)) { // Listen through 5 channels
  2656. return false;
  2657. }
  2658. return true;
  2659. },
  2660. socket_flags);
  2661. }
  2662. inline int Server::bind_internal(const char *host, int port, int socket_flags) {
  2663. if (!is_valid()) { return -1; }
  2664. svr_sock_ = create_server_socket(host, port, socket_flags);
  2665. if (svr_sock_ == INVALID_SOCKET) { return -1; }
  2666. if (port == 0) {
  2667. struct sockaddr_storage address;
  2668. socklen_t len = sizeof(address);
  2669. if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&address),
  2670. &len) == -1) {
  2671. return -1;
  2672. }
  2673. if (address.ss_family == AF_INET) {
  2674. return ntohs(reinterpret_cast<struct sockaddr_in *>(&address)->sin_port);
  2675. } else if (address.ss_family == AF_INET6) {
  2676. return ntohs(
  2677. reinterpret_cast<struct sockaddr_in6 *>(&address)->sin6_port);
  2678. } else {
  2679. return -1;
  2680. }
  2681. } else {
  2682. return port;
  2683. }
  2684. }
  2685. inline bool Server::listen_internal() {
  2686. auto ret = true;
  2687. is_running_ = true;
  2688. {
  2689. std::unique_ptr<TaskQueue> task_queue(new_task_queue());
  2690. for (;;) {
  2691. if (svr_sock_ == INVALID_SOCKET) {
  2692. // The server socket was closed by 'stop' method.
  2693. break;
  2694. }
  2695. auto val = detail::select_read(svr_sock_, 0, 100000);
  2696. if (val == 0) { // Timeout
  2697. continue;
  2698. }
  2699. socket_t sock = accept(svr_sock_, nullptr, nullptr);
  2700. if (sock == INVALID_SOCKET) {
  2701. if (errno == EMFILE) {
  2702. // The per-process limit of open file descriptors has been reached.
  2703. // Try to accept new connections after a short sleep.
  2704. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  2705. continue;
  2706. }
  2707. if (svr_sock_ != INVALID_SOCKET) {
  2708. detail::close_socket(svr_sock_);
  2709. ret = false;
  2710. } else {
  2711. ; // The server socket was closed by user.
  2712. }
  2713. break;
  2714. }
  2715. task_queue->enqueue([=]() { process_and_close_socket(sock); });
  2716. }
  2717. task_queue->shutdown();
  2718. }
  2719. is_running_ = false;
  2720. return ret;
  2721. }
  2722. inline bool Server::routing(Request &req, Response &res, Stream &strm,
  2723. bool last_connection) {
  2724. // File handler
  2725. if (req.method == "GET" && handle_file_request(req, res)) { return true; }
  2726. if (detail::expect_content(req)) {
  2727. // Content reader handler
  2728. {
  2729. ContentReader reader(
  2730. [&](ContentReceiver receiver) {
  2731. return read_content_with_content_receiver(
  2732. strm, last_connection, req, res, receiver, nullptr, nullptr);
  2733. },
  2734. [&](MultipartContentHeader header, ContentReceiver receiver) {
  2735. return read_content_with_content_receiver(
  2736. strm, last_connection, req, res, nullptr, header, receiver);
  2737. });
  2738. if (req.method == "POST") {
  2739. if (dispatch_request_for_content_reader(
  2740. req, res, reader, post_handlers_for_content_reader_)) {
  2741. return true;
  2742. }
  2743. } else if (req.method == "PUT") {
  2744. if (dispatch_request_for_content_reader(
  2745. req, res, reader, put_handlers_for_content_reader_)) {
  2746. return true;
  2747. }
  2748. } else if (req.method == "PATCH") {
  2749. if (dispatch_request_for_content_reader(
  2750. req, res, reader, patch_handlers_for_content_reader_)) {
  2751. return true;
  2752. }
  2753. }
  2754. }
  2755. // Read content into `req.body`
  2756. if (!read_content(strm, last_connection, req, res)) { return false; }
  2757. }
  2758. // Regular handler
  2759. if (req.method == "GET" || req.method == "HEAD") {
  2760. return dispatch_request(req, res, get_handlers_);
  2761. } else if (req.method == "POST") {
  2762. return dispatch_request(req, res, post_handlers_);
  2763. } else if (req.method == "PUT") {
  2764. return dispatch_request(req, res, put_handlers_);
  2765. } else if (req.method == "DELETE") {
  2766. return dispatch_request(req, res, delete_handlers_);
  2767. } else if (req.method == "OPTIONS") {
  2768. return dispatch_request(req, res, options_handlers_);
  2769. } else if (req.method == "PATCH") {
  2770. return dispatch_request(req, res, patch_handlers_);
  2771. }
  2772. res.status = 400;
  2773. return false;
  2774. }
  2775. inline bool Server::dispatch_request(Request &req, Response &res,
  2776. Handlers &handlers) {
  2777. for (const auto &x : handlers) {
  2778. const auto &pattern = x.first;
  2779. const auto &handler = x.second;
  2780. if (std::regex_match(req.path, req.matches, pattern)) {
  2781. handler(req, res);
  2782. return true;
  2783. }
  2784. }
  2785. return false;
  2786. }
  2787. inline bool
  2788. Server::dispatch_request_for_content_reader(Request &req, Response &res,
  2789. ContentReader content_reader,
  2790. HandersForContentReader &handlers) {
  2791. for (const auto &x : handlers) {
  2792. const auto &pattern = x.first;
  2793. const auto &handler = x.second;
  2794. if (std::regex_match(req.path, req.matches, pattern)) {
  2795. handler(req, res, content_reader);
  2796. return true;
  2797. }
  2798. }
  2799. return false;
  2800. }
  2801. inline bool
  2802. Server::process_request(Stream &strm, bool last_connection,
  2803. bool &connection_close,
  2804. const std::function<void(Request &)> &setup_request) {
  2805. std::array<char, 2048> buf{};
  2806. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  2807. // Connection has been closed on client
  2808. if (!line_reader.getline()) { return false; }
  2809. Request req;
  2810. Response res;
  2811. res.version = "HTTP/1.1";
  2812. // Check if the request URI doesn't exceed the limit
  2813. if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
  2814. Headers dummy;
  2815. detail::read_headers(strm, dummy);
  2816. res.status = 414;
  2817. return write_response(strm, last_connection, req, res);
  2818. }
  2819. // Request line and headers
  2820. if (!parse_request_line(line_reader.ptr(), req) ||
  2821. !detail::read_headers(strm, req.headers)) {
  2822. res.status = 400;
  2823. return write_response(strm, last_connection, req, res);
  2824. }
  2825. if (req.get_header_value("Connection") == "close") {
  2826. connection_close = true;
  2827. }
  2828. if (req.version == "HTTP/1.0" &&
  2829. req.get_header_value("Connection") != "Keep-Alive") {
  2830. connection_close = true;
  2831. }
  2832. req.set_header("REMOTE_ADDR", strm.get_remote_addr());
  2833. if (req.has_header("Range")) {
  2834. const auto &range_header_value = req.get_header_value("Range");
  2835. if (!detail::parse_range_header(range_header_value, req.ranges)) {
  2836. // TODO: error
  2837. }
  2838. }
  2839. if (setup_request) { setup_request(req); }
  2840. // Rounting
  2841. if (routing(req, res, strm, last_connection)) {
  2842. if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; }
  2843. } else {
  2844. if (res.status == -1) { res.status = 404; }
  2845. }
  2846. return write_response(strm, last_connection, req, res);
  2847. }
  2848. inline bool Server::is_valid() const { return true; }
  2849. inline bool Server::process_and_close_socket(socket_t sock) {
  2850. return detail::process_and_close_socket(
  2851. false, sock, keep_alive_max_count_, read_timeout_sec_, read_timeout_usec_,
  2852. [this](Stream &strm, bool last_connection, bool &connection_close) {
  2853. return process_request(strm, last_connection, connection_close,
  2854. nullptr);
  2855. });
  2856. }
  2857. // HTTP client implementation
  2858. inline Client::Client(const std::string &host, int port,
  2859. const std::string &client_cert_path,
  2860. const std::string &client_key_path)
  2861. : host_(host), port_(port),
  2862. host_and_port_(host_ + ":" + std::to_string(port_)),
  2863. client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
  2864. inline Client::~Client() {}
  2865. inline bool Client::is_valid() const { return true; }
  2866. inline socket_t Client::create_client_socket() const {
  2867. if (!proxy_host_.empty()) {
  2868. return detail::create_client_socket(proxy_host_.c_str(), proxy_port_,
  2869. timeout_sec_, interface_);
  2870. }
  2871. return detail::create_client_socket(host_.c_str(), port_, timeout_sec_,
  2872. interface_);
  2873. }
  2874. inline bool Client::read_response_line(Stream &strm, Response &res) {
  2875. std::array<char, 2048> buf;
  2876. detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
  2877. if (!line_reader.getline()) { return false; }
  2878. const static std::regex re("(HTTP/1\\.[01]) (\\d+?) .*\r\n");
  2879. std::cmatch m;
  2880. if (std::regex_match(line_reader.ptr(), m, re)) {
  2881. res.version = std::string(m[1]);
  2882. res.status = std::stoi(std::string(m[2]));
  2883. }
  2884. return true;
  2885. }
  2886. inline bool Client::send(const Request &req, Response &res) {
  2887. auto sock = create_client_socket();
  2888. if (sock == INVALID_SOCKET) { return false; }
  2889. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2890. if (is_ssl() && !proxy_host_.empty()) {
  2891. bool error;
  2892. if (!connect(sock, res, error)) { return error; }
  2893. }
  2894. #endif
  2895. return process_and_close_socket(
  2896. sock, 1, [&](Stream &strm, bool last_connection, bool &connection_close) {
  2897. return handle_request(strm, req, res, last_connection,
  2898. connection_close);
  2899. });
  2900. }
  2901. inline bool Client::send(const std::vector<Request> &requests,
  2902. std::vector<Response> &responses) {
  2903. size_t i = 0;
  2904. while (i < requests.size()) {
  2905. auto sock = create_client_socket();
  2906. if (sock == INVALID_SOCKET) { return false; }
  2907. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2908. if (is_ssl() && !proxy_host_.empty()) {
  2909. Response res;
  2910. bool error;
  2911. if (!connect(sock, res, error)) { return false; }
  2912. }
  2913. #endif
  2914. if (!process_and_close_socket(sock, requests.size() - i,
  2915. [&](Stream &strm, bool last_connection,
  2916. bool &connection_close) -> bool {
  2917. auto &req = requests[i++];
  2918. auto res = Response();
  2919. auto ret = handle_request(strm, req, res,
  2920. last_connection,
  2921. connection_close);
  2922. if (ret) {
  2923. responses.emplace_back(std::move(res));
  2924. }
  2925. return ret;
  2926. })) {
  2927. return false;
  2928. }
  2929. }
  2930. return true;
  2931. }
  2932. inline bool Client::handle_request(Stream &strm, const Request &req,
  2933. Response &res, bool last_connection,
  2934. bool &connection_close) {
  2935. if (req.path.empty()) { return false; }
  2936. bool ret;
  2937. if (!is_ssl() && !proxy_host_.empty()) {
  2938. auto req2 = req;
  2939. req2.path = "http://" + host_and_port_ + req.path;
  2940. ret = process_request(strm, req2, res, last_connection, connection_close);
  2941. } else {
  2942. ret = process_request(strm, req, res, last_connection, connection_close);
  2943. }
  2944. if (!ret) { return false; }
  2945. if (300 < res.status && res.status < 400 && follow_location_) {
  2946. ret = redirect(req, res);
  2947. }
  2948. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2949. if (res.status == 401 || res.status == 407) {
  2950. auto is_proxy = res.status == 407;
  2951. const auto &username =
  2952. is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
  2953. const auto &password =
  2954. is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
  2955. if (!username.empty() && !password.empty()) {
  2956. std::map<std::string, std::string> auth;
  2957. if (parse_www_authenticate(res, auth, is_proxy)) {
  2958. Request new_req = req;
  2959. auto key = is_proxy ? "Proxy-Authorization" : "WWW-Authorization";
  2960. new_req.headers.erase(key);
  2961. new_req.headers.insert(make_digest_authentication_header(
  2962. req, auth, 1, random_string(10), username, password, is_proxy));
  2963. Response new_res;
  2964. ret = send(new_req, new_res);
  2965. if (ret) { res = new_res; }
  2966. }
  2967. }
  2968. }
  2969. #endif
  2970. return ret;
  2971. }
  2972. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2973. inline bool Client::connect(socket_t sock, Response &res, bool &error) {
  2974. error = true;
  2975. Response res2;
  2976. if (!detail::process_socket(
  2977. true, sock, 1, read_timeout_sec_, read_timeout_usec_,
  2978. [&](Stream &strm, bool /*last_connection*/, bool &connection_close) {
  2979. Request req2;
  2980. req2.method = "CONNECT";
  2981. req2.path = host_and_port_;
  2982. return process_request(strm, req2, res2, false, connection_close);
  2983. })) {
  2984. detail::close_socket(sock);
  2985. error = false;
  2986. return false;
  2987. }
  2988. if (res2.status == 407) {
  2989. if (!proxy_digest_auth_username_.empty() &&
  2990. !proxy_digest_auth_password_.empty()) {
  2991. std::map<std::string, std::string> auth;
  2992. if (parse_www_authenticate(res2, auth, true)) {
  2993. Response res3;
  2994. if (!detail::process_socket(
  2995. true, sock, 1, read_timeout_sec_, read_timeout_usec_,
  2996. [&](Stream &strm, bool /*last_connection*/,
  2997. bool &connection_close) {
  2998. Request req3;
  2999. req3.method = "CONNECT";
  3000. req3.path = host_and_port_;
  3001. req3.headers.insert(make_digest_authentication_header(
  3002. req3, auth, 1, random_string(10),
  3003. proxy_digest_auth_username_, proxy_digest_auth_password_,
  3004. true));
  3005. return process_request(strm, req3, res3, false,
  3006. connection_close);
  3007. })) {
  3008. detail::close_socket(sock);
  3009. error = false;
  3010. return false;
  3011. }
  3012. }
  3013. } else {
  3014. res = res2;
  3015. return false;
  3016. }
  3017. }
  3018. return true;
  3019. }
  3020. #endif
  3021. inline bool Client::redirect(const Request &req, Response &res) {
  3022. if (req.redirect_count == 0) { return false; }
  3023. auto location = res.get_header_value("location");
  3024. if (location.empty()) { return false; }
  3025. const static std::regex re(
  3026. R"(^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*(?:\?[^#]*)?)(?:#.*)?)");
  3027. std::smatch m;
  3028. if (!regex_match(location, m, re)) { return false; }
  3029. auto scheme = is_ssl() ? "https" : "http";
  3030. auto next_scheme = m[1].str();
  3031. auto next_host = m[2].str();
  3032. auto next_path = m[3].str();
  3033. if (next_scheme.empty()) { next_scheme = scheme; }
  3034. if (next_scheme.empty()) { next_scheme = scheme; }
  3035. if (next_host.empty()) { next_host = host_; }
  3036. if (next_path.empty()) { next_path = "/"; }
  3037. if (next_scheme == scheme && next_host == host_) {
  3038. return detail::redirect(*this, req, res, next_path);
  3039. } else {
  3040. if (next_scheme == "https") {
  3041. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3042. SSLClient cli(next_host.c_str());
  3043. cli.copy_settings(*this);
  3044. return detail::redirect(cli, req, res, next_path);
  3045. #else
  3046. return false;
  3047. #endif
  3048. } else {
  3049. Client cli(next_host.c_str());
  3050. cli.copy_settings(*this);
  3051. return detail::redirect(cli, req, res, next_path);
  3052. }
  3053. }
  3054. }
  3055. inline bool Client::write_request(Stream &strm, const Request &req,
  3056. bool last_connection) {
  3057. detail::BufferStream bstrm;
  3058. // Request line
  3059. const auto &path = detail::encode_url(req.path);
  3060. bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str());
  3061. // Additonal headers
  3062. Headers headers;
  3063. if (last_connection) { headers.emplace("Connection", "close"); }
  3064. if (!req.has_header("Host")) {
  3065. if (is_ssl()) {
  3066. if (port_ == 443) {
  3067. headers.emplace("Host", host_);
  3068. } else {
  3069. headers.emplace("Host", host_and_port_);
  3070. }
  3071. } else {
  3072. if (port_ == 80) {
  3073. headers.emplace("Host", host_);
  3074. } else {
  3075. headers.emplace("Host", host_and_port_);
  3076. }
  3077. }
  3078. }
  3079. if (!req.has_header("Accept")) { headers.emplace("Accept", "*/*"); }
  3080. if (!req.has_header("User-Agent")) {
  3081. headers.emplace("User-Agent", "cpp-httplib/0.5");
  3082. }
  3083. if (req.body.empty()) {
  3084. if (req.content_provider) {
  3085. auto length = std::to_string(req.content_length);
  3086. headers.emplace("Content-Length", length);
  3087. } else {
  3088. headers.emplace("Content-Length", "0");
  3089. }
  3090. } else {
  3091. if (!req.has_header("Content-Type")) {
  3092. headers.emplace("Content-Type", "text/plain");
  3093. }
  3094. if (!req.has_header("Content-Length")) {
  3095. auto length = std::to_string(req.body.size());
  3096. headers.emplace("Content-Length", length);
  3097. }
  3098. }
  3099. if (!basic_auth_username_.empty() && !basic_auth_password_.empty()) {
  3100. headers.insert(make_basic_authentication_header(
  3101. basic_auth_username_, basic_auth_password_, false));
  3102. }
  3103. if (!proxy_basic_auth_username_.empty() &&
  3104. !proxy_basic_auth_password_.empty()) {
  3105. headers.insert(make_basic_authentication_header(
  3106. proxy_basic_auth_username_, proxy_basic_auth_password_, true));
  3107. }
  3108. detail::write_headers(bstrm, req, headers);
  3109. // Flush buffer
  3110. auto &data = bstrm.get_buffer();
  3111. strm.write(data.data(), data.size());
  3112. // Body
  3113. if (req.body.empty()) {
  3114. if (req.content_provider) {
  3115. size_t offset = 0;
  3116. size_t end_offset = req.content_length;
  3117. DataSink data_sink;
  3118. data_sink.write = [&](const char *d, size_t l) {
  3119. auto written_length = strm.write(d, l);
  3120. offset += written_length;
  3121. };
  3122. while (offset < end_offset) {
  3123. req.content_provider(offset, end_offset - offset, data_sink);
  3124. }
  3125. }
  3126. } else {
  3127. strm.write(req.body);
  3128. }
  3129. return true;
  3130. }
  3131. inline std::shared_ptr<Response> Client::send_with_content_provider(
  3132. const char *method, const char *path, const Headers &headers,
  3133. const std::string &body, size_t content_length,
  3134. ContentProvider content_provider, const char *content_type) {
  3135. Request req;
  3136. req.method = method;
  3137. req.headers = headers;
  3138. req.path = path;
  3139. req.headers.emplace("Content-Type", content_type);
  3140. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3141. if (compress_) {
  3142. if (content_provider) {
  3143. size_t offset = 0;
  3144. DataSink data_sink;
  3145. data_sink.write = [&](const char *data, size_t data_len) {
  3146. req.body.append(data, data_len);
  3147. offset += data_len;
  3148. };
  3149. while (offset < content_length) {
  3150. content_provider(offset, content_length - offset, data_sink);
  3151. }
  3152. } else {
  3153. req.body = body;
  3154. }
  3155. if (!detail::compress(req.body)) { return nullptr; }
  3156. req.headers.emplace("Content-Encoding", "gzip");
  3157. } else
  3158. #endif
  3159. {
  3160. if (content_provider) {
  3161. req.content_length = content_length;
  3162. req.content_provider = content_provider;
  3163. } else {
  3164. req.body = body;
  3165. }
  3166. }
  3167. auto res = std::make_shared<Response>();
  3168. return send(req, *res) ? res : nullptr;
  3169. }
  3170. inline bool Client::process_request(Stream &strm, const Request &req,
  3171. Response &res, bool last_connection,
  3172. bool &connection_close) {
  3173. // Send request
  3174. if (!write_request(strm, req, last_connection)) { return false; }
  3175. // Receive response and headers
  3176. if (!read_response_line(strm, res) ||
  3177. !detail::read_headers(strm, res.headers)) {
  3178. return false;
  3179. }
  3180. if (res.get_header_value("Connection") == "close" ||
  3181. res.version == "HTTP/1.0") {
  3182. connection_close = true;
  3183. }
  3184. if (req.response_handler) {
  3185. if (!req.response_handler(res)) { return false; }
  3186. }
  3187. // Body
  3188. if (req.method != "HEAD" && req.method != "CONNECT") {
  3189. ContentReceiver out = [&](const char *buf, size_t n) {
  3190. if (res.body.size() + n > res.body.max_size()) { return false; }
  3191. res.body.append(buf, n);
  3192. return true;
  3193. };
  3194. if (req.content_receiver) {
  3195. out = [&](const char *buf, size_t n) {
  3196. return req.content_receiver(buf, n);
  3197. };
  3198. }
  3199. int dummy_status;
  3200. if (!detail::read_content(strm, res, std::numeric_limits<size_t>::max(),
  3201. dummy_status, req.progress, out)) {
  3202. return false;
  3203. }
  3204. }
  3205. // Log
  3206. if (logger_) { logger_(req, res); }
  3207. return true;
  3208. }
  3209. inline bool Client::process_and_close_socket(
  3210. socket_t sock, size_t request_count,
  3211. std::function<bool(Stream &strm, bool last_connection,
  3212. bool &connection_close)>
  3213. callback) {
  3214. request_count = std::min(request_count, keep_alive_max_count_);
  3215. return detail::process_and_close_socket(true, sock, request_count,
  3216. read_timeout_sec_, read_timeout_usec_,
  3217. callback);
  3218. }
  3219. inline bool Client::is_ssl() const { return false; }
  3220. inline std::shared_ptr<Response> Client::Get(const char *path) {
  3221. return Get(path, Headers(), Progress());
  3222. }
  3223. inline std::shared_ptr<Response> Client::Get(const char *path,
  3224. Progress progress) {
  3225. return Get(path, Headers(), std::move(progress));
  3226. }
  3227. inline std::shared_ptr<Response> Client::Get(const char *path,
  3228. const Headers &headers) {
  3229. return Get(path, headers, Progress());
  3230. }
  3231. inline std::shared_ptr<Response>
  3232. Client::Get(const char *path, const Headers &headers, Progress progress) {
  3233. Request req;
  3234. req.method = "GET";
  3235. req.path = path;
  3236. req.headers = headers;
  3237. req.progress = std::move(progress);
  3238. auto res = std::make_shared<Response>();
  3239. return send(req, *res) ? res : nullptr;
  3240. }
  3241. inline std::shared_ptr<Response> Client::Get(const char *path,
  3242. ContentReceiver content_receiver) {
  3243. return Get(path, Headers(), nullptr, std::move(content_receiver), Progress());
  3244. }
  3245. inline std::shared_ptr<Response> Client::Get(const char *path,
  3246. ContentReceiver content_receiver,
  3247. Progress progress) {
  3248. return Get(path, Headers(), nullptr, std::move(content_receiver),
  3249. std::move(progress));
  3250. }
  3251. inline std::shared_ptr<Response> Client::Get(const char *path,
  3252. const Headers &headers,
  3253. ContentReceiver content_receiver) {
  3254. return Get(path, headers, nullptr, std::move(content_receiver), Progress());
  3255. }
  3256. inline std::shared_ptr<Response> Client::Get(const char *path,
  3257. const Headers &headers,
  3258. ContentReceiver content_receiver,
  3259. Progress progress) {
  3260. return Get(path, headers, nullptr, std::move(content_receiver),
  3261. std::move(progress));
  3262. }
  3263. inline std::shared_ptr<Response> Client::Get(const char *path,
  3264. const Headers &headers,
  3265. ResponseHandler response_handler,
  3266. ContentReceiver content_receiver) {
  3267. return Get(path, headers, std::move(response_handler), content_receiver,
  3268. Progress());
  3269. }
  3270. inline std::shared_ptr<Response> Client::Get(const char *path,
  3271. const Headers &headers,
  3272. ResponseHandler response_handler,
  3273. ContentReceiver content_receiver,
  3274. Progress progress) {
  3275. Request req;
  3276. req.method = "GET";
  3277. req.path = path;
  3278. req.headers = headers;
  3279. req.response_handler = std::move(response_handler);
  3280. req.content_receiver = std::move(content_receiver);
  3281. req.progress = std::move(progress);
  3282. auto res = std::make_shared<Response>();
  3283. return send(req, *res) ? res : nullptr;
  3284. }
  3285. inline std::shared_ptr<Response> Client::Head(const char *path) {
  3286. return Head(path, Headers());
  3287. }
  3288. inline std::shared_ptr<Response> Client::Head(const char *path,
  3289. const Headers &headers) {
  3290. Request req;
  3291. req.method = "HEAD";
  3292. req.headers = headers;
  3293. req.path = path;
  3294. auto res = std::make_shared<Response>();
  3295. return send(req, *res) ? res : nullptr;
  3296. }
  3297. inline std::shared_ptr<Response> Client::Post(const char *path,
  3298. const std::string &body,
  3299. const char *content_type) {
  3300. return Post(path, Headers(), body, content_type);
  3301. }
  3302. inline std::shared_ptr<Response> Client::Post(const char *path,
  3303. const Headers &headers,
  3304. const std::string &body,
  3305. const char *content_type) {
  3306. return send_with_content_provider("POST", path, headers, body, 0, nullptr,
  3307. content_type);
  3308. }
  3309. inline std::shared_ptr<Response> Client::Post(const char *path,
  3310. const Params &params) {
  3311. return Post(path, Headers(), params);
  3312. }
  3313. inline std::shared_ptr<Response> Client::Post(const char *path,
  3314. size_t content_length,
  3315. ContentProvider content_provider,
  3316. const char *content_type) {
  3317. return Post(path, Headers(), content_length, content_provider, content_type);
  3318. }
  3319. inline std::shared_ptr<Response>
  3320. Client::Post(const char *path, const Headers &headers, size_t content_length,
  3321. ContentProvider content_provider, const char *content_type) {
  3322. return send_with_content_provider("POST", path, headers, std::string(),
  3323. content_length, content_provider,
  3324. content_type);
  3325. }
  3326. inline std::shared_ptr<Response>
  3327. Client::Post(const char *path, const Headers &headers, const Params &params) {
  3328. std::string query;
  3329. for (auto it = params.begin(); it != params.end(); ++it) {
  3330. if (it != params.begin()) { query += "&"; }
  3331. query += it->first;
  3332. query += "=";
  3333. query += detail::encode_url(it->second);
  3334. }
  3335. return Post(path, headers, query, "application/x-www-form-urlencoded");
  3336. }
  3337. inline std::shared_ptr<Response>
  3338. Client::Post(const char *path, const MultipartFormDataItems &items) {
  3339. return Post(path, Headers(), items);
  3340. }
  3341. inline std::shared_ptr<Response>
  3342. Client::Post(const char *path, const Headers &headers,
  3343. const MultipartFormDataItems &items) {
  3344. auto boundary = detail::make_multipart_data_boundary();
  3345. std::string body;
  3346. for (const auto &item : items) {
  3347. body += "--" + boundary + "\r\n";
  3348. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3349. if (!item.filename.empty()) {
  3350. body += "; filename=\"" + item.filename + "\"";
  3351. }
  3352. body += "\r\n";
  3353. if (!item.content_type.empty()) {
  3354. body += "Content-Type: " + item.content_type + "\r\n";
  3355. }
  3356. body += "\r\n";
  3357. body += item.content + "\r\n";
  3358. }
  3359. body += "--" + boundary + "--\r\n";
  3360. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3361. return Post(path, headers, body, content_type.c_str());
  3362. }
  3363. inline std::shared_ptr<Response> Client::Put(const char *path,
  3364. const std::string &body,
  3365. const char *content_type) {
  3366. return Put(path, Headers(), body, content_type);
  3367. }
  3368. inline std::shared_ptr<Response> Client::Put(const char *path,
  3369. const Headers &headers,
  3370. const std::string &body,
  3371. const char *content_type) {
  3372. return send_with_content_provider("PUT", path, headers, body, 0, nullptr,
  3373. content_type);
  3374. }
  3375. inline std::shared_ptr<Response> Client::Put(const char *path,
  3376. size_t content_length,
  3377. ContentProvider content_provider,
  3378. const char *content_type) {
  3379. return Put(path, Headers(), content_length, content_provider, content_type);
  3380. }
  3381. inline std::shared_ptr<Response>
  3382. Client::Put(const char *path, const Headers &headers, size_t content_length,
  3383. ContentProvider content_provider, const char *content_type) {
  3384. return send_with_content_provider("PUT", path, headers, std::string(),
  3385. content_length, content_provider,
  3386. content_type);
  3387. }
  3388. inline std::shared_ptr<Response> Client::Put(const char *path,
  3389. const Params &params) {
  3390. return Put(path, Headers(), params);
  3391. }
  3392. inline std::shared_ptr<Response>
  3393. Client::Put(const char *path, const Headers &headers, const Params &params) {
  3394. std::string query;
  3395. for (auto it = params.begin(); it != params.end(); ++it) {
  3396. if (it != params.begin()) { query += "&"; }
  3397. query += it->first;
  3398. query += "=";
  3399. query += detail::encode_url(it->second);
  3400. }
  3401. return Put(path, headers, query, "application/x-www-form-urlencoded");
  3402. }
  3403. inline std::shared_ptr<Response> Client::Patch(const char *path,
  3404. const std::string &body,
  3405. const char *content_type) {
  3406. return Patch(path, Headers(), body, content_type);
  3407. }
  3408. inline std::shared_ptr<Response> Client::Patch(const char *path,
  3409. const Headers &headers,
  3410. const std::string &body,
  3411. const char *content_type) {
  3412. return send_with_content_provider("PATCH", path, headers, body, 0, nullptr,
  3413. content_type);
  3414. }
  3415. inline std::shared_ptr<Response> Client::Patch(const char *path,
  3416. size_t content_length,
  3417. ContentProvider content_provider,
  3418. const char *content_type) {
  3419. return Patch(path, Headers(), content_length, content_provider, content_type);
  3420. }
  3421. inline std::shared_ptr<Response>
  3422. Client::Patch(const char *path, const Headers &headers, size_t content_length,
  3423. ContentProvider content_provider, const char *content_type) {
  3424. return send_with_content_provider("PATCH", path, headers, std::string(),
  3425. content_length, content_provider,
  3426. content_type);
  3427. }
  3428. inline std::shared_ptr<Response> Client::Delete(const char *path) {
  3429. return Delete(path, Headers(), std::string(), nullptr);
  3430. }
  3431. inline std::shared_ptr<Response> Client::Delete(const char *path,
  3432. const std::string &body,
  3433. const char *content_type) {
  3434. return Delete(path, Headers(), body, content_type);
  3435. }
  3436. inline std::shared_ptr<Response> Client::Delete(const char *path,
  3437. const Headers &headers) {
  3438. return Delete(path, headers, std::string(), nullptr);
  3439. }
  3440. inline std::shared_ptr<Response> Client::Delete(const char *path,
  3441. const Headers &headers,
  3442. const std::string &body,
  3443. const char *content_type) {
  3444. Request req;
  3445. req.method = "DELETE";
  3446. req.headers = headers;
  3447. req.path = path;
  3448. if (content_type) { req.headers.emplace("Content-Type", content_type); }
  3449. req.body = body;
  3450. auto res = std::make_shared<Response>();
  3451. return send(req, *res) ? res : nullptr;
  3452. }
  3453. inline std::shared_ptr<Response> Client::Options(const char *path) {
  3454. return Options(path, Headers());
  3455. }
  3456. inline std::shared_ptr<Response> Client::Options(const char *path,
  3457. const Headers &headers) {
  3458. Request req;
  3459. req.method = "OPTIONS";
  3460. req.path = path;
  3461. req.headers = headers;
  3462. auto res = std::make_shared<Response>();
  3463. return send(req, *res) ? res : nullptr;
  3464. }
  3465. inline void Client::set_timeout_sec(time_t timeout_sec) {
  3466. timeout_sec_ = timeout_sec;
  3467. }
  3468. inline void Client::set_read_timeout(time_t sec, time_t usec) {
  3469. read_timeout_sec_ = sec;
  3470. read_timeout_usec_ = usec;
  3471. }
  3472. inline void Client::set_keep_alive_max_count(size_t count) {
  3473. keep_alive_max_count_ = count;
  3474. }
  3475. inline void Client::set_basic_auth(const char *username, const char *password) {
  3476. basic_auth_username_ = username;
  3477. basic_auth_password_ = password;
  3478. }
  3479. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3480. inline void Client::set_digest_auth(const char *username,
  3481. const char *password) {
  3482. digest_auth_username_ = username;
  3483. digest_auth_password_ = password;
  3484. }
  3485. #endif
  3486. inline void Client::set_follow_location(bool on) { follow_location_ = on; }
  3487. inline void Client::set_compress(bool on) { compress_ = on; }
  3488. inline void Client::set_interface(const char *intf) { interface_ = intf; }
  3489. inline void Client::set_proxy(const char *host, int port) {
  3490. proxy_host_ = host;
  3491. proxy_port_ = port;
  3492. }
  3493. inline void Client::set_proxy_basic_auth(const char *username,
  3494. const char *password) {
  3495. proxy_basic_auth_username_ = username;
  3496. proxy_basic_auth_password_ = password;
  3497. }
  3498. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3499. inline void Client::set_proxy_digest_auth(const char *username,
  3500. const char *password) {
  3501. proxy_digest_auth_username_ = username;
  3502. proxy_digest_auth_password_ = password;
  3503. }
  3504. #endif
  3505. inline void Client::set_logger(Logger logger) { logger_ = std::move(logger); }
  3506. /*
  3507. * SSL Implementation
  3508. */
  3509. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3510. namespace detail {
  3511. template <typename U, typename V, typename T>
  3512. inline bool process_and_close_socket_ssl(
  3513. bool is_client_request, socket_t sock, size_t keep_alive_max_count,
  3514. time_t read_timeout_sec, time_t read_timeout_usec, SSL_CTX *ctx,
  3515. std::mutex &ctx_mutex, U SSL_connect_or_accept, V setup, T callback) {
  3516. assert(keep_alive_max_count > 0);
  3517. SSL *ssl = nullptr;
  3518. {
  3519. std::lock_guard<std::mutex> guard(ctx_mutex);
  3520. ssl = SSL_new(ctx);
  3521. }
  3522. if (!ssl) {
  3523. close_socket(sock);
  3524. return false;
  3525. }
  3526. auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
  3527. SSL_set_bio(ssl, bio, bio);
  3528. if (!setup(ssl)) {
  3529. SSL_shutdown(ssl);
  3530. {
  3531. std::lock_guard<std::mutex> guard(ctx_mutex);
  3532. SSL_free(ssl);
  3533. }
  3534. close_socket(sock);
  3535. return false;
  3536. }
  3537. auto ret = false;
  3538. if (SSL_connect_or_accept(ssl) == 1) {
  3539. if (keep_alive_max_count > 1) {
  3540. auto count = keep_alive_max_count;
  3541. while (count > 0 &&
  3542. (is_client_request ||
  3543. detail::select_read(sock, CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND,
  3544. CPPHTTPLIB_KEEPALIVE_TIMEOUT_USECOND) > 0)) {
  3545. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec);
  3546. auto last_connection = count == 1;
  3547. auto connection_close = false;
  3548. ret = callback(ssl, strm, last_connection, connection_close);
  3549. if (!ret || connection_close) { break; }
  3550. count--;
  3551. }
  3552. } else {
  3553. SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec);
  3554. auto dummy_connection_close = false;
  3555. ret = callback(ssl, strm, true, dummy_connection_close);
  3556. }
  3557. }
  3558. SSL_shutdown(ssl);
  3559. {
  3560. std::lock_guard<std::mutex> guard(ctx_mutex);
  3561. SSL_free(ssl);
  3562. }
  3563. close_socket(sock);
  3564. return ret;
  3565. }
  3566. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  3567. static std::shared_ptr<std::vector<std::mutex>> openSSL_locks_;
  3568. class SSLThreadLocks {
  3569. public:
  3570. SSLThreadLocks() {
  3571. openSSL_locks_ =
  3572. std::make_shared<std::vector<std::mutex>>(CRYPTO_num_locks());
  3573. CRYPTO_set_locking_callback(locking_callback);
  3574. }
  3575. ~SSLThreadLocks() { CRYPTO_set_locking_callback(nullptr); }
  3576. private:
  3577. static void locking_callback(int mode, int type, const char * /*file*/,
  3578. int /*line*/) {
  3579. auto &locks = *openSSL_locks_;
  3580. if (mode & CRYPTO_LOCK) {
  3581. locks[type].lock();
  3582. } else {
  3583. locks[type].unlock();
  3584. }
  3585. }
  3586. };
  3587. #endif
  3588. class SSLInit {
  3589. public:
  3590. SSLInit() {
  3591. #if OPENSSL_VERSION_NUMBER < 0x1010001fL
  3592. SSL_load_error_strings();
  3593. SSL_library_init();
  3594. #else
  3595. OPENSSL_init_ssl(
  3596. OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
  3597. #endif
  3598. }
  3599. ~SSLInit() {
  3600. #if OPENSSL_VERSION_NUMBER < 0x1010001fL
  3601. ERR_free_strings();
  3602. #endif
  3603. }
  3604. private:
  3605. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  3606. SSLThreadLocks thread_init_;
  3607. #endif
  3608. };
  3609. // SSL socket stream implementation
  3610. inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl,
  3611. time_t read_timeout_sec,
  3612. time_t read_timeout_usec)
  3613. : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
  3614. read_timeout_usec_(read_timeout_usec) {}
  3615. inline SSLSocketStream::~SSLSocketStream() {}
  3616. inline int SSLSocketStream::read(char *ptr, size_t size) {
  3617. if (SSL_pending(ssl_) > 0 ||
  3618. select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0) {
  3619. return SSL_read(ssl_, ptr, static_cast<int>(size));
  3620. }
  3621. return -1;
  3622. }
  3623. inline int SSLSocketStream::write(const char *ptr, size_t size) {
  3624. return SSL_write(ssl_, ptr, static_cast<int>(size));
  3625. }
  3626. inline int SSLSocketStream::write(const char *ptr) {
  3627. return write(ptr, strlen(ptr));
  3628. }
  3629. inline int SSLSocketStream::write(const std::string &s) {
  3630. return write(s.data(), s.size());
  3631. }
  3632. inline std::string SSLSocketStream::get_remote_addr() const {
  3633. return detail::get_remote_addr(sock_);
  3634. }
  3635. static SSLInit sslinit_;
  3636. } // namespace detail
  3637. // SSL HTTP server implementation
  3638. inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
  3639. const char *client_ca_cert_file_path,
  3640. const char *client_ca_cert_dir_path) {
  3641. ctx_ = SSL_CTX_new(SSLv23_server_method());
  3642. if (ctx_) {
  3643. SSL_CTX_set_options(ctx_,
  3644. SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  3645. SSL_OP_NO_COMPRESSION |
  3646. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  3647. // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
  3648. // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
  3649. // EC_KEY_free(ecdh);
  3650. if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
  3651. SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
  3652. 1) {
  3653. SSL_CTX_free(ctx_);
  3654. ctx_ = nullptr;
  3655. } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
  3656. // if (client_ca_cert_file_path) {
  3657. // auto list = SSL_load_client_CA_file(client_ca_cert_file_path);
  3658. // SSL_CTX_set_client_CA_list(ctx_, list);
  3659. // }
  3660. SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
  3661. client_ca_cert_dir_path);
  3662. SSL_CTX_set_verify(
  3663. ctx_,
  3664. SSL_VERIFY_PEER |
  3665. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  3666. nullptr);
  3667. }
  3668. }
  3669. }
  3670. inline SSLServer::~SSLServer() {
  3671. if (ctx_) { SSL_CTX_free(ctx_); }
  3672. }
  3673. inline bool SSLServer::is_valid() const { return ctx_; }
  3674. inline bool SSLServer::process_and_close_socket(socket_t sock) {
  3675. return detail::process_and_close_socket_ssl(
  3676. false, sock, keep_alive_max_count_, read_timeout_sec_, read_timeout_usec_,
  3677. ctx_, ctx_mutex_, SSL_accept, [](SSL * /*ssl*/) { return true; },
  3678. [this](SSL *ssl, Stream &strm, bool last_connection,
  3679. bool &connection_close) {
  3680. return process_request(strm, last_connection, connection_close,
  3681. [&](Request &req) { req.ssl = ssl; });
  3682. });
  3683. }
  3684. // SSL HTTP client implementation
  3685. inline SSLClient::SSLClient(const std::string &host, int port,
  3686. const std::string &client_cert_path,
  3687. const std::string &client_key_path)
  3688. : Client(host, port, client_cert_path, client_key_path) {
  3689. ctx_ = SSL_CTX_new(SSLv23_client_method());
  3690. detail::split(&host_[0], &host_[host_.size()], '.',
  3691. [&](const char *b, const char *e) {
  3692. host_components_.emplace_back(std::string(b, e));
  3693. });
  3694. if (!client_cert_path.empty() && !client_key_path.empty()) {
  3695. if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
  3696. SSL_FILETYPE_PEM) != 1 ||
  3697. SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
  3698. SSL_FILETYPE_PEM) != 1) {
  3699. SSL_CTX_free(ctx_);
  3700. ctx_ = nullptr;
  3701. }
  3702. }
  3703. }
  3704. inline SSLClient::~SSLClient() {
  3705. if (ctx_) { SSL_CTX_free(ctx_); }
  3706. }
  3707. inline bool SSLClient::is_valid() const { return ctx_; }
  3708. inline void SSLClient::set_ca_cert_path(const char *ca_cert_file_path,
  3709. const char *ca_cert_dir_path) {
  3710. if (ca_cert_file_path) { ca_cert_file_path_ = ca_cert_file_path; }
  3711. if (ca_cert_dir_path) { ca_cert_dir_path_ = ca_cert_dir_path; }
  3712. }
  3713. inline void SSLClient::enable_server_certificate_verification(bool enabled) {
  3714. server_certificate_verification_ = enabled;
  3715. }
  3716. inline long SSLClient::get_openssl_verify_result() const {
  3717. return verify_result_;
  3718. }
  3719. inline SSL_CTX *SSLClient::ssl_context() const noexcept { return ctx_; }
  3720. inline bool SSLClient::process_and_close_socket(
  3721. socket_t sock, size_t request_count,
  3722. std::function<bool(Stream &strm, bool last_connection,
  3723. bool &connection_close)>
  3724. callback) {
  3725. request_count = std::min(request_count, keep_alive_max_count_);
  3726. return is_valid() &&
  3727. detail::process_and_close_socket_ssl(
  3728. true, sock, request_count, read_timeout_sec_, read_timeout_usec_,
  3729. ctx_, ctx_mutex_,
  3730. [&](SSL *ssl) {
  3731. if (ca_cert_file_path_.empty()) {
  3732. SSL_CTX_set_verify(ctx_, SSL_VERIFY_NONE, nullptr);
  3733. } else {
  3734. if (!SSL_CTX_load_verify_locations(
  3735. ctx_, ca_cert_file_path_.c_str(), nullptr)) {
  3736. return false;
  3737. }
  3738. SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER, nullptr);
  3739. }
  3740. if (SSL_connect(ssl) != 1) { return false; }
  3741. if (server_certificate_verification_) {
  3742. verify_result_ = SSL_get_verify_result(ssl);
  3743. if (verify_result_ != X509_V_OK) { return false; }
  3744. auto server_cert = SSL_get_peer_certificate(ssl);
  3745. if (server_cert == nullptr) { return false; }
  3746. if (!verify_host(server_cert)) {
  3747. X509_free(server_cert);
  3748. return false;
  3749. }
  3750. X509_free(server_cert);
  3751. }
  3752. return true;
  3753. },
  3754. [&](SSL *ssl) {
  3755. SSL_set_tlsext_host_name(ssl, host_.c_str());
  3756. return true;
  3757. },
  3758. [&](SSL * /*ssl*/, Stream &strm, bool last_connection,
  3759. bool &connection_close) {
  3760. return callback(strm, last_connection, connection_close);
  3761. });
  3762. }
  3763. inline bool SSLClient::is_ssl() const { return true; }
  3764. inline bool SSLClient::verify_host(X509 *server_cert) const {
  3765. /* Quote from RFC2818 section 3.1 "Server Identity"
  3766. If a subjectAltName extension of type dNSName is present, that MUST
  3767. be used as the identity. Otherwise, the (most specific) Common Name
  3768. field in the Subject field of the certificate MUST be used. Although
  3769. the use of the Common Name is existing practice, it is deprecated and
  3770. Certification Authorities are encouraged to use the dNSName instead.
  3771. Matching is performed using the matching rules specified by
  3772. [RFC2459]. If more than one identity of a given type is present in
  3773. the certificate (e.g., more than one dNSName name, a match in any one
  3774. of the set is considered acceptable.) Names may contain the wildcard
  3775. character * which is considered to match any single domain name
  3776. component or component fragment. E.g., *.a.com matches foo.a.com but
  3777. not bar.foo.a.com. f*.com matches foo.com but not bar.com.
  3778. In some cases, the URI is specified as an IP address rather than a
  3779. hostname. In this case, the iPAddress subjectAltName must be present
  3780. in the certificate and must exactly match the IP in the URI.
  3781. */
  3782. return verify_host_with_subject_alt_name(server_cert) ||
  3783. verify_host_with_common_name(server_cert);
  3784. }
  3785. inline bool
  3786. SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
  3787. auto ret = false;
  3788. auto type = GEN_DNS;
  3789. struct in6_addr addr6;
  3790. struct in_addr addr;
  3791. size_t addr_len = 0;
  3792. #ifndef __MINGW32__
  3793. if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
  3794. type = GEN_IPADD;
  3795. addr_len = sizeof(struct in6_addr);
  3796. } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
  3797. type = GEN_IPADD;
  3798. addr_len = sizeof(struct in_addr);
  3799. }
  3800. #endif
  3801. auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
  3802. X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
  3803. if (alt_names) {
  3804. auto dsn_matched = false;
  3805. auto ip_mached = false;
  3806. auto count = sk_GENERAL_NAME_num(alt_names);
  3807. for (auto i = 0; i < count && !dsn_matched; i++) {
  3808. auto val = sk_GENERAL_NAME_value(alt_names, i);
  3809. if (val->type == type) {
  3810. auto name = (const char *)ASN1_STRING_get0_data(val->d.ia5);
  3811. auto name_len = (size_t)ASN1_STRING_length(val->d.ia5);
  3812. if (strlen(name) == name_len) {
  3813. switch (type) {
  3814. case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
  3815. case GEN_IPADD:
  3816. if (!memcmp(&addr6, name, addr_len) ||
  3817. !memcmp(&addr, name, addr_len)) {
  3818. ip_mached = true;
  3819. }
  3820. break;
  3821. }
  3822. }
  3823. }
  3824. }
  3825. if (dsn_matched || ip_mached) { ret = true; }
  3826. }
  3827. GENERAL_NAMES_free((STACK_OF(GENERAL_NAME) *)alt_names);
  3828. return ret;
  3829. }
  3830. inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
  3831. const auto subject_name = X509_get_subject_name(server_cert);
  3832. if (subject_name != nullptr) {
  3833. char name[BUFSIZ];
  3834. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  3835. name, sizeof(name));
  3836. if (name_len != -1) { return check_host_name(name, name_len); }
  3837. }
  3838. return false;
  3839. }
  3840. inline bool SSLClient::check_host_name(const char *pattern,
  3841. size_t pattern_len) const {
  3842. if (host_.size() == pattern_len && host_ == pattern) { return true; }
  3843. // Wildcard match
  3844. // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
  3845. std::vector<std::string> pattern_components;
  3846. detail::split(&pattern[0], &pattern[pattern_len], '.',
  3847. [&](const char *b, const char *e) {
  3848. pattern_components.emplace_back(std::string(b, e));
  3849. });
  3850. if (host_components_.size() != pattern_components.size()) { return false; }
  3851. auto itr = pattern_components.begin();
  3852. for (const auto &h : host_components_) {
  3853. auto &p = *itr;
  3854. if (p != h && p != "*") {
  3855. auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
  3856. !p.compare(0, p.size() - 1, h));
  3857. if (!partial_match) { return false; }
  3858. }
  3859. ++itr;
  3860. }
  3861. return true;
  3862. }
  3863. #endif
  3864. // ----------------------------------------------------------------------------
  3865. } // namespace httplib
  3866. #endif // CPPHTTPLIB_HTTPLIB_H