jutil.cpp 77 KB

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