jutil.cpp 67 KB

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