espcfg.cpp 36 KB

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