jutil.cpp 68 KB

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