dasess.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720
  1. /*##############################################################################
  2. Copyright (C) 2011 HPCC Systems.
  3. All rights reserved. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as
  5. published by the Free Software Foundation, either version 3 of the
  6. License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ############################################################################## */
  14. #define da_decl __declspec(dllexport)
  15. #include "platform.h"
  16. #include "jlib.hpp"
  17. #include "jfile.hpp"
  18. #include "jsuperhash.hpp"
  19. #include "jmisc.hpp"
  20. #include "jencrypt.hpp"
  21. #include "dacoven.hpp"
  22. #include "mpbuff.hpp"
  23. #include "mpcomm.hpp"
  24. #include "mputil.hpp"
  25. #include "daserver.hpp"
  26. #include "dasubs.ipp"
  27. #include "dasds.hpp"
  28. #include "daclient.hpp"
  29. #include "daldap.hpp"
  30. #include "dasess.hpp"
  31. #ifdef _MSC_VER
  32. #pragma warning (disable : 4355)
  33. #endif
  34. const char *queryRoleName(DaliClientRole role)
  35. {
  36. switch (role) {
  37. case DCR_Private: return "Private";
  38. case DCR_Diagnostic: return "Diagnostic";
  39. case DCR_ThorSlave: return "ThorSlave";
  40. case DCR_ThorMaster: return "ThorMaster";
  41. case DCR_EclServer: return "EclServer";
  42. case DCR_EclScheduler: return "EclScheduler";
  43. case DCR_EclAgent: return "EclAgent";
  44. case DCR_AgentExec: return "AgentExec";
  45. case DCR_DaliServer:return "DaliServer";
  46. case DCR_SashaServer: return "SashaServer";
  47. case DCR_Util: return "Util";
  48. case DCR_Dfu: return "Dfu";
  49. case DCR_DfuServer: return "DfuServer";
  50. case DCR_EspServer: return "EspServer";
  51. case DCR_WuClient: return "WuClient";
  52. case DCR_Config: return "Config";
  53. case DCR_Scheduler: return "Scheduler";
  54. case DCR_RoxyMaster: return "RoxieMaster";
  55. case DCR_RoxySlave: return "RoxieSlave";
  56. case DCR_BackupGen: return "BackupGen";
  57. case DCR_Other: return "Other";
  58. }
  59. return "Unknown";
  60. }
  61. interface ISessionManagerServer: implements IConnectionMonitor
  62. {
  63. virtual SessionId registerSession(SecurityToken tok,SessionId parentid) = 0;
  64. virtual SessionId registerClientProcess(INode *node,IGroup *&grp, DaliClientRole role) = 0;
  65. virtual void addProcessSession(SessionId id, INode *node, DaliClientRole role) = 0;
  66. virtual void addSession(SessionId id) = 0;
  67. virtual SessionId lookupProcessSession(INode *node) = 0;
  68. virtual INode *getProcessSessionNode(SessionId id) =0;
  69. virtual int getPermissionsLDAP(const char *key,const char *obj,IUserDescriptor *udesc,unsigned flags, int *err)=0;
  70. virtual void stopSession(SessionId sessid,bool failed) = 0;
  71. virtual void setClientAuth(IDaliClientAuthConnection *authconn) = 0;
  72. virtual void setLDAPconnection(IDaliLdapConnection *_ldapconn) = 0;
  73. virtual bool authorizeConnection(int role,bool revoke) = 0;
  74. virtual void start() = 0;
  75. virtual void ready() = 0;
  76. virtual void stop() = 0;
  77. };
  78. static SessionId mySessionId=0;
  79. static ISessionManager *SessionManager=NULL;
  80. static ISessionManagerServer *SessionManagerServer=NULL;
  81. static CriticalSection sessionCrit;
  82. #define SESSIONREPLYTIMEOUT (3*60*1000)
  83. #define CLDAPE_getpermtimeout (-1)
  84. #define CLDAPE_ldapfailure (-2)
  85. class CDaliLDAP_Exception: public CInterface, implements IException
  86. {
  87. int errcode;
  88. public:
  89. CDaliLDAP_Exception(int _errcode)
  90. {
  91. errcode = _errcode;
  92. }
  93. int errorCode() const { return errcode; }
  94. StringBuffer & errorMessage(StringBuffer &str) const
  95. {
  96. if (errcode==0)
  97. return str;
  98. str.appendf("LDAP Exception(%d): ",errcode);
  99. if (errcode==CLDAPE_getpermtimeout)
  100. return str.append("getPermissionsLDAP - timeout to LDAP server");
  101. if (errcode==CLDAPE_ldapfailure)
  102. return str.append("getPermissionsLDAP - LDAP server failure");
  103. return str.append("Unknown Exception");
  104. }
  105. MessageAudience errorAudience() const { return MSGAUD_user; }
  106. IMPLEMENT_IINTERFACE;
  107. };
  108. class CdelayedTerminate: public Thread // slightly obfuscated stop code
  109. {
  110. byte err;
  111. int run()
  112. {
  113. while (getRandom()%711!=0) getRandom(); // look busy
  114. ERRLOG("Server fault %d",(int)err);
  115. while (getRandom()%7!=0) Sleep(1);
  116. exit(0);
  117. }
  118. public:
  119. CdelayedTerminate(byte _err)
  120. {
  121. err = _err;
  122. start();
  123. Release();
  124. Sleep(100);
  125. }
  126. };
  127. class CSessionState: public CInterface
  128. {
  129. protected: friend class CSessionStateTable;
  130. SessionId id;
  131. public:
  132. CSessionState(SessionId _id)
  133. {
  134. id = _id;
  135. }
  136. SessionId getId() const
  137. {
  138. return id;
  139. }
  140. };
  141. class CSessionStateTable: private SuperHashTableOf<CSessionState,SessionId>
  142. {
  143. CheckedCriticalSection sessstatesect;
  144. void onAdd(void *) {}
  145. void onRemove(void *e)
  146. {
  147. CSessionState &elem=*(CSessionState *)e;
  148. elem.Release();
  149. }
  150. unsigned getHashFromElement(const void *e) const
  151. {
  152. const CSessionState &elem=*(const CSessionState *)e;
  153. SessionId id=elem.id;
  154. return low(id)^(unsigned)high(id);
  155. }
  156. unsigned getHashFromFindParam(const void *fp) const
  157. {
  158. SessionId id = *(const SessionId *)fp;
  159. return low(id)^(unsigned)high(id);
  160. }
  161. const void * getFindParam(const void *p) const
  162. {
  163. const CSessionState &elem=*(const CSessionState *)p;
  164. return (void *)&elem.id;
  165. }
  166. bool matchesFindParam(const void * et, const void *fp, unsigned) const
  167. {
  168. return ((CSessionState *)et)->id==*(SessionId *)fp;
  169. }
  170. IMPLEMENT_SUPERHASHTABLEOF_REF_FIND(CSessionState,SessionId);
  171. public:
  172. CSessionStateTable()
  173. {
  174. }
  175. ~CSessionStateTable() {
  176. CHECKEDCRITICALBLOCK(sessstatesect,60000);
  177. releaseAll();
  178. }
  179. bool add(CSessionState *e) // takes ownership
  180. {
  181. CHECKEDCRITICALBLOCK(sessstatesect,60000);
  182. if (SuperHashTableOf<CSessionState,SessionId>::find(&e->id))
  183. return false;
  184. SuperHashTableOf<CSessionState,SessionId>::add(*e);
  185. return true;
  186. }
  187. const CSessionState *query(SessionId id)
  188. {
  189. CHECKEDCRITICALBLOCK(sessstatesect,60000);
  190. return SuperHashTableOf<CSessionState,SessionId>::find(&id);
  191. }
  192. void remove(SessionId id)
  193. {
  194. CHECKEDCRITICALBLOCK(sessstatesect,60000);
  195. SuperHashTableOf<CSessionState,SessionId>::remove(&id);
  196. }
  197. };
  198. class CProcessSessionState: public CSessionState
  199. {
  200. INode *node;
  201. DaliClientRole role;
  202. public:
  203. CProcessSessionState(SessionId id,INode *_node,DaliClientRole _role)
  204. : CSessionState(id)
  205. {
  206. node = _node;
  207. node->Link();
  208. role = _role;
  209. }
  210. ~CProcessSessionState()
  211. {
  212. node->Release();
  213. }
  214. INode &queryNode() const
  215. {
  216. return *node;
  217. }
  218. DaliClientRole queryRole() const
  219. {
  220. return role;
  221. }
  222. StringBuffer &getDetails(StringBuffer &buf)
  223. {
  224. StringBuffer ep;
  225. return buf.appendf("%16"I64F"X: %s, role=%s",CSessionState::id,node->endpoint().getUrlStr(ep).str(),queryRoleName(role));
  226. }
  227. };
  228. class CMapProcessToSession: private SuperHashTableOf<CProcessSessionState,INode>
  229. {
  230. CheckedCriticalSection mapprocesssect;
  231. void onAdd(void *) {}
  232. void onRemove(void *e) {} // do nothing
  233. unsigned getHashFromElement(const void *e) const
  234. {
  235. const CProcessSessionState &elem=*(const CProcessSessionState *)e;
  236. return elem.queryNode().getHash();
  237. }
  238. unsigned getHashFromFindParam(const void *fp) const
  239. {
  240. return ((INode *)fp)->getHash();
  241. }
  242. const void * getFindParam(const void *p) const
  243. {
  244. const CProcessSessionState &elem=*(const CProcessSessionState *)p;
  245. return (void *)&elem.queryNode();
  246. }
  247. bool matchesFindParam(const void * et, const void *fp, unsigned) const
  248. {
  249. return ((CProcessSessionState *)et)->queryNode().equals((INode *)fp);
  250. }
  251. IMPLEMENT_SUPERHASHTABLEOF_REF_FIND(CProcessSessionState,INode);
  252. public:
  253. CMapProcessToSession()
  254. {
  255. }
  256. ~CMapProcessToSession()
  257. {
  258. CHECKEDCRITICALBLOCK(mapprocesssect,60000);
  259. releaseAll();
  260. }
  261. bool add(CProcessSessionState *e)
  262. {
  263. CHECKEDCRITICALBLOCK(mapprocesssect,60000);
  264. if (SuperHashTableOf<CProcessSessionState,INode>::find(&e->queryNode()))
  265. return false;
  266. SuperHashTableOf<CProcessSessionState,INode>::add(*e);
  267. return true;
  268. }
  269. CProcessSessionState *query(INode *n)
  270. {
  271. CHECKEDCRITICALBLOCK(mapprocesssect,60000);
  272. return SuperHashTableOf<CProcessSessionState,INode>::find(n);
  273. }
  274. void remove(INode *n,ISessionManagerServer *manager)
  275. {
  276. CHECKEDCRITICALBLOCK(mapprocesssect,60000);
  277. CProcessSessionState *sstate = SuperHashTableOf<CProcessSessionState,INode>::find(n);
  278. if (sstate) {
  279. if (manager)
  280. manager->authorizeConnection(sstate->queryRole(),true);
  281. SuperHashTableOf<CProcessSessionState,INode>::removeExact(sstate);
  282. }
  283. }
  284. unsigned count()
  285. {
  286. CHECKEDCRITICALBLOCK(mapprocesssect,60000);
  287. return SuperHashTableOf<CProcessSessionState,INode>::count();
  288. }
  289. CProcessSessionState *next(const CProcessSessionState *s)
  290. {
  291. CHECKEDCRITICALBLOCK(mapprocesssect,60000);
  292. return (CProcessSessionState *)SuperHashTableOf<CProcessSessionState,INode>::next(s);
  293. }
  294. };
  295. enum MSessionRequestKind {
  296. MSR_REGISTER_PROCESS_SESSION,
  297. MSR_SECONDARY_REGISTER_PROCESS_SESSION,
  298. MSR_REGISTER_SESSION,
  299. MSR_SECONDARY_REGISTER_SESSION,
  300. MSR_LOOKUP_PROCESS_SESSION,
  301. MSR_STOP_SESSION,
  302. MSR_IMPORT_CAPABILITIES,
  303. MSR_LOOKUP_LDAP_PERMISSIONS,
  304. MSR_EXIT // TBD
  305. };
  306. class CSessionRequestServer: public Thread
  307. {
  308. bool stopped;
  309. ISessionManagerServer &manager;
  310. Semaphore acceptConnections;
  311. public:
  312. CSessionRequestServer(ISessionManagerServer &_manager)
  313. : Thread("Session Manager, CSessionRequestServer"), manager(_manager)
  314. {
  315. stopped = true;
  316. }
  317. int run()
  318. {
  319. ICoven &coven=queryCoven();
  320. CMessageHandler<CSessionRequestServer> handler("CSessionRequestServer",this,&CSessionRequestServer::processMessage);
  321. stopped = false;
  322. CMessageBuffer mb;
  323. while (!stopped) {
  324. try {
  325. mb.clear();
  326. if (coven.recv(mb,RANK_ALL,MPTAG_DALI_SESSION_REQUEST,NULL))
  327. handler.handleMessage(mb);
  328. else
  329. stopped = true;
  330. }
  331. catch (IException *e)
  332. {
  333. EXCLOG(e, "CDaliPublisherServer");
  334. e->Release();
  335. }
  336. }
  337. return 0;
  338. }
  339. void processMessage(CMessageBuffer &mb)
  340. {
  341. ICoven &coven=queryCoven();
  342. SessionId id;
  343. int fn;
  344. mb.read(fn);
  345. switch (fn) {
  346. case MSR_REGISTER_PROCESS_SESSION: {
  347. acceptConnections.wait();
  348. acceptConnections.signal();
  349. Owned<INode> node(deserializeINode(mb));
  350. Owned<INode> servernode(deserializeINode(mb)); // hopefully me, but not if forwarded
  351. int role=0;
  352. if (mb.length()-mb.getPos()>=sizeof(role)) { // a capability block present
  353. mb.read(role);
  354. if (!manager.authorizeConnection(role,false)) {
  355. SocketEndpoint sender = mb.getSender();
  356. mb.clear();
  357. coven.reply(mb);
  358. MilliSleep(100+getRandom()%1000); // Causes client to 'work' for a short time.
  359. Owned<INode> node = createINode(sender);
  360. coven.disconnect(node);
  361. break;
  362. }
  363. #ifdef _DEBUG
  364. StringBuffer eps;
  365. PROGLOG("Connection to %s authorized",mb.getSender().getUrlStr(eps).str());
  366. #endif
  367. }
  368. IGroup *covengrp;
  369. id = manager.registerClientProcess(node.get(),covengrp,(DaliClientRole)role);
  370. mb.clear().append(id);
  371. if (covengrp->rank(servernode)==RANK_NULL) { // must have been redirected
  372. covengrp->Release(); // no good, so just use one we know about (may use something more sophisticated later)
  373. INode *na = servernode.get();
  374. covengrp = createIGroup(1, &na);
  375. }
  376. covengrp->serialize(mb);
  377. covengrp->Release();
  378. coven.reply(mb);
  379. }
  380. break;
  381. case MSR_SECONDARY_REGISTER_PROCESS_SESSION: {
  382. mb.read(id);
  383. Owned<INode> node (deserializeINode(mb));
  384. int role;
  385. mb.read(role);
  386. manager.addProcessSession(id,node.get(),(DaliClientRole)role);
  387. mb.clear();
  388. coven.reply(mb);
  389. }
  390. break;
  391. case MSR_REGISTER_SESSION: {
  392. SecurityToken tok;
  393. SessionId parentid;
  394. mb.read(tok).read(parentid);
  395. SessionId id = manager.registerSession(tok,parentid);
  396. mb.clear().append(id);
  397. coven.reply(mb);
  398. }
  399. break;
  400. case MSR_SECONDARY_REGISTER_SESSION: {
  401. mb.read(id);
  402. manager.addSession(id);
  403. mb.clear();
  404. coven.reply(mb);
  405. }
  406. break;
  407. case MSR_LOOKUP_PROCESS_SESSION: {
  408. // looks up from node or from id
  409. Owned<INode> node (deserializeINode(mb));
  410. if (node->endpoint().isNull()&&(mb.length()-mb.getPos()>=sizeof(id))) {
  411. mb.read(id);
  412. INode *n = manager.getProcessSessionNode(id);
  413. if (n)
  414. node.setown(n);
  415. node->serialize(mb.clear());
  416. }
  417. else {
  418. id = manager.lookupProcessSession(node.get());
  419. mb.clear().append(id);
  420. }
  421. coven.reply(mb);
  422. }
  423. break;
  424. case MSR_STOP_SESSION: {
  425. SessionId sessid;
  426. bool failed;
  427. mb.read(sessid).read(failed);
  428. manager.stopSession(sessid,failed);
  429. mb.clear();
  430. coven.reply(mb);
  431. }
  432. break;
  433. case MSR_LOOKUP_LDAP_PERMISSIONS: {
  434. StringAttr key;
  435. StringAttr obj;
  436. Owned<IUserDescriptor> udesc=createUserDescriptor();
  437. StringAttr username;
  438. StringAttr passwordenc;
  439. mb.read(key).read(obj);
  440. udesc->deserialize(mb);
  441. #ifdef _DALIUSER_STACKTRACE
  442. //following debug code to be removed
  443. StringBuffer sb;
  444. udesc->getUserName(sb);
  445. if (0==sb.length() || !strcmpi(sb.str(), "daliuser"))
  446. {
  447. DBGLOG("UNEXPECTED USER '%s' in %s line %ld",username,__FILE__, __LINE__);
  448. PrintStackReport();
  449. }
  450. #endif
  451. unsigned auditflags = 0;
  452. if (mb.length()-mb.getPos()>=sizeof(auditflags))
  453. mb.read(auditflags);
  454. int err = 0;
  455. int ret=manager.getPermissionsLDAP(key,obj,udesc,auditflags,&err);
  456. mb.clear().append(ret);
  457. if (err)
  458. mb.append(err);
  459. coven.reply(mb);
  460. }
  461. break;
  462. }
  463. }
  464. void ready()
  465. {
  466. acceptConnections.signal();
  467. }
  468. void stop()
  469. {
  470. if (!stopped) {
  471. stopped = true;
  472. queryCoven().cancel(RANK_ALL, MPTAG_DALI_SESSION_REQUEST);
  473. }
  474. join();
  475. }
  476. };
  477. class CSessionManagerBase: public CInterface, implements ISessionManager
  478. {
  479. protected:
  480. CheckedCriticalSection sessmanagersect;
  481. public:
  482. IMPLEMENT_IINTERFACE;
  483. CSessionManagerBase()
  484. {
  485. servernotifys.kill();
  486. }
  487. virtual ~CSessionManagerBase()
  488. {
  489. }
  490. class CSessionSubscriptionProxy: public CInterface, implements ISubscription
  491. {
  492. ISessionNotify *sub;
  493. SubscriptionId id;
  494. MemoryAttr ma;
  495. SessionId sessid;
  496. public:
  497. IMPLEMENT_IINTERFACE;
  498. CSessionSubscriptionProxy(ISessionNotify *_sub,SessionId _sessid)
  499. {
  500. sub = LINK(_sub);
  501. sessid = _sessid;
  502. MemoryBuffer mb;
  503. mb.append(sessid);
  504. ma.set(mb.length(),mb.toByteArray());
  505. id = queryCoven().getUniqueId();
  506. }
  507. ~CSessionSubscriptionProxy()
  508. {
  509. sub->Release();
  510. }
  511. ISessionNotify *queryNotify()
  512. {
  513. return sub;
  514. }
  515. const MemoryAttr &queryData()
  516. {
  517. return ma;
  518. }
  519. SubscriptionId getId()
  520. {
  521. return id;
  522. }
  523. void doNotify(bool aborted)
  524. {
  525. if (aborted)
  526. sub->aborted(sessid);
  527. else
  528. sub->closed(sessid);
  529. }
  530. void notify(MemoryBuffer &mb)
  531. {
  532. bool aborted;
  533. mb.read(aborted);
  534. doNotify(aborted);
  535. }
  536. void abort()
  537. {
  538. //NH: TBD
  539. }
  540. bool aborted()
  541. {
  542. return false;
  543. }
  544. };
  545. CIArrayOf<CSessionSubscriptionProxy>servernotifys;
  546. SubscriptionId subscribeSession(SessionId sessid, ISessionNotify *inotify)
  547. {
  548. CSessionSubscriptionProxy *proxy;
  549. SubscriptionId id;
  550. {
  551. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  552. proxy = new CSessionSubscriptionProxy(inotify,sessid);
  553. id = proxy->getId();
  554. if (sessid==SESSID_DALI_SERVER) {
  555. servernotifys.append(*proxy);
  556. return id;
  557. }
  558. }
  559. querySubscriptionManager(SESSION_PUBLISHER)->add(proxy,id);
  560. return id;
  561. }
  562. void unsubscribeSession(SubscriptionId id)
  563. {
  564. {
  565. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  566. // check not a server subscription
  567. ForEachItemIn(i,servernotifys) {
  568. if (servernotifys.item(i).getId()==id) {
  569. servernotifys.remove(i);
  570. return;
  571. }
  572. }
  573. }
  574. querySubscriptionManager(SESSION_PUBLISHER)->remove(id);
  575. }
  576. class cNotify: public CInterface, implements ISessionNotify
  577. {
  578. public:
  579. IMPLEMENT_IINTERFACE;
  580. Semaphore sem;
  581. void closed(SessionId id)
  582. {
  583. //PROGLOG("Session closed %"I64F"x",id);
  584. sem.signal();
  585. }
  586. void aborted(SessionId id)
  587. {
  588. //PROGLOG("Session aborted %"I64F"x",id);
  589. sem.signal();
  590. }
  591. };
  592. bool sessionStopped(SessionId id, unsigned timeout)
  593. {
  594. Owned<INode> node = getProcessSessionNode(id);
  595. if (node.get()==NULL)
  596. return true;
  597. if (timeout==0)
  598. return false;
  599. Owned<cNotify> cnotify = new cNotify;
  600. querySessionManager().subscribeSession(id,cnotify);
  601. if (cnotify->sem.wait(timeout))
  602. return false;
  603. node.setown(getProcessSessionNode(id));
  604. return node.get()==NULL;
  605. }
  606. void notifyServerStopped(bool aborted)
  607. {
  608. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  609. // check not a server subscription
  610. ForEachItemIn(i,servernotifys) {
  611. servernotifys.item(i).doNotify(aborted);
  612. }
  613. }
  614. };
  615. class CClientSessionManager: public CSessionManagerBase, implements IConnectionMonitor
  616. {
  617. bool securitydisabled;
  618. public:
  619. IMPLEMENT_IINTERFACE;
  620. CClientSessionManager()
  621. {
  622. securitydisabled = false;
  623. }
  624. virtual ~CClientSessionManager()
  625. {
  626. stop();
  627. }
  628. SessionId lookupProcessSession(INode *node)
  629. {
  630. if (!node)
  631. return mySessionId;
  632. CMessageBuffer mb;
  633. mb.append((int)MSR_LOOKUP_PROCESS_SESSION);
  634. node->serialize(mb);
  635. if (!queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT))
  636. return 0;
  637. SessionId ret;
  638. mb.read(ret);
  639. return ret;
  640. }
  641. virtual INode *getProcessSessionNode(SessionId id)
  642. {
  643. if (!id)
  644. return NULL;
  645. CMessageBuffer mb;
  646. mb.append((int)MSR_LOOKUP_PROCESS_SESSION);
  647. queryNullNode()->serialize(mb);
  648. mb.append(id);
  649. if (!queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT))
  650. return NULL;
  651. Owned<INode> node = deserializeINode(mb);
  652. if (node->endpoint().isNull())
  653. return NULL;
  654. return node.getClear();
  655. }
  656. int getPermissionsLDAP(const char *key,const char *obj,IUserDescriptor *udesc,unsigned auditflags,int *err)
  657. {
  658. if (err)
  659. *err = 0;
  660. if (securitydisabled)
  661. return -1;
  662. if (queryDaliServerVersion().compare("1.8") < 0) {
  663. securitydisabled = true;
  664. return -1;
  665. }
  666. CMessageBuffer mb;
  667. mb.append((int)MSR_LOOKUP_LDAP_PERMISSIONS);
  668. mb.append(key).append(obj);
  669. #ifdef _DALIUSER_STACKTRACE
  670. //following debug code to be removed
  671. StringBuffer sb;
  672. udesc->getUserName(sb);
  673. if (0==sb.length() || !strcmpi(sb.str(), "daliuser"))
  674. {
  675. DBGLOG("UNEXPECTED USER '%s' in %s line %ld",sb.str(),__FILE__, __LINE__);
  676. PrintStackReport();
  677. }
  678. #endif
  679. udesc->serialize(mb);
  680. mb.append(auditflags);
  681. if (!queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT))
  682. return 0;
  683. int ret=-1;
  684. if (mb.remaining()>=sizeof(ret)) {
  685. mb.read(ret);
  686. int e = 0;
  687. if (mb.remaining()>=sizeof(e)) {
  688. if (err)
  689. *err = e;
  690. else if (e)
  691. throw new CDaliLDAP_Exception(e);
  692. }
  693. }
  694. if (ret==-1)
  695. securitydisabled = true;
  696. return ret;
  697. }
  698. bool checkScopeScansLDAP()
  699. {
  700. assertex(!"checkScopeScansLDAP called on client");
  701. return true; // actually only used server size
  702. }
  703. unsigned getLDAPflags()
  704. {
  705. assertex(!"getLdapFlags called on client");
  706. return 0;
  707. }
  708. void setLDAPflags(unsigned)
  709. {
  710. assertex(!"setLdapFlags called on client");
  711. }
  712. bool authorizeConnection(DaliClientRole,bool)
  713. {
  714. return true;
  715. }
  716. SessionId startSession(SecurityToken tok, SessionId parentid)
  717. {
  718. CMessageBuffer mb;
  719. mb.append((int)MSR_REGISTER_SESSION).append(tok).append(parentid);
  720. if (!queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST),SESSIONREPLYTIMEOUT)
  721. return 0;
  722. SessionId ret;
  723. mb.read(ret);
  724. return ret;
  725. }
  726. void stopSession(SessionId sessid, bool failed)
  727. {
  728. if (sessid==SESSID_DALI_SERVER) {
  729. notifyServerStopped(failed);
  730. return;
  731. }
  732. CMessageBuffer mb;
  733. mb.append((int)MSR_STOP_SESSION).append(sessid).append(failed);
  734. queryCoven().sendRecv(mb,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT);
  735. }
  736. void onClose(SocketEndpoint &ep)
  737. {
  738. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  739. Owned<INode> node = createINode(ep);
  740. if (queryCoven().inCoven(node)) {
  741. StringBuffer str;
  742. PROGLOG("Coven Session Stopping (%s)",ep.getUrlStr(str).str());
  743. if (queryCoven().size()==1)
  744. notifyServerStopped(true);
  745. }
  746. }
  747. void start()
  748. {
  749. addMPConnectionMonitor(this);
  750. }
  751. void stop()
  752. {
  753. }
  754. void ready()
  755. {
  756. removeMPConnectionMonitor(this);
  757. }
  758. StringBuffer &getClientProcessList(StringBuffer &buf)
  759. {
  760. // dummy
  761. return buf;
  762. }
  763. StringBuffer &getClientProcessEndpoint(SessionId,StringBuffer &buf)
  764. {
  765. // dummy
  766. return buf;
  767. }
  768. unsigned queryClientCount()
  769. {
  770. // dummy
  771. return 0;
  772. }
  773. void importCapabilities(MemoryBuffer &mb)
  774. {
  775. CMessageBuffer msg;
  776. msg.append((int)MSR_IMPORT_CAPABILITIES);
  777. msg.append(mb.length(), mb.toByteArray());
  778. queryCoven().sendRecv(msg,RANK_RANDOM,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT);
  779. }
  780. };
  781. class CLdapWorkItem : public Thread
  782. {
  783. StringAttr key;
  784. StringAttr obj;
  785. Linked<IUserDescriptor> udesc;
  786. Linked<IDaliLdapConnection> ldapconn;
  787. unsigned flags;
  788. bool running;
  789. Semaphore contsem;
  790. Semaphore ready;
  791. Semaphore &threaddone;
  792. int ret;
  793. public:
  794. IMPLEMENT_IINTERFACE;
  795. CLdapWorkItem(IDaliLdapConnection *_ldapconn,Semaphore &_threaddone)
  796. : ldapconn(_ldapconn), threaddone(_threaddone)
  797. {
  798. running = false;
  799. }
  800. void start(const char *_key,const char *_obj,IUserDescriptor *_udesc,unsigned _flags)
  801. {
  802. key.set(_key);
  803. obj.set(_obj);
  804. udesc.set(_udesc);
  805. flags = _flags;
  806. ret = CLDAPE_ldapfailure;
  807. if (!running) {
  808. running = true;
  809. Thread::start();
  810. }
  811. contsem.signal();
  812. }
  813. int run()
  814. {
  815. loop {
  816. contsem.wait();
  817. if (!running)
  818. break;
  819. try {
  820. ret = ldapconn->getPermissions(key,obj,udesc,flags);
  821. }
  822. catch(IException *e) {
  823. LOG(MCoperatorError, unknownJob, e, "CLdapWorkItem");
  824. e->Release();
  825. }
  826. ready.signal();
  827. }
  828. threaddone.signal();
  829. return 0;
  830. }
  831. bool wait(unsigned timeout, int &_ret)
  832. {
  833. if (ready.wait(timeout)) {
  834. _ret = ret;
  835. return true;
  836. }
  837. _ret = 0;
  838. return false;
  839. }
  840. void stop()
  841. {
  842. running = false;
  843. contsem.signal();
  844. }
  845. static CLdapWorkItem *get(IDaliLdapConnection *_ldapconn,Semaphore &_threaddone)
  846. {
  847. if (!_threaddone.wait(1000*60*5)) {
  848. ERRLOG("Too many stalled LDAP threads");
  849. return NULL;
  850. }
  851. return new CLdapWorkItem(_ldapconn,_threaddone);
  852. }
  853. };
  854. class CCovenSessionManager: public CSessionManagerBase, implements ISessionManagerServer, implements ISubscriptionManager
  855. {
  856. CSessionRequestServer sessionrequestserver;
  857. CSessionStateTable sessionstates;
  858. CMapProcessToSession processlookup;
  859. Owned<IDaliLdapConnection> ldapconn;
  860. Owned<CLdapWorkItem> ldapworker;
  861. Semaphore ldapsig;
  862. atomic_t ldapwaiting;
  863. Semaphore workthreadsem;
  864. bool stopping;
  865. void remoteAddProcessSession(rank_t dst,SessionId id,INode *node, DaliClientRole role)
  866. {
  867. CMessageBuffer mb;
  868. mb.append((int)MSR_SECONDARY_REGISTER_PROCESS_SESSION).append(id);
  869. node->serialize(mb);
  870. int r = (int)role;
  871. mb.append(role);
  872. queryCoven().sendRecv(mb,dst,MPTAG_DALI_SESSION_REQUEST);
  873. // no fail currently
  874. }
  875. void remoteAddSession(rank_t dst,SessionId id)
  876. {
  877. CMessageBuffer mb;
  878. mb.append((int)MSR_SECONDARY_REGISTER_SESSION).append(id);
  879. queryCoven().sendRecv(mb,dst,MPTAG_DALI_SESSION_REQUEST);
  880. // no fail currently
  881. }
  882. public:
  883. IMPLEMENT_IINTERFACE;
  884. CCovenSessionManager()
  885. : sessionrequestserver(*this)
  886. {
  887. mySessionId = queryCoven().getUniqueId(); // tell others in coven TBD
  888. registerSubscriptionManager(SESSION_PUBLISHER,this);
  889. atomic_set(&ldapwaiting,0);
  890. workthreadsem.signal(10);
  891. stopping = false;
  892. ldapsig.signal();
  893. }
  894. ~CCovenSessionManager()
  895. {
  896. stubs.kill();
  897. }
  898. void start()
  899. {
  900. sessionrequestserver.start();
  901. }
  902. void stop()
  903. {
  904. stopping = true;
  905. if (!ldapsig.wait(60*1000))
  906. WARNLOG("LDAP stalled(1)");
  907. if (ldapworker) {
  908. ldapworker->stop();
  909. if (!ldapworker->join(1000))
  910. WARNLOG("LDAP stalled(2)");
  911. ldapworker.clear();
  912. }
  913. ldapconn.clear();
  914. removeMPConnectionMonitor(this);
  915. sessionrequestserver.stop();
  916. }
  917. void ready()
  918. {
  919. addMPConnectionMonitor(this);
  920. sessionrequestserver.ready();
  921. }
  922. void setLDAPconnection(IDaliLdapConnection *_ldapconn)
  923. {
  924. if (_ldapconn&&(_ldapconn->getLDAPflags()&DLF_ENABLED))
  925. ldapconn.setown(_ldapconn);
  926. else {
  927. ldapconn.clear();
  928. ::Release(_ldapconn);
  929. }
  930. }
  931. void setClientAuth(IDaliClientAuthConnection *_authconn)
  932. {
  933. }
  934. void addProcessSession(SessionId id,INode *client,DaliClientRole role)
  935. {
  936. StringBuffer str;
  937. PROGLOG("Session starting %"I64F"x (%s) : role=%s",id,client->endpoint().getUrlStr(str).str(),queryRoleName(role));
  938. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  939. CProcessSessionState *s = new CProcessSessionState(id,client,role);
  940. while (!sessionstates.add(s)) { // takes ownership
  941. WARNLOG("Dali session manager: session already registered");
  942. sessionstates.remove(id);
  943. }
  944. while (!processlookup.add(s)) {
  945. ERRLOG("Dali session manager: registerClient process session already registered");
  946. processlookup.remove(client,this);
  947. }
  948. }
  949. void addSession(SessionId id)
  950. {
  951. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  952. CSessionState *s = new CSessionState(id);
  953. while (!sessionstates.add(s)) { // takes ownership
  954. WARNLOG("Dali session manager: session already registered (2)");
  955. sessionstates.remove(id);
  956. }
  957. }
  958. SessionId registerSession(SecurityToken, SessionId parent)
  959. {
  960. // this is where security token should be checked
  961. // not in critical block (otherwise possibility of deadlock)
  962. ICoven &coven=queryCoven();
  963. SessionId id = coven.getUniqueId();
  964. rank_t myrank = coven.getServerRank();
  965. rank_t ownerrank = coven.chooseServer(id);
  966. // first do local
  967. if (myrank==ownerrank)
  968. addSession(id);
  969. else
  970. remoteAddSession(ownerrank,id);
  971. ForEachOtherNodeInGroup(r,coven.queryGroup()) {
  972. if (r!=ownerrank)
  973. remoteAddSession(r,id);
  974. }
  975. return id;
  976. }
  977. SessionId registerClientProcess(INode *client, IGroup *& retcoven, DaliClientRole role)
  978. {
  979. // not in critical block (otherwise possibility of deadlock)
  980. retcoven = NULL;
  981. ICoven &coven=queryCoven();
  982. SessionId id = coven.getUniqueId();
  983. rank_t myrank = coven.getServerRank();
  984. rank_t ownerrank = coven.chooseServer(id);
  985. // first do local
  986. if (myrank==ownerrank)
  987. addProcessSession(id,client,role);
  988. else
  989. remoteAddProcessSession(ownerrank,id,client,role);
  990. ForEachOtherNodeInGroup(r,coven.queryGroup()) {
  991. if (r!=ownerrank)
  992. remoteAddProcessSession(r,id,client,role);
  993. }
  994. retcoven = coven.getGroup();
  995. return id;
  996. }
  997. SessionId lookupProcessSession(INode *node)
  998. {
  999. if (!node)
  1000. return mySessionId;
  1001. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  1002. CProcessSessionState *s= processlookup.query(node);
  1003. return s?s->getId():0;
  1004. }
  1005. INode *getProcessSessionNode(SessionId id)
  1006. {
  1007. StringBuffer eps;
  1008. if (SessionManager->getClientProcessEndpoint(id,eps).length()!=0)
  1009. return createINode(eps.str());
  1010. return NULL;
  1011. }
  1012. virtual int getPermissionsLDAP(const char *key,const char *obj,IUserDescriptor *udesc,unsigned flags, int *err)
  1013. {
  1014. if (err)
  1015. *err = 0;
  1016. if (!ldapconn)
  1017. return -1;
  1018. #ifdef _NO_LDAP
  1019. return -1;
  1020. #else
  1021. if ((ldapconn->getLDAPflags()&(DLF_SAFE|DLF_ENABLED))!=(DLF_SAFE|DLF_ENABLED))
  1022. return ldapconn->getPermissions(key,obj,udesc,flags);
  1023. atomic_inc(&ldapwaiting);
  1024. unsigned retries = 0;
  1025. while (!stopping) {
  1026. if (ldapsig.wait(1000)) {
  1027. atomic_dec(&ldapwaiting);
  1028. if (!ldapworker)
  1029. ldapworker.setown(CLdapWorkItem::get(ldapconn,workthreadsem));
  1030. if (ldapworker) {
  1031. ldapworker->start(key,obj,udesc,flags);
  1032. for (unsigned i=0;i<10;i++) {
  1033. if (i)
  1034. WARNLOG("LDAP stalled(%d) - retrying",i);
  1035. int ret;
  1036. if (ldapworker->wait(1000*20,ret)) {
  1037. if (ret==CLDAPE_ldapfailure) {
  1038. LOG(MCoperatorError, unknownJob, "LDAP - failure (returning no access for %s)",obj);
  1039. ldapsig.signal();
  1040. if (err)
  1041. *err = CLDAPE_ldapfailure;
  1042. return 0;
  1043. }
  1044. else {
  1045. ldapsig.signal();
  1046. return ret;
  1047. }
  1048. }
  1049. if (atomic_read(&ldapwaiting)>10) // give up quicker if piling up
  1050. break;
  1051. if (i==5) { // one retry
  1052. ldapworker->stop(); // abandon thread
  1053. ldapworker.clear();
  1054. ldapworker.setown(CLdapWorkItem::get(ldapconn,workthreadsem));
  1055. if (ldapworker)
  1056. ldapworker->start(key,obj,udesc,flags);
  1057. }
  1058. }
  1059. if (ldapworker)
  1060. ldapworker->stop();
  1061. ldapworker.clear(); // abandon thread
  1062. }
  1063. LOG(MCoperatorError, unknownJob, "LDAP stalled - aborting (returning no access for %s)",obj);
  1064. ldapsig.signal();
  1065. if (err)
  1066. *err = CLDAPE_getpermtimeout;
  1067. return 0;
  1068. }
  1069. else {
  1070. unsigned waiting = atomic_read(&ldapwaiting);
  1071. static unsigned last=0;
  1072. static unsigned lasttick=0;
  1073. static unsigned first50=0;
  1074. if ((waiting!=last)&&(msTick()-lasttick>1000)) {
  1075. WARNLOG("%d threads waiting for ldap",waiting);
  1076. last = waiting;
  1077. lasttick = msTick();
  1078. }
  1079. if (waiting>50) {
  1080. if (first50==0)
  1081. first50 = msTick();
  1082. else if (msTick()-first50>60*1000) {
  1083. LOG(MCoperatorError, unknownJob, "LDAP stalled - aborting (returning 0 for %s)", obj);
  1084. if (err)
  1085. *err = CLDAPE_getpermtimeout;
  1086. break;
  1087. }
  1088. }
  1089. else
  1090. first50 = 0;
  1091. }
  1092. }
  1093. atomic_dec(&ldapwaiting);
  1094. return 0;
  1095. #endif
  1096. }
  1097. virtual bool checkScopeScansLDAP()
  1098. {
  1099. #ifdef _NO_LDAP
  1100. return false;
  1101. #else
  1102. return ldapconn?ldapconn->checkScopeScans():false;
  1103. #endif
  1104. }
  1105. virtual unsigned getLDAPflags()
  1106. {
  1107. #ifdef _NO_LDAP
  1108. return 0;
  1109. #else
  1110. return ldapconn?ldapconn->getLDAPflags():0;
  1111. #endif
  1112. }
  1113. void setLDAPflags(unsigned flags)
  1114. {
  1115. #ifndef _NO_LDAP
  1116. if (ldapconn)
  1117. ldapconn->setLDAPflags(flags);
  1118. #endif
  1119. }
  1120. bool authorizeConnection(int role,bool revoke)
  1121. {
  1122. return true;
  1123. }
  1124. SessionId startSession(SecurityToken tok, SessionId parentid)
  1125. {
  1126. return registerSession(tok,parentid);
  1127. }
  1128. void setSessionDependancy(SessionId id , SessionId dependsonid )
  1129. {
  1130. UNIMPLEMENTED; // TBD
  1131. }
  1132. void clearSessionDependancy(SessionId id , SessionId dependsonid )
  1133. {
  1134. UNIMPLEMENTED; // TBD
  1135. }
  1136. protected:
  1137. class CSessionSubscriptionStub: public CInterface
  1138. {
  1139. ISubscription *subs;
  1140. SubscriptionId id;
  1141. SessionId sessid;
  1142. public:
  1143. IMPLEMENT_IINTERFACE;
  1144. CSessionSubscriptionStub(ISubscription *_subs,SubscriptionId _id) // takes ownership
  1145. {
  1146. subs = _subs;
  1147. id = _id;
  1148. const MemoryAttr &ma = subs->queryData();
  1149. MemoryBuffer mb(ma.length(),ma.get());
  1150. mb.read(sessid);
  1151. }
  1152. ~CSessionSubscriptionStub()
  1153. {
  1154. subs->Release();
  1155. }
  1156. SubscriptionId getId() { return id; }
  1157. SessionId getSessionId() { return sessid; }
  1158. void notify(bool abort)
  1159. {
  1160. MemoryBuffer mb;
  1161. mb.append(abort);
  1162. subs->notify(mb);
  1163. }
  1164. };
  1165. CIArrayOf<CSessionSubscriptionStub> stubs;
  1166. unsigned findsub(SubscriptionId id)
  1167. {
  1168. ForEachItemIn(i,stubs) {
  1169. CSessionSubscriptionStub &stub = stubs.item(i);
  1170. if (stub.getId()==id)
  1171. return i;
  1172. }
  1173. return NotFound;
  1174. }
  1175. void add(ISubscription *subs,SubscriptionId id)
  1176. {
  1177. CSessionSubscriptionStub *nstub;
  1178. {
  1179. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  1180. nstub = new CSessionSubscriptionStub(subs,id);
  1181. if (sessionstates.query(nstub->getSessionId())||(nstub->getSessionId()==mySessionId)) {
  1182. stubs.append(*nstub);
  1183. return;
  1184. }
  1185. }
  1186. // see if session known
  1187. MemoryBuffer mb;
  1188. bool abort=true;
  1189. mb.append(abort);
  1190. ERRLOG("Session Manager - adding unknown session ID %"I64F"x", nstub->getSessionId());
  1191. subs->notify(mb);
  1192. delete nstub;
  1193. return;
  1194. }
  1195. void remove(SubscriptionId id)
  1196. {
  1197. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  1198. unsigned i=findsub(id);
  1199. if (i!=NotFound)
  1200. stubs.remove(i);
  1201. }
  1202. void stopSession(SessionId id, bool abort)
  1203. {
  1204. PROGLOG("Session stopping %"I64F"x %s",id,abort?"aborted":"ok");
  1205. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  1206. // do in multiple stages as may remove one or more sub sussions
  1207. loop {
  1208. CIArrayOf<CSessionSubscriptionStub> tonotify;
  1209. for (unsigned i=stubs.ordinality();i;) {
  1210. CSessionSubscriptionStub &stub = stubs.item(--i);
  1211. if (stub.getSessionId()==id) {
  1212. stubs.remove(i, true);
  1213. tonotify.append(stub);
  1214. }
  1215. }
  1216. if (tonotify.ordinality()==0)
  1217. break;
  1218. CHECKEDCRITICALUNBLOCK(sessmanagersect,60000);
  1219. ForEachItemIn(j,tonotify) {
  1220. CSessionSubscriptionStub &stub = tonotify.item(j);
  1221. try { stub.notify(abort); }
  1222. catch (IException *e) { e->Release(); } // subscriber session may abort during stopSession
  1223. }
  1224. }
  1225. const CSessionState *state = sessionstates.query(id);
  1226. if (state) {
  1227. const CProcessSessionState *pstate = QUERYINTERFACE(state,const CProcessSessionState);
  1228. if (pstate)
  1229. processlookup.remove(&pstate->queryNode(),this);
  1230. sessionstates.remove(id);
  1231. }
  1232. }
  1233. void onClose(SocketEndpoint &ep)
  1234. {
  1235. StringBuffer str;
  1236. PROGLOG("Client closed (%s)",ep.getUrlStr(str).str());
  1237. SessionId idtostop;
  1238. {
  1239. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  1240. Owned<INode> node = createINode(ep);
  1241. if (queryCoven().inCoven(node)) {
  1242. StringBuffer str;
  1243. PROGLOG("Coven Session Stopping (%s)",ep.getUrlStr(str).str());
  1244. // more TBD here
  1245. return;
  1246. }
  1247. CProcessSessionState *s= processlookup.query(node);
  1248. if (!s)
  1249. return;
  1250. idtostop = s->getId();
  1251. }
  1252. stopSession(idtostop,true);
  1253. }
  1254. StringBuffer &getClientProcessList(StringBuffer &buf)
  1255. {
  1256. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  1257. unsigned n = processlookup.count();
  1258. CProcessSessionState *s=NULL;
  1259. for (unsigned i=0;i<n;i++) {
  1260. s=processlookup.next(s);
  1261. if (!s)
  1262. break;
  1263. s->getDetails(buf).append('\n');
  1264. }
  1265. return buf;
  1266. }
  1267. StringBuffer &getClientProcessEndpoint(SessionId id,StringBuffer &buf)
  1268. {
  1269. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  1270. const CSessionState *state = sessionstates.query(id);
  1271. if (state) {
  1272. const CProcessSessionState *pstate = QUERYINTERFACE(state,const CProcessSessionState);
  1273. if (pstate)
  1274. return pstate->queryNode().endpoint().getUrlStr(buf);
  1275. }
  1276. return buf;
  1277. }
  1278. unsigned queryClientCount()
  1279. {
  1280. CHECKEDCRITICALBLOCK(sessmanagersect,60000);
  1281. return processlookup.count();
  1282. }
  1283. };
  1284. ISessionManager &querySessionManager()
  1285. {
  1286. CriticalBlock block(sessionCrit);
  1287. if (!SessionManager) {
  1288. assertex(!isCovenActive()||!queryCoven().inCoven()); // Check not Coven server (if occurs - not initialized correctly;
  1289. // If !coven someone is checking for dali so allow
  1290. SessionManager = new CClientSessionManager();
  1291. }
  1292. return *SessionManager;
  1293. }
  1294. class CDaliSessionServer: public CInterface, public IDaliServer
  1295. {
  1296. public:
  1297. IMPLEMENT_IINTERFACE;
  1298. CDaliSessionServer()
  1299. {
  1300. }
  1301. void start()
  1302. {
  1303. CriticalBlock block(sessionCrit);
  1304. assertex(queryCoven().inCoven()); // must be member of coven
  1305. CCovenSessionManager *serv = new CCovenSessionManager();
  1306. SessionManagerServer = serv;
  1307. SessionManager = serv;
  1308. SessionManagerServer->start();
  1309. }
  1310. void suspend()
  1311. {
  1312. }
  1313. void stop()
  1314. {
  1315. CriticalBlock block(sessionCrit);
  1316. SessionManagerServer->stop();
  1317. SessionManagerServer->Release();
  1318. SessionManagerServer = NULL;
  1319. SessionManager = NULL;
  1320. }
  1321. void ready()
  1322. {
  1323. SessionManagerServer->ready();
  1324. }
  1325. void nodeDown(rank_t rank)
  1326. {
  1327. assertex(!"TBD");
  1328. }
  1329. };
  1330. IDaliServer *createDaliSessionServer()
  1331. {
  1332. return new CDaliSessionServer();
  1333. }
  1334. void setLDAPconnection(IDaliLdapConnection *ldapconn)
  1335. {
  1336. if (SessionManagerServer)
  1337. SessionManagerServer->setLDAPconnection(ldapconn);
  1338. }
  1339. void setClientAuth(IDaliClientAuthConnection *authconn)
  1340. {
  1341. if (SessionManagerServer)
  1342. SessionManagerServer->setClientAuth(authconn);
  1343. }
  1344. #define REG_SLEEP 5000
  1345. bool registerClientProcess(ICommunicator *comm, IGroup *& retcoven,unsigned timeout,DaliClientRole role)
  1346. {
  1347. // NB doesn't use coven as not yet set up
  1348. if (comm->queryGroup().ordinality()==0)
  1349. return false;
  1350. CTimeMon tm(timeout);
  1351. retcoven = NULL;
  1352. unsigned nextLog = 0, lastNextLog = 0;
  1353. unsigned t=REG_SLEEP;
  1354. unsigned remaining;
  1355. rank_t r;
  1356. while (!tm.timedout(&remaining)) {
  1357. if (remaining>t)
  1358. remaining = t;
  1359. r = getRandom()%comm->queryGroup().ordinality();
  1360. bool ok = false;
  1361. if (remaining>10000) // MP protocol has a minimum time of 10s so if remaining < 10s use a detachable thread
  1362. ok = comm->verifyConnection(r,remaining);
  1363. else {
  1364. struct cThread: public Thread
  1365. {
  1366. IMPLEMENT_IINTERFACE;
  1367. Semaphore sem;
  1368. Linked<ICommunicator> comm;
  1369. bool ok;
  1370. Owned<IException> exc;
  1371. unsigned remaining;
  1372. rank_t r;
  1373. cThread(ICommunicator *_comm,rank_t _r,unsigned _remaining)
  1374. : Thread ("dasess.registerClientProcess"), comm(_comm)
  1375. {
  1376. r = _r;
  1377. remaining = _remaining;
  1378. ok = false;
  1379. }
  1380. int run()
  1381. {
  1382. try {
  1383. if (comm->verifyConnection(r,remaining))
  1384. ok = true;
  1385. }
  1386. catch (IException *e)
  1387. {
  1388. exc.setown(e);
  1389. }
  1390. sem.signal();
  1391. return 0;
  1392. }
  1393. } *t = new cThread(comm,r,remaining);
  1394. t->start();
  1395. t->sem.wait(remaining);
  1396. ok = t->ok;
  1397. if (t->exc.get()) {
  1398. IException *e = t->exc.getClear();
  1399. t->Release();
  1400. throw e;
  1401. }
  1402. t->Release();
  1403. }
  1404. if (ok) {
  1405. CMessageBuffer mb;
  1406. mb.append((int)MSR_REGISTER_PROCESS_SESSION);
  1407. queryMyNode()->serialize(mb);
  1408. comm->queryGroup().queryNode(r).serialize(mb);
  1409. mb.append((int)role);
  1410. if (comm->sendRecv(mb,r,MPTAG_DALI_SESSION_REQUEST,SESSIONREPLYTIMEOUT)) {
  1411. if (!mb.length())
  1412. {
  1413. // failed system capability match,
  1414. retcoven = comm->getGroup(); // continue as if - will fail later more obscurely.
  1415. return true;
  1416. }
  1417. mb.read(mySessionId);
  1418. retcoven = deserializeIGroup(mb);
  1419. return true;
  1420. }
  1421. }
  1422. StringBuffer str;
  1423. PROGLOG("Failed to connect to Dali Server %s.", comm->queryGroup().queryNode(r).endpoint().getUrlStr(str).str());
  1424. if (tm.timedout())
  1425. {
  1426. PROGLOG("%s", str.append(" Timed out.").str());
  1427. break;
  1428. }
  1429. else if (0 == nextLog)
  1430. {
  1431. PROGLOG("%s", str.append(" Retrying...").str());
  1432. if ((lastNextLog * REG_SLEEP) >= 60000) // limit to a minute between logging
  1433. nextLog = 60000 / REG_SLEEP;
  1434. else
  1435. nextLog = lastNextLog + 2; // wait +2 REG_SLEEP pauses before next logging
  1436. lastNextLog = nextLog;
  1437. }
  1438. else
  1439. --nextLog;
  1440. Sleep(REG_SLEEP);
  1441. }
  1442. return false;
  1443. }
  1444. extern void stopClientProcess()
  1445. {
  1446. CriticalBlock block(sessionCrit);
  1447. if (mySessionId&&SessionManager) {
  1448. try {
  1449. querySessionManager().stopSession(mySessionId,false);
  1450. }
  1451. catch (IDaliClient_Exception *e) {
  1452. if (e->errorCode()!=DCERR_server_closed)
  1453. throw;
  1454. e->Release();
  1455. }
  1456. mySessionId = 0;
  1457. }
  1458. }
  1459. class CProcessSessionWatchdog
  1460. {
  1461. };
  1462. class CUserDescriptor: public CInterface, implements IUserDescriptor
  1463. {
  1464. StringAttr username;
  1465. StringAttr passwordenc;
  1466. public:
  1467. IMPLEMENT_IINTERFACE;
  1468. StringBuffer &getUserName(StringBuffer &buf)
  1469. {
  1470. return buf.append(username);
  1471. }
  1472. StringBuffer &getPassword(StringBuffer &buf)
  1473. {
  1474. decrypt(buf,passwordenc);
  1475. return buf;
  1476. }
  1477. virtual void set(const char *name,const char *password)
  1478. {
  1479. username.set(name);
  1480. StringBuffer buf;
  1481. encrypt(buf,password);
  1482. passwordenc.set(buf.str());
  1483. }
  1484. virtual void clear()
  1485. {
  1486. username.clear();
  1487. passwordenc.clear();
  1488. }
  1489. void serialize(MemoryBuffer &mb)
  1490. {
  1491. mb.append(username).append(passwordenc);
  1492. }
  1493. void deserialize(MemoryBuffer &mb)
  1494. {
  1495. mb.read(username).read(passwordenc);
  1496. }
  1497. };
  1498. IUserDescriptor *createUserDescriptor()
  1499. {
  1500. return new CUserDescriptor;
  1501. }
  1502. MODULE_INIT(INIT_PRIORITY_DALI_DASESS)
  1503. {
  1504. return true;
  1505. }
  1506. MODULE_EXIT()
  1507. {
  1508. ::Release(SessionManager);
  1509. SessionManager = NULL;
  1510. }