jutil.cpp 84 KB

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