jutil.cpp 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135
  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 <limits.h>
  48. #include "build-config.h"
  49. #include "portlist.h"
  50. static NonReentrantSpinLock * cvtLock;
  51. #ifdef _WIN32
  52. static IRandomNumberGenerator * protectedGenerator;
  53. static CriticalSection * protectedGeneratorCs;
  54. #endif
  55. #if defined (__APPLE__)
  56. #include <mach-o/dyld.h>
  57. #include <mach/mach_time.h> /* mach_absolute_time */
  58. mach_timebase_info_data_t timebase_info = { 1,1 };
  59. #endif
  60. MODULE_INIT(INIT_PRIORITY_SYSTEM)
  61. {
  62. cvtLock = new NonReentrantSpinLock;
  63. #ifdef _WIN32
  64. protectedGenerator = createRandomNumberGenerator();
  65. protectedGeneratorCs = new CriticalSection;
  66. #endif
  67. #if defined (__APPLE__)
  68. if (mach_timebase_info(&timebase_info) != KERN_SUCCESS)
  69. return false;
  70. #endif
  71. return true;
  72. }
  73. MODULE_EXIT()
  74. {
  75. delete cvtLock;
  76. #ifdef _WIN32
  77. protectedGenerator->Release();
  78. delete protectedGeneratorCs;
  79. #endif
  80. }
  81. //===========================================================================
  82. bool safe_ecvt(size_t len, char * buffer, double value, int numDigits, int * decimal, int * sign)
  83. {
  84. #ifdef _WIN32
  85. return _ecvt_s(buffer, len, value, numDigits, decimal, sign) == 0;
  86. #else
  87. NonReentrantSpinBlock block(*cvtLock);
  88. const char * result = ecvt(value, numDigits, decimal, sign);
  89. if (!result)
  90. return false;
  91. strncpy(buffer, result, len);
  92. return true;
  93. #endif
  94. }
  95. bool safe_fcvt(size_t len, char * buffer, double value, int numPlaces, int * decimal, int * sign)
  96. {
  97. #ifdef _WIN32
  98. return _fcvt_s(buffer, len, value, numPlaces, decimal, sign) == 0;
  99. #else
  100. NonReentrantSpinBlock block(*cvtLock);
  101. const char * result = fcvt(value, numPlaces, decimal, sign);
  102. if (!result)
  103. return false;
  104. strncpy(buffer, result, len);
  105. return true;
  106. #endif
  107. }
  108. //===========================================================================
  109. bool j_isnan(double x)
  110. {
  111. #ifdef _MSC_VER
  112. return _isnan(x)!=0;
  113. #else
  114. return std::isnan(x);
  115. #endif
  116. }
  117. bool j_isinf(double x)
  118. {
  119. #ifdef _MSC_VER
  120. int fpv = _fpclass(x);
  121. return (fpv==_FPCLASS_PINF || fpv==_FPCLASS_NINF);
  122. #else
  123. return std::isinf(x);
  124. #endif
  125. }
  126. #ifdef _WIN32
  127. void MilliSleep(unsigned milli)
  128. {
  129. Sleep(milli);
  130. }
  131. #else
  132. void MilliSleep(unsigned milli)
  133. {
  134. if (milli) {
  135. unsigned target = msTick()+milli;
  136. for (;;) {
  137. timespec sleepTime;
  138. if (milli>=1000)
  139. {
  140. sleepTime.tv_sec = milli/1000;
  141. milli %= 1000;
  142. }
  143. else
  144. sleepTime.tv_sec = 0;
  145. sleepTime.tv_nsec = milli * 1000000;
  146. if (nanosleep(&sleepTime, NULL)==0)
  147. break;
  148. if (errno!=EINTR) {
  149. PROGLOG("MilliSleep err %d",errno);
  150. break;
  151. }
  152. milli = target-msTick();
  153. if ((int)milli<=0)
  154. break;
  155. }
  156. }
  157. else
  158. ThreadYield(); // 0 means yield
  159. }
  160. #endif
  161. long atolong_l(const char * s,int l)
  162. {
  163. char t[32];
  164. memcpy(t,s,l);
  165. t[l]=0;
  166. return atol(t);
  167. }
  168. int atoi_l(const char * s,int l)
  169. {
  170. char t[32];
  171. memcpy(t,s,l);
  172. t[l]=0;
  173. return atoi(t);
  174. }
  175. __int64 atoi64_l(const char * s,int l)
  176. {
  177. __int64 result = 0;
  178. char sign = '+';
  179. while (l>0 && isspace(*s))
  180. {
  181. l--;
  182. s++;
  183. }
  184. if (l>0 && (*s == '-' || *s == '+'))
  185. {
  186. sign = *s;
  187. l--;
  188. s++;
  189. }
  190. while (l>0 && isdigit(*s))
  191. {
  192. result = 10 * result + ((*s) - '0');
  193. l--;
  194. s++;
  195. }
  196. if (sign == '-')
  197. return -result;
  198. else
  199. return result;
  200. }
  201. #ifndef _WIN32
  202. static char *_itoa(unsigned long n, char *str, int b, bool sign)
  203. {
  204. char *s = str;
  205. if (sign)
  206. n = -n;
  207. do
  208. {
  209. byte d = n % b;
  210. *(s++) = d+((d<10)?'0':('a'-10));
  211. }
  212. while ((n /= b) > 0);
  213. if (sign)
  214. *(s++) = '-';
  215. *s = '\0';
  216. // reverse
  217. char *s2 = str;
  218. s--;
  219. while (s2<s)
  220. {
  221. char tc = *s2;
  222. *(s2++) = *s;
  223. *(s--) = tc;
  224. }
  225. return str;
  226. }
  227. char *itoa(int n, char *str, int b)
  228. {
  229. return _itoa(n, str, b, (n<0));
  230. }
  231. char *ltoa(long n, char *str, int b)
  232. {
  233. return _itoa(n, str, b, (n<0));
  234. }
  235. char *ultoa(unsigned long n, char *str, int b)
  236. {
  237. return _itoa(n, str, b, false);
  238. }
  239. #endif
  240. void packNumber(char * target, const char * source, unsigned slen)
  241. {
  242. unsigned next = 0;
  243. while (slen)
  244. {
  245. unsigned c = *source++;
  246. if (c == ' ') c = '0';
  247. next = (next << 4) + (c - '0');
  248. slen--;
  249. if ((slen & 1) == 0)
  250. {
  251. *target++ = next;
  252. next = 0;
  253. }
  254. }
  255. }
  256. void unpackNumber(char * target, const char * source, unsigned tlen)
  257. {
  258. if (tlen & 1)
  259. {
  260. *target = '0' + *source++;
  261. tlen--;
  262. }
  263. while (tlen)
  264. {
  265. unsigned char next = *source++;
  266. *target++ = (next >> 4) + '0';
  267. *target++ = (next & 15) + '0';
  268. tlen -= 2;
  269. }
  270. }
  271. //-----------------------------------------------------------------------
  272. class jlib_thrown_decl CorruptDllException : public CInterfaceOf<ICorruptDllException>
  273. {
  274. public:
  275. CorruptDllException(int code, const char *_dllName, const char *_dlError)
  276. : errcode(code)
  277. {
  278. VStringBuffer s("Error loading %s: %s", _dllName, _dlError);
  279. msg.set(s.str());
  280. };
  281. int errorCode() const { return errcode; }
  282. StringBuffer & errorMessage(StringBuffer &str) const
  283. {
  284. return str.append(msg.get());
  285. }
  286. MessageAudience errorAudience() const
  287. {
  288. return MSGAUD_operator;
  289. }
  290. private:
  291. int errcode;
  292. StringAttr msg;
  293. };
  294. static bool isCorruptDll(const char *errorMessage)
  295. {
  296. // yuk.
  297. // Add other error strings for corrupt .so files as/when we encounter them
  298. if (strstr(errorMessage, "file too short") ||
  299. strstr(errorMessage, "ELF load command past end of file"))
  300. return true;
  301. return false;
  302. }
  303. //-----------------------------------------------------------------------
  304. #ifdef __APPLE__
  305. bool findLoadedModule(StringBuffer &ret, const char *match)
  306. {
  307. bool found = false;
  308. unsigned count = _dyld_image_count();
  309. for (unsigned i = 0; i<count; i++)
  310. {
  311. const char *ln = _dyld_get_image_name(i);
  312. if (ln)
  313. {
  314. if (strstr(ln, match))
  315. {
  316. ret.set(ln);
  317. found = true;
  318. break;
  319. }
  320. }
  321. }
  322. return found;
  323. }
  324. #elif !defined(WIN32)
  325. bool findLoadedModule(StringBuffer &ret, const char *match)
  326. {
  327. bool found = false;
  328. FILE *diskfp = fopen("/proc/self/maps", "r");
  329. if (diskfp)
  330. {
  331. char ln[_MAX_PATH];
  332. while (fgets(ln, sizeof(ln), diskfp))
  333. {
  334. if (strstr(ln, match))
  335. {
  336. const char *fullName = strchr(ln, '/');
  337. if (fullName)
  338. {
  339. char * lf = (char *) strchr(fullName, '\n');
  340. if (lf)
  341. {
  342. *lf = 0;
  343. ret.set(fullName);
  344. found = true;
  345. break;
  346. }
  347. }
  348. }
  349. }
  350. fclose(diskfp);
  351. }
  352. return found;
  353. }
  354. #endif
  355. HINSTANCE LoadSharedObject(const char *name, bool isGlobal, bool raiseOnError)
  356. {
  357. #if defined(_WIN32)
  358. UINT oldMode = SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);
  359. #else
  360. // don't think anything to do here.
  361. #endif
  362. DynamicScopeCtx scope;
  363. StringBuffer tmp;
  364. if (name&&isPathSepChar(*name)&&isPathSepChar(name[1])) {
  365. RemoteFilename rfn;
  366. rfn.setRemotePath(name);
  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. OWARNLOG("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. NO_SANITIZE("signed-integer-overflow") 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; // This can overflow and thus behaviour is theoretically undefined.
  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)
  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)
  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. int minus4096 = -4096; // Stops compiler being clever enough to report error
  1464. void doStackProbe()
  1465. {
  1466. byte local;
  1467. const volatile byte * x = (const byte *)&local;
  1468. byte forceload __attribute__((unused)) = x[minus4096];
  1469. }
  1470. #ifdef __GNUC__
  1471. #pragma GCC diagnostic pop
  1472. #endif
  1473. extern jlib_decl bool isContainerized()
  1474. {
  1475. #ifdef _CONTAINERIZED
  1476. return true;
  1477. #else
  1478. return false;
  1479. #endif
  1480. }
  1481. #ifdef _WIN32
  1482. DWORD dwTlsIndex = -1;
  1483. CriticalSection tlscrit;
  1484. void initThreadLocal(int len, void* val)
  1485. {
  1486. {
  1487. CriticalBlock b(tlscrit);
  1488. if(dwTlsIndex == -1)
  1489. {
  1490. if ((dwTlsIndex = TlsAlloc()) == TLS_OUT_OF_INDEXES)
  1491. throw MakeStringException(-1, "TlsAlloc failed");
  1492. }
  1493. }
  1494. LPVOID lpvData;
  1495. lpvData = TlsGetValue(dwTlsIndex);
  1496. if (lpvData != 0)
  1497. LocalFree((HLOCAL) lpvData);
  1498. // Initialize the TLS index for this thread.
  1499. lpvData = (LPVOID) LocalAlloc(LPTR, len);
  1500. memcpy((char*)lpvData, val, len);
  1501. if (! TlsSetValue(dwTlsIndex, lpvData))
  1502. throw MakeStringException(-1, "TlsSetValue error");
  1503. }
  1504. void* getThreadLocalVal()
  1505. {
  1506. if(dwTlsIndex == -1)
  1507. return NULL;
  1508. return TlsGetValue(dwTlsIndex);
  1509. }
  1510. void clearThreadLocal()
  1511. {
  1512. if(dwTlsIndex == -1)
  1513. return;
  1514. LPVOID lpvData = TlsGetValue(dwTlsIndex);
  1515. if (lpvData != 0)
  1516. {
  1517. LocalFree((HLOCAL) lpvData);
  1518. if (! TlsSetValue(dwTlsIndex, NULL))
  1519. throw MakeStringException(-1, "TlsSetValue error");
  1520. }
  1521. }
  1522. #else
  1523. // Key for the thread-specific buffer
  1524. static pthread_key_t buffer_key;
  1525. // Once-only initialisation of the key
  1526. static pthread_once_t buffer_key_once = PTHREAD_ONCE_INIT;
  1527. // Free the thread-specific buffer
  1528. static void buffer_destroy(void * buf)
  1529. {
  1530. if(buf)
  1531. free(buf);
  1532. }
  1533. // Allocate the key
  1534. static void buffer_key_alloc()
  1535. {
  1536. pthread_key_create(&buffer_key, buffer_destroy);
  1537. }
  1538. // Allocate the thread-specific buffer
  1539. void initThreadLocal(int len, void* val)
  1540. {
  1541. pthread_once(&buffer_key_once, buffer_key_alloc);
  1542. void* valbuf = malloc(len);
  1543. memcpy(valbuf, val, len);
  1544. pthread_setspecific(buffer_key, valbuf);
  1545. }
  1546. // Return the thread-specific buffer
  1547. void* getThreadLocalVal()
  1548. {
  1549. return (char *) pthread_getspecific(buffer_key);
  1550. }
  1551. void clearThreadLocal()
  1552. {
  1553. }
  1554. #endif
  1555. StringBuffer &expandMask(StringBuffer &buf, const char *mask, unsigned p, unsigned n)
  1556. {
  1557. const char *s=mask;
  1558. if (s)
  1559. while (*s) {
  1560. char next = *(s++);
  1561. if (next=='$') {
  1562. char pc = toupper(s[0]);
  1563. if (pc&&(s[1]=='$')) {
  1564. if (pc=='P') {
  1565. buf.append(p+1);
  1566. next = 0;
  1567. s+=2;
  1568. }
  1569. else if (pc=='N') {
  1570. buf.append(n);
  1571. next = 0;
  1572. s+=2;
  1573. }
  1574. }
  1575. }
  1576. if (next)
  1577. buf.append(next);
  1578. }
  1579. return buf;
  1580. }
  1581. static const char *findExtension(const char *fn)
  1582. {
  1583. if (!fn)
  1584. return NULL;
  1585. const char *ret = strchr(fn,'.');
  1586. if (ret) {
  1587. for (;;) {
  1588. ret++;
  1589. const char *s = strchr(ret,'.');
  1590. if (!s)
  1591. break;
  1592. ret = s;
  1593. }
  1594. }
  1595. return ret;
  1596. }
  1597. unsigned runExternalCommand(StringBuffer &output, StringBuffer &error, const char *cmd, const char *input)
  1598. {
  1599. return runExternalCommand(cmd, output, error, cmd, input);
  1600. }
  1601. unsigned runExternalCommand(const char *title, StringBuffer &output, StringBuffer &error, const char *cmd, const char *input)
  1602. {
  1603. try
  1604. {
  1605. Owned<IPipeProcess> pipe = createPipeProcess();
  1606. int ret = START_FAILURE;
  1607. if (pipe->run(title, cmd, ".", input != NULL, true, true, 1024*1024))
  1608. {
  1609. if (input)
  1610. {
  1611. pipe->write(strlen(input), input);
  1612. pipe->closeInput();
  1613. }
  1614. char buf[1024];
  1615. while (true)
  1616. {
  1617. size32_t read = pipe->read(sizeof(buf), buf);
  1618. if (!read)
  1619. break;
  1620. output.append(read, buf);
  1621. }
  1622. ret = pipe->wait();
  1623. while (true)
  1624. {
  1625. size32_t read = pipe->readError(sizeof(buf), buf);
  1626. if (!read)
  1627. break;
  1628. error.append(read, buf);
  1629. }
  1630. }
  1631. return ret;
  1632. }
  1633. catch (IException *E)
  1634. {
  1635. E->Release();
  1636. output.clear();
  1637. return START_FAILURE;
  1638. }
  1639. }
  1640. bool matchesMask(const char *fn, const char *mask, unsigned p, unsigned n)
  1641. {
  1642. StringBuffer match;
  1643. expandMask(match,mask,p,n);
  1644. return (stricmp(fn,match.str())==0);
  1645. }
  1646. bool constructMask(StringAttr &attr, const char *fn, unsigned p, unsigned n)
  1647. {
  1648. StringBuffer buf;
  1649. const char *ext = findExtension(fn);
  1650. if (!ext)
  1651. return false;
  1652. buf.append((size32_t)(ext-fn),fn).append("_$P$_of_$N$");
  1653. if (matchesMask(fn,buf.str(),p,n)) {
  1654. attr.set(buf.str());
  1655. return true;
  1656. }
  1657. return false;
  1658. }
  1659. bool deduceMask(const char *fn, bool expandN, StringAttr &mask, unsigned &pret, unsigned &nret)
  1660. {
  1661. const char *e = findExtension(fn);
  1662. if (!e)
  1663. return false;
  1664. for (;;) {
  1665. const char *s=e;
  1666. if (*s=='_') {
  1667. s++;
  1668. unsigned p = 0;
  1669. while (isdigit(*s))
  1670. p = p*10+*(s++)-'0';
  1671. if (p&&(memcmp(s,"_of_",4)==0)) {
  1672. s += 4;
  1673. pret = p-1;
  1674. p = 0;
  1675. while (isdigit(*s))
  1676. p = p*10+*(s++)-'0';
  1677. nret = p;
  1678. if (((*s==0)||(*s=='.'))&&(p>pret)) {
  1679. StringBuffer buf;
  1680. if (expandN)
  1681. buf.append((size32_t)(e-fn),fn).append("_$P$_of_").append(p);
  1682. else
  1683. buf.append((size32_t)(e-fn),fn).append("_$P$_of_$N$");
  1684. if (*s=='.')
  1685. buf.append(s);
  1686. mask.set(buf);
  1687. return true;
  1688. }
  1689. }
  1690. }
  1691. e--;
  1692. for (;;) {
  1693. if (e==fn)
  1694. return false;
  1695. if (*(e-1)=='.')
  1696. break;
  1697. e--;
  1698. }
  1699. }
  1700. return false;
  1701. }
  1702. //==============================================================
  1703. #ifdef _WIN32
  1704. class CWindowsAuthenticatedUser: implements IAuthenticatedUser, public CInterface
  1705. {
  1706. StringAttr name;
  1707. HANDLE usertoken;
  1708. public:
  1709. IMPLEMENT_IINTERFACE;
  1710. CWindowsAuthenticatedUser()
  1711. {
  1712. usertoken = (HANDLE)-1;
  1713. }
  1714. ~CWindowsAuthenticatedUser()
  1715. {
  1716. if (usertoken != (HANDLE)-1)
  1717. CloseHandle(usertoken);
  1718. }
  1719. bool login(const char *user, const char *passwd)
  1720. {
  1721. name.clear();
  1722. if (usertoken != (HANDLE)-1)
  1723. CloseHandle(usertoken);
  1724. StringBuffer domain("");
  1725. const char *ut = strchr(user,'\\');
  1726. if (ut) {
  1727. domain.clear().append((size32_t)(ut-user),user);
  1728. user = ut+1;
  1729. }
  1730. BOOL res = LogonUser((LPTSTR)user,(LPTSTR)(domain.length()==0?NULL:domain.str()),(LPTSTR)passwd,LOGON32_LOGON_NETWORK,LOGON32_PROVIDER_DEFAULT,&usertoken);
  1731. if (res==0)
  1732. return false;
  1733. name.set(user);
  1734. return true;
  1735. }
  1736. void impersonate()
  1737. {
  1738. if (!ImpersonateLoggedOnUser(usertoken))
  1739. throw makeOsException(GetLastError());
  1740. }
  1741. void revert()
  1742. {
  1743. RevertToSelf();
  1744. }
  1745. const char *username()
  1746. {
  1747. return name.get();
  1748. }
  1749. };
  1750. IAuthenticatedUser *createAuthenticatedUser() { return new CWindowsAuthenticatedUser; }
  1751. #elif defined(__linux__)
  1752. class CLinuxAuthenticatedUser: implements IAuthenticatedUser, public CInterface
  1753. {
  1754. StringAttr name;
  1755. uid_t uid;
  1756. gid_t gid;
  1757. uid_t saveuid;
  1758. gid_t savegid;
  1759. public:
  1760. IMPLEMENT_IINTERFACE;
  1761. bool login(const char *user, const char *passwd)
  1762. {
  1763. name.clear();
  1764. const char *ut = strchr(user,'\\');
  1765. if (ut)
  1766. user = ut+1; // remove windows domain
  1767. struct passwd *pw;
  1768. char *epasswd;
  1769. if ((pw = getpwnam(user)) == NULL)
  1770. return false;
  1771. struct spwd *spwd = getspnam(user);
  1772. if (spwd)
  1773. epasswd = spwd->sp_pwdp;
  1774. else
  1775. epasswd = pw->pw_passwd;
  1776. if (!epasswd||!*epasswd)
  1777. return false;
  1778. if (strcmp(crypt(passwd,epasswd),epasswd)!=0)
  1779. return false;
  1780. uid = pw->pw_uid;
  1781. gid = pw->pw_gid;
  1782. name.set(pw->pw_name);
  1783. return true;
  1784. }
  1785. void impersonate()
  1786. {
  1787. saveuid = geteuid();
  1788. savegid = getegid();
  1789. if (setegid(gid) == -1)
  1790. throw makeOsException(errno, "Failed to set effective group id");
  1791. if (seteuid(uid) == -1)
  1792. throw makeOsException(errno, "Failed to set effective user id");
  1793. }
  1794. void revert()
  1795. {
  1796. if (seteuid(saveuid) == -1)
  1797. throw makeOsException(errno, "Failed to restore effective group id");
  1798. if (setegid(savegid) == -1)
  1799. throw makeOsException(errno, "Failed to restore effective user id");
  1800. }
  1801. const char *username()
  1802. {
  1803. return name.get();
  1804. }
  1805. };
  1806. IAuthenticatedUser *createAuthenticatedUser() { return new CLinuxAuthenticatedUser; }
  1807. #elif defined(__FreeBSD__) || defined (__APPLE__)
  1808. IAuthenticatedUser *createAuthenticatedUser() { UNIMPLEMENTED; }
  1809. #endif
  1810. extern jlib_decl void serializeAtom(MemoryBuffer & target, IAtom * name)
  1811. {
  1812. StringBuffer lower(str(name));
  1813. lower.toLowerCase();
  1814. serialize(target, lower.str());
  1815. }
  1816. extern jlib_decl IAtom * deserializeAtom(MemoryBuffer & source)
  1817. {
  1818. StringAttr text;
  1819. deserialize(source, text);
  1820. if (text)
  1821. return createAtom(text);
  1822. return NULL;
  1823. }
  1824. //==============================================================
  1825. static const char enc64[65] =
  1826. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1827. "abcdefghijklmnopqrstuvwxyz"
  1828. "0123456789-_";
  1829. static inline void encode3_64(byte *in,StringBuffer &out)
  1830. {
  1831. // 3 bytes in 4 out
  1832. out.append(enc64[in[0]>>2]);
  1833. out.append(enc64[((in[0] << 4) & 0x30) | (in[1] >> 4)]);
  1834. out.append(enc64[((in[1] << 2) & 0x3c) | (in[2] >> 6)]);
  1835. out.append(enc64[in[2] & 0x3f]);
  1836. }
  1837. static NonReentrantSpinLock lock;
  1838. static unsigned uuidbin[5] = {0,0,0,0,0};
  1839. StringBuffer &genUUID(StringBuffer &out, bool nocase)
  1840. { // returns a 24 char UUID for nocase=false or 32 char for nocase=true
  1841. lock.enter();
  1842. // could be quicker using statics
  1843. if (uuidbin[0]==0) {
  1844. queryHostIP().getNetAddress(sizeof(uuidbin[0]),uuidbin);
  1845. uuidbin[1] = (unsigned)GetCurrentProcessId();
  1846. }
  1847. time_t t;
  1848. time(&t);
  1849. uuidbin[2] = (unsigned)t;
  1850. uuidbin[3] = msTick();
  1851. uuidbin[4]++;
  1852. byte *in = (byte *)uuidbin;
  1853. if (nocase) {
  1854. encode5_32(in,out);
  1855. encode5_32(in+5,out);
  1856. encode5_32(in+10,out);
  1857. encode5_32(in+15,out);
  1858. }
  1859. else {
  1860. encode3_64(in,out);
  1861. encode3_64(in+3,out);
  1862. encode3_64(in+6,out);
  1863. encode3_64(in+9,out);
  1864. byte tmp[3]; // drop two msb bytes from msec time
  1865. tmp[0] = in[12];
  1866. tmp[1] = in[13];
  1867. tmp[2] = in[16];
  1868. encode3_64(tmp,out);
  1869. encode3_64(in+17,out);
  1870. }
  1871. lock.leave();
  1872. return out;
  1873. }
  1874. //==============================================================
  1875. class jlib_decl CNameCountTable : public AtomRefTable
  1876. {
  1877. public:
  1878. CNameCountTable(bool _nocase=false) : AtomRefTable(_nocase) { }
  1879. StringBuffer &dump(StringBuffer &str)
  1880. {
  1881. SuperHashIteratorOf<HashKeyElement> iter(*this);
  1882. CriticalBlock b(crit);
  1883. ForEach (iter)
  1884. {
  1885. HashKeyElement &elem = iter.query();
  1886. str.append(elem.get()).append(", count = ").append(elem.queryReferences()).newline();
  1887. }
  1888. return str;
  1889. }
  1890. };
  1891. static CNameCountTable *namedCountHT;
  1892. MODULE_INIT(INIT_PRIORITY_SYSTEM)
  1893. {
  1894. namedCountHT = new CNameCountTable;
  1895. return true;
  1896. }
  1897. MODULE_EXIT()
  1898. {
  1899. delete namedCountHT;
  1900. }
  1901. NamedCount::NamedCount()
  1902. {
  1903. ht = NULL;
  1904. }
  1905. NamedCount::~NamedCount()
  1906. {
  1907. if (ht) namedCountHT->releaseKey(ht);
  1908. }
  1909. void NamedCount::set(const char *name)
  1910. {
  1911. ht = namedCountHT->queryCreate(name);
  1912. }
  1913. StringBuffer &dumpNamedCounts(StringBuffer &str)
  1914. {
  1915. return namedCountHT->dump(str);
  1916. }
  1917. //==============================================================
  1918. // class OffsetToString
  1919. OffsetToString::OffsetToString(offset_t offset)
  1920. {
  1921. #if defined(_MSC_VER) && !defined (_POSIX_) && (__STDC__ || _INTEGRAL_MAX_BITS < 64)
  1922. // fpos_t is defined as struct (see <stdio.h> in VC)
  1923. __int64 v = offset.lopart + (offset.hipart<<32);
  1924. m_buffer.append(v);
  1925. #else
  1926. m_buffer.append(offset);
  1927. #endif
  1928. }
  1929. /* Gentoo libc version omits these symbols which are directly */
  1930. /* referenced by some 3rd party libraries (sybase, Hasp). Until these */
  1931. /* libs get updated, provide linkable symbols within jlib for these... */
  1932. #if defined(__linux__) && (__GNUC__ >= 3)
  1933. const jlib_decl unsigned short int *__ctype_b = *__ctype_b_loc ();
  1934. const jlib_decl __int32_t *__ctype_tolower = *__ctype_tolower_loc();
  1935. const jlib_decl __int32_t *__ctype_toupper = *__ctype_toupper_loc();
  1936. // There seems to be some debate about whether these are needed
  1937. //#elif (__GNUC__ >= 3)
  1938. //const unsigned short int *__ctype_b = *__ctype_b_loc ();
  1939. //const unsigned int *__ctype_tolower = *__ctype_tolower_loc();
  1940. //const unsigned int *__ctype_toupper = *__ctype_toupper_loc();
  1941. #endif
  1942. //==============================================================
  1943. // URL Password, username handling
  1944. /*
  1945. From ftp://ftp.isi.edu/in-notes/rfc1738.txt:
  1946. http://<user>:<password>@<host>:<port>/<url-path>
  1947. Some or all of the parts "<user>:<password>@", ":<password>",
  1948. ":<port>", and "/<url-path>" may be excluded.
  1949. The user name (and password), if present, are followed by a
  1950. commercial at-sign "@". Within the user and password field, any ":",
  1951. "@", or "/" must be encoded.
  1952. */
  1953. jlib_decl StringBuffer& encodeUrlUseridPassword(StringBuffer& out, const char* in)
  1954. {
  1955. for (const char* p = in; *p; p++)
  1956. {
  1957. switch(*p)
  1958. {
  1959. // mentioned in rfc1738
  1960. case ':': out.append("%3A"); break;
  1961. case '@': out.append("%40"); break;
  1962. case '/': out.append("%2F"); break;
  1963. // these are not in the spec, but IE/Firefox has trouble if left un-encoded
  1964. case '%': out.append("%25"); break;
  1965. // these are not necessary: both IE and firefox handle them correctly
  1966. /*
  1967. case '&': out.append("%26"); break;
  1968. case ' ': out.append("%20"); break;
  1969. */
  1970. default: out.append(*p); break;
  1971. }
  1972. }
  1973. return out;
  1974. }
  1975. inline bool isHexChar(char c)
  1976. {
  1977. return (c>='0' && c<='9')
  1978. || (c>='A' && c<='F')
  1979. || (c>='a' && c<='f');
  1980. }
  1981. int hexValue(char c)
  1982. {
  1983. return (c>='0' && c<='9') ? c-'0' :
  1984. ((c>='A' && (c<='F') ? c-'A'+10 : c-'a'+10));
  1985. }
  1986. jlib_decl StringBuffer& decodeUrlUseridPassword(StringBuffer& out, const char* in)
  1987. {
  1988. for (const char* p = in; *p; p++)
  1989. {
  1990. if (*p=='%' && isHexChar(*(p+1)) && isHexChar(*(p+2)) )
  1991. {
  1992. char c1 = *(p+1), c2 = *(p+2);
  1993. int x = (hexValue(c1)<<4) + hexValue(c2);
  1994. out.appendf("%c",x);
  1995. p += 2;
  1996. }
  1997. else
  1998. out.appendf("%c",*p);
  1999. }
  2000. return out;
  2001. }
  2002. jlib_decl StringBuffer & passwordInput(const char* prompt, StringBuffer& passwd)
  2003. {
  2004. #ifdef _WIN32
  2005. printf("%s", prompt);
  2006. size32_t entrylen = passwd.length();
  2007. for (;;) {
  2008. char c = getch();
  2009. if (c == '\r')
  2010. break;
  2011. if (c == '\b') {
  2012. if (passwd.length()>entrylen) {
  2013. printf("\b \b");
  2014. passwd.setLength(passwd.length()-1);
  2015. }
  2016. }
  2017. else {
  2018. passwd.append(c);
  2019. printf("*");
  2020. }
  2021. }
  2022. printf("\n");
  2023. #else
  2024. // Unfortunately Linux tty can't easily support using '*' hiding
  2025. sigset_t saved_signals;
  2026. sigset_t set_signals;
  2027. struct termios saved_term;
  2028. struct termios set_term;
  2029. FILE *term = fopen(_PATH_TTY, "w+");
  2030. if (!term)
  2031. term = stdin;
  2032. int termfd = fileno(term);
  2033. fprintf(stdout, "%s", prompt);
  2034. fflush(stdout);
  2035. sigemptyset(&set_signals);
  2036. sigaddset(&set_signals, SIGINT);
  2037. sigaddset(&set_signals, SIGTSTP);
  2038. sigprocmask(SIG_BLOCK, &set_signals, &saved_signals);
  2039. tcgetattr(termfd, &saved_term);
  2040. set_term = saved_term;
  2041. set_term.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL);
  2042. tcsetattr(termfd, TCSAFLUSH, &set_term);
  2043. char c = EOF;
  2044. int rd = ::read(termfd,&c,1);
  2045. while ((rd==1)&&(c!='\r')&&(c!='\n')) {
  2046. passwd.append(c);
  2047. rd = ::read(termfd,&c,1);
  2048. }
  2049. int err = (rd<0)?errno:0;
  2050. tcsetattr(termfd, TCSAFLUSH, &saved_term);
  2051. sigprocmask(SIG_SETMASK, &saved_signals, 0);
  2052. if (term!=stdin)
  2053. fclose(term);
  2054. fprintf(stdout, "\n");
  2055. fflush(stdout);
  2056. if (err)
  2057. throw makeOsException(err);
  2058. #endif
  2059. return passwd;
  2060. }
  2061. StringBuffer & fillConfigurationDirectoryEntry(const char *dir,const char *name, const char *component, const char *instance, StringBuffer &dirout)
  2062. {
  2063. while (*dir) {
  2064. if (*dir=='[') {
  2065. if (memicmp(dir+1,"NAME]",5)==0) {
  2066. dirout.append(name);
  2067. dir += 5;
  2068. }
  2069. else if (memicmp(dir+1,"COMPONENT]",10)==0) {
  2070. dirout.append(component);
  2071. dir += 10;
  2072. }
  2073. else if (memicmp(dir+1,"INST]",5)==0){
  2074. dirout.append(instance);
  2075. dir += 5;
  2076. }
  2077. else
  2078. dirout.append('[');
  2079. }
  2080. else
  2081. dirout.append(*dir);
  2082. dir++;
  2083. }
  2084. return dirout;
  2085. }
  2086. IPropertyTree *getHPCCEnvironment()
  2087. {
  2088. StringBuffer envfile;
  2089. if (queryEnvironmentConf().getProp("environment",envfile) && envfile.length())
  2090. {
  2091. if (!isAbsolutePath(envfile.str()))
  2092. {
  2093. envfile.insert(0, CONFIG_DIR PATHSEPSTR);
  2094. }
  2095. Owned<IFile> file = createIFile(envfile.str());
  2096. if (file)
  2097. {
  2098. Owned<IFileIO> fileio = file->open(IFOread);
  2099. if (fileio)
  2100. return createPTree(*fileio, ipt_lowmem);
  2101. }
  2102. }
  2103. return NULL;
  2104. }
  2105. static Owned<IProperties> envConfFile;
  2106. static CriticalSection envConfCrit;
  2107. jlib_decl const IProperties &queryEnvironmentConf()
  2108. {
  2109. CriticalBlock b(envConfCrit);
  2110. if (!envConfFile)
  2111. envConfFile.setown(createProperties(CONFIG_DIR PATHSEPSTR ENV_CONF_FILE, true));
  2112. return *envConfFile;
  2113. }
  2114. static StringBuffer DAFSpassPhraseDec;//deprecated
  2115. static CriticalSection DAFSpassPhraseCrit;
  2116. //Deprecated, please use queryHPCCPKIKeyFiles() instead
  2117. jlib_decl bool querySecuritySettings(DAFSConnectCfg *_connectMethod,
  2118. unsigned short *_port,
  2119. const char * * _certificate,
  2120. const char * * _privateKey,
  2121. const char * * _passPhrase)//decrypted passphrase
  2122. {
  2123. if (_connectMethod)
  2124. *_connectMethod = SSLNone;//default
  2125. if (_port)
  2126. *_port = DAFILESRV_PORT;//default
  2127. const IProperties & conf = queryEnvironmentConf();
  2128. StringAttr sslMethod;
  2129. sslMethod.set(conf.queryProp("dfsUseSSL"));
  2130. if (!sslMethod.isEmpty())
  2131. {
  2132. DAFSConnectCfg tmpMethod;
  2133. // checking for true | false for backward compatibility
  2134. if ( strieq(sslMethod.str(), "SSLOnly") || strieq(sslMethod.str(), "true") )
  2135. tmpMethod = SSLOnly;
  2136. else if ( strieq(sslMethod.str(), "SSLFirst") )
  2137. tmpMethod = SSLFirst;
  2138. else if ( strieq(sslMethod.str(), "UnsecureFirst") )
  2139. tmpMethod = UnsecureFirst;
  2140. else // SSLNone or false or ...
  2141. tmpMethod = SSLNone;
  2142. if (_connectMethod)
  2143. *_connectMethod = tmpMethod;
  2144. if (_port)
  2145. {
  2146. if (tmpMethod == SSLOnly || tmpMethod == SSLFirst)
  2147. *_port = SECURE_DAFILESRV_PORT;
  2148. }
  2149. //Begin of deprecated code
  2150. bool dfsKeywords = false;
  2151. if (_certificate)
  2152. {
  2153. *_certificate = conf.queryProp("dfsSSLCertFile");
  2154. if (*_certificate)
  2155. dfsKeywords = true;
  2156. }
  2157. if (_privateKey)
  2158. {
  2159. *_privateKey = conf.queryProp("dfsSSLPrivateKeyFile");
  2160. if (*_privateKey)
  2161. dfsKeywords = true;
  2162. }
  2163. StringBuffer DAFSpassPhraseEnc;
  2164. if (_passPhrase)
  2165. {
  2166. CriticalBlock b(DAFSpassPhraseCrit);
  2167. if (DAFSpassPhraseDec.isEmpty())//previously retrieved/decrypted it?
  2168. {
  2169. const char *passPhrasePtr = conf.queryProp("dfsSSLPassPhrase");
  2170. if (!isEmptyString(passPhrasePtr))
  2171. {
  2172. DAFSpassPhraseEnc.append(passPhrasePtr);//got encrypted pwd
  2173. dfsKeywords = true;
  2174. }
  2175. }
  2176. }
  2177. if (!dfsKeywords && (_certificate || _privateKey || _passPhrase))
  2178. {
  2179. //end of deprecated code
  2180. const char *passPhrasePtr = nullptr;
  2181. queryHPCCPKIKeyFiles(_certificate, nullptr, _privateKey, _passPhrase ? &passPhrasePtr : nullptr);//use new keywords
  2182. if (!isEmptyString(passPhrasePtr))
  2183. {
  2184. CriticalBlock b(DAFSpassPhraseCrit);
  2185. if (DAFSpassPhraseEnc.isEmpty())
  2186. DAFSpassPhraseEnc.append(passPhrasePtr);//got encrypted pwd
  2187. }
  2188. }
  2189. if (_passPhrase)
  2190. {
  2191. CriticalBlock b(DAFSpassPhraseCrit);
  2192. if (DAFSpassPhraseDec.isEmpty() && !DAFSpassPhraseEnc.isEmpty())
  2193. decrypt(DAFSpassPhraseDec, DAFSpassPhraseEnc.str());
  2194. *_passPhrase = DAFSpassPhraseDec.str();//return decrypted password. Note the preferred queryHPCCPKIKeyFiles() method returns it encrypted
  2195. }
  2196. }
  2197. return true;
  2198. }
  2199. jlib_decl bool queryDafsSecSettings(DAFSConnectCfg *_connectMethod,
  2200. unsigned short *_port,
  2201. unsigned short *_sslport,
  2202. const char * * _certificate,
  2203. const char * * _privateKey,
  2204. const char * * _passPhrase)
  2205. {
  2206. bool ret = querySecuritySettings(_connectMethod, nullptr, _certificate, _privateKey, _passPhrase);
  2207. if (ret)
  2208. {
  2209. if (_port)
  2210. *_port = DAFILESRV_PORT;
  2211. if (_sslport)
  2212. *_sslport = SECURE_DAFILESRV_PORT;
  2213. }
  2214. return ret;
  2215. }
  2216. //query PKI values from environment.conf
  2217. jlib_decl bool queryHPCCPKIKeyFiles(const char * * _certificate,//HPCCCertificateFile
  2218. const char * * _publicKey, //HPCCPublicKeyFile
  2219. const char * * _privateKey, //HPCCPrivateKeyFile
  2220. const char * * _passPhrase) //HPCCPassPhrase
  2221. {
  2222. const IProperties & conf = queryEnvironmentConf();
  2223. if (_certificate)
  2224. *_certificate = conf.queryProp("HPCCCertificateFile");
  2225. if (_publicKey)
  2226. *_publicKey = conf.queryProp("HPCCPublicKeyFile");
  2227. if (_privateKey)
  2228. *_privateKey = conf.queryProp("HPCCPrivateKeyFile");
  2229. if (_passPhrase)
  2230. *_passPhrase = conf.queryProp("HPCCPassPhrase"); //return encrypted
  2231. return true;
  2232. }
  2233. static IPropertyTree *getOSSdirTree()
  2234. {
  2235. Owned<IPropertyTree> envtree = getHPCCEnvironment();
  2236. if (envtree) {
  2237. IPropertyTree *ret = envtree->queryPropTree("Software/Directories");
  2238. if (ret)
  2239. return createPTreeFromIPT(ret);
  2240. }
  2241. return NULL;
  2242. }
  2243. StringBuffer &getFileAccessUrl(StringBuffer &out)
  2244. {
  2245. Owned<IPropertyTree> envtree = getHPCCEnvironment();
  2246. if (envtree)
  2247. {
  2248. IPropertyTree *secureFileAccessInfo = envtree->queryPropTree("EnvSettings/SecureFileAccess");
  2249. if (secureFileAccessInfo)
  2250. {
  2251. const char *protocol = secureFileAccessInfo->queryProp("@protocol");
  2252. const char *host = secureFileAccessInfo->queryProp("@host");
  2253. unsigned port = secureFileAccessInfo->getPropInt("@port", (unsigned)-1);
  2254. if (isEmptyString(protocol))
  2255. OWARNLOG("Missing protocol from secure file access definition");
  2256. else if (isEmptyString(host))
  2257. OWARNLOG("Missing host from secure file access definition");
  2258. else if ((unsigned)-1 == port)
  2259. OWARNLOG("Missing port from secure file access definition");
  2260. else
  2261. out.appendf("%s://%s:%u/WsDfu", protocol, host, port);
  2262. }
  2263. }
  2264. return out;
  2265. }
  2266. bool getConfigurationDirectory(const IPropertyTree *useTree, const char *category, const char *component, const char *instance, StringBuffer &dirout)
  2267. {
  2268. Linked<const IPropertyTree> dirtree = useTree;
  2269. if (!dirtree)
  2270. dirtree.setown(getOSSdirTree());
  2271. if (dirtree && category && *category)
  2272. {
  2273. const char *name = dirtree->queryProp("@name");
  2274. if (name&&*name) {
  2275. StringBuffer q("Category[@name=\"");
  2276. q.append(category).append("\"]");
  2277. IPropertyTree *cat = dirtree->queryPropTree(q.str()); // assume only 1
  2278. if (cat) {
  2279. IPropertyTree *over = NULL;
  2280. if (instance&&*instance) {
  2281. q.clear().append("Override[@instance=\"").append(instance).append("\"]");
  2282. Owned<IPropertyTreeIterator> it1 = cat->getElements(q.str());
  2283. ForEach(*it1) {
  2284. IPropertyTree &o1 = it1->query();
  2285. if ((!component||!*component)) {
  2286. if (!over)
  2287. over = &o1;
  2288. }
  2289. else {
  2290. const char *comp = o1.queryProp("@component");
  2291. if (!comp||!*comp) {
  2292. if (!over)
  2293. over = &o1;
  2294. }
  2295. else if (strcmp(comp,component)==0) {
  2296. over = &o1;
  2297. break;
  2298. }
  2299. }
  2300. }
  2301. }
  2302. if (!over&&component&&*component) {
  2303. q.clear().append("Override[@component=\"").append(component).append("\"]");
  2304. Owned<IPropertyTreeIterator> it2 = cat->getElements(q.str());
  2305. ForEach(*it2) {
  2306. IPropertyTree &o2 = it2->query();
  2307. if ((!instance||!*instance)) {
  2308. over = &o2;
  2309. break;
  2310. }
  2311. else {
  2312. const char *inst = o2.queryProp("@instance");
  2313. if (!inst||!*inst) {
  2314. over = &o2;
  2315. break;
  2316. }
  2317. }
  2318. }
  2319. }
  2320. const char *dir = over?over->queryProp("@dir"):cat->queryProp("@dir");
  2321. if (dir&&*dir) {
  2322. fillConfigurationDirectoryEntry(dir,name,component,instance,dirout);
  2323. return true;
  2324. }
  2325. }
  2326. }
  2327. }
  2328. return false;
  2329. }
  2330. const char * matchConfigurationDirectoryEntry(const char *path,const char *mask,StringBuffer &name, StringBuffer &component, StringBuffer &instance)
  2331. {
  2332. // first check matches from (and set any values)
  2333. // only handles simple masks currently
  2334. StringBuffer var;
  2335. PointerArray val;
  2336. const char *m = mask;
  2337. const char *p = path;
  2338. for (;;) {
  2339. char c = *m;
  2340. if (!c)
  2341. break;
  2342. m++;
  2343. StringBuffer *out=NULL;
  2344. if (c=='[') {
  2345. if (memicmp(m,"NAME]",5)==0) {
  2346. out = &name;
  2347. m += 5;
  2348. }
  2349. else if (memicmp(m,"COMPONENT]",10)==0) {
  2350. out = &component;
  2351. m += 10;
  2352. }
  2353. else if (memicmp(m,"INST]",5)==0) {
  2354. out = &instance;
  2355. m += 5;
  2356. }
  2357. }
  2358. if (out) {
  2359. StringBuffer mtail;
  2360. while (*m&&!isPathSepChar(*m)&&(*m!='['))
  2361. mtail.append(*(m++));
  2362. StringBuffer ptail;
  2363. while (*p&&!isPathSepChar(*p))
  2364. ptail.append(*(p++));
  2365. if (ptail.length()<mtail.length())
  2366. return NULL;
  2367. size32_t l = ptail.length()-mtail.length();
  2368. if (l&&(memcmp(ptail.str()+l,mtail.str(),mtail.length())!=0))
  2369. return NULL;
  2370. out->clear().append(l,ptail.str());
  2371. }
  2372. else if (c!=*(p++))
  2373. return NULL;
  2374. }
  2375. if (!*p)
  2376. return p;
  2377. if (isPathSepChar(*p))
  2378. return p+1;
  2379. return NULL;
  2380. }
  2381. bool replaceConfigurationDirectoryEntry(const char *path,const char *frommask,const char *tomask,StringBuffer &out)
  2382. {
  2383. StringBuffer name;
  2384. StringBuffer comp;
  2385. StringBuffer inst;
  2386. const char *tail = matchConfigurationDirectoryEntry(path,frommask,name,comp,inst);
  2387. if (!tail)
  2388. return false;
  2389. fillConfigurationDirectoryEntry(tomask,name,comp,inst,out);
  2390. if (*tail)
  2391. addPathSepChar(out).append(tail);
  2392. return true;
  2393. }
  2394. static CriticalSection sect;
  2395. static StringAttr processPath;
  2396. const char * queryCurrentProcessPath()
  2397. {
  2398. CriticalBlock block(sect);
  2399. if (processPath.isEmpty())
  2400. {
  2401. #if _WIN32
  2402. HMODULE hModule = GetModuleHandle(NULL);
  2403. char path[MAX_PATH];
  2404. if (GetModuleFileName(hModule, path, MAX_PATH) != 0)
  2405. processPath.set(path);
  2406. #elif defined (__APPLE__)
  2407. char path[PATH_MAX];
  2408. uint32_t size = sizeof(path);
  2409. ssize_t len = _NSGetExecutablePath(path, &size);
  2410. switch(len)
  2411. {
  2412. case -1:
  2413. {
  2414. char * biggerPath = new char[size];
  2415. if (_NSGetExecutablePath(biggerPath, &size) == 0)
  2416. processPath.set(biggerPath);
  2417. delete [] biggerPath;
  2418. }
  2419. break;
  2420. case 0:
  2421. processPath.set(path);
  2422. break;
  2423. default:
  2424. break;
  2425. }
  2426. const char *canon = realpath(processPath.str(), nullptr);
  2427. if (canon)
  2428. {
  2429. processPath.clear();
  2430. processPath.set(canon);
  2431. free((void *) canon);
  2432. }
  2433. #else
  2434. char path[PATH_MAX + 1];
  2435. ssize_t len = readlink("/proc/self/exe", path, PATH_MAX);
  2436. if (len != -1)
  2437. {
  2438. path[len] = 0;
  2439. processPath.set(path);
  2440. }
  2441. #endif
  2442. }
  2443. if (processPath.isEmpty())
  2444. return NULL;
  2445. return processPath.str();
  2446. }
  2447. bool getPackageFolder(StringBuffer & path)
  2448. {
  2449. StringBuffer folder;
  2450. splitDirTail(queryCurrentProcessPath(), folder);
  2451. removeTrailingPathSepChar(folder);
  2452. if (folder.length())
  2453. {
  2454. StringBuffer foldersFolder;
  2455. splitDirTail(folder.str(), foldersFolder);
  2456. if (foldersFolder.length())
  2457. {
  2458. path = foldersFolder;
  2459. return true;
  2460. }
  2461. }
  2462. return false;
  2463. }
  2464. inline bool isOctChar(char c)
  2465. {
  2466. return (c>='0' && c<'8');
  2467. }
  2468. inline int octValue(char c)
  2469. {
  2470. return c-'0';
  2471. }
  2472. int parseCommandLine(const char * cmdline, MemoryBuffer &mb, const char** &argvout)
  2473. {
  2474. mb.append((char)0);
  2475. size32_t arg[256];
  2476. int argc = 0;
  2477. arg[0] = 0;
  2478. char quotechar = 0;
  2479. for (;;) {
  2480. char c = *(cmdline++);
  2481. switch(c) {
  2482. case ' ':
  2483. case '\t':
  2484. if (quotechar)
  2485. break;
  2486. // fall through
  2487. case 0: {
  2488. if (arg[argc]) {
  2489. while (mb.length()>arg[argc]) {
  2490. size32_t l = mb.length()-1;
  2491. const byte * b = ((const byte *)mb.bufferBase())+l;
  2492. if ((*b!=' ')&&(*b!='\t'))
  2493. break;
  2494. mb.setLength(l);
  2495. }
  2496. if (mb.length()>arg[argc]) {
  2497. mb.append((char)0);
  2498. argc++;
  2499. }
  2500. if (c) {
  2501. if (argc==256)
  2502. throw makeStringException(-1, "parseCommandLine: too many arguments");
  2503. arg[argc] = 0;
  2504. }
  2505. }
  2506. if (c)
  2507. continue;
  2508. argvout = (const char **)mb.reserve(argc*sizeof(const char *));
  2509. for (int i=0;i<argc;i++)
  2510. argvout[i] = arg[i]+(const char *)mb.bufferBase();
  2511. return argc;
  2512. }
  2513. break;
  2514. case '\'':
  2515. case '"':
  2516. if (c==quotechar) {
  2517. quotechar = 0;
  2518. continue;
  2519. }
  2520. if (quotechar)
  2521. break;
  2522. quotechar = c;
  2523. continue;
  2524. case '\\': {
  2525. if (*cmdline&&!quotechar) {
  2526. c = *(cmdline++);
  2527. switch (c) {
  2528. case 'a': c = '\a'; break;
  2529. case 'b': c = '\b'; break;
  2530. case 'f': c = '\f'; break;
  2531. case 'n': c = '\n'; break;
  2532. case 'r': c = '\r'; break;
  2533. case 't': c = '\t'; break;
  2534. case 'v': c = '\v'; break;
  2535. case 'x': case 'X': {
  2536. c = 0;
  2537. if (isHexChar(*cmdline)) {
  2538. c = hexValue(*(cmdline++));
  2539. if (isHexChar(*cmdline))
  2540. c = ((byte)c*16)+hexValue(*(cmdline++));
  2541. }
  2542. }
  2543. break;
  2544. case '0': case '1': case '2': case '3':
  2545. case '4': case '5': case '6': case '7': {
  2546. c = octValue(c);
  2547. if (isOctChar(*cmdline)) {
  2548. c = ((byte)c*8)+octValue(*(cmdline++));
  2549. if (isOctChar(*cmdline))
  2550. c = ((byte)c*8)+octValue(*(cmdline++));
  2551. }
  2552. }
  2553. break;
  2554. }
  2555. }
  2556. }
  2557. break;
  2558. }
  2559. if (!arg[argc])
  2560. arg[argc] = mb.length();
  2561. mb.append(c);
  2562. }
  2563. return 0;
  2564. }
  2565. jlib_decl StringBuffer &getTempFilePath(StringBuffer & target, const char * component, IPropertyTree * pTree)
  2566. {
  2567. StringBuffer dir;
  2568. if (pTree)
  2569. getConfigurationDirectory(pTree->queryPropTree("Directories"),"temp",component,pTree->queryProp("@name"),dir);
  2570. bool ok = false;
  2571. if (!dir.isEmpty())
  2572. {
  2573. ok = recursiveCreateDirectory(dir.str());
  2574. if (ok)
  2575. {
  2576. #ifdef _WIN32
  2577. return target.set(dir);
  2578. #else
  2579. int srtn = access(dir.str(), R_OK|W_OK|X_OK);
  2580. if (!srtn)
  2581. return target.set(dir);
  2582. #endif
  2583. }
  2584. }
  2585. // runtime dir
  2586. dir.clear();
  2587. dir.append(RUNTIME_DIR);
  2588. dir.append(PATHSEPCHAR).append("hpcc-data").append(PATHSEPCHAR).append(component);
  2589. dir.append(PATHSEPCHAR).append("temp");
  2590. ok = recursiveCreateDirectory(dir.str());
  2591. if (ok)
  2592. {
  2593. #ifdef _WIN32
  2594. return target.set(dir);
  2595. #else
  2596. int srtn = access(dir.str(), R_OK|W_OK|X_OK);
  2597. if (!srtn)
  2598. return target.set(dir);
  2599. #endif
  2600. }
  2601. // tmp dir
  2602. StringBuffer tmpdir;
  2603. #ifdef _WIN32
  2604. char path[_MAX_PATH+1];
  2605. if(GetTempPath(sizeof(path),path))
  2606. tmpdir.append(path);
  2607. else
  2608. tmpdir.append("C:\\TEMP"); // or C:\\Windows\\TEMP ?
  2609. #else
  2610. tmpdir.append(getenv("TMPDIR"));
  2611. if (tmpdir.isEmpty())
  2612. tmpdir.append("/tmp");
  2613. #endif
  2614. dir.clear();
  2615. dir.append(tmpdir);
  2616. dir.append(PATHSEPCHAR).append("HPCCSystems");
  2617. dir.append(PATHSEPCHAR).append("hpcc-data").append(PATHSEPCHAR).append(component);
  2618. dir.append(PATHSEPCHAR).append("temp");
  2619. ok = recursiveCreateDirectory(dir.str());
  2620. if (ok)
  2621. {
  2622. #ifdef _WIN32
  2623. return target.set(dir);
  2624. #else
  2625. int srtn = access(dir.str(), R_OK|W_OK|X_OK);
  2626. if (!srtn)
  2627. return target.set(dir);
  2628. #endif
  2629. }
  2630. #ifdef _WIN32
  2631. throw MakeStringException(-1, "Unable to create temp directory");
  2632. #else
  2633. // uniq tmp - perhaps previous dirs above were owned by others ...
  2634. dir.clear();
  2635. dir.append(tmpdir);
  2636. dir.append(PATHSEPCHAR).append("HPCCSystems-XXXXXX");
  2637. char templt[256];
  2638. strcpy(templt, dir.str());
  2639. char *td = mkdtemp(templt);
  2640. if (!td)
  2641. throw MakeStringException(-1, "Unable to create temp directory");
  2642. return target.set(templt);
  2643. #endif
  2644. }
  2645. const char *getEnumText(int value, const EnumMapping *map)
  2646. {
  2647. while (map->str)
  2648. {
  2649. if (value==map->val)
  2650. return map->str;
  2651. map++;
  2652. }
  2653. throwUnexpectedX("Unexpected value in getEnumText");
  2654. }
  2655. int getEnum(const char *v, const EnumMapping *map)
  2656. {
  2657. if (v && *v)
  2658. {
  2659. while (map->str)
  2660. {
  2661. if (stricmp(v, map->str)==0)
  2662. return map->val;
  2663. map++;
  2664. }
  2665. throwUnexpectedX("Unexpected value in getEnum");
  2666. }
  2667. return 0;
  2668. }
  2669. const char *getEnumText(int value, const EnumMapping *map, const char * defval)
  2670. {
  2671. while (map->str)
  2672. {
  2673. if (value==map->val)
  2674. return map->str;
  2675. map++;
  2676. }
  2677. return defval;
  2678. }
  2679. int getEnum(const char *v, const EnumMapping *map, int defval)
  2680. {
  2681. if (v && *v)
  2682. {
  2683. while (map->str)
  2684. {
  2685. if (stricmp(v, map->str)==0)
  2686. return map->val;
  2687. map++;
  2688. }
  2689. }
  2690. return defval;
  2691. }
  2692. //---------------------------------------------------------------------------------------------------------------------
  2693. extern jlib_decl offset_t friendlyStringToSize(const char *in)
  2694. {
  2695. char *tail;
  2696. offset_t result = strtoull(in, &tail, 10);
  2697. offset_t scale = 1;
  2698. if (*tail)
  2699. {
  2700. if (tail[1] == '\0')
  2701. {
  2702. switch (*tail)
  2703. {
  2704. case 'K': scale = 1000; break;
  2705. case 'M': scale = 1000000; break;
  2706. case 'G': scale = 1000000000; break;
  2707. case 'T': scale = 1000000000000; break;
  2708. case 'P': scale = 1000000000000000; break;
  2709. case 'E': scale = 1000000000000000000; break;
  2710. default:
  2711. throw makeStringExceptionV(0, "Invalid size suffix %s", tail);
  2712. }
  2713. }
  2714. else if (streq(tail+1, "i"))
  2715. {
  2716. switch (*tail)
  2717. {
  2718. case 'K': scale = 1llu<<10; break;
  2719. case 'M': scale = 1llu<<20; break;
  2720. case 'G': scale = 1llu<<30; break;
  2721. case 'T': scale = 1llu<<40; break;
  2722. case 'P': scale = 1llu<<50; break;
  2723. case 'E': scale = 1llu<<60; break;
  2724. default:
  2725. throw makeStringExceptionV(0, "Invalid size suffix %s", tail);
  2726. }
  2727. }
  2728. else
  2729. throw makeStringExceptionV(0, "Invalid size suffix %s", tail);
  2730. }
  2731. return result * scale;
  2732. }
  2733. void jlib_decl atomicWriteFile(const char *fileName, const char *output)
  2734. {
  2735. recursiveCreateDirectoryForFile(fileName);
  2736. #ifdef _WIN32
  2737. StringBuffer newFileName;
  2738. makeTempCopyName(newFileName, fileName);
  2739. Owned<IFile> newFile = createIFile(newFileName);
  2740. Owned<IFile> file = createIFile(fileName);
  2741. {
  2742. OwnedIFileIO ifileio = newFile->open(IFOcreate);
  2743. if (!ifileio)
  2744. throw MakeStringException(0, "atomicWriteFile: could not create output file %s", newFileName.str());
  2745. ifileio->write(0, strlen(output), output);
  2746. }
  2747. #else
  2748. VStringBuffer newFileName("%s.XXXXXX", fileName);
  2749. int fh = mkstemp(const_cast<char *>(newFileName.str()));
  2750. if (fh==-1)
  2751. throw MakeStringException(0, "atomicWriteFile: could not create output file for %s", fileName);
  2752. Owned<IFile> newFile = createIFile(newFileName);
  2753. Owned<IFile> file = createIFile(fileName);
  2754. {
  2755. OwnedIFileIO ifileio = createIFileIO(fh, IFOwrite);
  2756. if (!ifileio)
  2757. throw MakeStringException(0, "atomicWriteFile: could not create output file %s", newFileName.str());
  2758. ifileio->write(0, strlen(output), output);
  2759. }
  2760. #endif
  2761. if (file->exists())
  2762. file->remove();
  2763. newFile->rename(fileName);
  2764. }
  2765. //---------------------------------------------------------------------------------------------------------------------
  2766. //#define TESTURL
  2767. #ifdef TESTURL
  2768. static int doTests()
  2769. {
  2770. const char* ps[] = {
  2771. "ABCD", "@BCD", "%BCD","&BCD","A CD","A/CD", "A@@%%A","A&%/@"
  2772. };
  2773. const int N = sizeof(ps)/sizeof(char*);
  2774. for (int i=0; i<N; i++)
  2775. {
  2776. StringBuffer raw, encoded;
  2777. encodeUrlUseridPassword(encoded,ps[i]);
  2778. printf("Encoded: %s\n", encoded.str());
  2779. decodeUrlUseridPassword(raw,encoded);
  2780. if (strcmp(raw.str(),ps[i])!=0)
  2781. assert(!"decoding error");
  2782. }
  2783. return 0;
  2784. }
  2785. int gDummy = doTests();
  2786. #endif