jutil.cpp 74 KB

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