jutil.cpp 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813
  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. #ifdef _WIN32
  14. #pragma warning(disable: 4996)
  15. #include "winprocess.hpp"
  16. #include <conio.h>
  17. #endif
  18. #include "platform.h"
  19. #include "jmisc.hpp"
  20. #include "jutil.hpp"
  21. #include "jexcept.hpp"
  22. #include "jmutex.hpp"
  23. #include "jfile.hpp"
  24. #include "jprop.hpp"
  25. #include "jerror.hpp"
  26. #ifdef _WIN32
  27. #include <mmsystem.h> // for timeGetTime
  28. #include <float.h> //for _isnan and _fpclass
  29. #else
  30. #include <unistd.h> // read()
  31. #include <sys/wait.h>
  32. #include <pwd.h>
  33. #ifdef __linux__
  34. #include <crypt.h>
  35. #include <shadow.h>
  36. #endif
  37. #include <time.h>
  38. #include <stdio.h>
  39. #include <stdlib.h>
  40. #include <termios.h>
  41. #include <signal.h>
  42. #include <paths.h>
  43. #include <cmath>
  44. #endif
  45. #include "build-config.h"
  46. #include "portlist.h"
  47. static NonReentrantSpinLock * cvtLock;
  48. #ifdef _WIN32
  49. static IRandomNumberGenerator * protectedGenerator;
  50. static CriticalSection * protectedGeneratorCs;
  51. #endif
  52. #if defined (__APPLE__)
  53. #include <mach-o/dyld.h>
  54. #include <mach/mach_time.h> /* mach_absolute_time */
  55. mach_timebase_info_data_t timebase_info = { 1,1 };
  56. #endif
  57. MODULE_INIT(INIT_PRIORITY_SYSTEM)
  58. {
  59. cvtLock = new NonReentrantSpinLock;
  60. #ifdef _WIN32
  61. protectedGenerator = createRandomNumberGenerator();
  62. protectedGeneratorCs = new CriticalSection;
  63. #endif
  64. #if defined (__APPLE__)
  65. if (mach_timebase_info(&timebase_info) != KERN_SUCCESS)
  66. return false;
  67. #endif
  68. return true;
  69. }
  70. MODULE_EXIT()
  71. {
  72. delete cvtLock;
  73. #ifdef _WIN32
  74. protectedGenerator->Release();
  75. delete protectedGeneratorCs;
  76. #endif
  77. }
  78. //===========================================================================
  79. bool safe_ecvt(size_t len, char * buffer, double value, int numDigits, int * decimal, int * sign)
  80. {
  81. #ifdef _WIN32
  82. return _ecvt_s(buffer, len, value, numDigits, decimal, sign) == 0;
  83. #else
  84. NonReentrantSpinBlock block(*cvtLock);
  85. const char * result = ecvt(value, numDigits, decimal, sign);
  86. if (!result)
  87. return false;
  88. strncpy(buffer, result, len);
  89. return true;
  90. #endif
  91. }
  92. bool safe_fcvt(size_t len, char * buffer, double value, int numPlaces, int * decimal, int * sign)
  93. {
  94. #ifdef _WIN32
  95. return _fcvt_s(buffer, len, value, numPlaces, decimal, sign) == 0;
  96. #else
  97. NonReentrantSpinBlock block(*cvtLock);
  98. const char * result = fcvt(value, numPlaces, decimal, sign);
  99. if (!result)
  100. return false;
  101. strncpy(buffer, result, len);
  102. return true;
  103. #endif
  104. }
  105. //===========================================================================
  106. bool j_isnan(double x)
  107. {
  108. #ifdef _MSC_VER
  109. return _isnan(x)!=0;
  110. #else
  111. return std::isnan(x);
  112. #endif
  113. }
  114. bool j_isinf(double x)
  115. {
  116. #ifdef _MSC_VER
  117. int fpv = _fpclass(x);
  118. return (fpv==_FPCLASS_PINF || fpv==_FPCLASS_NINF);
  119. #else
  120. return std::isinf(x);
  121. #endif
  122. }
  123. #ifdef _WIN32
  124. void MilliSleep(unsigned milli)
  125. {
  126. Sleep(milli);
  127. }
  128. #else
  129. void MilliSleep(unsigned milli)
  130. {
  131. if (milli) {
  132. unsigned target = msTick()+milli;
  133. for (;;) {
  134. timespec sleepTime;
  135. if (milli>=1000)
  136. {
  137. sleepTime.tv_sec = milli/1000;
  138. milli %= 1000;
  139. }
  140. else
  141. sleepTime.tv_sec = 0;
  142. sleepTime.tv_nsec = milli * 1000000;
  143. if (nanosleep(&sleepTime, NULL)==0)
  144. break;
  145. if (errno!=EINTR) {
  146. PROGLOG("MilliSleep err %d",errno);
  147. break;
  148. }
  149. milli = target-msTick();
  150. if ((int)milli<=0)
  151. break;
  152. }
  153. }
  154. else
  155. ThreadYield(); // 0 means yield
  156. }
  157. #endif
  158. long atolong_l(const char * s,int l)
  159. {
  160. char t[32];
  161. memcpy(t,s,l);
  162. t[l]=0;
  163. return atol(t);
  164. }
  165. int atoi_l(const char * s,int l)
  166. {
  167. char t[32];
  168. memcpy(t,s,l);
  169. t[l]=0;
  170. return atoi(t);
  171. }
  172. __int64 atoi64_l(const char * s,int l)
  173. {
  174. __int64 result = 0;
  175. char sign = '+';
  176. while (l>0 && isspace(*s))
  177. {
  178. l--;
  179. s++;
  180. }
  181. if (l>0 && (*s == '-' || *s == '+'))
  182. {
  183. sign = *s;
  184. l--;
  185. s++;
  186. }
  187. while (l>0 && isdigit(*s))
  188. {
  189. result = 10 * result + ((*s) - '0');
  190. l--;
  191. s++;
  192. }
  193. if (sign == '-')
  194. return -result;
  195. else
  196. return result;
  197. }
  198. #ifndef _WIN32
  199. static char *_itoa(unsigned long n, char *str, int b, bool sign)
  200. {
  201. char *s = str;
  202. if (sign)
  203. n = -n;
  204. do
  205. {
  206. byte d = n % b;
  207. *(s++) = d+((d<10)?'0':('a'-10));
  208. }
  209. while ((n /= b) > 0);
  210. if (sign)
  211. *(s++) = '-';
  212. *s = '\0';
  213. // reverse
  214. char *s2 = str;
  215. s--;
  216. while (s2<s)
  217. {
  218. char tc = *s2;
  219. *(s2++) = *s;
  220. *(s--) = tc;
  221. }
  222. return str;
  223. }
  224. char *itoa(int n, char *str, int b)
  225. {
  226. return _itoa(n, str, b, (n<0));
  227. }
  228. char *ltoa(long n, char *str, int b)
  229. {
  230. return _itoa(n, str, b, (n<0));
  231. }
  232. char *ultoa(unsigned long n, char *str, int b)
  233. {
  234. return _itoa(n, str, b, false);
  235. }
  236. #endif
  237. void packNumber(char * target, const char * source, unsigned slen)
  238. {
  239. unsigned next = 0;
  240. while (slen)
  241. {
  242. unsigned c = *source++;
  243. if (c == ' ') c = '0';
  244. next = (next << 4) + (c - '0');
  245. slen--;
  246. if ((slen & 1) == 0)
  247. {
  248. *target++ = next;
  249. next = 0;
  250. }
  251. }
  252. }
  253. void unpackNumber(char * target, const char * source, unsigned tlen)
  254. {
  255. if (tlen & 1)
  256. {
  257. *target = '0' + *source++;
  258. tlen--;
  259. }
  260. while (tlen)
  261. {
  262. unsigned char next = *source++;
  263. *target++ = (next >> 4) + '0';
  264. *target++ = (next & 15) + '0';
  265. tlen -= 2;
  266. }
  267. }
  268. //-----------------------------------------------------------------------
  269. class jlib_thrown_decl CorruptDllException : public CInterfaceOf<ICorruptDllException>
  270. {
  271. public:
  272. CorruptDllException(int code, const char *_dllName, const char *_dlError)
  273. : errcode(code)
  274. {
  275. VStringBuffer s("Error loading %s: %s", _dllName, _dlError);
  276. msg.set(s.str());
  277. };
  278. int errorCode() const { return errcode; }
  279. StringBuffer & errorMessage(StringBuffer &str) const
  280. {
  281. return str.append(msg.get());
  282. }
  283. MessageAudience errorAudience() const
  284. {
  285. return MSGAUD_operator;
  286. }
  287. private:
  288. int errcode;
  289. StringAttr msg;
  290. };
  291. static bool isCorruptDll(const char *errorMessage)
  292. {
  293. // yuk.
  294. // Add other error strings for corrupt .so files as/when we encounter them
  295. if (strstr(errorMessage, "file too short") ||
  296. strstr(errorMessage, "ELF load command past end of file"))
  297. return true;
  298. return false;
  299. }
  300. //-----------------------------------------------------------------------
  301. #ifdef __APPLE__
  302. bool findLoadedModule(StringBuffer &ret, const char *match)
  303. {
  304. bool found = false;
  305. unsigned count = _dyld_image_count();
  306. for (unsigned i = 0; i<count; i++)
  307. {
  308. const char *ln = _dyld_get_image_name(i);
  309. if (ln)
  310. {
  311. if (strstr(ln, match))
  312. {
  313. ret.set(ln);
  314. found = true;
  315. break;
  316. }
  317. }
  318. }
  319. return found;
  320. }
  321. #elif !defined(WIN32)
  322. bool findLoadedModule(StringBuffer &ret, const char *match)
  323. {
  324. bool found = false;
  325. FILE *diskfp = fopen("/proc/self/maps", "r");
  326. if (diskfp)
  327. {
  328. char ln[_MAX_PATH];
  329. while (fgets(ln, sizeof(ln), diskfp))
  330. {
  331. if (strstr(ln, match))
  332. {
  333. const char *fullName = strchr(ln, '/');
  334. if (fullName)
  335. {
  336. char * lf = (char *) strchr(fullName, '\n');
  337. if (lf)
  338. {
  339. *lf = 0;
  340. ret.set(fullName);
  341. found = true;
  342. break;
  343. }
  344. }
  345. }
  346. }
  347. fclose(diskfp);
  348. }
  349. return found;
  350. }
  351. #endif
  352. HINSTANCE LoadSharedObject(const char *name, bool isGlobal, bool raiseOnError)
  353. {
  354. #if defined(_WIN32)
  355. UINT oldMode = SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);
  356. #else
  357. // don't think anything to do here.
  358. #endif
  359. DynamicScopeCtx scope;
  360. StringBuffer tmp;
  361. if (name&&isPathSepChar(*name)&&isPathSepChar(name[1])) {
  362. RemoteFilename rfn;
  363. rfn.setRemotePath(name);
  364. SocketEndpoint ep;
  365. if (!rfn.isLocal()) {
  366. // I guess could copy to a temporary location but currently just fail
  367. throw MakeStringException(-1,"LoadSharedObject: %s is not a local file",name);
  368. }
  369. name = rfn.getLocalPath(tmp).str();
  370. }
  371. #if defined(_WIN32)
  372. HINSTANCE h = LoadLibrary(name);
  373. if (!LoadSucceeded(h))
  374. {
  375. int errcode = GetLastError();
  376. StringBuffer errmsg;
  377. formatSystemError(errmsg, errcode);
  378. //Strip trailing newlines - makes output/errors messages cleaner
  379. unsigned len = errmsg.length();
  380. while (len)
  381. {
  382. char c = errmsg.charAt(len-1);
  383. if ((c != '\r') && (c != '\n'))
  384. break;
  385. len--;
  386. }
  387. errmsg.setLength(len);
  388. DBGLOG("Error loading %s: %d - %s", name, errcode, errmsg.str());
  389. if (raiseOnError)
  390. throw MakeStringException(0, "Error loading %s: %d - %s", name, errcode, errmsg.str());
  391. }
  392. #else
  393. HINSTANCE h = dlopen((char *)name, isGlobal ? RTLD_NOW|RTLD_GLOBAL : RTLD_NOW);
  394. if(h == NULL)
  395. {
  396. // Try again, with .so extension if necessary
  397. StringBuffer path, tail, ext;
  398. splitFilename(name, &path, &path, &tail, &ext, false);
  399. if (!streq(ext.str(), SharedObjectExtension))
  400. {
  401. // Assume if there's no .so, there may also be no lib at the beginning
  402. if (strncmp(tail.str(), SharedObjectPrefix, strlen(SharedObjectPrefix)) != 0)
  403. path.append(SharedObjectPrefix);
  404. path.append(tail).append(ext).append(SharedObjectExtension);
  405. name = path.str();
  406. h = dlopen((char *)name, isGlobal ? RTLD_NOW|RTLD_GLOBAL : RTLD_NOW);
  407. }
  408. if (h == NULL)
  409. {
  410. StringBuffer dlErrorMsg(dlerror());
  411. DBGLOG("Warning: Could not load %s: %s", name, dlErrorMsg.str());
  412. if (raiseOnError)
  413. {
  414. if (isCorruptDll(dlErrorMsg.str()))
  415. throw new CorruptDllException(errno, name, dlErrorMsg.str());
  416. else
  417. throw MakeStringException(0, "Error loading %s: %s", name, dlErrorMsg.str());
  418. }
  419. }
  420. }
  421. #endif
  422. scope.setSoContext(h);
  423. #if defined(_WIN32)
  424. SetErrorMode(oldMode);
  425. #else
  426. // don't think anything to do here.
  427. #endif
  428. return h;
  429. }
  430. void FreeSharedObject(HINSTANCE h)
  431. {
  432. ExitModuleObjects(h);
  433. #if defined(_WIN32)
  434. FreeLibrary(h);
  435. #else
  436. dlclose(h);
  437. #endif
  438. }
  439. bool SharedObject::load(const char * dllName, bool isGlobal, bool raiseOnError)
  440. {
  441. unload();
  442. #ifdef _WIN32
  443. UINT oldMode = SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);
  444. if (dllName)
  445. {
  446. h=LoadSharedObject(dllName, isGlobal, raiseOnError);
  447. bRefCounted = true;
  448. }
  449. else
  450. {
  451. h=GetModuleHandle(NULL);
  452. bRefCounted = false;
  453. }
  454. SetErrorMode(oldMode);
  455. #else
  456. h=LoadSharedObject(dllName, isGlobal, raiseOnError);
  457. bRefCounted = true;
  458. #endif
  459. if (!LoadSucceeded(h))
  460. {
  461. h = 0;
  462. return false;
  463. }
  464. return true;
  465. }
  466. bool SharedObject::loadCurrentExecutable()
  467. {
  468. unload();
  469. #ifdef _WIN32
  470. h=GetModuleHandle(NULL);
  471. bRefCounted = false;
  472. #else
  473. h=dlopen(NULL, RTLD_NOW);
  474. bRefCounted = true;
  475. #endif
  476. return true;
  477. }
  478. bool SharedObject::loadResources(const char * dllName)
  479. {
  480. #ifdef _WIN32
  481. UINT oldMode = SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);
  482. h = LoadLibraryEx(dllName, NULL, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);
  483. if (!LoadSucceeded(h))
  484. h = LoadLibraryEx(dllName, NULL, LOAD_LIBRARY_AS_DATAFILE); // the LOAD_LIBRARY_AS_IMAGE_RESOURCE flag is not supported on all versions of Windows
  485. SetErrorMode(oldMode);
  486. return LoadSucceeded(h);
  487. #else
  488. UNIMPLEMENTED;
  489. #endif
  490. }
  491. void *SharedObject::getEntry(const char * name) const
  492. {
  493. return GetSharedProcedure(getInstanceHandle(), name);
  494. }
  495. void SharedObject::unload()
  496. {
  497. if (h && bRefCounted) FreeSharedObject(h);
  498. h = 0;
  499. }
  500. //-----------------------------------------------------------------------
  501. IPluggableFactory *loadPlugin(const IPropertyTree *pluginInfo)
  502. {
  503. const char *pluginName = pluginInfo->queryProp("@pluginName");
  504. const char *entrypoint = pluginInfo->queryProp("@entrypoint");
  505. if (!pluginName || !entrypoint)
  506. throw makeStringException(0, "Plugin information missing plugin name or entrypoint");
  507. Owned<SharedObject> pluginDll = new SharedObject;
  508. if (!pluginDll->load(pluginName, false, true))
  509. throw makeStringExceptionV(0, "Failed to load plugin %s", pluginName);
  510. IPluggableFactoryFactory pf = (IPluggableFactoryFactory) pluginDll->getEntry(entrypoint);
  511. if (!pf)
  512. throw makeStringExceptionV(0, "Function %s not found in plugin %s", entrypoint, pluginName);
  513. IPluggableFactory *factory = pf(pluginDll, pluginInfo);
  514. if (!factory)
  515. throw makeStringExceptionV(0, "Factory function %s returned NULL in plugin %s", entrypoint, pluginName);
  516. return factory;
  517. }
  518. //-----------------------------------------------------------------------
  519. /*
  520. We use a 64 bit number for generating temporaries so that we are unlikely to get any
  521. clashes (being paranoid). This should mean if a temporary ID is allocated 1,000,000,000
  522. times a second, then we won't repeat until 400 years later - assuming the machine stays
  523. alive for that long.
  524. Using a 32 bit number we loop after about an hour if we allocated 1,000,000 a second -
  525. not an unreasonable estimate for the future.
  526. */
  527. static unique_id_t nextTemporaryId;
  528. StringBuffer & appendUniqueId(StringBuffer & target, unique_id_t value)
  529. {
  530. //Just generate a temporary name from the __int64 -
  531. //Don't care about the format, therfore use base 32 in reverse order.
  532. while (value)
  533. {
  534. unsigned next = ((unsigned)value) & 31;
  535. value = value >> 5;
  536. if (next < 10)
  537. target.append((char)(next+'0'));
  538. else
  539. target.append((char)(next+'A'-10));
  540. }
  541. return target;
  542. }
  543. unique_id_t getUniqueId()
  544. {
  545. return ++nextTemporaryId;
  546. }
  547. StringBuffer & getUniqueId(StringBuffer & target)
  548. {
  549. return appendUniqueId(target, ++nextTemporaryId);
  550. }
  551. void resetUniqueId()
  552. {
  553. nextTemporaryId = 0;
  554. }
  555. //-----------------------------------------------------------------------
  556. #define make_numtostr(VTYPE) \
  557. int numtostr(char *dst, signed VTYPE _value) \
  558. { \
  559. int c; \
  560. unsigned VTYPE value; \
  561. if (_value<0) \
  562. { \
  563. *(dst++) = '-'; \
  564. value = (unsigned VTYPE) -_value; \
  565. c = 1; \
  566. } \
  567. else \
  568. { \
  569. c = 0; \
  570. value = _value; \
  571. } \
  572. char temp[11], *end = temp+10; \
  573. char *tmp = end; \
  574. *tmp = '\0'; \
  575. \
  576. while (value>=10) \
  577. { \
  578. unsigned VTYPE next = value / 10; \
  579. *(--tmp) = ((char)(value-next*10))+'0'; \
  580. value = next; \
  581. } \
  582. *(--tmp) = ((char)value)+'0'; \
  583. \
  584. int diff = (int)(end-tmp); \
  585. int i=diff+1; \
  586. while (i--) *(dst++) = *(tmp++); \
  587. \
  588. return c+diff; \
  589. }
  590. #define make_unumtostr(VTYPE) \
  591. int numtostr(char *dst, unsigned VTYPE value) \
  592. { \
  593. char temp[11], *end = temp+10; \
  594. char *tmp = end; \
  595. *tmp = '\0'; \
  596. \
  597. while (value>=10) \
  598. { \
  599. unsigned VTYPE next = value / 10; \
  600. *(--tmp) = ((char)(value-next*10))+'0'; \
  601. value = next; \
  602. } \
  603. *(--tmp) = ((char)value)+'0'; \
  604. \
  605. int diff = (int)(end-tmp); \
  606. int i=diff+1; \
  607. while (i--) *(dst++) = *(tmp++); \
  608. \
  609. return diff; \
  610. }
  611. make_numtostr(char);
  612. make_numtostr(short);
  613. make_numtostr(int);
  614. make_numtostr(long);
  615. make_unumtostr(char);
  616. make_unumtostr(short);
  617. make_unumtostr(int);
  618. make_unumtostr(long);
  619. int numtostr(char *dst, __int64 _value)
  620. {
  621. int c;
  622. unsigned __int64 value;
  623. if (_value<0)
  624. {
  625. *(dst++) = '-';
  626. value = (unsigned __int64) -_value;
  627. c = 1;
  628. }
  629. else
  630. {
  631. value = _value;
  632. c = 0;
  633. }
  634. char temp[24], *end = temp+23, *tmp = end;
  635. *tmp = '\0';
  636. unsigned __int32 v3 = (unsigned __int32)(value / LLC(10000000000));
  637. unsigned __int64 vv = value - ((unsigned __int64)v3*LLC(10000000000));
  638. unsigned __int32 v2 = (unsigned __int32)(vv / 100000);
  639. unsigned __int32 v1 = (unsigned __int32) (vv - (v2 * 100000));
  640. unsigned __int32 next;
  641. while (v1>=10)
  642. {
  643. next = v1/10;
  644. *(--tmp) = ((char)(v1-next*10))+'0';
  645. v1 = next;
  646. }
  647. *(--tmp) = ((char)v1)+'0';
  648. if (v2)
  649. {
  650. char *d = end-5;
  651. while (d != tmp)
  652. *(--tmp) = '0';
  653. while (v2>=10)
  654. {
  655. next = v2/10;
  656. *(--tmp) = ((char)(v2-next*10))+'0';
  657. v2 = next;
  658. }
  659. *(--tmp) = ((char)v2)+'0';
  660. }
  661. if (v3)
  662. {
  663. char *d = end-10;
  664. while (d != tmp)
  665. *(--tmp) = '0';
  666. while (v3>=10)
  667. {
  668. next = v3/10;
  669. *(--tmp) = ((char)(v3-next*10))+'0';
  670. v3 = next;
  671. }
  672. *(--tmp) = ((char)v3)+'0';
  673. }
  674. int diff = (int)(end-tmp);
  675. #ifdef USEMEMCPY
  676. memcpy(dst, tmp, diff+1);
  677. #else
  678. int i=diff+1;
  679. while (i--)
  680. { *(dst++) = *(tmp++);
  681. }
  682. #endif
  683. return c+diff;
  684. }
  685. int numtostr(char *dst, unsigned __int64 value)
  686. {
  687. char temp[24], *end = temp+23, *tmp = end;
  688. *tmp = '\0';
  689. unsigned __int32 v3 = (unsigned __int32)(value / LLC(10000000000));
  690. unsigned __int64 vv = value - ((unsigned __int64)v3*LLC(10000000000));
  691. unsigned __int32 v2 = (unsigned __int32)(vv / 100000);
  692. unsigned __int32 v1 = (unsigned __int32) (vv - (v2 * 100000));
  693. unsigned __int32 next;
  694. while (v1>=10)
  695. {
  696. next = v1/10;
  697. *(--tmp) = ((char)(v1-next*10))+'0';
  698. v1 = next;
  699. }
  700. *(--tmp) = ((char)v1)+'0';
  701. if (v2)
  702. {
  703. char *d = end-5;
  704. while (d != tmp)
  705. *(--tmp) = '0';
  706. while (v2>=10)
  707. {
  708. next = v2/10;
  709. *(--tmp) = ((char)(v2-next*10))+'0';
  710. v2 = next;
  711. }
  712. *(--tmp) = ((char)v2)+'0';
  713. }
  714. if (v3)
  715. {
  716. char *d = end-10;
  717. while (d != tmp)
  718. *(--tmp) = '0';
  719. while (v3>=10)
  720. {
  721. next = v3/10;
  722. *(--tmp) = ((char)(v3-next*10))+'0';
  723. v3 = next;
  724. }
  725. *(--tmp) = ((char)v3)+'0';
  726. }
  727. int diff = (int)(end-tmp);
  728. #ifdef USEMEMCPY
  729. memcpy(dst, tmp, diff+1);
  730. #else
  731. int i=diff+1;
  732. while (i--)
  733. { *(dst++) = *(tmp++);
  734. }
  735. #endif
  736. return diff;
  737. }
  738. class CRandom: public IRandomNumberGenerator, public CInterface
  739. {
  740. // from Knuth if I remember correctly
  741. #define HISTORYSIZE 55
  742. #define HISTORYMAX (HISTORYSIZE-1)
  743. unsigned history[HISTORYSIZE];
  744. unsigned ptr;
  745. unsigned lower;
  746. public:
  747. IMPLEMENT_IINTERFACE;
  748. CRandom()
  749. {
  750. seed((unsigned)get_cycles_now());
  751. }
  752. void seed(unsigned su)
  753. {
  754. ptr = HISTORYMAX;
  755. lower = 23;
  756. double s = 91648253+su;
  757. double a = 1389796;
  758. double m = 2147483647;
  759. unsigned i;
  760. for (i=0;i<HISTORYSIZE;i++) { // just used for initialization
  761. s *= a;
  762. int q = (int)(s/m);
  763. s -= q*m;
  764. history[i] = (unsigned)s;
  765. }
  766. }
  767. unsigned next()
  768. {
  769. if (ptr==0) {
  770. ptr = HISTORYMAX;
  771. lower--;
  772. }
  773. else {
  774. ptr--;
  775. if (lower==0)
  776. lower = HISTORYMAX;
  777. else
  778. lower--;
  779. }
  780. unsigned ret = history[ptr]+history[lower];
  781. history[ptr] = ret;
  782. return ret;
  783. }
  784. } RandomMain;
  785. static CriticalSection gobalRandomSect;
  786. unsigned getRandom()
  787. {
  788. CriticalBlock block(gobalRandomSect); // this is a shame but it is not thread-safe without
  789. return RandomMain.next();
  790. }
  791. void seedRandom(unsigned seed)
  792. {
  793. CriticalBlock block(gobalRandomSect);
  794. RandomMain.seed(seed);
  795. }
  796. IRandomNumberGenerator *createRandomNumberGenerator()
  797. {
  798. return new CRandom();
  799. }
  800. #ifdef WIN32
  801. // This function has the same prototype for rand_r, but seed is ignored.
  802. jlib_decl int rand_r(unsigned int *seed)
  803. {
  804. CriticalBlock procedure(*protectedGeneratorCs);
  805. return (protectedGenerator->next() & RAND_R_MAX);
  806. }
  807. #if ((RAND_R_MAX & (RAND_R_MAX+1)) != 0)
  808. #error RAND_R_MAX expected to be 2^n-1
  809. #endif
  810. #endif
  811. class CShuffledIterator: implements IShuffledIterator, public CInterface
  812. {
  813. CRandom rand;
  814. unsigned *seq;
  815. unsigned idx;
  816. unsigned num;
  817. public:
  818. IMPLEMENT_IINTERFACE;
  819. CShuffledIterator(unsigned _num)
  820. {
  821. num = _num;
  822. idx = 0;
  823. seq = NULL;
  824. }
  825. ~CShuffledIterator()
  826. {
  827. delete [] seq;
  828. }
  829. bool first()
  830. {
  831. if (!seq)
  832. seq = new unsigned[num];
  833. idx = 0;
  834. if (!num)
  835. return false;
  836. unsigned i;
  837. for (i=0;i<num;i++)
  838. seq[i] = i;
  839. while (i>1) {
  840. unsigned j = rand.next()%i; // NB i is correct here
  841. i--;
  842. unsigned t = seq[j];
  843. seq[j] = seq[i];
  844. seq[i] = t;
  845. }
  846. return true;
  847. }
  848. bool isValid()
  849. {
  850. return idx<num;
  851. }
  852. bool next()
  853. {
  854. if (idx<num)
  855. idx++;
  856. return isValid();
  857. }
  858. unsigned get()
  859. {
  860. return lookup(idx);
  861. }
  862. unsigned lookup(unsigned i)
  863. {
  864. if (!seq)
  865. first();
  866. return seq[i%num];
  867. }
  868. void seed(unsigned su)
  869. {
  870. rand.seed(su);
  871. }
  872. };
  873. extern jlib_decl IShuffledIterator *createShuffledIterator(unsigned n)
  874. {
  875. return new CShuffledIterator(n);
  876. }
  877. /* Check whether a string is a valid C identifier. */
  878. bool isCIdentifier(const char* id)
  879. {
  880. if (id==NULL || *id==0)
  881. return false;
  882. if (!isalpha(*id) && *id!='_')
  883. return false;
  884. for (++id; *id != 0; id++)
  885. if (!isalnum(*id) && *id!='_')
  886. return false;
  887. return true;
  888. }
  889. //-------------------------------------------------------------------
  890. static const char BASE64_enc[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  891. "abcdefghijklmnopqrstuvwxyz"
  892. "0123456789+/";
  893. static const unsigned char BASE64_dec[256] =
  894. {
  895. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  896. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  897. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x3f,
  898. 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  899. 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
  900. 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00,
  901. 0x00, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
  902. 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00,
  903. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  904. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  905. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  906. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  907. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  908. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  909. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  910. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
  911. static const char pad = '=';
  912. //
  913. // Encode the input in a base64 format
  914. //
  915. // const void * data -> data to be encoded
  916. // long length -> length in bytes of this data
  917. // IIOStream &out -> Write the result into this stream
  918. //
  919. void JBASE64_Encode(const void *data, long length, IIOStream &out, bool addLineBreaks/*=true*/)
  920. {
  921. const unsigned char *in = static_cast<const unsigned char *>(data);
  922. unsigned char one;
  923. unsigned char two;
  924. unsigned char three;
  925. long i;
  926. for(i = 0; i < length && length - i >= 3;)
  927. {
  928. one = *(in + i++);
  929. two = *(in + i++);
  930. three = *(in + i++);
  931. // 0x30 -> 0011 0000 b
  932. // 0x3c -> 0011 1100 b
  933. // 0x3f -> 0011 1111 b
  934. //
  935. writeCharToStream(out, BASE64_enc[one >> 2]);
  936. writeCharToStream(out, BASE64_enc[((one << 4) & 0x30) | (two >> 4)]);
  937. writeCharToStream(out, BASE64_enc[((two << 2) & 0x3c) | (three >> 6)]);
  938. writeCharToStream(out, BASE64_enc[three & 0x3f]);
  939. if(addLineBreaks && (i % 54 == 0))
  940. {
  941. writeCharToStream(out, '\n');
  942. }
  943. }
  944. switch(length - i)
  945. {
  946. case 2:
  947. one = *(in + i++);
  948. two = *(in + i++);
  949. writeCharToStream(out, BASE64_enc[one >> 2]);
  950. writeCharToStream(out, BASE64_enc[((one << 4) & 0x30) | (two >> 4)]);
  951. writeCharToStream(out, BASE64_enc[(two << 2) & 0x3c]);
  952. writeCharToStream(out, pad);
  953. break;
  954. case 1:
  955. one = *(in + i++);
  956. writeCharToStream(out, BASE64_enc[one >> 2]);
  957. writeCharToStream(out, BASE64_enc[(one << 4) & 0x30]);
  958. writeCharToStream(out, pad);
  959. writeCharToStream(out, pad);
  960. break;
  961. }
  962. }
  963. // JCSMORE could have IIOStream StringBuffer adapter inplace of below.
  964. void JBASE64_Encode(const void *data, long length, StringBuffer &out, bool addLineBreaks/*=true*/)
  965. {
  966. const unsigned char *in = static_cast<const unsigned char *>(data);
  967. unsigned char one;
  968. unsigned char two;
  969. unsigned char three;
  970. long i;
  971. for(i = 0; i < length && length - i >= 3;)
  972. {
  973. one = *(in + i++);
  974. two = *(in + i++);
  975. three = *(in + i++);
  976. // 0x30 -> 0011 0000 b
  977. // 0x3c -> 0011 1100 b
  978. // 0x3f -> 0011 1111 b
  979. //
  980. out.append(BASE64_enc[one >> 2]);
  981. out.append(BASE64_enc[((one << 4) & 0x30) | (two >> 4)]);
  982. out.append(BASE64_enc[((two << 2) & 0x3c) | (three >> 6)]);
  983. out.append(BASE64_enc[three & 0x3f]);
  984. if(addLineBreaks && (i % 54 == 0))
  985. {
  986. out.append('\n');
  987. }
  988. }
  989. switch(length - i)
  990. {
  991. case 2:
  992. one = *(in + i++);
  993. two = *(in + i++);
  994. out.append(BASE64_enc[one >> 2]);
  995. out.append(BASE64_enc[((one << 4) & 0x30) | (two >> 4)]);
  996. out.append(BASE64_enc[(two << 2) & 0x3c]);
  997. out.append(pad);
  998. break;
  999. case 1:
  1000. one = *(in + i++);
  1001. out.append(BASE64_enc[one >> 2]);
  1002. out.append(BASE64_enc[(one << 4) & 0x30]);
  1003. out.append(pad);
  1004. out.append(pad);
  1005. break;
  1006. }
  1007. }
  1008. //
  1009. // Decode the input in a base64 format
  1010. //
  1011. // const char *in -> The string to be decoded
  1012. // StringBuffer & out -> Decoded string here
  1013. //
  1014. StringBuffer &JBASE64_Decode(ISimpleReadStream &in, StringBuffer &out)
  1015. {
  1016. unsigned char c1, cs[3];
  1017. unsigned char &c2 = *cs;
  1018. unsigned char &c3 = *(cs+1);
  1019. unsigned char &c4 = *(cs+2);
  1020. unsigned char d1, d2, d3, d4;
  1021. for(;;)
  1022. {
  1023. if (in.read(1, &c1))
  1024. break;
  1025. if (!c1)
  1026. break;
  1027. else if (!isspace(c1))
  1028. {
  1029. in.read(3, cs);
  1030. d1 = BASE64_dec[c1];
  1031. d2 = BASE64_dec[c2];
  1032. d3 = BASE64_dec[c3];
  1033. d4 = BASE64_dec[c4];
  1034. out.append((char)((d1 << 2) | (d2 >> 4)));
  1035. if(c3 == pad)
  1036. break;
  1037. out.append((char)((d2 << 4) | (d3 >> 2)));
  1038. if(c4 == pad)
  1039. break;
  1040. out.append((char)((d3 << 6) | d4));
  1041. }
  1042. }
  1043. return out;
  1044. }
  1045. MemoryBuffer &JBASE64_Decode(ISimpleReadStream &in, MemoryBuffer &out)
  1046. {
  1047. unsigned char c1, cs[3];
  1048. unsigned char &c2 = *cs;
  1049. unsigned char &c3 = *(cs+1);
  1050. unsigned char &c4 = *(cs+2);
  1051. unsigned char d1, d2, d3, d4;
  1052. for(;;)
  1053. {
  1054. if (in.read(1, &c1) != 1)
  1055. break;
  1056. if (!c1)
  1057. break;
  1058. else if (!isspace(c1))
  1059. {
  1060. in.read(3, cs);
  1061. d1 = BASE64_dec[c1];
  1062. d2 = BASE64_dec[c2];
  1063. d3 = BASE64_dec[c3];
  1064. d4 = BASE64_dec[c4];
  1065. out.append((char)((d1 << 2) | (d2 >> 4)));
  1066. if(c3 == pad)
  1067. break;
  1068. out.append((char)((d2 << 4) | (d3 >> 2)));
  1069. if(c4 == pad)
  1070. break;
  1071. out.append((char)((d3 << 6) | d4));
  1072. }
  1073. }
  1074. return out;
  1075. }
  1076. StringBuffer &JBASE64_Decode(const char *incs, StringBuffer &out)
  1077. {
  1078. unsigned char c1, c2, c3, c4;
  1079. unsigned char d1, d2, d3, d4;
  1080. for(;;)
  1081. {
  1082. c1 = *incs++;
  1083. if (!c1)
  1084. break;
  1085. else if (!isspace(c1))
  1086. {
  1087. c2 = *incs++;
  1088. c3 = *incs++;
  1089. c4 = *incs++;
  1090. d1 = BASE64_dec[c1];
  1091. d2 = BASE64_dec[c2];
  1092. d3 = BASE64_dec[c3];
  1093. d4 = BASE64_dec[c4];
  1094. out.append((char)((d1 << 2) | (d2 >> 4)));
  1095. if(c3 == pad)
  1096. break;
  1097. out.append((char)((d2 << 4) | (d3 >> 2)));
  1098. if(c4 == pad)
  1099. break;
  1100. out.append((char)((d3 << 6) | d4));
  1101. }
  1102. }
  1103. return out;
  1104. }
  1105. MemoryBuffer &JBASE64_Decode(const char *incs, MemoryBuffer &out)
  1106. {
  1107. unsigned char c1, c2, c3, c4;
  1108. unsigned char d1, d2, d3, d4;
  1109. for(;;)
  1110. {
  1111. c1 = *incs++;
  1112. if (!c1)
  1113. break;
  1114. else if (!isspace(c1))
  1115. {
  1116. c2 = *incs++;
  1117. c3 = *incs++;
  1118. c4 = *incs++;
  1119. d1 = BASE64_dec[c1];
  1120. d2 = BASE64_dec[c2];
  1121. d3 = BASE64_dec[c3];
  1122. d4 = BASE64_dec[c4];
  1123. out.append((char)((d1 << 2) | (d2 >> 4)));
  1124. if(c3 == pad)
  1125. break;
  1126. out.append((char)((d2 << 4) | (d3 >> 2)));
  1127. if(c4 == pad)
  1128. break;
  1129. out.append((char)((d3 << 6) | d4));
  1130. }
  1131. }
  1132. return out;
  1133. }
  1134. bool JBASE64_Decode(size32_t length, const char *incs, StringBuffer &out)
  1135. {
  1136. out.ensureCapacity(((length / 4) + 1) * 3);
  1137. const char * end = incs + length;
  1138. unsigned char c1;
  1139. unsigned char c[4];
  1140. unsigned cIndex = 0;
  1141. unsigned char d1, d2, d3, d4;
  1142. bool fullQuartetDecoded = false;
  1143. while (incs < end)
  1144. {
  1145. c1 = *incs++;
  1146. if (isspace(c1))
  1147. continue;
  1148. if (!BASE64_dec[c1] && ('A' != c1) && (pad != c1))
  1149. {
  1150. // Forbidden char
  1151. fullQuartetDecoded = false;
  1152. break;
  1153. }
  1154. c[cIndex++] = c1;
  1155. fullQuartetDecoded = false;
  1156. if (4 == cIndex)
  1157. {
  1158. d1 = BASE64_dec[c[0]];
  1159. d2 = BASE64_dec[c[1]];
  1160. d3 = BASE64_dec[c[2]];
  1161. d4 = BASE64_dec[c[3]];
  1162. out.append((char)((d1 << 2) | (d2 >> 4)));
  1163. fullQuartetDecoded = true;
  1164. if (pad == c[2])
  1165. break;
  1166. out.append((char)((d2 << 4) | (d3 >> 2)));
  1167. if( pad == c[3])
  1168. break;
  1169. out.append((char)((d3 << 6) | d4));
  1170. cIndex = 0;
  1171. }
  1172. }
  1173. return fullQuartetDecoded;
  1174. }
  1175. static const char enc32[33] =
  1176. "abcdefghijklmnopqrstuvwxyz"
  1177. "234567";
  1178. static inline void encode5_32(const byte *in,StringBuffer &out)
  1179. {
  1180. // 5 bytes in 8 out
  1181. out.append(enc32[(in[0] >> 3)]);
  1182. out.append(enc32[((in[0] & 0x07) << 2) | (in[1] >> 6)]);
  1183. out.append(enc32[(in[1] >> 1) & 0x1f]);
  1184. out.append(enc32[((in[1] & 0x01) << 4) | (in[2] >> 4)]);
  1185. out.append(enc32[((in[2] & 0x0f) << 1) | (in[3] >> 7)]);
  1186. out.append(enc32[(in[3] >> 2) & 0x1f]);
  1187. out.append(enc32[((in[3] & 0x03) << 3) | (in[4] >> 5)]);
  1188. out.append(enc32[in[4] & 0x1f]);
  1189. }
  1190. void JBASE32_Encode(const char *in,StringBuffer &out)
  1191. {
  1192. size32_t len = (size32_t)strlen(in);
  1193. while (len>=5) {
  1194. encode5_32((const byte *)in,out);
  1195. in += 5;
  1196. len -= 5;
  1197. }
  1198. byte rest[5];
  1199. memcpy(rest,in,len);
  1200. memset(rest+len,0,5-len);
  1201. encode5_32(rest,out);
  1202. }
  1203. static inline byte decode_32c(char c)
  1204. {
  1205. byte b = (byte)c;
  1206. if (b>=97) {
  1207. if (b<=122)
  1208. return b-97;
  1209. }
  1210. else if ((b>=50)&&(b<=55))
  1211. return b-24;
  1212. return 0;
  1213. }
  1214. void JBASE32_Decode(const char *bi,StringBuffer &out)
  1215. {
  1216. for (;;) {
  1217. byte b[8];
  1218. for (unsigned i=0;i<8;i++)
  1219. b[i] = decode_32c(*(bi++));
  1220. byte o;
  1221. o = ((b[0] & 0x1f) << 3) | ((b[1] & 0x1c) >> 2);
  1222. if (!o) return;
  1223. out.append(o);
  1224. o = ((b[1] & 0x03) << 6) | ((b[2] & 0x1f) << 1) | ((b[3] & 0x10) >> 4);
  1225. if (!o) return;
  1226. out.append(o);
  1227. o = ((b[3] & 0x0f) << 4) | ((b[4] & 0x1e) >> 1);
  1228. if (!o) return;
  1229. out.append(o);
  1230. o = ((b[4] & 0x01) << 7) | ((b[5] & 0x1f) << 2) | ((b[6] & 0x18) >> 3);
  1231. if (!o) return;
  1232. out.append(o);
  1233. o = ((b[6] & 0x07) << 5) | (b[7] & 0x1f);
  1234. if (!o) return;
  1235. out.append(o);
  1236. }
  1237. }
  1238. static void DelimToStringArray(const char *csl, StringArray &dst, const char *delim, bool deldup)
  1239. {
  1240. if (!csl)
  1241. return;
  1242. const char *s = csl;
  1243. char c;
  1244. if (!delim)
  1245. c = ',';
  1246. else if (*delim&&!delim[1])
  1247. c = *delim;
  1248. else
  1249. c = 0;
  1250. StringBuffer str;
  1251. unsigned dstlen=dst.ordinality();
  1252. for (;;) {
  1253. while (isspace(*s))
  1254. s++;
  1255. if (!*s&&(dst.ordinality()==dstlen)) // this check is to allow trailing separators (e.g. ",," is 3 (NULL) entries) but not generate an entry for ""
  1256. break;
  1257. const char *e = s;
  1258. while (*e) {
  1259. if (c) {
  1260. if (*e==c)
  1261. break;
  1262. }
  1263. else if (strchr(delim,*e))
  1264. break;
  1265. e++;
  1266. }
  1267. str.clear().append((size32_t)(e-s),s).clip();
  1268. if (deldup) {
  1269. const char *s1 = str.str();
  1270. unsigned i;
  1271. for (i=0;i<dst.ordinality();i++)
  1272. if (strcmp(s1,dst.item(i))==0)
  1273. break;
  1274. if (i>=dst.ordinality())
  1275. dst.append(s1);
  1276. }
  1277. else
  1278. dst.append(str.str());
  1279. if (!*e)
  1280. break;
  1281. s = e+1;
  1282. }
  1283. }
  1284. void StringArray::appendList(const char *list, const char *delim)
  1285. {
  1286. DelimToStringArray(list, *this, delim, false);
  1287. }
  1288. void StringArray::appendListUniq(const char *list, const char *delim)
  1289. {
  1290. DelimToStringArray(list, *this, delim, true);
  1291. }
  1292. StringBuffer &StringArray::getString(StringBuffer &ret, const char *delim)
  1293. {
  1294. ForEachItemIn(i, *this)
  1295. {
  1296. const char *v = item(i);
  1297. ret.append(v);
  1298. if (i+1 != ordinality())
  1299. ret.append(delim);
  1300. }
  1301. return ret;
  1302. }
  1303. void StringArray::sortAscii(bool nocase)
  1304. {
  1305. PARENT::sort(nocase ? CCmp::compareNC : CCmp::compare);
  1306. }
  1307. void StringArray::sortAsciiReverse(bool nocase)
  1308. {
  1309. PARENT::sort(nocase ? CCmp::revCompareNC : CCmp::revCompare);
  1310. }
  1311. void StringArray::sortCompare(int (*compare)(const char * const * l, const char * const * r))
  1312. {
  1313. PARENT::sort(compare);
  1314. }
  1315. #ifdef _WIN32
  1316. unsigned msTick() { return timeGetTime(); }
  1317. unsigned usTick()
  1318. {
  1319. static __int64 freq=0;
  1320. LARGE_INTEGER v;
  1321. if (!freq) {
  1322. if (QueryPerformanceFrequency(&v))
  1323. freq=v.QuadPart;
  1324. if (!freq)
  1325. return 0;
  1326. }
  1327. if (!QueryPerformanceCounter(&v))
  1328. return 0;
  1329. return (unsigned) ((v.QuadPart*1000000)/freq); // hope dividend doesn't overflow though it might
  1330. }
  1331. #else
  1332. #ifdef CLOCK_MONOTONIC
  1333. static bool use_gettimeofday=false;
  1334. unsigned msTick()
  1335. {
  1336. if (!use_gettimeofday) {
  1337. timespec tm;
  1338. if (clock_gettime(CLOCK_MONOTONIC, &tm)>=0)
  1339. return tm.tv_sec*1000+(tm.tv_nsec/1000000);
  1340. use_gettimeofday = true;
  1341. fprintf(stderr,"clock_gettime CLOCK_MONOTONIC returns %d",errno); // don't use PROGLOG
  1342. }
  1343. struct timeval tm;
  1344. gettimeofday(&tm,NULL);
  1345. return tm.tv_sec*1000+(tm.tv_usec/1000);
  1346. }
  1347. unsigned usTick()
  1348. {
  1349. if (!use_gettimeofday) {
  1350. timespec tm;
  1351. if (clock_gettime(CLOCK_MONOTONIC, &tm)>=0)
  1352. return tm.tv_sec*1000000+(tm.tv_nsec/1000);
  1353. use_gettimeofday = true;
  1354. fprintf(stderr,"clock_gettime CLOCK_MONOTONIC returns %d",errno); // don't use PROGLOG
  1355. }
  1356. struct timeval tm;
  1357. gettimeofday(&tm,NULL);
  1358. return tm.tv_sec*1000000+tm.tv_usec;
  1359. }
  1360. #elif __APPLE__
  1361. unsigned usTick()
  1362. {
  1363. __uint64 nano = mach_absolute_time() * (uint64_t)timebase_info.numer / (uint64_t)timebase_info.denom;
  1364. return nano / 1000;
  1365. }
  1366. unsigned msTick()
  1367. {
  1368. __uint64 nano = mach_absolute_time() * (uint64_t)timebase_info.numer / (uint64_t)timebase_info.denom;
  1369. return nano / 1000000;
  1370. }
  1371. #else
  1372. #warning "clock_gettime(CLOCK_MONOTONIC) not supported"
  1373. unsigned msTick()
  1374. {
  1375. struct timeval tm;
  1376. gettimeofday(&tm,NULL);
  1377. return tm.tv_sec*1000+(tm.tv_usec/1000);
  1378. }
  1379. unsigned usTick()
  1380. {
  1381. struct timeval tm;
  1382. gettimeofday(&tm,NULL);
  1383. return tm.tv_sec*1000000+tm.tv_usec;
  1384. }
  1385. #endif
  1386. #endif
  1387. int make_daemon(bool printpid)
  1388. {
  1389. #ifndef _WIN32
  1390. pid_t pid, sid;
  1391. pid = fork();
  1392. if (pid < 0) {
  1393. PrintLog("fork failed\n");
  1394. return(EXIT_FAILURE);
  1395. }
  1396. if (pid > 0) {
  1397. if (printpid) {
  1398. int status;
  1399. waitpid(pid, &status, 0);
  1400. if (WEXITSTATUS(status)!=0)
  1401. return EXIT_FAILURE;
  1402. }
  1403. exit(EXIT_SUCCESS);
  1404. }
  1405. if ((sid = setsid()) < 0) {
  1406. PrintLog("error: set sid failed\n");
  1407. return(EXIT_FAILURE);
  1408. }
  1409. umask(0);
  1410. pid = fork(); // To prevent zombies
  1411. if (pid < 0) {
  1412. PrintLog("fork failed (2)\n");
  1413. return(EXIT_FAILURE);
  1414. }
  1415. if (pid > 0) {
  1416. if (printpid)
  1417. fprintf(stdout,"%d\n",pid);
  1418. exit(EXIT_SUCCESS);
  1419. }
  1420. if (!freopen("/dev/null", "r", stdin) ||
  1421. !freopen("/dev/null", "w", stdout) ||
  1422. !freopen("/dev/null", "w", stderr)) {
  1423. PrintLog("reopen std in/out/err failed\n");
  1424. return(EXIT_FAILURE);
  1425. }
  1426. return(EXIT_SUCCESS);
  1427. #else
  1428. return 0;
  1429. #endif
  1430. }
  1431. //Calculate the greatest common divisor using Euclid's method
  1432. unsigned __int64 greatestCommonDivisor(unsigned __int64 left, unsigned __int64 right)
  1433. {
  1434. for (;;)
  1435. {
  1436. if (left > right)
  1437. {
  1438. if (right == 0)
  1439. return left;
  1440. left = left % right;
  1441. }
  1442. else
  1443. {
  1444. if (left == 0)
  1445. return right;
  1446. right = right % left;
  1447. }
  1448. }
  1449. }
  1450. //The whole point of this function is to force memory to be accessed on the stack to avoid page faults.
  1451. //Therefore disable the gcc warning.
  1452. #ifdef __GNUC__
  1453. #pragma GCC diagnostic push
  1454. #pragma GCC diagnostic ignored "-Wuninitialized"
  1455. #endif
  1456. //In a separate module to stop optimizer removing the surrounding catch.
  1457. void doStackProbe()
  1458. {
  1459. byte local;
  1460. const volatile byte * x = (const byte *)&local;
  1461. byte forceload __attribute__((unused)) = x[-4096];
  1462. }
  1463. #ifdef __GNUC__
  1464. #pragma GCC diagnostic pop
  1465. #endif
  1466. #ifdef _WIN32
  1467. DWORD dwTlsIndex = -1;
  1468. CriticalSection tlscrit;
  1469. void initThreadLocal(int len, void* val)
  1470. {
  1471. {
  1472. CriticalBlock b(tlscrit);
  1473. if(dwTlsIndex == -1)
  1474. {
  1475. if ((dwTlsIndex = TlsAlloc()) == TLS_OUT_OF_INDEXES)
  1476. throw MakeStringException(-1, "TlsAlloc failed");
  1477. }
  1478. }
  1479. LPVOID lpvData;
  1480. lpvData = TlsGetValue(dwTlsIndex);
  1481. if (lpvData != 0)
  1482. LocalFree((HLOCAL) lpvData);
  1483. // Initialize the TLS index for this thread.
  1484. lpvData = (LPVOID) LocalAlloc(LPTR, len);
  1485. memcpy((char*)lpvData, val, len);
  1486. if (! TlsSetValue(dwTlsIndex, lpvData))
  1487. throw MakeStringException(-1, "TlsSetValue error");
  1488. }
  1489. void* getThreadLocalVal()
  1490. {
  1491. if(dwTlsIndex == -1)
  1492. return NULL;
  1493. return TlsGetValue(dwTlsIndex);
  1494. }
  1495. void clearThreadLocal()
  1496. {
  1497. if(dwTlsIndex == -1)
  1498. return;
  1499. LPVOID lpvData = TlsGetValue(dwTlsIndex);
  1500. if (lpvData != 0)
  1501. {
  1502. LocalFree((HLOCAL) lpvData);
  1503. if (! TlsSetValue(dwTlsIndex, NULL))
  1504. throw MakeStringException(-1, "TlsSetValue error");
  1505. }
  1506. }
  1507. #else
  1508. // Key for the thread-specific buffer
  1509. static pthread_key_t buffer_key;
  1510. // Once-only initialisation of the key
  1511. static pthread_once_t buffer_key_once = PTHREAD_ONCE_INIT;
  1512. // Free the thread-specific buffer
  1513. static void buffer_destroy(void * buf)
  1514. {
  1515. if(buf)
  1516. free(buf);
  1517. }
  1518. // Allocate the key
  1519. static void buffer_key_alloc()
  1520. {
  1521. pthread_key_create(&buffer_key, buffer_destroy);
  1522. }
  1523. // Allocate the thread-specific buffer
  1524. void initThreadLocal(int len, void* val)
  1525. {
  1526. pthread_once(&buffer_key_once, buffer_key_alloc);
  1527. void* valbuf = malloc(len);
  1528. memcpy(valbuf, val, len);
  1529. pthread_setspecific(buffer_key, valbuf);
  1530. }
  1531. // Return the thread-specific buffer
  1532. void* getThreadLocalVal()
  1533. {
  1534. return (char *) pthread_getspecific(buffer_key);
  1535. }
  1536. void clearThreadLocal()
  1537. {
  1538. }
  1539. #endif
  1540. StringBuffer &expandMask(StringBuffer &buf, const char *mask, unsigned p, unsigned n)
  1541. {
  1542. const char *s=mask;
  1543. if (s)
  1544. while (*s) {
  1545. char next = *(s++);
  1546. if (next=='$') {
  1547. char pc = toupper(s[0]);
  1548. if (pc&&(s[1]=='$')) {
  1549. if (pc=='P') {
  1550. buf.append(p+1);
  1551. next = 0;
  1552. s+=2;
  1553. }
  1554. else if (pc=='N') {
  1555. buf.append(n);
  1556. next = 0;
  1557. s+=2;
  1558. }
  1559. }
  1560. }
  1561. if (next)
  1562. buf.append(next);
  1563. }
  1564. return buf;
  1565. }
  1566. static const char *findExtension(const char *fn)
  1567. {
  1568. if (!fn)
  1569. return NULL;
  1570. const char *ret = strchr(fn,'.');
  1571. if (ret) {
  1572. for (;;) {
  1573. ret++;
  1574. const char *s = strchr(ret,'.');
  1575. if (!s)
  1576. break;
  1577. ret = s;
  1578. }
  1579. }
  1580. return ret;
  1581. }
  1582. unsigned runExternalCommand(StringBuffer &output, StringBuffer &error, const char *cmd, const char *input)
  1583. {
  1584. try
  1585. {
  1586. Owned<IPipeProcess> pipe = createPipeProcess();
  1587. int ret = START_FAILURE;
  1588. if (pipe->run(cmd, cmd, ".", input != NULL, true, true, 1024*1024))
  1589. {
  1590. if (input)
  1591. {
  1592. pipe->write(strlen(input), input);
  1593. pipe->closeInput();
  1594. }
  1595. char buf[1024];
  1596. while (true)
  1597. {
  1598. size32_t read = pipe->read(sizeof(buf), buf);
  1599. if (!read)
  1600. break;
  1601. output.append(read, buf);
  1602. }
  1603. ret = pipe->wait();
  1604. while (true)
  1605. {
  1606. size32_t read = pipe->readError(sizeof(buf), buf);
  1607. if (!read)
  1608. break;
  1609. error.append(read, buf);
  1610. }
  1611. }
  1612. return ret;
  1613. }
  1614. catch (IException *E)
  1615. {
  1616. E->Release();
  1617. output.clear();
  1618. return START_FAILURE;
  1619. }
  1620. }
  1621. bool matchesMask(const char *fn, const char *mask, unsigned p, unsigned n)
  1622. {
  1623. StringBuffer match;
  1624. expandMask(match,mask,p,n);
  1625. return (stricmp(fn,match.str())==0);
  1626. }
  1627. bool constructMask(StringAttr &attr, const char *fn, unsigned p, unsigned n)
  1628. {
  1629. StringBuffer buf;
  1630. const char *ext = findExtension(fn);
  1631. if (!ext)
  1632. return false;
  1633. buf.append((size32_t)(ext-fn),fn).append("_$P$_of_$N$");
  1634. if (matchesMask(fn,buf.str(),p,n)) {
  1635. attr.set(buf.str());
  1636. return true;
  1637. }
  1638. return false;
  1639. }
  1640. bool deduceMask(const char *fn, bool expandN, StringAttr &mask, unsigned &pret, unsigned &nret)
  1641. {
  1642. const char *e = findExtension(fn);
  1643. if (!e)
  1644. return false;
  1645. for (;;) {
  1646. const char *s=e;
  1647. if (*s=='_') {
  1648. s++;
  1649. unsigned p = 0;
  1650. while (isdigit(*s))
  1651. p = p*10+*(s++)-'0';
  1652. if (p&&(memcmp(s,"_of_",4)==0)) {
  1653. s += 4;
  1654. pret = p-1;
  1655. p = 0;
  1656. while (isdigit(*s))
  1657. p = p*10+*(s++)-'0';
  1658. nret = p;
  1659. if (((*s==0)||(*s=='.'))&&(p>pret)) {
  1660. StringBuffer buf;
  1661. if (expandN)
  1662. buf.append((size32_t)(e-fn),fn).append("_$P$_of_").append(p);
  1663. else
  1664. buf.append((size32_t)(e-fn),fn).append("_$P$_of_$N$");
  1665. if (*s=='.')
  1666. buf.append(s);
  1667. mask.set(buf);
  1668. return true;
  1669. }
  1670. }
  1671. }
  1672. e--;
  1673. for (;;) {
  1674. if (e==fn)
  1675. return false;
  1676. if (*(e-1)=='.')
  1677. break;
  1678. e--;
  1679. }
  1680. }
  1681. return false;
  1682. }
  1683. //==============================================================
  1684. #ifdef _WIN32
  1685. class CWindowsAuthenticatedUser: implements IAuthenticatedUser, public CInterface
  1686. {
  1687. StringAttr name;
  1688. HANDLE usertoken;
  1689. public:
  1690. IMPLEMENT_IINTERFACE;
  1691. CWindowsAuthenticatedUser()
  1692. {
  1693. usertoken = (HANDLE)-1;
  1694. }
  1695. ~CWindowsAuthenticatedUser()
  1696. {
  1697. if (usertoken != (HANDLE)-1)
  1698. CloseHandle(usertoken);
  1699. }
  1700. bool login(const char *user, const char *passwd)
  1701. {
  1702. name.clear();
  1703. if (usertoken != (HANDLE)-1)
  1704. CloseHandle(usertoken);
  1705. StringBuffer domain("");
  1706. const char *ut = strchr(user,'\\');
  1707. if (ut) {
  1708. domain.clear().append((size32_t)(ut-user),user);
  1709. user = ut+1;
  1710. }
  1711. BOOL res = LogonUser((LPTSTR)user,(LPTSTR)(domain.length()==0?NULL:domain.str()),(LPTSTR)passwd,LOGON32_LOGON_NETWORK,LOGON32_PROVIDER_DEFAULT,&usertoken);
  1712. if (res==0)
  1713. return false;
  1714. name.set(user);
  1715. return true;
  1716. }
  1717. void impersonate()
  1718. {
  1719. if (!ImpersonateLoggedOnUser(usertoken))
  1720. throw makeOsException(GetLastError());
  1721. }
  1722. void revert()
  1723. {
  1724. RevertToSelf();
  1725. }
  1726. const char *username()
  1727. {
  1728. return name.get();
  1729. }
  1730. };
  1731. IAuthenticatedUser *createAuthenticatedUser() { return new CWindowsAuthenticatedUser; }
  1732. #elif defined(__linux__)
  1733. class CLinuxAuthenticatedUser: implements IAuthenticatedUser, public CInterface
  1734. {
  1735. StringAttr name;
  1736. uid_t uid;
  1737. gid_t gid;
  1738. uid_t saveuid;
  1739. gid_t savegid;
  1740. public:
  1741. IMPLEMENT_IINTERFACE;
  1742. bool login(const char *user, const char *passwd)
  1743. {
  1744. name.clear();
  1745. const char *ut = strchr(user,'\\');
  1746. if (ut)
  1747. user = ut+1; // remove windows domain
  1748. struct passwd *pw;
  1749. char *epasswd;
  1750. if ((pw = getpwnam(user)) == NULL)
  1751. return false;
  1752. struct spwd *spwd = getspnam(user);
  1753. if (spwd)
  1754. epasswd = spwd->sp_pwdp;
  1755. else
  1756. epasswd = pw->pw_passwd;
  1757. if (!epasswd||!*epasswd)
  1758. return false;
  1759. if (strcmp(crypt(passwd,epasswd),epasswd)!=0)
  1760. return false;
  1761. uid = pw->pw_uid;
  1762. gid = pw->pw_gid;
  1763. name.set(pw->pw_name);
  1764. return true;
  1765. }
  1766. void impersonate()
  1767. {
  1768. saveuid = geteuid();
  1769. savegid = getegid();
  1770. if (setegid(gid) == -1)
  1771. throw makeOsException(errno, "Failed to set effective group id");
  1772. if (seteuid(uid) == -1)
  1773. throw makeOsException(errno, "Failed to set effective user id");
  1774. }
  1775. void revert()
  1776. {
  1777. if (seteuid(saveuid) == -1)
  1778. throw makeOsException(errno, "Failed to restore effective group id");
  1779. if (setegid(savegid) == -1)
  1780. throw makeOsException(errno, "Failed to restore effective user id");
  1781. }
  1782. const char *username()
  1783. {
  1784. return name.get();
  1785. }
  1786. };
  1787. IAuthenticatedUser *createAuthenticatedUser() { return new CLinuxAuthenticatedUser; }
  1788. #elif defined(__FreeBSD__) || defined (__APPLE__)
  1789. IAuthenticatedUser *createAuthenticatedUser() { UNIMPLEMENTED; }
  1790. #endif
  1791. extern jlib_decl void serializeAtom(MemoryBuffer & target, IAtom * name)
  1792. {
  1793. StringBuffer lower(str(name));
  1794. lower.toLowerCase();
  1795. serialize(target, lower.str());
  1796. }
  1797. extern jlib_decl IAtom * deserializeAtom(MemoryBuffer & source)
  1798. {
  1799. StringAttr text;
  1800. deserialize(source, text);
  1801. if (text)
  1802. return createAtom(text);
  1803. return NULL;
  1804. }
  1805. //==============================================================
  1806. static const char enc64[65] =
  1807. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1808. "abcdefghijklmnopqrstuvwxyz"
  1809. "0123456789-_";
  1810. static inline void encode3_64(byte *in,StringBuffer &out)
  1811. {
  1812. // 3 bytes in 4 out
  1813. out.append(enc64[in[0]>>2]);
  1814. out.append(enc64[((in[0] << 4) & 0x30) | (in[1] >> 4)]);
  1815. out.append(enc64[((in[1] << 2) & 0x3c) | (in[2] >> 6)]);
  1816. out.append(enc64[in[2] & 0x3f]);
  1817. }
  1818. static NonReentrantSpinLock lock;
  1819. static unsigned uuidbin[5] = {0,0,0,0,0};
  1820. StringBuffer &genUUID(StringBuffer &out, bool nocase)
  1821. { // returns a 24 char UUID for nocase=false or 32 char for nocase=true
  1822. lock.enter();
  1823. // could be quicker using statics
  1824. if (uuidbin[0]==0) {
  1825. queryHostIP().getNetAddress(sizeof(uuidbin[0]),uuidbin);
  1826. uuidbin[1] = (unsigned)GetCurrentProcessId();
  1827. }
  1828. time_t t;
  1829. time(&t);
  1830. uuidbin[2] = (unsigned)t;
  1831. uuidbin[3] = msTick();
  1832. uuidbin[4]++;
  1833. byte *in = (byte *)uuidbin;
  1834. if (nocase) {
  1835. encode5_32(in,out);
  1836. encode5_32(in+5,out);
  1837. encode5_32(in+10,out);
  1838. encode5_32(in+15,out);
  1839. }
  1840. else {
  1841. encode3_64(in,out);
  1842. encode3_64(in+3,out);
  1843. encode3_64(in+6,out);
  1844. encode3_64(in+9,out);
  1845. byte tmp[3]; // drop two msb bytes from msec time
  1846. tmp[0] = in[12];
  1847. tmp[1] = in[13];
  1848. tmp[2] = in[16];
  1849. encode3_64(tmp,out);
  1850. encode3_64(in+17,out);
  1851. }
  1852. lock.leave();
  1853. return out;
  1854. }
  1855. //==============================================================
  1856. class jlib_decl CNameCountTable : public AtomRefTable
  1857. {
  1858. public:
  1859. CNameCountTable(bool _nocase=false) : AtomRefTable(_nocase) { }
  1860. StringBuffer &dump(StringBuffer &str)
  1861. {
  1862. SuperHashIteratorOf<HashKeyElement> iter(*this);
  1863. CriticalBlock b(crit);
  1864. ForEach (iter)
  1865. {
  1866. HashKeyElement &elem = iter.query();
  1867. str.append(elem.get()).append(", count = ").append(elem.queryReferences()).newline();
  1868. }
  1869. return str;
  1870. }
  1871. };
  1872. static CNameCountTable *namedCountHT;
  1873. MODULE_INIT(INIT_PRIORITY_SYSTEM)
  1874. {
  1875. namedCountHT = new CNameCountTable;
  1876. return true;
  1877. }
  1878. MODULE_EXIT()
  1879. {
  1880. delete namedCountHT;
  1881. }
  1882. NamedCount::NamedCount()
  1883. {
  1884. ht = NULL;
  1885. }
  1886. NamedCount::~NamedCount()
  1887. {
  1888. if (ht) namedCountHT->releaseKey(ht);
  1889. }
  1890. void NamedCount::set(const char *name)
  1891. {
  1892. ht = namedCountHT->queryCreate(name);
  1893. }
  1894. StringBuffer &dumpNamedCounts(StringBuffer &str)
  1895. {
  1896. return namedCountHT->dump(str);
  1897. }
  1898. //==============================================================
  1899. // class OffsetToString
  1900. OffsetToString::OffsetToString(offset_t offset)
  1901. {
  1902. #if defined(_MSC_VER) && !defined (_POSIX_) && (__STDC__ || _INTEGRAL_MAX_BITS < 64)
  1903. // fpos_t is defined as struct (see <stdio.h> in VC)
  1904. __int64 v = offset.lopart + (offset.hipart<<32);
  1905. m_buffer.append(v);
  1906. #else
  1907. m_buffer.append(offset);
  1908. #endif
  1909. }
  1910. /* Gentoo libc version omits these symbols which are directly */
  1911. /* referenced by some 3rd party libraries (sybase, Hasp). Until these */
  1912. /* libs get updated, provide linkable symbols within jlib for these... */
  1913. #if defined(__linux__) && (__GNUC__ >= 3)
  1914. const jlib_decl unsigned short int *__ctype_b = *__ctype_b_loc ();
  1915. const jlib_decl __int32_t *__ctype_tolower = *__ctype_tolower_loc();
  1916. const jlib_decl __int32_t *__ctype_toupper = *__ctype_toupper_loc();
  1917. // There seems to be some debate about whether these are needed
  1918. //#elif (__GNUC__ >= 3)
  1919. //const unsigned short int *__ctype_b = *__ctype_b_loc ();
  1920. //const unsigned int *__ctype_tolower = *__ctype_tolower_loc();
  1921. //const unsigned int *__ctype_toupper = *__ctype_toupper_loc();
  1922. #endif
  1923. //==============================================================
  1924. // URL Password, username handling
  1925. /*
  1926. From ftp://ftp.isi.edu/in-notes/rfc1738.txt:
  1927. http://<user>:<password>@<host>:<port>/<url-path>
  1928. Some or all of the parts "<user>:<password>@", ":<password>",
  1929. ":<port>", and "/<url-path>" may be excluded.
  1930. The user name (and password), if present, are followed by a
  1931. commercial at-sign "@". Within the user and password field, any ":",
  1932. "@", or "/" must be encoded.
  1933. */
  1934. jlib_decl StringBuffer& encodeUrlUseridPassword(StringBuffer& out, const char* in)
  1935. {
  1936. for (const char* p = in; *p; p++)
  1937. {
  1938. switch(*p)
  1939. {
  1940. // mentioned in rfc1738
  1941. case ':': out.append("%3A"); break;
  1942. case '@': out.append("%40"); break;
  1943. case '/': out.append("%2F"); break;
  1944. // these are not in the spec, but IE/Firefox has trouble if left un-encoded
  1945. case '%': out.append("%25"); break;
  1946. // these are not necessary: both IE and firefox handle them correctly
  1947. /*
  1948. case '&': out.append("%26"); break;
  1949. case ' ': out.append("%20"); break;
  1950. */
  1951. default: out.append(*p); break;
  1952. }
  1953. }
  1954. return out;
  1955. }
  1956. inline bool isHexChar(char c)
  1957. {
  1958. return (c>='0' && c<='9')
  1959. || (c>='A' && c<='F')
  1960. || (c>='a' && c<='f');
  1961. }
  1962. int hexValue(char c)
  1963. {
  1964. return (c>='0' && c<='9') ? c-'0' :
  1965. ((c>='A' && (c<='F') ? c-'A'+10 : c-'a'+10));
  1966. }
  1967. jlib_decl StringBuffer& decodeUrlUseridPassword(StringBuffer& out, const char* in)
  1968. {
  1969. for (const char* p = in; *p; p++)
  1970. {
  1971. if (*p=='%' && isHexChar(*(p+1)) && isHexChar(*(p+2)) )
  1972. {
  1973. char c1 = *(p+1), c2 = *(p+2);
  1974. int x = (hexValue(c1)<<4) + hexValue(c2);
  1975. out.appendf("%c",x);
  1976. p += 2;
  1977. }
  1978. else
  1979. out.appendf("%c",*p);
  1980. }
  1981. return out;
  1982. }
  1983. StringBuffer jlib_decl passwordInput(const char* prompt, StringBuffer& passwd)
  1984. {
  1985. #ifdef _WIN32
  1986. printf("%s", prompt);
  1987. size32_t entrylen = passwd.length();
  1988. for (;;) {
  1989. char c = getch();
  1990. if (c == '\r')
  1991. break;
  1992. if (c == '\b') {
  1993. if (passwd.length()>entrylen) {
  1994. printf("\b \b");
  1995. passwd.setLength(passwd.length()-1);
  1996. }
  1997. }
  1998. else {
  1999. passwd.append(c);
  2000. printf("*");
  2001. }
  2002. }
  2003. printf("\n");
  2004. #else
  2005. // unfortuantely linux tty can't easily support using '*' hiding
  2006. sigset_t saved_signals;
  2007. sigset_t set_signals;
  2008. struct termios saved_term;
  2009. struct termios set_term;
  2010. FILE *term = fopen(_PATH_TTY, "w+");
  2011. if (!term)
  2012. term = stdin;
  2013. int termfd = fileno(term);
  2014. fprintf(stdout, "%s", prompt);
  2015. fflush(stdout);
  2016. sigemptyset(&set_signals);
  2017. sigaddset(&set_signals, SIGINT);
  2018. sigaddset(&set_signals, SIGTSTP);
  2019. sigprocmask(SIG_BLOCK, &set_signals, &saved_signals);
  2020. tcgetattr(termfd, &saved_term);
  2021. set_term = saved_term;
  2022. set_term.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL);
  2023. tcsetattr(termfd, TCSAFLUSH, &set_term);
  2024. char c = EOF;
  2025. int rd = ::read(termfd,&c,1);
  2026. while ((rd==1)&&(c!='\r')&&(c!='\n')) {
  2027. passwd.append(c);
  2028. rd = ::read(termfd,&c,1);
  2029. }
  2030. int err = (rd<0)?errno:0;
  2031. tcsetattr(termfd, TCSAFLUSH, &saved_term);
  2032. sigprocmask(SIG_SETMASK, &saved_signals, 0);
  2033. if (term!=stdin)
  2034. fclose(term);
  2035. if (err)
  2036. throw makeOsException(err);
  2037. #endif
  2038. return passwd;
  2039. }
  2040. StringBuffer & fillConfigurationDirectoryEntry(const char *dir,const char *name, const char *component, const char *instance, StringBuffer &dirout)
  2041. {
  2042. while (*dir) {
  2043. if (*dir=='[') {
  2044. if (memicmp(dir+1,"NAME]",5)==0) {
  2045. dirout.append(name);
  2046. dir += 5;
  2047. }
  2048. else if (memicmp(dir+1,"COMPONENT]",10)==0) {
  2049. dirout.append(component);
  2050. dir += 10;
  2051. }
  2052. else if (memicmp(dir+1,"INST]",5)==0){
  2053. dirout.append(instance);
  2054. dir += 5;
  2055. }
  2056. else
  2057. dirout.append('[');
  2058. }
  2059. else
  2060. dirout.append(*dir);
  2061. dir++;
  2062. }
  2063. return dirout;
  2064. }
  2065. IPropertyTree *getHPCCEnvironment()
  2066. {
  2067. StringBuffer envfile;
  2068. if (queryEnvironmentConf().getProp("environment",envfile) && envfile.length())
  2069. {
  2070. if (!isAbsolutePath(envfile.str()))
  2071. {
  2072. envfile.insert(0, CONFIG_DIR PATHSEPSTR);
  2073. }
  2074. Owned<IFile> file = createIFile(envfile.str());
  2075. if (file)
  2076. {
  2077. Owned<IFileIO> fileio = file->open(IFOread);
  2078. if (fileio)
  2079. return createPTree(*fileio);
  2080. }
  2081. }
  2082. return NULL;
  2083. }
  2084. static Owned<IProperties> envConfFile;
  2085. static CriticalSection envConfCrit;
  2086. jlib_decl const IProperties &queryEnvironmentConf()
  2087. {
  2088. CriticalBlock b(envConfCrit);
  2089. if (!envConfFile)
  2090. envConfFile.setown(createProperties(CONFIG_DIR PATHSEPSTR ENV_CONF_FILE, true));
  2091. return *envConfFile;
  2092. }
  2093. static CriticalSection securitySettingsCrit;
  2094. static bool useSSL = false;
  2095. static StringAttr certificate;
  2096. static StringAttr privateKey;
  2097. static bool retrieved = false;
  2098. jlib_decl bool querySecuritySettings(bool * _useSSL,
  2099. unsigned short *_port,
  2100. const char * * _certificate,
  2101. const char * * _privateKey)
  2102. {
  2103. if (!retrieved)
  2104. {
  2105. CriticalBlock b(securitySettingsCrit);
  2106. if (!retrieved)
  2107. {
  2108. try
  2109. {
  2110. StringBuffer configFileSpec;
  2111. #ifndef _WIN32
  2112. configFileSpec.set(CONFIG_DIR).append(PATHSEPSTR).append("environment.conf");
  2113. #endif
  2114. Owned<IProperties> conf = createProperties(configFileSpec.str(), true);
  2115. useSSL = conf->getPropBool("dfsUseSSL", false);
  2116. if (useSSL)
  2117. {
  2118. certificate.set(conf->queryProp("dfsSSLCertFile"));
  2119. privateKey.set(conf->queryProp("dfsSSLPrivateKeyFile"));
  2120. }
  2121. retrieved = true;
  2122. }
  2123. catch (IException *e)
  2124. {
  2125. EXCLOG(e, "Error processing environment.conf\n");
  2126. throwUnexpected();
  2127. }
  2128. }
  2129. }
  2130. if (retrieved)
  2131. {
  2132. if (_useSSL)
  2133. *_useSSL = useSSL;
  2134. if (_port)
  2135. *_port = useSSL ? SECURE_DAFILESRV_PORT : DAFILESRV_PORT;
  2136. if (_certificate)
  2137. *_certificate = certificate.get();
  2138. if (_privateKey)
  2139. *_privateKey = privateKey.get();
  2140. }
  2141. else
  2142. {
  2143. if (_useSSL)
  2144. *_useSSL = false;
  2145. if (_port)
  2146. *_port = DAFILESRV_PORT;
  2147. }
  2148. return retrieved;
  2149. }
  2150. static IPropertyTree *getOSSdirTree()
  2151. {
  2152. Owned<IPropertyTree> envtree = getHPCCEnvironment();
  2153. if (envtree) {
  2154. IPropertyTree *ret = envtree->queryPropTree("Software/Directories");
  2155. if (ret)
  2156. return createPTreeFromIPT(ret);
  2157. }
  2158. return NULL;
  2159. }
  2160. bool getConfigurationDirectory(const IPropertyTree *useTree, const char *category, const char *component, const char *instance, StringBuffer &dirout)
  2161. {
  2162. Linked<const IPropertyTree> dirtree = useTree;
  2163. if (!dirtree)
  2164. dirtree.setown(getOSSdirTree());
  2165. if (dirtree && category && *category)
  2166. {
  2167. const char *name = dirtree->queryProp("@name");
  2168. if (name&&*name) {
  2169. StringBuffer q("Category[@name=\"");
  2170. q.append(category).append("\"]");
  2171. IPropertyTree *cat = dirtree->queryPropTree(q.str()); // assume only 1
  2172. if (cat) {
  2173. IPropertyTree *over = NULL;
  2174. if (instance&&*instance) {
  2175. q.clear().append("Override[@instance=\"").append(instance).append("\"]");
  2176. Owned<IPropertyTreeIterator> it1 = cat->getElements(q.str());
  2177. ForEach(*it1) {
  2178. IPropertyTree &o1 = it1->query();
  2179. if ((!component||!*component)) {
  2180. if (!over)
  2181. over = &o1;
  2182. }
  2183. else {
  2184. const char *comp = o1.queryProp("@component");
  2185. if (!comp||!*comp) {
  2186. if (!over)
  2187. over = &o1;
  2188. }
  2189. else if (strcmp(comp,component)==0) {
  2190. over = &o1;
  2191. break;
  2192. }
  2193. }
  2194. }
  2195. }
  2196. if (!over&&component&&*component) {
  2197. q.clear().append("Override[@component=\"").append(component).append("\"]");
  2198. Owned<IPropertyTreeIterator> it2 = cat->getElements(q.str());
  2199. ForEach(*it2) {
  2200. IPropertyTree &o2 = it2->query();
  2201. if ((!instance||!*instance)) {
  2202. over = &o2;
  2203. break;
  2204. }
  2205. else {
  2206. const char *inst = o2.queryProp("@instance");
  2207. if (!inst||!*inst) {
  2208. over = &o2;
  2209. break;
  2210. }
  2211. }
  2212. }
  2213. }
  2214. const char *dir = over?over->queryProp("@dir"):cat->queryProp("@dir");
  2215. if (dir&&*dir) {
  2216. fillConfigurationDirectoryEntry(dir,name,component,instance,dirout);
  2217. return true;
  2218. }
  2219. }
  2220. }
  2221. }
  2222. return false;
  2223. }
  2224. const char * matchConfigurationDirectoryEntry(const char *path,const char *mask,StringBuffer &name, StringBuffer &component, StringBuffer &instance)
  2225. {
  2226. // first check matches from (and set any values)
  2227. // only handles simple masks currently
  2228. StringBuffer var;
  2229. PointerArray val;
  2230. const char *m = mask;
  2231. const char *p = path;
  2232. for (;;) {
  2233. char c = *m;
  2234. if (!c)
  2235. break;
  2236. m++;
  2237. StringBuffer *out=NULL;
  2238. if (c=='[') {
  2239. if (memicmp(m,"NAME]",5)==0) {
  2240. out = &name;
  2241. m += 5;
  2242. }
  2243. else if (memicmp(m,"COMPONENT]",10)==0) {
  2244. out = &component;
  2245. m += 10;
  2246. }
  2247. else if (memicmp(m,"INST]",5)==0) {
  2248. out = &instance;
  2249. m += 5;
  2250. }
  2251. }
  2252. if (out) {
  2253. StringBuffer mtail;
  2254. while (*m&&!isPathSepChar(*m)&&(*m!='['))
  2255. mtail.append(*(m++));
  2256. StringBuffer ptail;
  2257. while (*p&&!isPathSepChar(*p))
  2258. ptail.append(*(p++));
  2259. if (ptail.length()<mtail.length())
  2260. return NULL;
  2261. size32_t l = ptail.length()-mtail.length();
  2262. if (l&&(memcmp(ptail.str()+l,mtail.str(),mtail.length())!=0))
  2263. return NULL;
  2264. out->clear().append(l,ptail.str());
  2265. }
  2266. else if (c!=*(p++))
  2267. return NULL;
  2268. }
  2269. if (!*p)
  2270. return p;
  2271. if (isPathSepChar(*p))
  2272. return p+1;
  2273. return NULL;
  2274. }
  2275. bool replaceConfigurationDirectoryEntry(const char *path,const char *frommask,const char *tomask,StringBuffer &out)
  2276. {
  2277. StringBuffer name;
  2278. StringBuffer comp;
  2279. StringBuffer inst;
  2280. const char *tail = matchConfigurationDirectoryEntry(path,frommask,name,comp,inst);
  2281. if (!tail)
  2282. return false;
  2283. fillConfigurationDirectoryEntry(tomask,name,comp,inst,out);
  2284. if (*tail)
  2285. addPathSepChar(out).append(tail);
  2286. return true;
  2287. }
  2288. static CriticalSection sect;
  2289. static StringAttr processPath;
  2290. const char * queryCurrentProcessPath()
  2291. {
  2292. CriticalBlock block(sect);
  2293. if (processPath.isEmpty())
  2294. {
  2295. #if _WIN32
  2296. HMODULE hModule = GetModuleHandle(NULL);
  2297. char path[MAX_PATH];
  2298. if (GetModuleFileName(hModule, path, MAX_PATH) != 0)
  2299. processPath.set(path);
  2300. #elif defined (__APPLE__)
  2301. char path[PATH_MAX];
  2302. uint32_t size = sizeof(path);
  2303. ssize_t len = _NSGetExecutablePath(path, &size);
  2304. switch(len)
  2305. {
  2306. case -1:
  2307. {
  2308. char * biggerPath = new char[size];
  2309. if (_NSGetExecutablePath(biggerPath, &size) == 0)
  2310. processPath.set(biggerPath);
  2311. delete [] biggerPath;
  2312. }
  2313. break;
  2314. case 0:
  2315. processPath.set(path);
  2316. break;
  2317. default:
  2318. break;
  2319. }
  2320. #else
  2321. char path[PATH_MAX + 1];
  2322. ssize_t len = readlink("/proc/self/exe", path, PATH_MAX);
  2323. if (len != -1)
  2324. {
  2325. path[len] = 0;
  2326. processPath.set(path);
  2327. }
  2328. #endif
  2329. }
  2330. if (processPath.isEmpty())
  2331. return NULL;
  2332. return processPath.str();
  2333. }
  2334. inline bool isOctChar(char c)
  2335. {
  2336. return (c>='0' && c<'8');
  2337. }
  2338. inline int octValue(char c)
  2339. {
  2340. return c-'0';
  2341. }
  2342. int parseCommandLine(const char * cmdline, MemoryBuffer &mb, const char** &argvout)
  2343. {
  2344. mb.append((char)0);
  2345. size32_t arg[256];
  2346. int argc = 0;
  2347. arg[0] = 0;
  2348. char quotechar = 0;
  2349. for (;;) {
  2350. char c = *(cmdline++);
  2351. switch(c) {
  2352. case ' ':
  2353. case '\t':
  2354. if (quotechar)
  2355. break;
  2356. // fall through
  2357. case 0: {
  2358. if (arg[argc]) {
  2359. while (mb.length()>arg[argc]) {
  2360. size32_t l = mb.length()-1;
  2361. const byte * b = ((const byte *)mb.bufferBase())+l;
  2362. if ((*b!=' ')&&(*b!='\t'))
  2363. break;
  2364. mb.setLength(l);
  2365. }
  2366. if (mb.length()>arg[argc]) {
  2367. mb.append((char)0);
  2368. argc++;
  2369. }
  2370. if (c) {
  2371. if (argc==256)
  2372. throw makeStringException(-1, "parseCommandLine: too many arguments");
  2373. arg[argc] = 0;
  2374. }
  2375. }
  2376. if (c)
  2377. continue;
  2378. argvout = (const char **)mb.reserve(argc*sizeof(const char *));
  2379. for (int i=0;i<argc;i++)
  2380. argvout[i] = arg[i]+(const char *)mb.bufferBase();
  2381. return argc;
  2382. }
  2383. break;
  2384. case '\'':
  2385. case '"':
  2386. if (c==quotechar) {
  2387. quotechar = 0;
  2388. continue;
  2389. }
  2390. if (quotechar)
  2391. break;
  2392. quotechar = c;
  2393. continue;
  2394. case '\\': {
  2395. if (*cmdline&&!quotechar) {
  2396. c = *(cmdline++);
  2397. switch (c) {
  2398. case 'a': c = '\a'; break;
  2399. case 'b': c = '\b'; break;
  2400. case 'f': c = '\f'; break;
  2401. case 'n': c = '\n'; break;
  2402. case 'r': c = '\r'; break;
  2403. case 't': c = '\t'; break;
  2404. case 'v': c = '\v'; break;
  2405. case 'x': case 'X': {
  2406. c = 0;
  2407. if (isHexChar(*cmdline)) {
  2408. c = hexValue(*(cmdline++));
  2409. if (isHexChar(*cmdline))
  2410. c = ((byte)c*16)+hexValue(*(cmdline++));
  2411. }
  2412. }
  2413. break;
  2414. case '0': case '1': case '2': case '3':
  2415. case '4': case '5': case '6': case '7': {
  2416. c = octValue(c);
  2417. if (isOctChar(*cmdline)) {
  2418. c = ((byte)c*8)+octValue(*(cmdline++));
  2419. if (isOctChar(*cmdline))
  2420. c = ((byte)c*8)+octValue(*(cmdline++));
  2421. }
  2422. }
  2423. break;
  2424. }
  2425. }
  2426. }
  2427. break;
  2428. }
  2429. if (!arg[argc])
  2430. arg[argc] = mb.length();
  2431. mb.append(c);
  2432. }
  2433. return 0;
  2434. }
  2435. jlib_decl StringBuffer &getTempFilePath(StringBuffer & target, const char * component, IPropertyTree * pTree)
  2436. {
  2437. StringBuffer dir;
  2438. if (pTree)
  2439. getConfigurationDirectory(pTree->queryPropTree("Directories"),"temp",component,pTree->queryProp("@name"),dir);
  2440. if (!dir.length())
  2441. {
  2442. #ifdef _WIN32
  2443. char path[_MAX_PATH+1];
  2444. if(GetTempPath(sizeof(path),path))
  2445. dir.append(path).append("HPCCSystems\\hpcc-data");
  2446. else
  2447. dir.append("c:\\HPCCSystems\\hpcc-data\\temp");
  2448. #else
  2449. dir.append(getenv("TMPDIR"));
  2450. if (!dir.length())
  2451. dir.append("/var/lib");
  2452. dir.append("/HPCCSystems/hpcc-data/temp");
  2453. #endif
  2454. }
  2455. dir.append(PATHSEPCHAR).append(component);
  2456. recursiveCreateDirectory(dir.str());
  2457. return target.set(dir);
  2458. }
  2459. jlib_decl const char *getEnumText(int value, const mapEnums *map)
  2460. {
  2461. const char *defval = map->str;
  2462. while (map->str)
  2463. {
  2464. if (value==map->val)
  2465. return map->str;
  2466. map++;
  2467. }
  2468. assertex(!"Unexpected value in getEnumText");
  2469. return defval;
  2470. }
  2471. //#define TESTURL
  2472. #ifdef TESTURL
  2473. static int doTests()
  2474. {
  2475. const char* ps[] = {
  2476. "ABCD", "@BCD", "%BCD","&BCD","A CD","A/CD", "A@@%%A","A&%/@"
  2477. };
  2478. const int N = sizeof(ps)/sizeof(char*);
  2479. for (int i=0; i<N; i++)
  2480. {
  2481. StringBuffer raw, encoded;
  2482. encodeUrlUseridPassword(encoded,ps[i]);
  2483. printf("Encoded: %s\n", encoded.str());
  2484. decodeUrlUseridPassword(raw,encoded);
  2485. if (strcmp(raw.str(),ps[i])!=0)
  2486. assert(!"decoding error");
  2487. }
  2488. return 0;
  2489. }
  2490. int gDummy = doTests();
  2491. #endif