jutil.cpp 69 KB

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