jutil.cpp 71 KB

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