espcfg.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  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. #ifdef _WIN32
  15. //#define ESP_SUPPORT_DALI_CONFIG
  16. //CRT
  17. #include <process.h>
  18. #endif
  19. //Jlib
  20. #include "jliball.hpp"
  21. //SCM Interfaces
  22. #include "esp.hpp"
  23. #include "espplugin.hpp"
  24. #include "espplugin.ipp"
  25. #include "espcfg.ipp"
  26. #include "xslprocessor.hpp"
  27. #include "espcontext.hpp"
  28. #include "mplog.hpp"
  29. #include "rmtfile.hpp"
  30. //#include <dalienv.hpp>
  31. /*
  32. #if defined(USING_MPATROL)
  33. #define ESP_BUILTIN
  34. #endif
  35. */
  36. //#define ESP_BUILTIN
  37. extern "C" {
  38. ESP_FACTORY IEspService * esp_service_factory(const char *name, const char* type, IPropertyTree *cfg, const char *process);
  39. ESP_FACTORY IEspRpcBinding * esp_binding_factory(const char *name, const char* type, IPropertyTree *cfg, const char *process);
  40. ESP_FACTORY IEspProtocol * esp_protocol_factory(const char *name, const char* type, IPropertyTree *cfg, const char *process);
  41. };
  42. #ifdef ESP_BUILTIN
  43. builtin espdirect;
  44. #endif
  45. // add suffix and prefix when necessary
  46. void fixPlugin(StringBuffer& plugin)
  47. {
  48. if (stricmp(plugin.str()+plugin.length()-sizeof(SharedObjectExtension)+1,SharedObjectExtension)==0)
  49. return;
  50. plugin.insert(0,SharedObjectPrefix);
  51. plugin.append(SharedObjectExtension);
  52. }
  53. void CEspConfig::loadBuiltIns()
  54. {
  55. #ifdef ESP_BUILTIN
  56. espdirect.prot = esp_protocol_factory;
  57. espdirect.bind = esp_binding_factory;
  58. espdirect.serv = esp_service_factory;
  59. #endif
  60. }
  61. builtin *CEspConfig::getBuiltIn(string name)
  62. {
  63. #ifdef ESP_BUILTIN
  64. //if (name.compare("pixall.dll")==0 || name.compare("pixall.so")==0)
  65. return &espdirect;
  66. #else //ESP_DIRECT
  67. return NULL;
  68. #endif
  69. }
  70. StringBuffer &CVSBuildToEspVersion(char const * tag, StringBuffer & out)
  71. {
  72. unsigned build = 0;
  73. unsigned subbuild = 0;
  74. while(!isdigit(*tag))
  75. {
  76. if(!*tag) break;
  77. tag++;
  78. }
  79. while(isdigit(*tag))
  80. {
  81. if(!*tag) break;
  82. build = 10*build + (*tag-'0');
  83. tag++;
  84. }
  85. if(isalpha(*tag))
  86. {
  87. if(islower(*tag))
  88. subbuild = *tag-'a'+1;
  89. else
  90. subbuild = *tag-'A'+1;
  91. }
  92. out.append(build/10).append('.').append(build%10).append(subbuild);
  93. return out;
  94. }
  95. int CSessionCleaner::run()
  96. {
  97. try
  98. {
  99. PROGLOG("CSessionCleaner Thread started.");
  100. VStringBuffer xpath("%s*", PathSessionSession);
  101. int checkSessionTimeoutMillSeconds = checkSessionTimeoutSeconds * 1000;
  102. while(!stopping)
  103. {
  104. if (!m_isDetached)
  105. {
  106. Owned<IRemoteConnection> conn = querySDS().connect(espSessionSDSPath.get(), myProcessSession(), RTM_LOCK_WRITE, SESSION_SDS_LOCK_TIMEOUT);
  107. if (!conn)
  108. throw MakeStringException(-1, "Failed to connect to %s.", PathSessionRoot);
  109. CDateTime now;
  110. now.setNow();
  111. time_t timeNow = now.getSimple();
  112. Owned<IPropertyTreeIterator> iter1 = conn->queryRoot()->getElements(PathSessionApplication);
  113. ForEach(*iter1)
  114. {
  115. ICopyArrayOf<IPropertyTree> toRemove;
  116. Owned<IPropertyTreeIterator> iter2 = iter1->query().getElements(xpath.str());
  117. ForEach(*iter2)
  118. {
  119. IPropertyTree& item = iter2->query();
  120. if (timeNow >= item.getPropInt64(PropSessionTimeoutAt, 0))
  121. toRemove.append(item);
  122. }
  123. ForEachItemIn(i, toRemove)
  124. {
  125. iter1->query().removeTree(&toRemove.item(i));
  126. }
  127. }
  128. }
  129. sem.wait(checkSessionTimeoutMillSeconds);
  130. }
  131. }
  132. catch(IException *e)
  133. {
  134. StringBuffer msg;
  135. IERRLOG("CSessionCleaner::run() Exception %d:%s", e->errorCode(), e->errorMessage(msg).str());
  136. e->Release();
  137. }
  138. catch(...)
  139. {
  140. IERRLOG("Unknown CSessionCleaner::run() Exception");
  141. }
  142. return 0;
  143. }
  144. void CSessionCleaner::stop()
  145. {
  146. stopping = true;
  147. sem.signal();
  148. join();
  149. }
  150. void CEspConfig::ensureSDSSessionDomains()
  151. {
  152. bool hasAuthDomainSettings = false;
  153. bool hasSessionAuth = false;
  154. bool hasDefaultSessionDomain = false;
  155. int serverSessionTimeoutSeconds = 120 * ESP_SESSION_TIMEOUT;
  156. Owned<IPropertyTree> proc_cfg = getProcessConfig(m_envpt, m_process.str());
  157. Owned<IPropertyTreeIterator> it = proc_cfg->getElements("AuthDomains/AuthDomain");
  158. ForEach(*it)
  159. {
  160. hasAuthDomainSettings = true;
  161. IPropertyTree& authDomain = it->query();
  162. const char* authType = authDomain.queryProp("@authType");
  163. if (isEmptyString(authType) || (!strieq(authType, "AuthPerSessionOnly") && !strieq(authType, "AuthTypeMixed")))
  164. continue;
  165. hasSessionAuth = true;
  166. int clientSessionTimeoutSeconds;
  167. int clientSessionTimeoutMinutes = authDomain.getPropInt("@clientSessionTimeoutMinutes", ESP_SESSION_TIMEOUT);
  168. if (clientSessionTimeoutMinutes < 0)
  169. clientSessionTimeoutSeconds = ESP_SESSION_NEVER_TIMEOUT;
  170. else
  171. clientSessionTimeoutSeconds = clientSessionTimeoutMinutes * 60;
  172. //The serverSessionTimeoutMinutes is used to clean the sessions by ESP server after the sessions have been timed out on ESP clients.
  173. //Considering possible network delay, serverSessionTimeoutMinutes should be greater than clientSessionTimeoutMinutes.
  174. int serverSessionTimeoutMinutes = authDomain.getPropInt("@serverSessionTimeoutMinutes", 0);
  175. if ((serverSessionTimeoutMinutes < 0) || (clientSessionTimeoutMinutes < 0))
  176. serverSessionTimeoutSeconds = ESP_SESSION_NEVER_TIMEOUT;
  177. else
  178. serverSessionTimeoutSeconds = serverSessionTimeoutMinutes * 60;
  179. if (serverSessionTimeoutSeconds < clientSessionTimeoutSeconds)
  180. serverSessionTimeoutSeconds = 2 * clientSessionTimeoutSeconds;
  181. const char* authDomainName = authDomain.queryProp("@domainName");
  182. if (isEmptyString(authDomainName) || strieq(authDomainName, "default"))
  183. {
  184. if (hasDefaultSessionDomain)
  185. throw MakeStringException(-1, ">1 AuthDomains are not named.");
  186. hasDefaultSessionDomain = true;
  187. }
  188. }
  189. //Ensure SDS Session tree if there is session auth or there is no AuthDomain setting (ex. old environment.xml)
  190. if (hasSessionAuth || !hasAuthDomainSettings)
  191. {
  192. Owned<IRemoteConnection> conn = querySDS().connect(PathSessionRoot, myProcessSession(), RTM_LOCK_WRITE|RTM_CREATE_QUERY, SESSION_SDS_LOCK_TIMEOUT);
  193. if (!conn)
  194. throw MakeStringException(-1, "Failed to connect to %s.", PathSessionRoot);
  195. ensureESPSessionInTree(conn->queryRoot(), m_process.str());
  196. if (serverSessionTimeoutSeconds != ESP_SESSION_NEVER_TIMEOUT)
  197. {
  198. VStringBuffer espSessionSDSPath("%s/%s[@name=\"%s\"]", PathSessionRoot, PathSessionProcess, m_process.str());
  199. m_sessionCleaner.setown(new CSessionCleaner(espSessionSDSPath.str(), proc_cfg->getPropInt("@checkSessionTimeoutSeconds",
  200. ESP_CHECK_SESSION_TIMEOUT)));
  201. m_sessionCleaner->start();
  202. }
  203. }
  204. }
  205. void CEspConfig::ensureESPSessionInTree(IPropertyTree* sessionRoot, const char* procName)
  206. {
  207. VStringBuffer xpath("%s[@name=\"%s\"]", PathSessionProcess, procName);
  208. IPropertyTree* procSessionTree = sessionRoot->queryBranch(xpath.str());
  209. if (!procSessionTree)
  210. {
  211. IPropertyTree* processSessionTree = sessionRoot->addPropTree(PathSessionProcess);
  212. processSessionTree->setProp("@name", procName);
  213. }
  214. }
  215. CEspConfig::CEspConfig(IProperties* inputs, IPropertyTree* envpt, IPropertyTree* procpt, bool isDali)
  216. {
  217. hsami_=0;
  218. serverstatus=NULL;
  219. useDali=false;
  220. if(inputs)
  221. m_inputs.setown(inputs);
  222. if(!envpt || !procpt)
  223. return;
  224. m_envpt.setown(envpt);
  225. m_cfg.setown(procpt);
  226. loadBuiltIns();
  227. // load options
  228. const char* level = m_cfg->queryProp("@logLevel");
  229. m_options.logLevel = level ? atoi(level) : LogMin;
  230. m_options.logReq = readLogRequest(m_cfg->queryProp("@logRequests"));
  231. m_options.logResp = m_cfg->getPropBool("@logResponses", false);
  232. m_options.txSummaryLevel = m_cfg->getPropInt("@txSummaryLevel", LogMin);
  233. m_options.txSummaryResourceReq = m_cfg->getPropBool("@txSummaryResourceReq", false);
  234. m_options.frameTitle.set(m_cfg->queryProp("@name"));
  235. m_options.slowProcessingTime = m_cfg->getPropInt("@slowProcessingTime", 30) * 1000; //in msec
  236. if (!m_cfg->getProp("@name", m_process))
  237. {
  238. OERRLOG("EspProcess name not found");
  239. }
  240. else
  241. {
  242. DBGLOG("ESP process name [%s]", m_process.str());
  243. setIsDetachedFromDali(false);
  244. setIsSubscribedToDali(true);
  245. try
  246. {
  247. StringBuffer procDirectory;
  248. m_cfg->getProp("@directory", procDirectory);
  249. if (!procDirectory.isEmpty())
  250. {
  251. m_daliAttachStateFileName.setf("%s%c%s-AttachState.xml",procDirectory.str(), PATHSEPCHAR, m_process.str());
  252. try
  253. {
  254. Owned<IPTree> espProcAttachState = createPTreeFromXMLFile(m_daliAttachStateFileName);
  255. if (espProcAttachState)
  256. {
  257. setIsDetachedFromDali(!(espProcAttachState->getPropBool("@attached", true)));
  258. setIsSubscribedToDali(espProcAttachState->getPropBool("@subscribed", true));
  259. }
  260. else
  261. {
  262. ESPLOG(LogMin, "Could not load DALI Attach state file [%s] for ESP process [%s]", m_daliAttachStateFileName.str(), m_process.str());
  263. }
  264. }
  265. catch (...)
  266. {
  267. ESPLOG(LogMin, "Could not load DALI Attach state file [%s] for ESP process [%s]", m_daliAttachStateFileName.str(), m_process.str());
  268. }
  269. saveAttachState();
  270. }
  271. else
  272. ESPLOG(LogMin, "ESP Process [%s] configuration is missing '@directory' attribute, could not read AttachState", m_process.str());
  273. }
  274. catch (IException* e)
  275. {
  276. e->Release();
  277. ESPLOG(LogMin, "Could not load DALI Attach state file [%s] for ESP process [%s]", m_daliAttachStateFileName.str(), m_process.str());
  278. }
  279. catch (...)
  280. {
  281. ESPLOG(LogMin, "Could not load DALI Attach state file [%s] for ESP process [%s]", m_daliAttachStateFileName.str(), m_process.str());
  282. }
  283. if (isDetachedFromDali())
  284. OWARNLOG("ESP Process [%s] loading in DALI DETACHED state - Some ESP services do not load in detached state!", m_process.str());
  285. StringBuffer daliservers;
  286. if (m_cfg->getProp("@daliServers", daliservers))
  287. initDali(daliservers.str()); //won't init if detached
  288. const unsigned dafilesrvConnectTimeout = m_cfg->getPropInt("@dafilesrvConnectTimeout", 10)*1000;
  289. const unsigned dafilesrvReadTimeout = m_cfg->getPropInt("@dafilesrvReadTimeout", 10)*1000;
  290. setRemoteFileTimeouts(dafilesrvConnectTimeout, dafilesrvReadTimeout);
  291. #ifndef _DEBUG
  292. startPerformanceMonitor(m_cfg->getPropInt("@perfReportDelay", 60)*1000);
  293. #endif
  294. IPropertyTreeIterator *pt_iter = NULL;
  295. StringBuffer xpath;
  296. if (m_inputs->hasProp("SingleUserPass"))
  297. {
  298. StringBuffer plainesppass;
  299. StringBuffer encesppass;
  300. m_inputs->getProp("SingleUserPass", plainesppass);
  301. encrypt(encesppass, plainesppass.str());
  302. xpath.setf("SecurityManagers/SecurityManager[@type=\"SingleUserSecurityManager\"]/SingleUserSecurityManager/");
  303. pt_iter = m_cfg->getElements(xpath.str());
  304. if (pt_iter!=NULL)
  305. {
  306. IPropertyTree *ptree = NULL;
  307. pt_iter->first();
  308. while(pt_iter->isValid())
  309. {
  310. ptree = &pt_iter->query();
  311. if (ptree)
  312. {
  313. ptree->setProp("@SingleUserPass", encesppass.str());
  314. if (m_inputs->hasProp("SingleUserName"))
  315. {
  316. StringBuffer espusername;
  317. m_inputs->getProp("SingleUserName", espusername);
  318. ptree->setProp("@SingleUserName", espusername.str());
  319. }
  320. }
  321. pt_iter->next();
  322. }
  323. pt_iter->Release();
  324. pt_iter=NULL;
  325. }
  326. }
  327. //get the local computer name:
  328. m_cfg->getProp("@computer", m_computer);
  329. //get the local computer information:
  330. xpath.setf("Hardware/Computer[@name=\"%s\"]", m_computer.str());
  331. IPropertyTree *computer = m_envpt->queryPropTree(xpath.str());
  332. if (computer)
  333. {
  334. StringBuffer address;
  335. computer->getProp("@netAddress", address);
  336. int port = m_cfg->getPropInt("@port", 1500);
  337. if(strcmp(address.str(), ".") == 0)
  338. {
  339. GetHostName(address.clear());
  340. }
  341. m_address.set(address.str(), (unsigned short) port);
  342. }
  343. xpath.clear();
  344. xpath.append("EspService");
  345. pt_iter = m_cfg->getElements(xpath.str());
  346. if (pt_iter!=NULL)
  347. {
  348. IPropertyTree *ptree = NULL;
  349. pt_iter->first();
  350. while(pt_iter->isValid())
  351. {
  352. ptree = &pt_iter->query();
  353. if (ptree)
  354. {
  355. srv_cfg *svcfg = new srv_cfg;
  356. ptree->getProp("@name", svcfg->name);
  357. ptree->getProp("@type", svcfg->type);
  358. ptree->getProp("@plugin", svcfg->plugin);
  359. fixPlugin(svcfg->plugin);
  360. map<string, srv_cfg*>::value_type en(svcfg->name.str(), svcfg);
  361. m_services.insert(en);
  362. }
  363. pt_iter->next();
  364. }
  365. pt_iter->Release();
  366. pt_iter=NULL;
  367. }
  368. xpath.clear();
  369. xpath.append("EspProtocol");
  370. pt_iter = m_cfg->getElements(xpath.str());
  371. if (pt_iter!=NULL)
  372. {
  373. IPropertyTree *ptree = NULL;
  374. pt_iter->first();
  375. while(pt_iter->isValid())
  376. {
  377. ptree = &pt_iter->query();
  378. if (ptree)
  379. {
  380. protocol_cfg *pcfg = new protocol_cfg;
  381. ptree->getProp("@name", pcfg->name);
  382. ptree->getProp("@plugin", pcfg->plugin);
  383. fixPlugin(pcfg->plugin);
  384. ptree->getProp("@type", pcfg->type);
  385. map<string, protocol_cfg*>::value_type en(pcfg->name.str(), pcfg);
  386. m_protocols.insert(en);
  387. }
  388. pt_iter->next();
  389. }
  390. pt_iter->Release();
  391. pt_iter=NULL;
  392. }
  393. xpath.clear();
  394. xpath.append("EspBinding");
  395. pt_iter = m_cfg->getElements(xpath.str());
  396. if (pt_iter!=NULL)
  397. {
  398. IPropertyTree *ptree = NULL;
  399. pt_iter->first();
  400. while(pt_iter->isValid())
  401. {
  402. ptree = &pt_iter->query();
  403. if (ptree)
  404. {
  405. OwnedPtr<binding_cfg> bcfg(new binding_cfg);
  406. ptree->getProp("@name", bcfg->name);
  407. bcfg->port = ptree->getPropInt("@port", 0);
  408. if (bcfg->port == 0)
  409. DBGLOG("Binding %s is configured with port 0, it will not be loaded.", bcfg->name.str());
  410. else
  411. {
  412. ptree->getProp("@type", bcfg->type);
  413. if (!streq(bcfg->type.str(), "EsdlBinding"))
  414. {
  415. ptree->getProp("@plugin", bcfg->plugin);
  416. fixPlugin(bcfg->plugin);
  417. bcfg->isDefault = ptree->getPropBool("@defaultBinding", false);
  418. StringBuffer addr;
  419. ptree->getProp("@netAddress", addr);
  420. if (strcmp(addr.str(), ".") == 0)
  421. {
  422. // Here we interpret '.' as binding to all interfaces, so convert it to "0.0.0.0"
  423. bcfg->address.append("0.0.0.0");
  424. }
  425. else
  426. {
  427. bcfg->address.append(addr.str());
  428. }
  429. ptree->getProp("@service", bcfg->service_name);
  430. ptree->getProp("@protocol", bcfg->protocol_name);
  431. m_bindings.push_back(bcfg.getClear());
  432. }
  433. }
  434. }
  435. pt_iter->next();
  436. }
  437. pt_iter->Release();
  438. pt_iter=NULL;
  439. }
  440. }
  441. }
  442. void CEspConfig::sendAlert(int severity, char const * descr, char const * subject) const
  443. {
  444. }
  445. void CEspConfig::initDali(const char *servers)
  446. {
  447. CriticalBlock b(attachcrit);
  448. if (servers!=nullptr && *servers!=0 && !daliClientActive() && !isDetachedFromDali())
  449. {
  450. DBGLOG("Initializing DALI client [servers = %s]", servers);
  451. useDali=true;
  452. // Create server group
  453. Owned<IGroup> serverGroup = createIGroup(servers, DALI_SERVER_PORT);
  454. if (!serverGroup)
  455. throw MakeStringException(0, "Could not instantiate dali IGroup");
  456. // Initialize client process
  457. if (!initClientProcess(serverGroup, DCR_EspServer))
  458. throw MakeStringException(0, "Could not initialize dali client");
  459. serverstatus = new CSDSServerStatus("ESPserver");
  460. ensureSDSSessionDomains();
  461. // for auditing
  462. startLogMsgParentReceiver();
  463. connectLogMsgManagerToDali();
  464. }
  465. }
  466. void CEspConfig::initPtree(const char *location, bool isDali)
  467. {
  468. IPropertyTree* cfg = createPTreeFromXMLFile(location, ipt_caseInsensitive);
  469. if (cfg)
  470. {
  471. cfg->addProp("@config", location);
  472. m_envpt.setown(cfg);
  473. }
  474. }
  475. void CEspConfig::loadBinding(binding_cfg &xcfg)
  476. {
  477. map<string, srv_cfg*>::iterator sit = m_services.find(xcfg.service_name.str());
  478. map<string, protocol_cfg*>::iterator pit = m_protocols.find(xcfg.protocol_name.str());
  479. IEspService *isrv = NULL;
  480. IEspProtocol *iprot = NULL;
  481. if(sit == m_services.end())
  482. {
  483. OWARNLOG("Warning: Service %s not found for binding %s", xcfg.service_name.str(), xcfg.name.str());
  484. }
  485. else
  486. {
  487. isrv = (*sit).second->srv;
  488. }
  489. if(pit == m_protocols.end())
  490. {
  491. throw MakeStringException(-1, "Protocol %s not found for binding %s", xcfg.protocol_name.str(), xcfg.name.str());
  492. }
  493. else
  494. {
  495. iprot = (*pit).second->prot;
  496. if (iprot)
  497. {
  498. esp_binding_factory_t xproc = NULL;
  499. if(isrv != NULL)
  500. xcfg.service.setown(LINK(isrv));
  501. xcfg.protocol.setown(LINK(iprot));
  502. builtin *pdirect = getBuiltIn(xcfg.plugin.str());
  503. if (pdirect)
  504. {
  505. xproc = pdirect->bind;
  506. }
  507. else
  508. {
  509. Owned<IEspPlugin> pplg = getPlugin(xcfg.plugin.str());
  510. if (pplg)
  511. {
  512. xproc = (esp_binding_factory_t) pplg->getProcAddress("esp_binding_factory");
  513. }
  514. }
  515. if (xproc)
  516. {
  517. IEspRpcBinding* bind = xproc(xcfg.name.str(), xcfg.type.str(), m_envpt.get(), m_process.str());
  518. if (bind)
  519. LOG(MCoperatorInfo, unknownJob,"Load binding %s (type: %s, process: %s) succeeded", xcfg.name.str(), xcfg.type.str(), m_process.str());
  520. else
  521. OERRLOG("Failed to load binding %s (type: %s, process: %s)", xcfg.name.str(), xcfg.type.str(), m_process.str());
  522. xcfg.bind.setown(bind);
  523. if (serverstatus)
  524. {
  525. IPropertyTree *stTree= serverstatus->queryProperties()->addPropTree("ESPservice", createPTree("ESPservice", ipt_caseInsensitive));
  526. if (stTree)
  527. {
  528. stTree->setProp("@type", xcfg.service->getServiceType());
  529. stTree->setProp("@name", xcfg.service_name.str());
  530. stTree->setPropInt("@port", xcfg.port);
  531. }
  532. serverstatus->commitProperties();
  533. }
  534. }
  535. else
  536. throw MakeStringException(-1, "procedure esp_binding_factory can't be loaded");
  537. }
  538. else
  539. {
  540. throw MakeStringException(-1, "Protocol %s wasn't loaded correctly for the binding", xcfg.protocol_name.str());
  541. }
  542. }
  543. }
  544. void CEspConfig::loadProtocol(protocol_cfg &xcfg)
  545. {
  546. esp_protocol_factory_t xproc = NULL;
  547. builtin *pdirect = getBuiltIn(xcfg.plugin.str());
  548. if (pdirect)
  549. xproc = pdirect->prot;
  550. else
  551. {
  552. Owned<IEspPlugin> pplg = getPlugin(xcfg.plugin.str());
  553. if (pplg)
  554. {
  555. xproc = (esp_protocol_factory_t) pplg->getProcAddress("esp_protocol_factory");
  556. }
  557. }
  558. if (xproc)
  559. {
  560. xcfg.prot.setown(xproc(xcfg.name.str(), xcfg.type.str(), m_envpt.get(), m_process.str()));
  561. if (xcfg.prot)
  562. xcfg.prot->init(m_envpt.get(), m_process.str(), xcfg.name.str());
  563. }
  564. else
  565. throw MakeStringException(-1, "procedure esp_protocol_factory can't be loaded");
  566. }
  567. void CEspConfig::loadService(srv_cfg &xcfg)
  568. {
  569. esp_service_factory_t xproc = NULL;
  570. builtin *pdirect = getBuiltIn(xcfg.plugin.str());
  571. if (pdirect)
  572. xproc = pdirect->serv;
  573. else
  574. {
  575. Owned<IEspPlugin> pplg = getPlugin(xcfg.plugin.str());
  576. if (pplg)
  577. xproc = (esp_service_factory_t) pplg->getProcAddress("esp_service_factory");
  578. }
  579. if (xproc)
  580. xcfg.srv.setown(xproc(xcfg.name.str(), xcfg.type.str(), m_envpt.get(), m_process.str()));
  581. else
  582. throw MakeStringException(-1, "procedure esp_service_factory can't be loaded");
  583. }
  584. void CEspConfig::loadServices()
  585. {
  586. map<string, srv_cfg*>::iterator iter = m_services.begin();
  587. while (iter!=m_services.end())
  588. {
  589. #ifndef _USE_OPENLDAP
  590. const string svcName = iter->first;
  591. if (!strstr(svcName.data(), "ws_access"))
  592. #endif
  593. loadService(*(iter->second));
  594. #ifndef _USE_OPENLDAP
  595. else
  596. DBGLOG("Not loading service %s, platform built without LDAP", svcName.data());
  597. #endif
  598. iter++;
  599. }
  600. }
  601. void CEspConfig::loadProtocols()
  602. {
  603. map<string, protocol_cfg*>::iterator iter = m_protocols.begin();
  604. while (iter!=m_protocols.end())
  605. {
  606. loadProtocol(*(iter->second));
  607. iter++;
  608. }
  609. }
  610. void CEspConfig::loadBindings()
  611. {
  612. list<binding_cfg*>::iterator iter = m_bindings.begin();
  613. while (iter!=m_bindings.end())
  614. {
  615. #ifndef _USE_OPENLDAP
  616. const char * bindingName = (**iter).name.str();
  617. if (!strstr(bindingName, "ws_access"))
  618. #endif
  619. loadBinding(**iter);
  620. #ifndef _USE_OPENLDAP
  621. else
  622. DBGLOG("Not binding %s, platform built without LDAP", bindingName);
  623. #endif
  624. iter++;
  625. }
  626. }
  627. void CEspConfig::startEsdlMonitor()
  628. {
  629. start_esdl_monitor_t xproc = nullptr;
  630. Owned<IEspPlugin> pplg = getPlugin("esdl_svc_engine");
  631. if (pplg)
  632. {
  633. DBGLOG("Plugin esdl_svc_engine loaded.");
  634. xproc = (start_esdl_monitor_t) pplg->getProcAddress("startEsdlMonitor");
  635. }
  636. else
  637. throw MakeStringException(-1, "Plugin esdl_svc_engine can't be loaded");
  638. if (xproc)
  639. {
  640. DBGLOG("Procedure startEsdlMonitor loaded, now calling it...");
  641. xproc();
  642. }
  643. else
  644. throw MakeStringException(-1, "procedure startEsdlMonitor can't be loaded");
  645. }
  646. void CEspConfig::stopEsdlMonitor()
  647. {
  648. stop_esdl_monitor_t xproc = nullptr;
  649. Owned<IEspPlugin> pplg = getPlugin("esdl_svc_engine");
  650. if (pplg)
  651. xproc = (stop_esdl_monitor_t) pplg->getProcAddress("stopEsdlMonitor");
  652. if (xproc)
  653. xproc();
  654. }
  655. class ESPxsltIncludeHandler : public CInterface, implements IIncludeHandler
  656. {
  657. public:
  658. // IMPLEMENT_IINTERFACE;
  659. virtual void Link() const
  660. {
  661. CInterface::Link();
  662. }
  663. virtual bool Release() const
  664. {
  665. return CInterface::Release();
  666. }
  667. ESPxsltIncludeHandler()
  668. {
  669. }
  670. ~ESPxsltIncludeHandler()
  671. {
  672. }
  673. inline bool fileExists(StringBuffer &filename)
  674. {
  675. return (checkFileExists(filename.str()) || checkFileExists(filename.toUpperCase().str()) || checkFileExists(filename.toLowerCase().str()));
  676. }
  677. inline bool fileRead(const char *filename, MemoryBuffer &buff)
  678. {
  679. Owned<IFile> fi=createIFile(filename);
  680. if (fi)
  681. {
  682. Owned<IFileIO> fio=fi->open(IFOread);
  683. if (fio)
  684. {
  685. offset_t len=fio->size();
  686. size32_t memlen = (size32_t)len;
  687. assertex(len == memlen);
  688. if (fio->read(0, memlen, buff.reserveTruncate(memlen))==len)
  689. return true;
  690. }
  691. }
  692. buff.clear();
  693. return false;
  694. }
  695. const char *pastLast(const char *src, const char *fnd)
  696. {
  697. int fndlen=(fnd) ? strlen(fnd) : 0;
  698. int srclen=(src) ? strlen(src) : 0;
  699. if (fndlen && srclen)
  700. {
  701. while (srclen--)
  702. {
  703. if (!strnicmp(src+srclen, fnd, fndlen))
  704. return src+srclen+fndlen;
  705. }
  706. }
  707. return NULL;
  708. }
  709. //IIncludeHandler
  710. bool getInclude(const char* includename, MemoryBuffer& includebuf, bool& pathOnly)
  711. {
  712. if(!includename)
  713. return false;
  714. pathOnly = true;
  715. includebuf.clear();
  716. const char *finger=pastLast(includename, "esp/xslt/");
  717. if (finger)
  718. {
  719. StringBuffer filepath;
  720. if (fileExists(filepath.append(getCFD()).append("smc_xslt/").append(finger)) || fileExists(filepath.clear().append(getCFD()).append("xslt/").append(finger)))
  721. {
  722. includebuf.append(filepath.length(), filepath.str());
  723. return true;
  724. }
  725. }
  726. else
  727. {
  728. // First of all, it's better to use absolute path to specify the include, like /esp/xslt/ui_overrides.xslt.
  729. // When you specify the include as relative path, for example ./ui_overrides.xslt
  730. // the path will be expanded (by xmllib's source resolver) to its full path, beginning with file://
  731. // on windows it looks like: file:///C:/playground/esp_lsb2/xslt/ui_overrides.xslt
  732. // on linux: file:///home/yma/playground/esp_lsb2/xslt/ui_overrides.xslt
  733. // If current path not found, use root
  734. char dir[_MAX_PATH];
  735. if (!GetCurrentDirectory(sizeof(dir), dir)) {
  736. IERRLOG("ESPxsltIncludeHandler::getInclude: Current directory path too big, setting local path to null");
  737. dir[0] = 0;
  738. }
  739. #ifdef _WIN32
  740. for(int i = 0; i < _MAX_PATH; i++)
  741. {
  742. if(dir[i] == '\0')
  743. break;
  744. else if(dir[i] == PATHSEPCHAR)
  745. dir[i] = '/';
  746. }
  747. #endif
  748. finger = strstr(includename, dir);
  749. if(finger)
  750. {
  751. finger += strlen(dir) + 1;
  752. StringBuffer filepath(finger);
  753. if (fileExists(filepath))
  754. {
  755. includebuf.append(filepath.length(), filepath.str());
  756. return true;
  757. }
  758. }
  759. }
  760. return false;
  761. }
  762. };
  763. ESPxsltIncludeHandler g_includeHandler;
  764. void CEspConfig::bindServer(IEspServer &server, IEspContainer &container)
  765. {
  766. list<binding_cfg*>::iterator bit = m_bindings.begin();
  767. while (bit != m_bindings.end())
  768. {
  769. binding_cfg *pbfg = *bit;
  770. if (pbfg && pbfg->bind && pbfg->service && pbfg->protocol)
  771. {
  772. map<string, protocol_cfg*>::iterator pit = m_protocols.find(pbfg->protocol_name.str());
  773. if(pit == m_protocols.end())
  774. OWARNLOG("Protocol %s not found for binding %s", pbfg->protocol_name.str(), pbfg->name.str());
  775. else
  776. {
  777. Owned<IXslProcessor> xslp=getXslProcessor();
  778. if (xslp)
  779. {
  780. xslp->setDefIncludeHandler(dynamic_cast<IIncludeHandler*>(&g_includeHandler));
  781. pbfg->bind->setXslProcessor(xslp);
  782. }
  783. pbfg->bind->setContainer(&container);
  784. pbfg->service->setContainer(&container);
  785. pbfg->protocol->setContainer(&container);
  786. pbfg->bind->addProtocol(pbfg->protocol->getProtocolName(), *pbfg->protocol.get());
  787. if(pbfg->service != NULL)
  788. pbfg->bind->addService(pbfg->service->getServiceType(), pbfg->address.str(), pbfg->port, *pbfg->service.get());
  789. IEspProtocol* prot = (*pit).second->prot;
  790. server.addBinding(pbfg->name.str(), pbfg->address.str(), pbfg->port, *prot, *(pbfg->bind.get()), pbfg->isDefault, m_cfg.get());
  791. }
  792. }
  793. else
  794. {
  795. OERRLOG("Binding %s wasn't loaded correctly", pbfg->name.str());
  796. }
  797. bit++;
  798. }
  799. }
  800. void CEspConfig::saveAttachState()
  801. {
  802. StringBuffer espProcAttachState;
  803. espProcAttachState.setf( "<ESPAttachState StateSaveTimems='%d' attached='%s' subscribed='%s'/>", msTick(), isDetachedFromDali() ? "0" : "1", isSubscribedToDali() ? "1" : "0");
  804. DBGLOG("ESP Process [%s] State to be stored: '%s'", m_process.str(), espProcAttachState.str());
  805. Owned<IPropertyTree> serviceESDLDef = createPTreeFromXMLString(espProcAttachState.str(), ipt_caseInsensitive);
  806. saveXML(m_daliAttachStateFileName.str(), serviceESDLDef);
  807. }
  808. void CEspConfig::unloadBindings()
  809. {
  810. list<binding_cfg*>::iterator iter = m_bindings.begin();
  811. while (iter!=m_bindings.end())
  812. {
  813. binding_cfg *bcfg = *iter;
  814. if(bcfg!=NULL)
  815. {
  816. bcfg->protocol.clear();
  817. bcfg->bind.clear();
  818. bcfg->service.clear();
  819. delete bcfg;
  820. }
  821. iter++;
  822. }
  823. m_bindings.clear();
  824. }
  825. void CEspConfig::unloadServices()
  826. {
  827. map<string, srv_cfg*>::iterator srvi = m_services.begin();
  828. while (srvi!=m_services.end())
  829. {
  830. srv_cfg* scfg = srvi->second;
  831. if(scfg)
  832. {
  833. scfg->cfg.clear();
  834. scfg->srv.clear();
  835. delete scfg;
  836. }
  837. srvi++;
  838. }
  839. m_services.clear();
  840. }
  841. void CEspConfig::unloadProtocols()
  842. {
  843. map<string, protocol_cfg*>::iterator proti = m_protocols.begin();
  844. while (proti!=m_protocols.end())
  845. {
  846. protocol_cfg *pcfg = proti->second;
  847. if(pcfg)
  848. {
  849. pcfg->prot.clear();
  850. pcfg->cfg.clear();
  851. delete pcfg;
  852. }
  853. proti++;
  854. }
  855. m_protocols.clear();
  856. }
  857. IEspPlugin* CEspConfig::getPlugin(const char* name)
  858. {
  859. if(!name || !*name)
  860. return NULL;
  861. ForEachItemIn(x, m_plugins)
  862. {
  863. IEspPlugin* plgn = &m_plugins.item(x);
  864. if(plgn && stricmp(name, plgn->getName()) == 0)
  865. {
  866. return LINK(plgn);
  867. }
  868. }
  869. Owned<IEspPlugin> pplg = loadPlugin(name);
  870. if(pplg)
  871. {
  872. pplg->Link(); //YMA: intentional leak. Unloading DLLs during ESP shutdown causes all kinds of issues.
  873. m_plugins.append(*LINK(pplg));
  874. return LINK(pplg);
  875. }
  876. return NULL;
  877. }
  878. void CEspConfig::checkESPCache(IEspServer& server)
  879. {
  880. const char* cacheInitString = m_cfg->queryProp("@espCacheInitString");
  881. IPropertyTree* espCacheCfg = m_cfg->queryBranch("ESPCache");
  882. if (!espCacheCfg && isEmptyString(cacheInitString))
  883. return;
  884. if (!espCacheCfg)
  885. {
  886. if (!server.addCacheClient("default", cacheInitString))
  887. throw MakeStringException(-1, "Failed in checking ESP cache service using %s", cacheInitString);
  888. return;
  889. }
  890. Owned<IPropertyTreeIterator> iter = espCacheCfg->getElements("Group");
  891. ForEach(*iter)
  892. {
  893. IPropertyTree& espCacheGroup = iter->query();
  894. const char* id = espCacheGroup.queryProp("@id");
  895. const char* initString = espCacheGroup.queryProp("@initString");
  896. if (isEmptyString(id))
  897. throw MakeStringException(-1, "ESP cache ID not defined");
  898. if (isEmptyString(initString))
  899. throw MakeStringException(-1, "ESP cache initStrings not defined");
  900. if (!server.addCacheClient(id, initString))
  901. throw MakeStringException(-1, "Failed in checking ESP cache service using %s", initString);
  902. }
  903. }
  904. bool CEspConfig::reSubscribeESPToDali()
  905. {
  906. list<binding_cfg*>::iterator iter = m_bindings.begin();
  907. while (iter!=m_bindings.end())
  908. {
  909. binding_cfg& bindingConfig = **iter;
  910. if (bindingConfig.bind)
  911. {
  912. ESPLOG(LogMin, "Requesting binding '%s' to subscribe to DALI notifications", bindingConfig.name.str());
  913. bindingConfig.bind->subscribeBindingToDali();
  914. }
  915. iter++;
  916. }
  917. setIsSubscribedToDali(true);
  918. return true;
  919. }
  920. bool CEspConfig::unsubscribeESPFromDali()
  921. {
  922. list<binding_cfg*>::iterator iter = m_bindings.begin();
  923. while (iter!=m_bindings.end())
  924. {
  925. binding_cfg& bindingConfig = **iter;
  926. if (bindingConfig.bind)
  927. {
  928. ESPLOG(LogMin, "Requesting binding '%s' to un-subscribe from DALI notifications", bindingConfig.name.str());
  929. bindingConfig.bind->unsubscribeBindingFromDali();
  930. }
  931. iter++;
  932. }
  933. setIsSubscribedToDali(false);
  934. return true;
  935. }
  936. bool CEspConfig::detachESPFromDali(bool force)
  937. {
  938. CriticalBlock b(attachcrit);
  939. if (!isDetachedFromDali())
  940. {
  941. if(!force)
  942. {
  943. if (!canAllBindingsDetachFromDali())
  944. return false;
  945. }
  946. if (!unsubscribeESPFromDali())
  947. return false;
  948. list<binding_cfg*>::iterator iter = m_bindings.begin();
  949. while (iter!=m_bindings.end())
  950. {
  951. binding_cfg& xcfg = **iter;
  952. ESPLOG(LogMin, "Detach ESP From DALI: requesting binding: '%s' to detach...", xcfg.name.str());
  953. if (xcfg.bind)
  954. {
  955. xcfg.bind->detachBindingFromDali();
  956. }
  957. iter++;
  958. }
  959. setIsDetachedFromDali(true);
  960. disconnectLogMsgManagerFromDali();
  961. closedownClientProcess();
  962. saveAttachState();
  963. }
  964. return true;
  965. }
  966. bool CEspConfig::attachESPToDali()
  967. {
  968. bool success = true;
  969. CriticalBlock b(attachcrit);
  970. if (isDetachedFromDali())
  971. {
  972. setIsDetachedFromDali(false);
  973. StringBuffer daliservers;
  974. if (m_cfg->getProp("@daliServers", daliservers))
  975. initDali(daliservers.str());
  976. list<binding_cfg*>::iterator iter = m_bindings.begin();
  977. while (iter!=m_bindings.end())
  978. {
  979. binding_cfg& xcfg = **iter;
  980. ESPLOG(LogMin, "Attach ESP to DALI: requesting binding: '%s' to attach...", xcfg.name.str());
  981. if (xcfg.bind)
  982. {
  983. map<string, srv_cfg*>::iterator sit = m_services.find(xcfg.service_name.str());
  984. if(sit == m_services.end())
  985. ESPLOG(LogMin, "Warning: Service %s not found for the binding", xcfg.service_name.str());
  986. else
  987. ((*sit).second->srv)->attachServiceToDali();
  988. }
  989. iter++;
  990. }
  991. reSubscribeESPToDali();
  992. saveAttachState();
  993. }
  994. return success;
  995. }
  996. bool CEspConfig::canAllBindingsDetachFromDali()
  997. {
  998. list<binding_cfg*>::iterator iter = m_bindings.begin();
  999. while (iter!=m_bindings.end())
  1000. {
  1001. binding_cfg& xcfg = **iter;
  1002. if (!xcfg.bind->canDetachFromDali())
  1003. return false;
  1004. iter++;
  1005. }
  1006. return true;
  1007. }
  1008. IEspRpcBinding* CEspConfig::queryBinding(const char* name)
  1009. {
  1010. for (auto binding : m_bindings)
  1011. {
  1012. if (strcmp(binding->name.str(), name) == 0)
  1013. return binding->bind.get();
  1014. }
  1015. return nullptr;
  1016. }