soapbind.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #pragma warning( disable : 4786 )
  14. //Jlib
  15. #include "jliball.hpp"
  16. //SCM Interfaces
  17. #include "esp.hpp"
  18. //ESP Core
  19. #include "espthread.hpp"
  20. //ESP Bindings
  21. #include "SOAP/Platform/soapbind.hpp"
  22. #include "SOAP/client/soapclient.hpp"
  23. #include "http/platform/httpprot.hpp"
  24. #include "http/platform/httpservice.hpp"
  25. #include "SOAP/Platform/soapservice.hpp"
  26. #include "SOAP/Platform/soapmessage.hpp"
  27. #include "SOAP/xpp/xjx/xjxpp.hpp"
  28. #define ESP_FACTORY DECL_EXPORT
  29. CSoapBinding::CSoapBinding()
  30. {
  31. }
  32. CSoapBinding::~CSoapBinding()
  33. {
  34. }
  35. //IEspRpcBinding
  36. const char * CSoapBinding::getRpcType()
  37. {
  38. return "soap";
  39. }
  40. const char * CSoapBinding::getTransportType()
  41. {
  42. return "unknown";
  43. }
  44. int CSoapBinding::processRequest(IRpcMessage* rpc_call, IRpcMessage* rpc_response)
  45. {
  46. return 0;
  47. }
  48. CHttpSoapBinding::CHttpSoapBinding():EspHttpBinding(NULL, NULL, NULL)
  49. {
  50. log_level_=hsl_none;
  51. }
  52. CHttpSoapBinding::CHttpSoapBinding(IPropertyTree* cfg, const char *bindname, const char *procname, http_soap_log_level level)
  53. : EspHttpBinding(cfg, bindname, procname)
  54. {
  55. log_level_=level;
  56. }
  57. CHttpSoapBinding::~CHttpSoapBinding()
  58. {
  59. }
  60. const char * CHttpSoapBinding::getTransportType()
  61. {
  62. return "http";
  63. }
  64. static CSoapFault* makeSoapFault(CHttpRequest* request, IMultiException* me, const char *ns)
  65. {
  66. const char* svcName = request->queryServiceName();
  67. if (svcName && *svcName)
  68. {
  69. const char* method = request->queryServiceMethod();
  70. StringBuffer host;
  71. const char* wsdlAddr = request->queryParameters()->queryProp("__wsdl_address");
  72. if (wsdlAddr && *wsdlAddr)
  73. host.append(wsdlAddr);
  74. else
  75. {
  76. host.append(request->queryHost());
  77. if (request->getPort()>0)
  78. host.append(":").append(request->getPort());
  79. }
  80. VStringBuffer ns_ext("xmlns=\"%s\""
  81. " xsi:schemaLocation=\"%s %s/%s/%s?xsd\"",
  82. ns, ns, host.str(), svcName, method ? method : "");
  83. return new CSoapFault(me, ns_ext);
  84. }
  85. return new CSoapFault(me);
  86. }
  87. int CHttpSoapBinding::onSoapRequest(CHttpRequest* request, CHttpResponse* response)
  88. {
  89. IEspContext* ctx = request->queryContext();
  90. if (ctx && ctx->getResponseFormat()==ESPSerializationJSON)
  91. {
  92. int errcode = 0;
  93. StringBuffer msgbuf;
  94. try
  95. {
  96. return HandleSoapRequest(request,response);
  97. }
  98. catch (IMultiException* mex)
  99. {
  100. errcode = mex->errorCode();
  101. mex->serializeJSON(msgbuf, 0, true, true, true);
  102. StringBuffer errMessage;
  103. ctx->addTraceSummaryValue(LogMin, "msg", mex->errorMessage(errMessage).str(), TXSUMMARY_GRP_ENTERPRISE);
  104. mex->Release();
  105. }
  106. catch (IException* e)
  107. {
  108. errcode = e->errorCode();
  109. Owned<IMultiException> mex = MakeMultiException("Esp");
  110. mex->append(*e); // e is owned by mex
  111. mex->serializeJSON(msgbuf, 0, true, true, true);
  112. StringBuffer errMessage;
  113. ctx->addTraceSummaryValue(LogMin, "msg", e->errorMessage(errMessage).str(), TXSUMMARY_GRP_ENTERPRISE);
  114. }
  115. catch (...)
  116. {
  117. errcode = 500;
  118. Owned<IMultiException> mex = MakeMultiException("Esp");
  119. mex->append(*MakeStringException(500, "Internal Server Error"));
  120. mex->serializeJSON(msgbuf, 0, true, true, true);
  121. ctx->addTraceSummaryValue(LogMin, "msg", "Internal Server Error", TXSUMMARY_GRP_ENTERPRISE);
  122. }
  123. SetHTTPErrorStatus(errcode, response);
  124. response->setContentType(HTTP_TYPE_JSON);
  125. response->setContent(msgbuf.str());
  126. }
  127. else
  128. {
  129. Owned<CSoapFault> soapFault;
  130. try
  131. {
  132. return HandleSoapRequest(request,response);
  133. }
  134. catch (IMultiException* mex)
  135. {
  136. StringBuffer ns;
  137. soapFault.setown(makeSoapFault(request,mex, generateNamespace(*request->queryContext(), request, request->queryServiceName(), request->queryServiceMethod(), ns).str()));
  138. //SetHTTPErrorStatus(mex->errorCode(),response);
  139. SetHTTPErrorStatus(500,response);
  140. StringBuffer errMessage;
  141. ctx->addTraceSummaryValue(LogMin, "msg", mex->errorMessage(errMessage).str(), TXSUMMARY_GRP_ENTERPRISE);
  142. VStringBuffer fault("F%d", mex->errorCode());
  143. ctx->addTraceSummaryValue(LogMin, "custom_fields.soapFaultCode", fault.str(), TXSUMMARY_GRP_ENTERPRISE);
  144. mex->Release();
  145. }
  146. catch (IException* e)
  147. {
  148. StringBuffer ns;
  149. Owned<IMultiException> mex = MakeMultiException("Esp");
  150. mex->append(*e); // e is owned by mex
  151. soapFault.setown(makeSoapFault(request,mex, generateNamespace(*request->queryContext(), request, request->queryServiceName(), request->queryServiceMethod(), ns).str()));
  152. SetHTTPErrorStatus(500,response);
  153. StringBuffer errMessage;
  154. ctx->addTraceSummaryValue(LogMin, "msg", e->errorMessage(errMessage).str(), TXSUMMARY_GRP_ENTERPRISE);
  155. VStringBuffer fault("F%d", mex->errorCode());
  156. ctx->addTraceSummaryValue(LogMin, "custom_fields.soapFaultCode", fault.str(), TXSUMMARY_GRP_ENTERPRISE);
  157. }
  158. catch (...)
  159. {
  160. soapFault.setown(new CSoapFault(500,"Internal Server Error"));
  161. SetHTTPErrorStatus(500,response);
  162. ctx->addTraceSummaryValue(LogMin, "msg", "Internal Server Error", TXSUMMARY_GRP_ENTERPRISE);
  163. }
  164. //response->setContentType(soapFault->get_content_type());
  165. response->setContentType(HTTP_TYPE_TEXT_XML_UTF8);
  166. response->setContent(soapFault->get_text());
  167. }
  168. response->send();
  169. return -1;
  170. }
  171. int CHttpSoapBinding::HandleSoapRequest(CHttpRequest* request, CHttpResponse* response)
  172. {
  173. StringBuffer requeststr;
  174. request->getContent(requeststr);
  175. if (requeststr.length() == 0)
  176. throw MakeStringException(-1, "Content read is empty");
  177. IEspContext* ctx = request->queryContext();
  178. Owned<CSoapService> soapservice;
  179. Owned<CSoapRequest> soaprequest;
  180. Owned<CSoapResponse> soapresponse;
  181. soapservice.setown(new CSoapService(this));
  182. soaprequest.setown(new CSoapRequest);
  183. soaprequest->set_text(requeststr.str());
  184. StringBuffer contenttype;
  185. request->getContentType(contenttype);
  186. soaprequest->set_content_type(contenttype.str());
  187. soaprequest->setContext(ctx);
  188. CMimeMultiPart* multipart = request->queryMultiPart();
  189. if (multipart != nullptr)
  190. soaprequest->setOwnMultiPart(LINK(multipart));
  191. soapresponse.setown(new CSoapResponse);
  192. if (ctx && ctx->getResponseFormat()==ESPSerializationJSON)
  193. {
  194. soaprequest->setHttpReq(request);
  195. soapresponse->setHttpResp(response);
  196. }
  197. soapservice->processRequest(*soaprequest.get(), *soapresponse.get());
  198. //For JSON the response would have been sent except for certain errors, which will be thrown below
  199. if (!soapresponse->getHttpResp() || !soapresponse->getHttpResp()->getRespSent())
  200. {
  201. response->setVersion(HTTP_VERSION);
  202. int status = soapresponse->get_status();
  203. if (status == SOAP_OK)
  204. response->setStatus(HTTP_STATUS_OK);
  205. else if (status == SOAP_SERVER_ERROR || status == SOAP_RPC_ERROR || status == SOAP_CONNECTION_ERROR)
  206. {
  207. StringBuffer msg("Internal Server Error");
  208. const char* detail = soapresponse->get_err();
  209. if (detail && *detail)
  210. msg.appendf(" [%s]", detail);
  211. throw MakeStringExceptionDirect(500, msg.str());
  212. }
  213. else if (status == SOAP_CLIENT_ERROR || status == SOAP_REQUEST_TYPE_ERROR)
  214. {
  215. StringBuffer msg("Bad Request");
  216. const char* detail = soapresponse->get_err();
  217. if (detail && *detail)
  218. msg.appendf(" [%s]", detail);
  219. throw MakeStringExceptionDirect(400, msg.str());
  220. }
  221. else if (status == SOAP_AUTHENTICATION_REQUIRED)
  222. response->sendBasicChallenge(m_challenge_realm.str(), false);
  223. else if (status == SOAP_AUTHENTICATION_ERROR)
  224. {
  225. throw MakeStringExceptionDirect(401,"Unauthorized Access");
  226. }
  227. else
  228. response->setStatus(HTTP_STATUS_OK);
  229. response->setContentType(soapresponse->get_content_type());
  230. response->setContent(soapresponse->get_text());
  231. response->send();
  232. }
  233. return 0;
  234. }
  235. void CSoapRequestBinding::post(const char *proxy, const char* url, IRpcResponseBinding& response, const char *soapaction)
  236. {
  237. CRpcCall rpccall;
  238. CRpcResponse rpcresponse;
  239. rpccall.set_url(url);
  240. rpccall.setProxy(proxy);
  241. serialize(*static_cast<IRpcMessage*>(&rpccall));
  242. CSoapClient soapclient; //to add support for handling cookies soapclient(false);
  243. if (connectTimeoutMs_)
  244. soapclient.setConnectTimeoutMs(connectTimeoutMs_);
  245. if (readTimeoutSecs_)
  246. soapclient.setReadTimeoutSecs(readTimeoutSecs_);
  247. soapclient.setUsernameToken(soap_getUserId(), soap_getPassword(), soap_getRealm());
  248. int result = soapclient.postRequest(soapaction, rpccall, rpcresponse);
  249. if(result == SOAP_OK)
  250. {
  251. response.setRpcState(RPC_MESSAGE_OK);
  252. response.unserialize(rpcresponse, NULL, NULL);
  253. }
  254. else if(result == SOAP_CONNECTION_ERROR)
  255. {
  256. response.setRpcState(RPC_MESSAGE_CONNECTION_ERROR);
  257. }
  258. else
  259. {
  260. response.setRpcState(RPC_MESSAGE_ERROR);
  261. }
  262. }
  263. void CSoapComplexType::appendContent(IEspContext* ctx, MemoryBuffer& buffer, StringBuffer& mimetype)
  264. {
  265. StringBuffer content;
  266. if (ctx && ctx->getResponseFormat()==ESPSerializationJSON)
  267. {
  268. const char *jsonp = ctx->queryRequestParameters()->queryProp("jsonp");
  269. if (jsonp && *jsonp)
  270. content.append(jsonp).append('(');
  271. content.append('{');
  272. serializeStruct(ctx, content, (const char *)NULL);
  273. content.append('}');
  274. if (jsonp && *jsonp)
  275. content.append(");");
  276. mimetype.set("application/json");
  277. }
  278. else
  279. {
  280. buffer.append(38, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  281. serializeStruct(ctx, content, (const char *)NULL);
  282. mimetype.set("text/xml; charset=UTF-8");
  283. }
  284. buffer.append(content.length(), content.str());
  285. }
  286. void CSoapComplexType::appendContent(IEspContext* ctx, StringBuffer& buffer, StringBuffer& mimetype)
  287. {
  288. if (ctx && ctx->getResponseFormat()==ESPSerializationJSON)
  289. {
  290. const char *jsonp = ctx->queryRequestParameters()->queryProp("jsonp");
  291. if (jsonp && *jsonp)
  292. buffer.append(jsonp).append('(');
  293. buffer.append('{');
  294. serializeStruct(ctx, buffer, (const char *)nullptr);
  295. buffer.append('}');
  296. if (jsonp && *jsonp)
  297. buffer.append(");");
  298. mimetype.set("application/json");
  299. }
  300. else
  301. {
  302. buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  303. serializeStruct(ctx, buffer, (const char *)nullptr);
  304. mimetype.set("text/xml; charset=UTF-8");
  305. }
  306. }
  307. inline void open_element(IEspContext *ctx, StringBuffer &xml, const char *name, const char *uri, const char *prefix)
  308. {
  309. if (!name || !*name)
  310. return;
  311. xml.append("<");
  312. if (prefix && *prefix)
  313. xml.append(prefix).append(':');
  314. xml.append(name);
  315. if (uri && *uri)
  316. {
  317. xml.append("xmlns");
  318. if (prefix && *prefix)
  319. xml.append(':').append(prefix);
  320. xml.append("=\"").append(uri).append('\"');
  321. }
  322. }
  323. inline void start_child_attributes(IEspContext *ctx, StringBuffer &xml, const char *name)
  324. {
  325. }
  326. inline void start_child_elements(IEspContext *ctx, StringBuffer &xml, const char *name)
  327. {
  328. if (!name || !*name)
  329. return;
  330. xml.append('>');
  331. }
  332. inline void close_element(IEspContext *ctx, StringBuffer &xml, const char *name, const char *prefix)
  333. {
  334. if (!name || !*name)
  335. return;
  336. xml.append("</");
  337. if (prefix && *prefix)
  338. xml.append(prefix).append(':');
  339. xml.append(name).append('>');
  340. }
  341. void CSoapComplexType::serializeJSONStruct(IEspContext* ctx, StringBuffer& s, const char *name)
  342. {
  343. if (ctx && ctx->getResponseFormat()==ESPSerializationJSON)
  344. {
  345. appendJSONNameOrDelimit(s, name);
  346. s.append("{");
  347. serializeContent(ctx, s);
  348. s.append("}");
  349. return;
  350. }
  351. }
  352. void CSoapComplexType::serializeStruct(IEspContext* ctx, StringBuffer& s, const char *name)
  353. {
  354. const char *tag = (name && *name) ? name : getRootName();
  355. if (ctx && ctx->getResponseFormat()==ESPSerializationJSON)
  356. return serializeJSONStruct(ctx, s, tag);
  357. open_element(ctx, s, tag, getNsURI(), getNsPrefix());
  358. start_child_attributes(ctx, s, name);
  359. serializeAttributes(ctx, s);
  360. start_child_elements(ctx, s, tag);
  361. serializeContent(ctx, s);
  362. close_element(ctx, s, tag, getNsPrefix());
  363. }
  364. void CSoapComplexType::serializeItem(IEspContext* ctx, StringBuffer& s, const char *name)
  365. {
  366. if (ctx && ctx->getResponseFormat()==ESPSerializationJSON)
  367. return serializeJSONStruct(ctx, s, NULL);
  368. serializeStruct(ctx, s, name);
  369. }
  370. void CSoapResponseBinding::handleExceptions(IMultiException *me, const char *serv, const char *meth)
  371. {
  372. if (me->ordinality() > 0)
  373. {
  374. StringBuffer text;
  375. me->errorMessage(text);
  376. text.append('\n');
  377. IWARNLOG("Exception(s) in %s::%s - %s", serv, meth, text.str());
  378. IArrayOf<IException>& exceptions = me->getArray();
  379. ForEachItemIn(i, exceptions)
  380. noteException(*LINK(&exceptions.item(i)));
  381. }
  382. }
  383. void SetHTTPErrorStatus(int ErrorCode,CHttpResponse* response)
  384. {
  385. switch(ErrorCode)
  386. {
  387. case 204:
  388. response->setStatus(HTTP_STATUS_NO_CONTENT);
  389. break;
  390. case 301:
  391. response->setStatus(HTTP_STATUS_MOVED_PERMANENTLY);
  392. break;
  393. case 302:
  394. response->setStatus(HTTP_STATUS_REDIRECT);
  395. break;
  396. case 303:
  397. response->setStatus(HTTP_STATUS_REDIRECT_POST);
  398. break;
  399. case 400:
  400. response->setStatus(HTTP_STATUS_BAD_REQUEST);
  401. break;
  402. case 401:
  403. response->setStatus(HTTP_STATUS_UNAUTHORIZED);
  404. break;
  405. case 403:
  406. response->setStatus(HTTP_STATUS_FORBIDDEN);
  407. break;
  408. case 404:
  409. response->setStatus(HTTP_STATUS_NOT_FOUND);
  410. break;
  411. case 405:
  412. response->setStatus(HTTP_STATUS_NOT_ALLOWED);
  413. break;
  414. case 501:
  415. response->setStatus(HTTP_STATUS_NOT_IMPLEMENTED);
  416. break;
  417. default:
  418. response->setStatus(HTTP_STATUS_INTERNAL_SERVER_ERROR);
  419. }
  420. }