jutil.cpp 83 KB

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