jutil.cpp 70 KB

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