httptransport.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #pragma warning(disable : 4786)
  15. #ifdef WIN32
  16. #ifdef ESPHTTP_EXPORTS
  17. #define esp_http_decl __declspec(dllexport)
  18. #endif
  19. #endif
  20. //Jlib
  21. #include "jliball.hpp"
  22. //ESP Binidings
  23. #include "http/platform/httptransport.ipp"
  24. #include "bindutil.hpp"
  25. IEspHttpException* createEspHttpException(int code, const char *_msg, const char* _httpstatus)
  26. {
  27. return new CEspHttpException(code, _msg, _httpstatus);
  28. }
  29. bool httpContentFromFile(const char *filepath, StringBuffer &mimetype, MemoryBuffer &fileContents)
  30. {
  31. StringBuffer strfile(filepath);
  32. if (!checkFileExists(strfile.str()))
  33. if (!checkFileExists(strfile.toUpperCase().str()))
  34. if (!checkFileExists(strfile.toLowerCase().str()))
  35. return false;
  36. Owned<IFile> file = createIFile(strfile.str());
  37. if (file && file->isFile())
  38. {
  39. Owned<IFileIO> io = file->open(IFOread);
  40. if (io)
  41. {
  42. size32_t filesize = io->size();
  43. io->read(0, filesize, fileContents.reserveTruncate(filesize));
  44. mimetype.clear();
  45. const char *ext = strrchr(filepath, '.');
  46. if (ext)
  47. {
  48. ext++;
  49. if (!stricmp(ext, "html") || !stricmp(ext, "htm"))
  50. mimetype.append("text/html");
  51. else if (!stricmp(ext, "js"))
  52. mimetype.append("text/javascript");
  53. else if (!stricmp(ext, "jpeg") || !stricmp(ext, "jpg"))
  54. mimetype.append("image/gif");
  55. else if (!stricmp(ext, "gif"))
  56. mimetype.append("image/gif");
  57. else if (!stricmp(ext, "png"))
  58. mimetype.append("image/png");
  59. else if (!stricmp(ext, "xml") || !stricmp(ext, "xsl"))
  60. mimetype.append("text/xml");
  61. else if (!stricmp(ext, "txt") || !stricmp(ext, "text"))
  62. mimetype.append("text/plain");
  63. else if (!stricmp(ext, "zip"))
  64. mimetype.append("application/zip");
  65. else if (!stricmp(ext, "pdf"))
  66. mimetype.append("application/pdf");
  67. else if (!stricmp(ext, "pdf"))
  68. mimetype.append("application/pdf");
  69. else if (!stricmp(ext, "xpi"))
  70. mimetype.append("application/x-xpinstall");
  71. else if (!stricmp(ext, "exe") || !stricmp(ext, "class"))
  72. mimetype.append("application/octet-stream");
  73. else if (!stricmp(ext, "xsl") || !stricmp(ext, "xslt"))
  74. mimetype.append("text/xml");
  75. else if (!stricmp(ext, "css"))
  76. mimetype.append("text/css");
  77. else if (!stricmp(ext, "svg"))
  78. mimetype.append("image/svg+xml");
  79. }
  80. if (!mimetype.length())
  81. mimetype.append("application/octet-stream");
  82. return true;
  83. }
  84. }
  85. return false;
  86. }
  87. /***************************************************************************
  88. CHttpMessage Implementation
  89. This class implements common functions shared by both CHttpRequest
  90. and CHttpResponse
  91. ****************************************************************************/
  92. CHttpMessage::CHttpMessage(ISocket& socket) : m_socket(socket)
  93. {
  94. m_bufferedsocket.setown(createBufferedSocket(&socket));
  95. m_content_length = -1;
  96. m_content_length64 = -1;
  97. m_port = 80;
  98. m_paramCount = 0;
  99. m_attachCount = 0;
  100. m_supportClientXslt=-1;
  101. m_isForm = false;
  102. };
  103. CHttpMessage::~CHttpMessage()
  104. {
  105. try
  106. {
  107. m_bufferedsocket.clear();
  108. m_context.clear();
  109. m_queryparams.clear();
  110. m_content_stream.clear();
  111. }
  112. catch(...)
  113. {
  114. ERRLOG("In CHttpMessage::~CHttpMessage() -- Unknown exception.");
  115. }
  116. };
  117. int CHttpMessage::parseOneHeader(char* oneline)
  118. {
  119. if (getEspLogLevel()>LogNormal)
  120. DBGLOG("%s", oneline);
  121. if(!oneline)
  122. return -1;
  123. char* name = oneline;
  124. while(*name == ' ')
  125. name++;
  126. char* end = name;
  127. while(*end != '\0' && *end != ':')
  128. end++;
  129. char* value;
  130. if (*end == ':')
  131. {
  132. *end = '\0';
  133. value = end + 1;
  134. }
  135. else
  136. value = end;
  137. while(*value == ' ')
  138. value++;
  139. if(!stricmp(name, "Content-Type"))
  140. {
  141. m_content_type.set(value);
  142. }
  143. else if(!stricmp(name, "Content-Length"))
  144. {
  145. if(value != NULL)
  146. {
  147. m_content_length = atoi(value);
  148. m_content_length64 = atoi64_l(value,strlen(value));
  149. }
  150. }
  151. else if(!stricmp(name, "Host"))
  152. {
  153. if(value != NULL)
  154. {
  155. char* colon = strchr(value, ':');
  156. if(colon != NULL)
  157. {
  158. *colon = '\0';
  159. char* port = colon + 1;
  160. if(port != NULL)
  161. {
  162. m_port = atoi(port);
  163. }
  164. }
  165. m_host.set(value);
  166. }
  167. }
  168. else if(!stricmp(name, "Set-Cookie") || !stricmp(name, "Cookie"))
  169. {
  170. parseCookieHeader(value);
  171. }
  172. else
  173. {
  174. addHeader(name, value); //Insert into headers hashtable
  175. }
  176. return 0;
  177. }
  178. bool CHttpMessage::supportClientXslt()
  179. {
  180. if (m_supportClientXslt==-1)
  181. {
  182. bool ie6=false;
  183. bool moz5=false;
  184. bool opera=false;
  185. bool ff=false;
  186. StringBuffer uastr;
  187. getHeader("User-Agent", uastr);
  188. char *uagent=strdup(uastr.str());
  189. char *saveptr;
  190. char *token = strtok_r(uagent, "();", &saveptr);
  191. while(token)
  192. {
  193. while (*token==' ') token++;
  194. if (!strnicmp(token, "msie", 4))
  195. ie6=(token[5]>='6');
  196. else if (!strnicmp(token, "mozilla", 7))
  197. moz5=(token[8]>='5');
  198. else if (!strnicmp(token, "opera", 5))
  199. opera=true;
  200. else if (!strnicmp(token, "firefox", 7))
  201. ff=true;
  202. token = strtok_r( NULL, "();" , &saveptr);
  203. }
  204. free(uagent);
  205. m_supportClientXslt=(ff || moz5 || (ie6 && !opera)) ? 1 : 0;
  206. }
  207. return m_supportClientXslt==1;
  208. }
  209. /*
  210. void CHttpMessage::addRawXMLParameter(const char* path, IPropertyTree* tree)
  211. {
  212. const char* name = tree->queryName();
  213. if (stricmp(name, "RawArray")==0)
  214. {
  215. Owned<IPropertyTreeIterator> row = tree->getElements("Item");
  216. int items = 0;
  217. for (row->first(); row->isValid(); row->next())
  218. {
  219. IPropertyTree* pRow = &row->query();
  220. StringBuffer newpath(path);
  221. newpath.appendf(".%d",items);
  222. const char* value = pRow->queryProp(NULL);
  223. if (value)
  224. {
  225. if (*value)
  226. m_queryparams->setProp(newpath, value);
  227. }
  228. else
  229. {
  230. Owned<IPropertyTreeIterator> field = pRow->getElements("*");
  231. int baseLen = newpath.length();
  232. for (field->first(); field->isValid(); field->next())
  233. {
  234. newpath.appendf(".%s", field->query().queryName());
  235. addRawXMLParameter(newpath, &field->query());
  236. newpath.setLength(baseLen);
  237. }
  238. }
  239. items++;
  240. }
  241. if (items>0)
  242. {
  243. StringBuffer newpath(path),v;
  244. newpath.append(".itemcount");
  245. v.append(items);
  246. m_queryparams->setProp(newpath, v);
  247. m_paramCount++;
  248. }
  249. }
  250. else
  251. {
  252. const char* value = tree->queryProp(NULL);
  253. if (value)
  254. {
  255. if (*value)
  256. m_queryparams->setProp(path, value);
  257. }
  258. else // subtree
  259. {
  260. Owned<IPropertyTreeIterator> field = tree->getElements("*");
  261. for (field->first(); field->isValid(); field->next())
  262. {
  263. const char* fieldName = field->query().queryName();
  264. StringBuffer newpath(path);
  265. if (stricmp(fieldName, "RawArray")!=0)
  266. newpath.appendf(".%s",field->query().queryName());
  267. addRawXMLParameter(newpath, &field->query());
  268. }
  269. }
  270. }
  271. }
  272. void CHttpMessage::addRawXMLParameter(const char* path, const char *value)
  273. {
  274. Owned<IPropertyTree> tree;
  275. try
  276. {
  277. tree.setown(createPTreeFromXMLString(value));
  278. }
  279. catch(IException* e)
  280. {
  281. StringBuffer msg;
  282. e->errorMessage(msg);
  283. ERRLOG("Error parsing struct array: %s", msg.str());
  284. return;
  285. }
  286. addRawXMLParameter(path, tree);
  287. }
  288. */
  289. void CHttpMessage::addParameter(const char* paramname, const char *value)
  290. {
  291. if (!m_queryparams)
  292. m_queryparams.setown(createProperties(false));
  293. if (strcmp(paramname,"form")==0)
  294. m_isForm = true;
  295. if (!m_isForm)
  296. {
  297. // remove the leading '.'
  298. if (*paramname=='.')
  299. paramname++;
  300. }
  301. m_queryparams->setProp(paramname, value);
  302. m_paramCount++;
  303. }
  304. StringBuffer& CHttpMessage::getParameter(const char* paramname, StringBuffer& paramval)
  305. {
  306. if (m_queryparams)
  307. {
  308. const char *value = m_queryparams->queryProp(paramname);
  309. if (value)
  310. paramval.append(value);
  311. }
  312. return paramval;
  313. }
  314. void CHttpMessage::addAttachment(const char* name, StringBuffer& value)
  315. {
  316. if(name != NULL)
  317. {
  318. m_attachments.setValue(name, value);
  319. m_attachCount++;
  320. }
  321. }
  322. StringBuffer& CHttpMessage::getAttachment(const char* name, StringBuffer& attachment)
  323. {
  324. StringBuffer *value = m_attachments.getValue(name);
  325. if (value)
  326. {
  327. attachment.append(value->length(), value->str());
  328. }
  329. return attachment;
  330. }
  331. StringBuffer& CHttpMessage::getParamStr(StringBuffer& ret)
  332. {
  333. return ret.append(m_paramstr);
  334. }
  335. IProperties *CHttpMessage::queryParameters()
  336. {
  337. if (!m_queryparams)
  338. m_queryparams.setown(createProperties(false));
  339. return m_queryparams.get();
  340. }
  341. IProperties *CHttpMessage::getParameters()
  342. {
  343. if (!m_queryparams)
  344. m_queryparams.setown(createProperties(false));
  345. return m_queryparams.getLink();
  346. }
  347. int CHttpMessage::processHeaders(IMultiException *me)
  348. {
  349. return 0;
  350. }
  351. int CHttpMessage::readContent()
  352. {
  353. char buf[1024 + 1];
  354. int buflen = 1024;
  355. if(m_content_length > 0)
  356. {
  357. int totallen = m_content_length;
  358. if(buflen > totallen)
  359. buflen = totallen;
  360. int readlen = 0;
  361. for(;;)
  362. {
  363. readlen = m_bufferedsocket->read(buf, buflen);
  364. if(readlen < 0)
  365. {
  366. DBGLOG(">> Socket timed out because of incorrect Content-Length passed in from the other side");
  367. break;
  368. }
  369. if(readlen == 0)
  370. break;
  371. buf[readlen] = 0;
  372. m_content.append(readlen, buf);
  373. totallen -= readlen;
  374. if(totallen <= 0)
  375. break;
  376. if(buflen > totallen)
  377. buflen = totallen;
  378. }
  379. return 0;
  380. }
  381. return 0;
  382. }
  383. int CHttpMessage::readContentTillSocketClosed()
  384. {
  385. const int buflen = 1024;
  386. char buf[buflen + 1];
  387. StringBuffer headerValue;
  388. getHeader("Transfer-Encoding", headerValue);
  389. if (!stricmp(headerValue.str(), "chunked"))//Transfer-Encoding: chunked
  390. {
  391. for(;;)
  392. {
  393. int readlen = m_bufferedsocket->readline(buf, buflen, NULL);
  394. if(readlen <= 0)
  395. break;
  396. buf[readlen] = 0;
  397. int chunkSize;
  398. sscanf(buf, "%x", &chunkSize);
  399. if (chunkSize<=0)
  400. break;
  401. while (chunkSize > 0)
  402. {
  403. const int len = min(chunkSize, buflen);
  404. readlen = m_bufferedsocket->read(buf, len);
  405. if(readlen <= 0)
  406. break;
  407. chunkSize -= readlen;
  408. m_content.append(readlen, buf);
  409. }
  410. if (m_bufferedsocket->read(buf, 2) <= 0)//CR/LF
  411. break;
  412. }
  413. }
  414. else
  415. {
  416. for(;;)
  417. {
  418. int readlen = m_bufferedsocket->read(buf, buflen);
  419. if(readlen <= 0)
  420. break;
  421. buf[readlen] = 0;
  422. m_content.append(readlen, buf);
  423. }
  424. }
  425. return 0;
  426. }
  427. int CHttpMessage::receive(bool alwaysReadContent, IMultiException *me)
  428. {
  429. if (processHeaders(me)==-1)
  430. return -1;
  431. if (getEspLogLevel()>LogNormal)
  432. DBGLOG("Headers processed! content_length = %d", m_content_length);
  433. if (isUpload())
  434. return 0;
  435. m_context->addTraceSummaryValue("contLen", m_content_length);
  436. if(m_content_length > 0)
  437. {
  438. readContent();
  439. if (getEspLogLevel()>LogNormal)
  440. DBGLOG("length of content read = %d", m_content.length());
  441. }
  442. else if (alwaysReadContent && m_content_length == -1)
  443. {
  444. //HTTP protocol does not require a content length: read until socket closed
  445. readContentTillSocketClosed();
  446. if (getEspLogLevel()>LogNormal)
  447. DBGLOG("length of content read = %d", m_content.length());
  448. }
  449. if (getEspLogRequests() || getEspLogLevel()>LogNormal)
  450. {
  451. if(isTextMessage())
  452. DBGLOG("received HTTP content:\n%s", m_content.str());
  453. }
  454. return 0;
  455. }
  456. StringBuffer& CHttpMessage::getContent(StringBuffer& content)
  457. {
  458. content.append(m_content.length(), m_content.str());
  459. return content;
  460. }
  461. void CHttpMessage::setContent(const char* content)
  462. {
  463. m_content.clear();
  464. m_content.append(content);
  465. m_content_length = strlen(content);
  466. }
  467. void CHttpMessage::setContent(unsigned len, const char* content)
  468. {
  469. m_content.clear();
  470. m_content.append(len, content);
  471. m_content_length = len;
  472. }
  473. void CHttpMessage::setownContent(char* content)
  474. {
  475. size32_t len=strlen(content);
  476. m_content.setBuffer(len+1, content, len);
  477. m_content_length = len;
  478. }
  479. void CHttpMessage::setownContent(unsigned len, char* content)
  480. {
  481. m_content.setBuffer(len+1, content, len);
  482. m_content_length = len;
  483. }
  484. void CHttpMessage::setContent(IFileIOStream* stream)
  485. {
  486. if(stream != NULL)
  487. {
  488. m_content.clear();
  489. m_content_length = stream->size();
  490. m_content_length64 = stream->size();
  491. m_content_stream.setown(stream);
  492. }
  493. }
  494. /*
  495. void CHttpMessage::appendContent(const char* content)
  496. {
  497. m_content.append(content);
  498. m_content_length += strlen(content);
  499. }
  500. */
  501. StringBuffer& CHttpMessage::getContentType(StringBuffer& contenttype)
  502. {
  503. contenttype.append(m_content_type);
  504. return contenttype;
  505. }
  506. void CHttpMessage::setContentType(const char* contenttype)
  507. {
  508. m_content_type.set(contenttype);
  509. }
  510. void CHttpMessage::setVersion(const char* version)
  511. {
  512. m_version.set(version);
  513. }
  514. int CHttpMessage::parseFirstLine(char* oneline)
  515. {
  516. return 0;
  517. }
  518. void CHttpMessage::parseCookieHeader(char* cookiestr)
  519. {
  520. }
  521. StringBuffer& CHttpMessage::constructHeaderBuffer(StringBuffer& headerbuf, bool inclLen)
  522. {
  523. return headerbuf;
  524. }
  525. int CHttpMessage::send()
  526. {
  527. StringBuffer headers;
  528. constructHeaderBuffer(headers, true);
  529. int retcode = 0;
  530. // If m_content is empty but m_content_stream is set, the stream will not be logged here.
  531. if (getEspLogResponses() || getEspLogLevel(queryContext())>LogNormal)
  532. {
  533. DBGLOG("Sending out HTTP message:\n%s", headers.str());
  534. if(m_content_length > 0 && m_content.length() > 0)
  535. {
  536. if(isTextMessage())
  537. DBGLOG("sent HTTP Content:\n%s", m_content.str());
  538. else
  539. DBGLOG("sent HTTP <non-text content>");
  540. }
  541. }
  542. try
  543. {
  544. m_socket.write(headers.str(), headers.length());
  545. if(m_content_length > 0 && m_content.length() > 0)
  546. m_socket.write(m_content.str(), m_content.length());
  547. }
  548. catch (IException *e)
  549. {
  550. StringBuffer estr;
  551. DBGLOG("In CHttpMessage::send(%d) -- Exception(%d, %s) writing to socket(%d).", __LINE__, e->errorCode(), e->errorMessage(estr).str(), m_socket.OShandle());
  552. e->Release();
  553. return -1;
  554. }
  555. catch(...)
  556. {
  557. ERRLOG("In CHttpMessage::send(%d) -- Unknown exception writing to socket(%d).", __LINE__, m_socket.OShandle());
  558. return -1;
  559. }
  560. // When m_content is empty but the stream was set, read content from the stream.
  561. if(((m_content_length > 0 && m_content.length() == 0) || (m_content_length64 > 0)) && m_content_stream.get() != NULL)
  562. {
  563. //Read the file and send out 20K at a time.
  564. __int64 content_length = m_content_length;
  565. if ((m_content_length64 > 0) && (content_length != m_content_length64))
  566. content_length = m_content_length64;
  567. int buflen = 20*1024;
  568. if(buflen > content_length)
  569. buflen = (int) content_length;
  570. char* buffer = new char[buflen + 1];
  571. __int64 sizesent = 0;
  572. while(sizesent < content_length)
  573. {
  574. int sizeread = m_content_stream->read(buflen, buffer);
  575. if(sizeread > 0)
  576. {
  577. sizesent += sizeread;
  578. try
  579. {
  580. m_socket.write(buffer, sizeread);
  581. }
  582. catch (IException *e)
  583. {
  584. StringBuffer estr;
  585. LOG(MCexception(e), "In CHttpMessage::send(%d) -- Exception(%d, %s) writing to socket(%d).", __LINE__, e->errorCode(), e->errorMessage(estr).str(), m_socket.OShandle());
  586. e->Release();
  587. retcode = -1;
  588. break;
  589. }
  590. catch(...)
  591. {
  592. ERRLOG("In CHttpMessage::send(%d) -- Unknown exception writing to socket(%d).", __LINE__, m_socket.OShandle());
  593. retcode = -1;
  594. break;
  595. }
  596. }
  597. else
  598. {
  599. ERRLOG("Error read from file");
  600. break;
  601. }
  602. }
  603. delete buffer;
  604. }
  605. return retcode;
  606. }
  607. int CHttpMessage::startSend()
  608. {
  609. StringBuffer sendbuf;
  610. constructHeaderBuffer(sendbuf, false);
  611. if (getEspLogLevel(queryContext())>LogNormal)
  612. DBGLOG("Start Sending chunked HTTP message:\n %s", sendbuf.str());
  613. try
  614. {
  615. m_socket.write(sendbuf.str(), sendbuf.length());
  616. }
  617. catch (IException *e)
  618. {
  619. StringBuffer estr;
  620. DBGLOG("In CHttpMessage::send() -- Exception(%d, %s) writing to socket(%d).", e->errorCode(), e->errorMessage(estr).str(), m_socket.OShandle());
  621. e->Release();
  622. return -1;
  623. }
  624. catch(...)
  625. {
  626. ERRLOG("In CHttpMessage::send() -- Unknown exception writing to socket(%d).", m_socket.OShandle());
  627. return -1;
  628. }
  629. return 0;
  630. }
  631. int CHttpMessage::sendChunk(const char *chunk)
  632. {
  633. if (getEspLogLevel(queryContext())>LogNormal)
  634. DBGLOG("Sending HTTP chunk:\n %s", chunk);
  635. try
  636. {
  637. m_socket.write(chunk, strlen(chunk));
  638. }
  639. catch (IException *e)
  640. {
  641. StringBuffer estr;
  642. DBGLOG("In CHttpMessage::send() -- Exception(%d, %s) writing to socket(%d).", e->errorCode(), e->errorMessage(estr).str(), m_socket.OShandle());
  643. e->Release();
  644. return -1;
  645. }
  646. catch(...)
  647. {
  648. ERRLOG("In CHttpMessage::send() -- Unknown exception writing to socket(%d).", m_socket.OShandle());
  649. return -1;
  650. }
  651. return 0;
  652. }
  653. int CHttpMessage::sendFinalChunk(const char *chunk)
  654. {
  655. if (getEspLogLevel(queryContext())>LogNormal)
  656. DBGLOG("Sending HTTP Final chunk:\n %s", chunk);
  657. try
  658. {
  659. m_socket.write(chunk, strlen(chunk));
  660. m_socket.close();
  661. }
  662. catch (IException *e)
  663. {
  664. StringBuffer estr;
  665. DBGLOG("In CHttpMessage::send() -- Exception(%d, %s) writing to socket(%d).", e->errorCode(), e->errorMessage(estr).str(), m_socket.OShandle());
  666. e->Release();
  667. return -1;
  668. }
  669. catch(...)
  670. {
  671. ERRLOG("In CHttpMessage::send() -- Unknown exception writing to socket(%d).", m_socket.OShandle());
  672. return -1;
  673. }
  674. return 0;
  675. }
  676. int CHttpMessage::close()
  677. {
  678. int ret = 0;
  679. try
  680. {
  681. if(&m_socket != NULL)
  682. {
  683. m_socket.shutdown();
  684. m_socket.close();
  685. }
  686. }
  687. catch (IException *e)
  688. {
  689. StringBuffer estr;
  690. ERRLOG("Exception(%d, %s) - CHttpMessage::close(), closing socket.", e->errorCode(), e->errorMessage(estr).str());
  691. e->Release();
  692. ret = -1;
  693. }
  694. catch(...)
  695. {
  696. ERRLOG("General Exception - CHttpMessage::close(), closing socket.");
  697. ret = -1;
  698. }
  699. return ret;
  700. }
  701. void CHttpMessage::setHeader(const char* headername, const char* headerval)
  702. {
  703. if(!headername || !*headername)
  704. return;
  705. StringBuffer val;
  706. val.append(headername).append(": ").append(headerval);
  707. ForEachItemIn(x, m_headers)
  708. {
  709. const char* curst = m_headers.item(x);
  710. if(!curst)
  711. continue;
  712. const char* colon = strchr(curst, ':');
  713. if(!colon)
  714. continue;
  715. if(!strnicmp(headername, curst, colon - curst))
  716. {
  717. m_headers.replace(val.str(), x);
  718. return;
  719. }
  720. }
  721. m_headers.append(val.str());
  722. }
  723. void CHttpMessage::addHeader(const char* headername, const char* headerval)
  724. {
  725. if(headername == NULL || strlen(headername) == 0)
  726. return;
  727. StringBuffer header;
  728. header.append(headername);
  729. header.append(": ");
  730. header.append(headerval);
  731. m_headers.append(header.str());
  732. }
  733. StringBuffer& CHttpMessage::getHeader(const char* headername, StringBuffer& headerval)
  734. {
  735. if(headername == NULL || strlen(headername) == 0)
  736. return headerval;
  737. ForEachItemIn(x, m_headers)
  738. {
  739. const char* header = m_headers.item(x);
  740. if(header == NULL)
  741. continue;
  742. const char* colon = strchr(header, ':');
  743. if(colon == NULL)
  744. continue;
  745. if(strncmp(headername, header, colon - header) == 0)
  746. {
  747. headerval.append(colon + 2);
  748. break;
  749. }
  750. }
  751. return headerval;
  752. }
  753. bool isSoapContentType(const char* contenttype)
  754. {
  755. if(contenttype == NULL)
  756. return false;
  757. else
  758. return Utils::strncasecmp(contenttype, HTTP_TYPE_TEXT_XML, strlen(HTTP_TYPE_TEXT_XML)) == 0 ||
  759. Utils::strncasecmp(contenttype, HTTP_TYPE_SOAP, strlen(HTTP_TYPE_SOAP)) == 0;
  760. }
  761. bool CHttpMessage::isSoapMessage()
  762. {
  763. if(m_content_type.get() == NULL)
  764. return false;
  765. else if(Utils::strncasecmp(m_content_type.get(), HTTP_TYPE_MULTIPART_RELATED, strlen(HTTP_TYPE_MULTIPART_RELATED)) == 0)
  766. {
  767. CMimeMultiPart* mpart = queryMultiPart();
  768. if(mpart == NULL)
  769. return false;
  770. CMimeBodyPart* bpart = mpart->queryRootPart();
  771. if(bpart != NULL && isSoapContentType(bpart->getContentType()))
  772. return true;
  773. else
  774. return false;
  775. }
  776. else
  777. return isSoapContentType(m_content_type.get());
  778. }
  779. bool CHttpMessage::isFormSubmission()
  780. {
  781. return ((hasContentType(NULL) && (m_paramCount + m_attachCount) > 0) ||
  782. hasContentType(HTTP_TYPE_MULTIPART_FORMDATA) ||
  783. hasContentType(HTTP_TYPE_FORM_ENCODED));
  784. }
  785. /******************************************************************************
  786. CHttpRequest Implementation
  787. *******************************************************************************/
  788. CHttpRequest::CHttpRequest(ISocket& socket) : CHttpMessage(socket), m_pathIsParsed(false), m_sstype(sub_serv_unknown), m_MaxRequestEntityLength(0)
  789. {
  790. };
  791. CHttpRequest::~CHttpRequest()
  792. {
  793. };
  794. StringBuffer& CHttpRequest::getMethod(StringBuffer & method)
  795. {
  796. return method.append(m_httpMethod.str());
  797. }
  798. void CHttpRequest::setMethod(const char* method)
  799. {
  800. m_httpMethod.clear().append(method);
  801. }
  802. StringBuffer& CHttpRequest::getPath(StringBuffer & path)
  803. {
  804. return path.append(m_httpPath.str());
  805. }
  806. void CHttpRequest::setPath(const char* path)
  807. {
  808. m_httpPath.clear().append(path);
  809. }
  810. void CHttpRequest::parseQueryString(const char* querystr)
  811. {
  812. if(!querystr || !*querystr)
  813. return;
  814. bool useHeap = false;
  815. int querystrlen = strlen(querystr);
  816. if(querystrlen >= 0x80000)
  817. useHeap = true;
  818. char* querystrbuf = NULL;
  819. if(useHeap)
  820. querystrbuf = (char*)malloc(querystrlen + 1);
  821. else
  822. querystrbuf = (char*)alloca(querystrlen + 1);
  823. strcpy(querystrbuf, querystr);
  824. char* ptr = querystrbuf;
  825. char* curname = ptr;
  826. char* curvalue = NULL;
  827. while(true)
  828. {
  829. while(*ptr != '\0' && *ptr != '=' && *ptr != '&')
  830. ptr++;
  831. if(*ptr == '\0')
  832. {
  833. StringBuffer nameval;
  834. Utils::url_decode(curname, nameval);
  835. addParameter(nameval.str(), "");
  836. break;
  837. }
  838. else if(*ptr == '=')
  839. {
  840. *ptr = '\0';
  841. ptr++;
  842. if(*ptr == '\0')
  843. {
  844. StringBuffer nameval;
  845. Utils::url_decode(curname, nameval);
  846. addParameter(nameval.str(), "");
  847. break;
  848. }
  849. else if(*ptr == '&')
  850. {
  851. StringBuffer nameval;
  852. Utils::url_decode(curname, nameval);
  853. addParameter(nameval.str(), "");
  854. ptr++;
  855. if(*ptr == '\0')
  856. break;
  857. else
  858. curname = ptr;
  859. }
  860. else
  861. {
  862. curvalue = ptr;
  863. while(*ptr != '\0' && *ptr != '&')
  864. ptr++;
  865. if(*ptr == '\0')
  866. {
  867. StringBuffer nameval;
  868. StringBuffer valueval;
  869. Utils::url_decode(curname, nameval);
  870. Utils::url_decode(curvalue, valueval);
  871. addParameter(nameval.str(), valueval.str());
  872. break;
  873. }
  874. else //*ptr == '&'
  875. {
  876. *ptr = '\0';
  877. ptr++;
  878. StringBuffer nameval;
  879. StringBuffer valueval;
  880. Utils::url_decode(curname, nameval);
  881. Utils::url_decode(curvalue, valueval);
  882. addParameter(nameval.str(), valueval.str());
  883. if(*ptr == '\0')
  884. break;
  885. else
  886. curname = ptr;
  887. }
  888. }
  889. }
  890. else if(*ptr == '&')
  891. {
  892. *ptr=0;
  893. StringBuffer nameval;
  894. Utils::url_decode(curname, nameval);
  895. addParameter(nameval.str(), "");
  896. ptr++;
  897. if(!*ptr)
  898. break;
  899. else
  900. curname = ptr;
  901. }
  902. }
  903. if(useHeap && querystrbuf != NULL)
  904. delete querystrbuf;
  905. }
  906. int CHttpRequest::parseFirstLine(char* oneline)
  907. {
  908. //if (getEspLogLevel()>LogNormal)
  909. // DBGLOG("First Line of request=%s", oneline);
  910. DBGLOG("HTTP First Line: %s", oneline);
  911. if(*oneline == 0)
  912. return -1;
  913. const char* curptr = oneline;
  914. StringBuffer method;
  915. curptr = Utils::getWord(curptr, method);
  916. if(!stricmp(method.str(), POST_METHOD))
  917. {
  918. setMethod(POST_METHOD);
  919. }
  920. else if(!stricmp(method.str(), GET_METHOD))
  921. {
  922. setMethod(GET_METHOD);
  923. }
  924. else if(!stricmp(method.str(), HEAD_METHOD))
  925. {
  926. setMethod(HEAD_METHOD);
  927. }
  928. StringBuffer pathbuf;
  929. curptr = Utils::getWord(curptr, pathbuf);
  930. int len = pathbuf.length();
  931. char* buff;
  932. if(len == 0)
  933. {
  934. buff = new char[2];
  935. buff[0] = '/';
  936. buff[1] = '\0';
  937. }
  938. else
  939. {
  940. if(pathbuf.charAt(0) != '/')
  941. {
  942. buff = new char[len + 2];
  943. buff[0] = '/';
  944. strcpy(buff + 1, pathbuf.str());
  945. }
  946. else
  947. {
  948. buff = new char[len + 1];
  949. strcpy(buff, pathbuf.str());
  950. }
  951. }
  952. char* qmark = strchr(buff, '?');
  953. if(qmark != NULL)
  954. {
  955. *qmark = '\0';
  956. }
  957. // Decode path
  958. StringBuffer path;
  959. Utils::url_decode(buff, path);
  960. setPath(path.str());
  961. // Parse and decode parameters
  962. if(qmark != NULL)
  963. {
  964. char* querystr = qmark + 1;
  965. m_paramstr.set(querystr);
  966. addParameter("__querystring", querystr); //MORE- requested by dimitri
  967. parseQueryString(querystr);
  968. }
  969. delete[] buff;
  970. return 0;
  971. }
  972. void CHttpRequest::parseCookieHeader(char* cookiestr)
  973. {
  974. if(cookiestr == NULL)
  975. return;
  976. int version;
  977. char* curword;
  978. char* curptr = cookiestr;
  979. const char* separators = ",;";
  980. curptr = Utils::getWord(curptr, curword, separators);
  981. StringBuffer name, value;
  982. Utils::parseNVPair(curword, name, value);
  983. CEspCookie* cookie = NULL;
  984. if(name.length() == 0 || stricmp(name.str(), "$Version"))
  985. {
  986. version = 0;
  987. cookie = new CEspCookie(name.str(), value.str());
  988. cookie->setVersion(version);
  989. m_cookies.append(*cookie);
  990. }
  991. else
  992. {
  993. version = atoi(value.str());
  994. }
  995. while(curptr != NULL && *curptr != 0)
  996. {
  997. curptr = Utils::getWord(curptr, curword, separators);
  998. if(curword == NULL)
  999. break;
  1000. StringBuffer name, value;
  1001. Utils::parseNVPair(curword, name, value);
  1002. if(name.length() == 0)
  1003. continue;
  1004. if(name.charAt(0) != '$')
  1005. {
  1006. cookie = new CEspCookie(name.str(), value.str());
  1007. cookie->setVersion(version);
  1008. m_cookies.append(*cookie);
  1009. }
  1010. else if(stricmp(name.str(), "$Path") == 0 && cookie != NULL)
  1011. cookie->setPath(value.str());
  1012. else if(stricmp(name.str(), "$Domain") == 0 && cookie != NULL)
  1013. cookie->setDomain(value.str());
  1014. else if(stricmp(name.str(), "$Port") == 0 && cookie != NULL)
  1015. cookie->setPorts(value.str());
  1016. }
  1017. }
  1018. void CHttpRequest::parseEspPathInfo()
  1019. {
  1020. if (!m_pathIsParsed)
  1021. {
  1022. m_espPathEx.clear();
  1023. m_espMethodName.clear();
  1024. m_espServiceName.clear();
  1025. size32_t pathlen=m_httpPath.length();
  1026. if (!pathlen)
  1027. m_sstype=(m_queryparams && m_queryparams->hasProp("main")) ? sub_serv_main : sub_serv_root;
  1028. else
  1029. {
  1030. char *pathstr = strdup(m_httpPath.str());
  1031. char *finger = pathstr;
  1032. if (!strnicmp(finger, "http://", 7))
  1033. finger+=7;
  1034. char *thumb=finger;
  1035. while (*thumb!=0 && *thumb!='/')
  1036. {
  1037. if (*thumb=='@' || *thumb==':')
  1038. {
  1039. finger=strchr(thumb, '/');
  1040. break;
  1041. }
  1042. thumb++;
  1043. }
  1044. bool missingTrailSlash = false;
  1045. if (finger)
  1046. {
  1047. while (*finger == '/')
  1048. finger++;
  1049. //look for the service and method names
  1050. //
  1051. if (finger && finger[0] != '\0')
  1052. {
  1053. thumb=strchr(finger, '/');
  1054. if (thumb)
  1055. {
  1056. char *pathex = strchr(thumb+1, '/');
  1057. if (pathex)
  1058. {
  1059. *pathex=0;
  1060. m_espPathEx.append(pathex+1);
  1061. }
  1062. *thumb=0;
  1063. m_espMethodName.append(thumb+1);
  1064. }
  1065. else
  1066. missingTrailSlash = true;
  1067. m_espServiceName.append(finger);
  1068. }
  1069. }
  1070. free(pathstr);
  1071. if (m_espMethodName.length())
  1072. {
  1073. if (!stricmp(m_espMethodName.str(), "files_"))
  1074. m_sstype=sub_serv_files;
  1075. else if (!stricmp(m_espMethodName.str(), "content_"))
  1076. m_sstype=sub_serv_content;
  1077. else if (!stricmp(m_espMethodName.str(), "result_"))
  1078. m_sstype=sub_serv_result;
  1079. else if (!stricmp(m_espMethodName.str(), "iframe"))
  1080. m_sstype=sub_serv_iframe;
  1081. else if (!stricmp(m_espMethodName.str(), "itext"))
  1082. m_sstype=sub_serv_itext;
  1083. else if (!stricmp(m_espMethodName.str(), "relogin_"))
  1084. m_sstype=sub_serv_relogin;
  1085. else if (!stricmp(m_espMethodName.str(), "version_"))
  1086. m_sstype=sub_serv_getversion;
  1087. }
  1088. //not a special service URL, determine the action type
  1089. if (m_sstype==sub_serv_unknown)
  1090. {
  1091. if (m_queryparams && (m_queryparams->hasProp("wsdl") || m_queryparams->hasProp("wsdl_ext")))
  1092. m_sstype=sub_serv_wsdl;
  1093. else if (m_queryparams && (m_queryparams->hasProp("xsd")))
  1094. m_sstype=sub_serv_xsd;
  1095. else if (m_queryparams && (m_queryparams->hasProp("reqxml_")))
  1096. m_sstype=sub_serv_reqsamplexml;
  1097. else if (m_queryparams && (m_queryparams->hasProp("respxml_")))
  1098. m_sstype=sub_serv_respsamplexml;
  1099. else if (m_queryparams && (m_queryparams->hasProp("soap_builder_")))
  1100. m_sstype=sub_serv_soap_builder;
  1101. else if (m_queryparams && m_queryparams->hasProp("config_"))
  1102. m_sstype=sub_serv_config;
  1103. else if (m_espServiceName.length()==0)
  1104. m_sstype=(m_queryparams && m_queryparams->hasProp("main")) ? sub_serv_main : sub_serv_root;
  1105. else if (m_espMethodName.length()==0)
  1106. m_sstype = missingTrailSlash ? sub_serv_index_redirect : sub_serv_index;
  1107. else if (m_queryparams && m_queryparams->hasProp("form_"))
  1108. m_sstype=sub_serv_form;
  1109. else if (m_queryparams && m_queryparams->hasProp("form"))
  1110. m_sstype=sub_serv_xform;
  1111. else if (isUpload())
  1112. m_sstype=sub_serv_file_upload;
  1113. else if (getParameterCount())// queryParamStr()!=NULL && *queryParamStr()!=0)
  1114. m_sstype=sub_serv_query;
  1115. else
  1116. m_sstype=sub_serv_method;
  1117. }
  1118. }
  1119. m_pathIsParsed=true;
  1120. }
  1121. }
  1122. void CHttpRequest::getEspPathInfo(sub_service &sstype, StringBuffer *pathEx, StringBuffer *service, StringBuffer *method, bool upcase)
  1123. {
  1124. parseEspPathInfo();
  1125. sstype = m_sstype;
  1126. if (pathEx)
  1127. {
  1128. pathEx->clear().append(m_espPathEx);
  1129. if (upcase)
  1130. pathEx->toUpperCase();
  1131. }
  1132. if (service)
  1133. {
  1134. service->clear().append(m_espServiceName);
  1135. service->toUpperCase();
  1136. }
  1137. if (method)
  1138. {
  1139. method->clear().append(m_espMethodName);
  1140. method->toUpperCase();
  1141. }
  1142. }
  1143. void CHttpRequest::getBasicRealm(StringBuffer& realm)
  1144. {
  1145. StringBuffer authheader;
  1146. getHeader("WWW-Authenticate", authheader);
  1147. if(authheader.length() == 0)
  1148. return;
  1149. if(Utils::strncasecmp(authheader.str(), "Basic ", strlen("Basic ")) != 0)
  1150. return;
  1151. const char* strt = strchr(authheader.str(), '\"');
  1152. ++strt;
  1153. if (strt)
  1154. {
  1155. const char* end = strchr(strt, '\"');
  1156. if (end)
  1157. {
  1158. realm.append(strt, 0, end - strt);
  1159. }
  1160. }
  1161. }
  1162. int CHttpRequest::getPeerPort()
  1163. {
  1164. char peername[256];
  1165. return m_socket.peer_name(peername, 256);
  1166. }
  1167. StringBuffer& CHttpRequest::getPeer(StringBuffer& Peer)
  1168. {
  1169. StringBuffer ForwardIPs;
  1170. getHeader("X-Forwarded-For", ForwardIPs);
  1171. if(ForwardIPs.length() != 0)
  1172. {
  1173. //IPs will ne in the form xxx.xxx.xxx.xxx,yyy.yyy.yyy.yyy,zzz.zzz.zzz.zzz
  1174. //We want to take the first IP in the list
  1175. const char* strt = strchr(ForwardIPs.str(), ',');
  1176. if(strt!= NULL)
  1177. Peer.append(strt - ForwardIPs.str(),ForwardIPs.str());
  1178. else
  1179. Peer.appendf("%s",ForwardIPs.str());
  1180. }
  1181. else
  1182. {
  1183. char peerchr[256];
  1184. int port = m_socket.peer_name(peerchr, 256);
  1185. Peer.append(peerchr);
  1186. }
  1187. return Peer;
  1188. }
  1189. void CHttpRequest::getBasicAuthorization(StringBuffer& userid, StringBuffer& password,StringBuffer& realm)
  1190. {
  1191. StringBuffer authheader;
  1192. getHeader("Authorization", authheader);
  1193. if(authheader.length() == 0)
  1194. return;
  1195. if(Utils::strncasecmp(authheader.str(), "Basic ", strlen("Basic ")) != 0)
  1196. return;
  1197. StringBuffer uidpair;
  1198. Utils::base64decode(authheader.length() - strlen("Basic "), authheader.str() + strlen("Basic "), uidpair);
  1199. const char* pairstr = strchr(uidpair.str(), '\\');
  1200. if(pairstr!=NULL)
  1201. {
  1202. realm.append(pairstr - uidpair.str(),uidpair.str());
  1203. pairstr++;
  1204. }
  1205. else
  1206. {
  1207. pairstr = uidpair.str();
  1208. getBasicRealm(realm);
  1209. }
  1210. const char* colon = strchr(pairstr, ':');
  1211. if(colon == NULL)
  1212. {
  1213. userid.append(pairstr);
  1214. }
  1215. else
  1216. {
  1217. userid.append(colon - pairstr, pairstr);
  1218. password.append(colon + 1);
  1219. }
  1220. }
  1221. int CHttpRequest::receive(IMultiException *me)
  1222. {
  1223. if (CHttpMessage::receive(false, me)==-1)
  1224. return -1;
  1225. //if(hasContentType("application/x-www-form-urlencoded"))
  1226. if(hasContentType(HTTP_TYPE_FORM_ENCODED))
  1227. {
  1228. parseQueryString(m_content.str());
  1229. }
  1230. else if(hasContentType(HTTP_TYPE_MULTIPART_FORMDATA) && !isUpload())
  1231. {
  1232. CMimeMultiPart* mpart = queryMultiPart();
  1233. if(mpart != NULL)
  1234. {
  1235. int count = mpart->getBodyCount();
  1236. for(int i = 0; i < count; i++)
  1237. {
  1238. CMimeBodyPart* bpart = mpart->queryBodyPart(i);
  1239. if(bpart == NULL)
  1240. continue;
  1241. const char* cdisp = bpart->getContentDisposition();
  1242. StringBuffer contentbuf;
  1243. bpart->getContent(contentbuf);
  1244. StringBuffer namebuf;
  1245. char* curword = NULL;
  1246. char* curptr = (char*)cdisp;
  1247. const char* separators = ";";
  1248. bool isFile = false;
  1249. StringBuffer filename;
  1250. while(curptr != NULL && *curptr != 0)
  1251. {
  1252. curptr = Utils::getWord(curptr, curword, separators, true);
  1253. if(curword == NULL)
  1254. break;
  1255. StringBuffer name, value;
  1256. Utils::parseNVPair(curword, name, value);
  1257. if(name.length() > 0 && stricmp(name.str(), "name") == 0)
  1258. {
  1259. namebuf.append(value.str());
  1260. }
  1261. else if(name.length() > 0 && stricmp(name.str(), "filename") == 0)
  1262. {
  1263. value.swapWith(filename);
  1264. isFile = true;
  1265. }
  1266. }
  1267. if(!isFile)
  1268. addParameter(namebuf.str(), contentbuf.str());
  1269. else
  1270. {
  1271. addParameter(namebuf.str(), filename.str());
  1272. addAttachment(namebuf.str(), contentbuf);
  1273. }
  1274. }
  1275. }
  1276. }
  1277. m_context->addTraceSummaryTimeStamp("rcv");
  1278. return 0;
  1279. }
  1280. void CHttpRequest::updateContext()
  1281. {
  1282. if(m_context)
  1283. {
  1284. m_context->setContextPath(m_httpPath.str());
  1285. StringBuffer temp;
  1286. getPeer(temp);
  1287. if(temp.length())
  1288. m_context->setPeer(temp.str());
  1289. m_context->setRequestParameters(queryParameters());
  1290. short servPort;
  1291. temp.clear();
  1292. getServAddress(temp, servPort);
  1293. m_context->setServAddress(temp.str(), servPort);
  1294. StringBuffer userid, password, realm;
  1295. getBasicAuthorization(userid, password, realm);
  1296. if(userid.length() > 0)
  1297. {
  1298. m_context->setUserID(userid.str());
  1299. m_context->setPassword(password.str());
  1300. m_context->setRealm(realm.str());
  1301. }
  1302. if (m_queryparams)
  1303. {
  1304. if (m_queryparams->getPropInt("no_ns_"))
  1305. m_context->addOptions(ESPCTX_NO_NAMESPACES);
  1306. if (m_queryparams->hasProp("wsdl"))
  1307. m_context->addOptions(ESPCTX_WSDL);
  1308. if (m_queryparams->hasProp("wsdl_ext"))
  1309. m_context->addOptions(ESPCTX_WSDL|ESPCTX_WSDL_EXT);
  1310. if (m_queryparams->hasProp("no_annot_"))
  1311. m_context->addOptions(ESPCTX_NO_ANNOTATION);
  1312. if (m_queryparams->hasProp("all_annot_"))
  1313. m_context->addOptions(ESPCTX_ALL_ANNOTATION);
  1314. }
  1315. // set client version
  1316. StringBuffer action;
  1317. getHeader("SOAPAction", action);
  1318. // URL first, then SOAPAction
  1319. const char *verstr = queryParameters()->queryProp("ver_");
  1320. if (verstr && *verstr)
  1321. m_context->setClientVersion(atof(verstr));
  1322. else
  1323. {
  1324. verstr=strstr(action.str(), "ver_=");
  1325. if (verstr)
  1326. m_context->setClientVersion(atof(verstr+5));
  1327. else
  1328. m_context->setClientVersion(0.0);
  1329. }
  1330. StringBuffer useragent;
  1331. getHeader("User-Agent", useragent);
  1332. m_context->setUseragent(useragent.str());
  1333. }
  1334. }
  1335. StringBuffer& CHttpRequest::constructHeaderBuffer(StringBuffer& headerbuf, bool inclLength)
  1336. {
  1337. if(m_httpMethod.length() > 0)
  1338. headerbuf.append(queryMethod()).append(" ");
  1339. else
  1340. headerbuf.append("POST ");
  1341. if(m_httpPath.length() > 0)
  1342. headerbuf.append(queryPath()).append(" ");
  1343. else
  1344. headerbuf.append("/ ");
  1345. if(m_version.length() > 0)
  1346. headerbuf.append(m_version.get());
  1347. else
  1348. headerbuf.append(HTTP_VERSION);
  1349. headerbuf.append("\r\n");
  1350. if(m_host.length() > 0)
  1351. {
  1352. headerbuf.append("Host: ").append(m_host.get());
  1353. if(m_port != 80)
  1354. {
  1355. headerbuf.append(":").append(m_port);
  1356. }
  1357. headerbuf.append("\r\n");
  1358. }
  1359. headerbuf.append("Content-Type: ");
  1360. if(m_content_type.length() > 0)
  1361. headerbuf.append(m_content_type.get());
  1362. else
  1363. headerbuf.append("text/xml; charset=UTF-8");
  1364. headerbuf.append("\r\n");
  1365. if(inclLength && m_content_length > 0)
  1366. headerbuf.append("Content-Length: ").append(m_content_length).append("\r\n");
  1367. if(m_cookies.length() > 0)
  1368. {
  1369. headerbuf.append("Cookie: ");
  1370. int version = m_cookies.item(0).getVersion();
  1371. if(version >= 1)
  1372. headerbuf.append("$Version=").append('"').append(version).append('"').append(',');
  1373. ForEachItemIn(x, m_cookies)
  1374. {
  1375. CEspCookie* cookie = &m_cookies.item(x);
  1376. if(cookie == NULL)
  1377. continue;
  1378. cookie->appendToRequestHeader(headerbuf);
  1379. }
  1380. headerbuf.append("\r\n");
  1381. }
  1382. ForEachItemIn(x, m_headers)
  1383. {
  1384. const char* oneheader = (const char*)m_headers.item(x);
  1385. headerbuf.append(oneheader).append("\r\n");
  1386. }
  1387. headerbuf.append("\r\n");
  1388. return headerbuf;
  1389. }
  1390. int CHttpRequest::processHeaders(IMultiException *me)
  1391. {
  1392. char oneline[MAX_HTTP_HEADER_LEN + 2];
  1393. int lenread = m_bufferedsocket->readline(oneline, MAX_HTTP_HEADER_LEN + 1, me);
  1394. if(lenread <= 0) //special case client connected and disconnected, load balancer ping?
  1395. return -1;
  1396. else if (lenread > MAX_HTTP_HEADER_LEN)
  1397. throw createEspHttpException(HTTP_STATUS_BAD_REQUEST_CODE, "Bad Request", HTTP_STATUS_BAD_REQUEST);
  1398. m_header.set(oneline);
  1399. parseFirstLine(oneline);
  1400. lenread = m_bufferedsocket->readline(oneline, MAX_HTTP_HEADER_LEN + 1, me);
  1401. while(lenread >= 0 && oneline[0] != '\0')
  1402. {
  1403. if(lenread > MAX_HTTP_HEADER_LEN)
  1404. throw createEspHttpException(HTTP_STATUS_BAD_REQUEST_CODE, "Bad Request", HTTP_STATUS_BAD_REQUEST);
  1405. m_header.append('\n').append(oneline);
  1406. parseOneHeader(oneline);
  1407. lenread = m_bufferedsocket->readline(oneline, MAX_HTTP_HEADER_LEN + 1, me);
  1408. }
  1409. if (getEspLogRequests() || getEspLogLevel()>LogNormal)
  1410. {
  1411. DBGLOG("Request Headers:\n%s", m_header.str());
  1412. }
  1413. if(m_content_length > 0 && m_MaxRequestEntityLength > 0 && m_content_length > m_MaxRequestEntityLength && (!isUpload()))
  1414. throw createEspHttpException(HTTP_STATUS_BAD_REQUEST_CODE, "The request length was too long.", HTTP_STATUS_BAD_REQUEST);
  1415. return 0;
  1416. }
  1417. int CHttpRequest::readContentToFile(StringBuffer netAddress, StringBuffer path)
  1418. {
  1419. char buf[1024 + 1];
  1420. int buflen = 1024;
  1421. int readlen = 0;
  1422. __int64 totallen = m_content_length64;
  1423. if(buflen > totallen)
  1424. buflen = (int) totallen;
  1425. StringBuffer lengthStr;
  1426. lengthStr.append(m_content_length64);
  1427. Owned<CMimeMultiPart> m_multipart = new CMimeMultiPart("1.0", m_content_type.get(), "", "", "");
  1428. m_multipart->parseContentType(m_content_type.get());
  1429. //Read the first one of data to find out the file name, as well as the beginning of the file content
  1430. bool lastChuck = false;
  1431. MemoryBuffer fileContent;
  1432. StringBuffer fileName;
  1433. while(fileName.length() < 1)
  1434. {
  1435. readlen = m_bufferedsocket->read(buf, buflen);
  1436. if(readlen < 0)
  1437. {
  1438. DBGLOG(">> Socket timed out because of incorrect Content-Length passed in from the other side");
  1439. break;
  1440. }
  1441. if(readlen == 0)
  1442. break;
  1443. buf[readlen] = 0;
  1444. fileContent.append(readlen, buf);
  1445. //find out the file name, as well as the beginning of the file content
  1446. m_multipart->readUploadFile(fileContent, fileName);
  1447. totallen -= readlen;
  1448. if(totallen <= 0)
  1449. break;
  1450. if(buflen > totallen)
  1451. buflen = (int) totallen;
  1452. }
  1453. if (fileName.length() < 1)
  1454. {
  1455. DBGLOG(">> File cannot be uploaded.");
  1456. return 0;
  1457. }
  1458. //Create IFile to store the file
  1459. StringBuffer name0(fileName), name1(fileName), fileToSave, fileToUse;
  1460. char* str = (char*) name1.reverse().str();
  1461. char* pStr = (char*) strchr(str, '\\');
  1462. if (!pStr)
  1463. pStr = strchr(str, '/');
  1464. if (pStr)
  1465. {
  1466. pStr[0] = 0;
  1467. name0.clear().append(str).reverse();
  1468. }
  1469. fileToSave.appendf("%s/%s.part", path.str(), name0.str());
  1470. fileToUse.appendf("%s/%s", path.str(), name0.str());
  1471. RemoteFilename rfn;
  1472. SocketEndpoint ep;
  1473. ep.set(netAddress.str());
  1474. rfn.setPath(ep, fileToSave.str());
  1475. Owned<IFile> file = createIFile(rfn);
  1476. if (!file)
  1477. {
  1478. DBGLOG(">> File %s cannot be uploaded.", name0.str());
  1479. return 0;
  1480. }
  1481. Owned<IFileIO> fileio = file->open(IFOcreate);
  1482. if (!fileio)
  1483. {
  1484. DBGLOG(">> File %s cannot be uploaded.", name0.str());
  1485. return 0;
  1486. }
  1487. //If this is the last chuck of data, we need to remove the boundry line at the end of data
  1488. if(totallen <= 0)
  1489. lastChuck = true;
  1490. else if(totallen < 1024)
  1491. { //if there is only one chuck left, the boundry line may be broken in the first chuck and the last chuck.
  1492. lastChuck = true;
  1493. readlen = m_bufferedsocket->read(buf, buflen);
  1494. if(readlen < 0)
  1495. {
  1496. DBGLOG(">> Socket timed out because of incorrect Content-Length passed in from the other side");
  1497. return 0;
  1498. }
  1499. if(readlen == 0)
  1500. return 0;
  1501. buf[readlen] = 0;
  1502. fileContent.append(readlen, buf);
  1503. }
  1504. //remove the boundry line at the end of data
  1505. if (lastChuck)
  1506. m_multipart->checkEndOfFile(fileContent);
  1507. //Save the data into the file
  1508. if (fileio->write(0, fileContent.length(), fileContent.toByteArray()) != fileContent.length())
  1509. {
  1510. DBGLOG(">> File %s cannot be uploaded.", name0.str());
  1511. return 0;
  1512. }
  1513. if(lastChuck)
  1514. {
  1515. file->rename(fileToUse.str());
  1516. return 0;
  1517. }
  1518. //The file has more than two chucks. Now, look though the rest of the chucks.
  1519. __int64 offset = fileContent.length();
  1520. for(;;)
  1521. {
  1522. readlen = m_bufferedsocket->read(buf, buflen);
  1523. if(readlen < 0)
  1524. {
  1525. DBGLOG(">> Socket timed out because of incorrect Content-Length passed in from the other side");
  1526. break;
  1527. }
  1528. if(readlen == 0)
  1529. break;
  1530. buf[readlen] = 0;
  1531. fileContent.clear().append(readlen, buf);
  1532. //For the last one or two chucks, remove the boundry line at the end of data.
  1533. totallen -= readlen;
  1534. if(totallen <= 0)
  1535. lastChuck = true;
  1536. else if(totallen < 1024)
  1537. {
  1538. lastChuck = true;
  1539. buflen = (int) totallen;
  1540. readlen = m_bufferedsocket->read(buf, buflen);
  1541. if(readlen < 0)
  1542. {
  1543. DBGLOG(">> Socket timed out because of incorrect Content-Length passed in from the other side");
  1544. break;
  1545. }
  1546. if(readlen == 0)
  1547. break;
  1548. buf[readlen] = 0;
  1549. fileContent.append(readlen, buf);
  1550. }
  1551. if (lastChuck)
  1552. {
  1553. m_multipart->checkEndOfFile(fileContent);
  1554. DBGLOG(">> The length of the last chuck=<%d>", fileContent.length());
  1555. }
  1556. if (fileio->write(offset, fileContent.length(), fileContent.toByteArray()) != fileContent.length())
  1557. {
  1558. DBGLOG(">> File %s cannot be uploaded.", name0.str());
  1559. break;
  1560. }
  1561. if (lastChuck)
  1562. break;
  1563. offset += readlen;
  1564. }
  1565. file->rename(fileToUse.str());
  1566. return 0;
  1567. }
  1568. /******************************************************************************
  1569. CHttpResponse Implementation
  1570. *******************************************************************************/
  1571. CHttpResponse::CHttpResponse(ISocket& socket) : CHttpMessage(socket), m_timeout(BSOCKET_CLIENT_READ_TIMEOUT)
  1572. {
  1573. }
  1574. CHttpResponse::~CHttpResponse()
  1575. {
  1576. }
  1577. void CHttpResponse::setTimeOut(unsigned int timeout)
  1578. {
  1579. m_timeout = timeout;
  1580. }
  1581. void CHttpResponse::setStatus(const char* status)
  1582. {
  1583. m_status.set(status);
  1584. }
  1585. StringBuffer& CHttpResponse::getStatus(StringBuffer& status)
  1586. {
  1587. status.append(m_status.get());
  1588. return status;
  1589. }
  1590. StringBuffer& CHttpResponse::constructHeaderBuffer(StringBuffer& headerbuf, bool inclLen)
  1591. {
  1592. if(m_version.length() > 0)
  1593. headerbuf.append(m_version.get()).append(" ");
  1594. else
  1595. headerbuf.append(HTTP_VERSION).append(" ");
  1596. if(m_status.length() > 0)
  1597. headerbuf.append(m_status.get());
  1598. else
  1599. headerbuf.append(HTTP_STATUS_OK);
  1600. headerbuf.append("\r\n");
  1601. headerbuf.append("Content-Type: ");
  1602. if(m_content_type.length() > 0)
  1603. headerbuf.append(m_content_type.get());
  1604. else
  1605. headerbuf.append("text/xml; charset=UTF-8");
  1606. headerbuf.append("\r\n");
  1607. if(inclLen && m_content_length > 0)
  1608. headerbuf.append("Content-Length: ").append(m_content_length).append("\r\n");
  1609. headerbuf.append("Connection: close\r\n");
  1610. ForEachItemIn(x, m_cookies)
  1611. {
  1612. CEspCookie* cookie = &m_cookies.item(x);
  1613. if(cookie == NULL)
  1614. continue;
  1615. StringBuffer cookiehn;
  1616. cookie->getSetCookieHeaderName(cookiehn);
  1617. headerbuf.append(cookiehn.str()).append(": ");
  1618. cookie->appendToResponseHeader(headerbuf);
  1619. headerbuf.append("\r\n");
  1620. }
  1621. ForEachItemIn(i, m_headers)
  1622. {
  1623. const char* oneheader = (const char*)m_headers.item(i);
  1624. headerbuf.append(oneheader).append("\r\n");
  1625. }
  1626. if(m_context.get())
  1627. {
  1628. StringArray& customHeaders = m_context->queryCustomHeaders();
  1629. ForEachItemIn(j, customHeaders)
  1630. {
  1631. const char* oneheader = (const char*)customHeaders.item(j);
  1632. if(oneheader && *oneheader)
  1633. headerbuf.append(oneheader).append("\r\n");
  1634. }
  1635. }
  1636. headerbuf.append("\r\n");
  1637. return headerbuf;
  1638. }
  1639. int CHttpResponse::parseFirstLine(char* oneline)
  1640. {
  1641. if(*oneline == 0)
  1642. return -1;
  1643. if (getEspLogLevel()>LogNormal)
  1644. DBGLOG("http response status = %s", oneline);
  1645. char* ptr = oneline;
  1646. while(*ptr != '\0' && *ptr != ' ')
  1647. ptr++;
  1648. if(*ptr != '\0')
  1649. {
  1650. *ptr = 0;
  1651. ptr++;
  1652. }
  1653. m_version.set(oneline);
  1654. while(*ptr == ' ')
  1655. ptr++;
  1656. m_status.set(ptr);
  1657. return 0;
  1658. }
  1659. void CHttpResponse::parseOneCookie(char* cookiestr)
  1660. {
  1661. if(cookiestr == NULL)
  1662. return;
  1663. char* curword;
  1664. char* curptr = cookiestr;
  1665. CEspCookie* cookie = NULL;
  1666. curptr = Utils::getWord(curptr, curword, ";");
  1667. StringBuffer name, value;
  1668. Utils::parseNVPair(curword, name, value);
  1669. if(name.length() == 0)
  1670. return;
  1671. cookie = new CEspCookie(name.str(), value.str());
  1672. m_cookies.append(*cookie);
  1673. while(curptr != NULL && *curptr != 0)
  1674. {
  1675. curptr = Utils::getWord(curptr, curword, ";");
  1676. if(curword == NULL)
  1677. break;
  1678. StringBuffer name, value;
  1679. Utils::parseNVPair(curword, name, value);
  1680. if(name.length() == 0)
  1681. continue;
  1682. else if(stricmp(name.str(), "Version") == 0)
  1683. cookie->setVersion(atoi(value.str()));
  1684. else if(stricmp(name.str(), "Path") == 0)
  1685. cookie->setPath(value.str());
  1686. else if(stricmp(name.str(), "Domain") == 0)
  1687. cookie->setDomain(value.str());
  1688. else if(stricmp(name.str(), "Port") == 0)
  1689. cookie->setPorts(value.str());
  1690. else if(stricmp(name.str(), "Max-Age") == 0)
  1691. cookie->setMaxAge(atoi(value.str()));
  1692. else if(stricmp(name.str(), "Discard") == 0)
  1693. cookie->setDiscard(true);
  1694. else if(stricmp(name.str(), "Secure") == 0)
  1695. cookie->setSecure(true);
  1696. else if(stricmp(name.str(), "Comment") == 0)
  1697. cookie->setComment(value.str());
  1698. else if(stricmp(name.str(), "CommentURL") == 0)
  1699. cookie->setCommentURL(value.str());
  1700. }
  1701. }
  1702. void CHttpResponse::parseCookieHeader(char* cookiestr)
  1703. {
  1704. if(cookiestr == NULL)
  1705. return;
  1706. //TODO: for now assume each Set-Cookie only has one cookie.
  1707. parseOneCookie(cookiestr);
  1708. }
  1709. void CHttpResponse::sendBasicChallenge(const char* realm, bool includeContent)
  1710. {
  1711. StringBuffer authheader;
  1712. authheader.appendf("Basic realm=\"%s\"", realm);
  1713. addHeader("WWW-Authenticate", authheader.str());
  1714. if (includeContent)
  1715. {
  1716. setContentType("text/html; charset=UTF-8");
  1717. setContent(
  1718. "<html xmlns=\"http://www.w3.org/1999/xhtml\">"
  1719. "<head>"
  1720. "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>"
  1721. "<title>ESP - Access Denied</title>"
  1722. "<script type='text/javascript'>"
  1723. "function closeWin() { top.opener=top; top.close(); }"
  1724. "</script>"
  1725. "</head>"
  1726. "<body onload=\"javascript:closeWin();\">"
  1727. "<b>Access Denied -- Valid username and password required!</b>"
  1728. "</body>"
  1729. "</html>"
  1730. );
  1731. }
  1732. setStatus(HTTP_STATUS_UNAUTHORIZED);
  1733. send();
  1734. }
  1735. void CHttpResponse::sendBasicChallenge(const char* realm, const char* content)
  1736. {
  1737. StringBuffer authheader;
  1738. authheader.appendf("Basic realm=\"%s\"", realm);
  1739. addHeader("WWW-Authenticate", authheader.str());
  1740. if (content != NULL && *content != '\0')
  1741. {
  1742. setContentType("text/html; charset=UTF-8");
  1743. setContent(content);
  1744. }
  1745. setStatus(HTTP_STATUS_UNAUTHORIZED);
  1746. send();
  1747. }
  1748. int CHttpResponse::processHeaders(IMultiException *me)
  1749. {
  1750. char oneline[MAX_HTTP_HEADER_LEN + 1];
  1751. int lenread = m_bufferedsocket->readline(oneline, MAX_HTTP_HEADER_LEN, me);
  1752. if(lenread <= 0)
  1753. return -1;
  1754. // Process "100 Continue" headers
  1755. // Some HTTP/1.1 webservers may send back "100 Continue" before it reads the posted request body.
  1756. while(Utils::strncasecmp(oneline, "HTTP/1.1 100", strlen("HTTP/1.1 100")) == 0)
  1757. {
  1758. //Read until empty line, meaning the end of "100 Continue" part
  1759. while(lenread >= 0 && oneline[0] != '\0')
  1760. {
  1761. lenread = m_bufferedsocket->readline(oneline, MAX_HTTP_HEADER_LEN, me);
  1762. }
  1763. // Read the next line, should be the status line.
  1764. lenread = m_bufferedsocket->readline(oneline, MAX_HTTP_HEADER_LEN, me);
  1765. if(lenread <= 0)
  1766. return 0;
  1767. }
  1768. parseFirstLine(oneline);
  1769. lenread = m_bufferedsocket->readline(oneline, MAX_HTTP_HEADER_LEN, me);
  1770. while(lenread >= 0 && oneline[0] != '\0')
  1771. {
  1772. parseOneHeader(oneline);
  1773. lenread = m_bufferedsocket->readline(oneline, MAX_HTTP_HEADER_LEN, me);
  1774. }
  1775. return 0;
  1776. }
  1777. bool CHttpResponse::httpContentFromFile(const char *filepath)
  1778. {
  1779. StringBuffer mimetype;
  1780. MemoryBuffer content;
  1781. bool ok = ::httpContentFromFile(filepath, mimetype, content);
  1782. if (ok)
  1783. {
  1784. setContent(content.length(), content.toByteArray());
  1785. setContentType(mimetype.str());
  1786. setStatus(HTTP_STATUS_OK);
  1787. }
  1788. else
  1789. {
  1790. setStatus(HTTP_STATUS_NOT_FOUND);
  1791. }
  1792. return ok;
  1793. }
  1794. int CHttpResponse::receive(IMultiException *me)
  1795. {
  1796. // If it's receiving a response, it's behaving as the client side of this conversation.
  1797. if(m_bufferedsocket.get() != NULL)
  1798. m_bufferedsocket->setReadTimeout(m_timeout);
  1799. return CHttpMessage::receive(me);
  1800. }
  1801. int CHttpResponse::receive(bool alwaysReadContent, IMultiException *me)
  1802. {
  1803. // If it's receiving a response, it's behaving as the client side of this conversation.
  1804. if(m_bufferedsocket.get() != NULL)
  1805. m_bufferedsocket->setReadTimeout(m_timeout);
  1806. if (processHeaders(me)==-1)
  1807. return -1;
  1808. if (getEspLogLevel()>LogNormal)
  1809. DBGLOG("Response headers processed! content_length = %d", m_content_length);
  1810. char status_class = '2';
  1811. if(m_status.length() > 0)
  1812. status_class = *(m_status.get());
  1813. if(m_content_length > 0)
  1814. {
  1815. readContent();
  1816. if (getEspLogLevel()>LogNormal)
  1817. DBGLOG("length of response content read = %d", m_content.length());
  1818. }
  1819. else if(alwaysReadContent && status_class != '4' && status_class != '5' && m_content_length == -1)
  1820. {
  1821. //HTTP protocol does not require a content length: read until socket closed
  1822. readContentTillSocketClosed();
  1823. if (getEspLogLevel()>LogNormal)
  1824. DBGLOG("length of content read = %d", m_content.length());
  1825. }
  1826. if (getEspLogRequests() || getEspLogLevel()>LogNormal)
  1827. {
  1828. if(isTextMessage())
  1829. DBGLOG("received HTTP response = %s", m_content.str());
  1830. }
  1831. return 0;
  1832. }
  1833. int CHttpResponse::sendException(IEspHttpException* e)
  1834. {
  1835. StringBuffer msg;
  1836. e->errorMessage(msg);
  1837. setStatus(e->getHttpStatus());
  1838. setContentType(HTTP_TYPE_TEXT_PLAIN);
  1839. setContent(msg.str());
  1840. send();
  1841. return 0;
  1842. }
  1843. bool CHttpResponse::handleExceptions(IXslProcessor *xslp, IMultiException *me, const char *serv, const char *meth, const char *errorXslt)
  1844. {
  1845. IEspContext *context=queryContext();
  1846. if (me->ordinality()>0)
  1847. {
  1848. StringBuffer text;
  1849. me->errorMessage(text);
  1850. text.append('\n');
  1851. WARNLOG("Exception(s) in %s::%s - %s", serv, meth, text.str());
  1852. if (errorXslt)
  1853. {
  1854. me->serialize(text.clear());
  1855. StringBuffer theOutput;
  1856. xslTransformHelper(xslp, text.str(), errorXslt, theOutput, context->queryXslParameters());
  1857. setContent(theOutput.str());
  1858. setContentType("text/html");
  1859. send();
  1860. return true;
  1861. }
  1862. }
  1863. return false;
  1864. }