jutil.cpp 70 KB

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