jutil.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. #ifndef JUTIL_HPP
  14. #define JUTIL_HPP
  15. #include "jlib.hpp"
  16. #include "jstring.hpp"
  17. #include "jarray.hpp"
  18. #include "jbuff.hpp"
  19. #if defined (__APPLE__)
  20. #include <mach/mach_time.h>
  21. extern mach_timebase_info_data_t timebase_info; // Calibration for nanosecond timer
  22. #endif
  23. //#define NAMEDCOUNTS
  24. interface IPropertyTree;
  25. interface IProperties;
  26. void jlib_decl MilliSleep(unsigned milli);
  27. long jlib_decl atolong_l(const char * s,int l);
  28. int jlib_decl atoi_l(const char * s,int l);
  29. __int64 jlib_decl atoi64_l(const char * s,int l);
  30. inline __int64 atoi64(const char* s) { return atoi64_l(s, (int)strlen(s)); }
  31. #ifndef _WIN32
  32. extern jlib_decl char * itoa(int n, char *str, int b);
  33. extern jlib_decl char * ltoa(long n, char *str, int b);
  34. extern jlib_decl char * ultoa(unsigned long n, char *str, int b);
  35. #define Sleep(milli) MilliSleep(milli)
  36. #endif
  37. bool jlib_decl j_isnan(double x);
  38. bool jlib_decl j_isinf(double x);
  39. void jlib_decl packNumber(char * target, const char * source, unsigned slen);
  40. void jlib_decl unpackNumber(char * target, const char * source, unsigned tlen);
  41. int jlib_decl numtostr(char *dst, char _value);
  42. int jlib_decl numtostr(char *dst, short _value);
  43. int jlib_decl numtostr(char *dst, int _value);
  44. int jlib_decl numtostr(char *dst, long _value);
  45. int jlib_decl numtostr(char *dst, __int64 _value);
  46. int jlib_decl numtostr(char *dst, unsigned char value);
  47. int jlib_decl numtostr(char *dst, unsigned short value);
  48. int jlib_decl numtostr(char *dst, unsigned int value);
  49. int jlib_decl numtostr(char *dst, unsigned long value);
  50. int jlib_decl numtostr(char *dst, unsigned __int64 _value);
  51. #ifndef _WIN32
  52. /**
  53. * Return full path name of a currently loaded dll that matches the supplied tail
  54. *
  55. * @param ret StringBuffer to receive full path name
  56. * @param match Partial name to be located
  57. * @return True if a matching loaded dll was found
  58. */
  59. extern jlib_decl bool findLoadedModule(StringBuffer &ret, const char *match);
  60. #endif
  61. extern jlib_decl HINSTANCE LoadSharedObject(const char *name, bool isGlobal, bool raiseOnError);
  62. extern jlib_decl void FreeSharedObject(HINSTANCE h);
  63. class jlib_decl SharedObject : public CInterfaceOf<IInterface>
  64. {
  65. public:
  66. SharedObject() { h = 0; bRefCounted = false; }
  67. ~SharedObject() { unload(); }
  68. bool load(const char * dllName, bool isGlobal, bool raiseOnError=false);
  69. bool loadCurrentExecutable();
  70. bool loadResources(const char * dllName);
  71. bool loaded() const { return h != 0; }
  72. void unload();
  73. HINSTANCE getInstanceHandle() const { return h; }
  74. void *getEntry(const char * name) const;
  75. public:
  76. HINSTANCE h;
  77. bool bRefCounted;
  78. };
  79. // Interface for dynamically-loadable plugins
  80. interface IPluggableFactory : extends IInterface
  81. {
  82. virtual bool initializeStore() = 0;
  83. };
  84. typedef IPluggableFactory * (* IPluggableFactoryFactory)(const SharedObject *dll, const IPropertyTree *);
  85. extern jlib_decl IPluggableFactory *loadPlugin(const IPropertyTree* pluginInfo);
  86. //---------------------------------------------------------------------------
  87. //functions for generating unique identifiers consisting of 0..9,A..V
  88. typedef unsigned __int64 unique_id_t;
  89. extern jlib_decl StringBuffer & appendUniqueId(StringBuffer & target, unique_id_t value);
  90. extern jlib_decl unique_id_t getUniqueId();
  91. extern jlib_decl StringBuffer & getUniqueId(StringBuffer & target);
  92. extern jlib_decl void resetUniqueId();
  93. extern jlib_decl unsigned getRandom(); // global
  94. extern jlib_decl void seedRandom(unsigned seed);
  95. interface IRandomNumberGenerator: public IInterface
  96. {
  97. virtual void seed(unsigned seedval)=0;
  98. virtual unsigned next()=0;
  99. };
  100. extern jlib_decl IRandomNumberGenerator *createRandomNumberGenerator();
  101. // functions to populate buffers with randomly generated data
  102. extern jlib_decl void fillRandomData(size32_t writeSz, void *writePtr);
  103. extern jlib_decl void fillRandomData(size32_t writeSz, MemoryBuffer &mb);
  104. #ifdef WIN32
  105. // Reentrant version of the rand() function for use with multithreaded applications.
  106. // rand_r return value between 0 and RAND_R_MAX (exclusive). Not that RAND_MAX is
  107. // implementation dependent: SHORT_MAX on Windows, INT_MAX on Linux.
  108. jlib_decl int rand_r(unsigned int *seed);
  109. #define RAND_R_MAX INT_MAX
  110. #else
  111. #define RAND_R_MAX RAND_MAX
  112. #endif
  113. inline int fastRand()
  114. {
  115. // rand() causes Coverity can issue a 'WEAK_CRYPTO' warning, but we only use fastRand() where deemed safe to do so.
  116. // coverity[DC.WEAK_CRYPTO]
  117. return rand();
  118. }
  119. interface IShuffledIterator: extends IInterface
  120. {
  121. virtual void seed(unsigned seedval)=0; // ony required for repeatability
  122. virtual bool first()=0;
  123. virtual bool isValid() = 0;
  124. virtual bool next() = 0;
  125. virtual unsigned get() = 0;
  126. virtual unsigned lookup(unsigned idx) = 0; // looks up idx'th entry
  127. };
  128. extern jlib_decl IShuffledIterator *createShuffledIterator(unsigned n); // returns iterator that returns 0..n-1 in shuffled order
  129. /* misc */
  130. extern jlib_decl bool isCIdentifier(const char* id);
  131. /* base64 encoder/decoder */
  132. extern jlib_decl void JBASE64_Encode(const void *data, long length, StringBuffer &out, bool addLineBreaks=true);
  133. extern jlib_decl void JBASE64_Encode(const void *data, long length, IIOStream &out, bool addLineBreaks=true);
  134. extern jlib_decl StringBuffer &JBASE64_Decode(const char *in, StringBuffer &out);
  135. extern jlib_decl MemoryBuffer &JBASE64_Decode(const char *in, MemoryBuffer &out);
  136. extern jlib_decl StringBuffer &JBASE64_Decode(ISimpleReadStream &in, StringBuffer &out);
  137. extern jlib_decl MemoryBuffer &JBASE64_Decode(ISimpleReadStream &in, MemoryBuffer &out);
  138. /**
  139. * Decode base 64 encoded string.
  140. * It handles forbidden printable and non-printable chars. Space(s) inserted among the valid chars,
  141. * missing pad chars and invalid length.
  142. *
  143. * @param length Length of the input string.
  144. * @param in Pointer to base64 encoded string
  145. * @param out Decoded string if the input is valid
  146. * @return True when success
  147. */
  148. extern jlib_decl bool JBASE64_Decode(size32_t length, const char *in, StringBuffer &out);
  149. extern jlib_decl void JBASE32_Encode(const char *in,StringBuffer &out); // result all lower
  150. extern jlib_decl void JBASE32_Decode(const char *in,StringBuffer &out);
  151. /* URL: http://user:passwd@host:port/path */
  152. extern jlib_decl StringBuffer& encodeUrlUseridPassword(StringBuffer& out, const char* in);
  153. extern jlib_decl StringBuffer& decodeUrlUseridPassword(StringBuffer& out, const char* in);
  154. //--------------------------------------------------------------------------------------------------------------------
  155. class StringPointerArrayMapper : public SimpleArrayMapper<const char *>
  156. {
  157. typedef const char * MEMBER;
  158. public:
  159. static void construct(const char * & member, const char * newValue)
  160. {
  161. member = strdup(newValue);
  162. }
  163. static void destruct(MEMBER & member)
  164. {
  165. free(const_cast<char *>(member));
  166. }
  167. static inline bool matches(MEMBER const & member, const char * param)
  168. {
  169. return strcmp(member, param) == 0;
  170. }
  171. };
  172. class jlib_decl StringArray : public ArrayOf<const char *, const char *, StringPointerArrayMapper>
  173. {
  174. struct CCmp
  175. {
  176. static int compare(char const * const *l, char const * const *r) { return strcmp(*l, *r); }
  177. static int compareNC(char const * const *l, char const * const *r) { return stricmp(*l, *r); }
  178. static int revCompare(char const * const *l, char const * const *r) { return strcmp(*r, *l); }
  179. static int revCompareNC(char const * const *l, char const * const *r) { return stricmp(*r, *l); }
  180. };
  181. typedef ArrayOf<const char *, const char *, StringPointerArrayMapper> PARENT;
  182. public:
  183. // Appends a list in a string delimited by 'delim'
  184. void appendList(const char *list, const char *delim, bool trimSpaces = true);
  185. // Appends a list in a string delimited by 'delim' without duplicates
  186. void appendListUniq(const char *list, const char *delim, bool trimSpaces = true);
  187. StringBuffer &getString(StringBuffer &ret, const char *delim); // get CSV string of array contents
  188. void sortAscii(bool nocase=false);
  189. void sortAsciiReverse(bool nocase=false);
  190. void sortCompare(int (*compare)(const char * const * l, const char * const * r));
  191. private:
  192. using PARENT::sort; // prevent access to this function - to avoid ambiguity
  193. };
  194. class CIStringArray : public StringArray, public CInterface
  195. {
  196. };
  197. extern jlib_decl unsigned msTick();
  198. extern jlib_decl unsigned usTick();
  199. extern jlib_decl int write_pidfile(const char * instance);
  200. extern jlib_decl void doStackProbe();
  201. #ifndef arraysize
  202. #define arraysize(T) (sizeof(T)/sizeof(*T))
  203. #endif
  204. extern jlib_decl unsigned runExternalCommand(StringBuffer &output, StringBuffer &error, const char *cmd, const char *input);
  205. extern jlib_decl unsigned __int64 greatestCommonDivisor(unsigned __int64 left, unsigned __int64 right);
  206. inline unsigned hex2num(char next)
  207. {
  208. if ((next >= '0') && (next <= '9'))
  209. return next - '0';
  210. if ((next >= 'a') && (next <= 'f'))
  211. return next - 'a' + 10;
  212. if ((next >= 'A') && (next <= 'F'))
  213. return next - 'A' + 10;
  214. return 0;
  215. }
  216. extern jlib_decl void initThreadLocal(int len, void* val);
  217. extern jlib_decl void* getThreadLocalVal();
  218. extern jlib_decl void clearThreadLocal();
  219. extern jlib_decl bool matchesMask(const char *fn, const char *mask, unsigned p, unsigned n);
  220. extern jlib_decl StringBuffer &expandMask(StringBuffer &buf, const char *mask, unsigned p, unsigned n);
  221. extern jlib_decl bool constructMask(StringAttr &attr, const char *fn, unsigned p, unsigned n);
  222. extern jlib_decl bool deduceMask(const char *fn, bool expandN, StringAttr &mask, unsigned &p, unsigned &n); // p is 0 based in these routines
  223. class HashKeyElement;
  224. class jlib_decl NamedCount
  225. {
  226. HashKeyElement *ht;
  227. public:
  228. NamedCount();
  229. ~NamedCount();
  230. void set(const char *name);
  231. };
  232. #ifdef NAMEDCOUNTS
  233. #define DECL_NAMEDCOUNT NamedCount namedCount
  234. #define INIT_NAMEDCOUNT namedCount.set(typeid(*this).name())
  235. #else
  236. #define DECL_NAMEDCOUNT
  237. #define INIT_NAMEDCOUNT {}
  238. #endif
  239. extern jlib_decl StringBuffer &dumpNamedCounts(StringBuffer &str);
  240. interface IAuthenticatedUser: extends IInterface
  241. {
  242. virtual bool login(const char *user, const char *passwd) = 0;
  243. virtual void impersonate()=0;
  244. virtual void revert()=0;
  245. virtual const char *username()=0;
  246. };
  247. interface IAtom;
  248. extern jlib_decl IAuthenticatedUser *createAuthenticatedUser();
  249. extern jlib_decl void serializeAtom(MemoryBuffer & target, IAtom * name);
  250. extern jlib_decl IAtom * deserializeAtom(MemoryBuffer & source);
  251. template <class KEY, class VALUE, class COMPARE>
  252. VALUE * binsearch(KEY key, VALUE * * values, unsigned num, COMPARE * cmp)
  253. {
  254. unsigned l = 0;
  255. unsigned u = num;
  256. while(l<u)
  257. {
  258. unsigned i = l+(u-l)/2;
  259. int c = cmp->compare(key, values[i]);
  260. if(c == 0)
  261. {
  262. return values[i];
  263. }
  264. else if(c < 0)
  265. {
  266. u = i;
  267. }
  268. else
  269. {
  270. l = i+1;
  271. }
  272. }
  273. return NULL;
  274. }
  275. extern jlib_decl StringBuffer &genUUID(StringBuffer &in, bool nocase=false);
  276. // Convert offset_t to string
  277. // Note that offset_t can be 32, 64 bit integers or a structure
  278. class jlib_decl OffsetToString
  279. {
  280. StringBuffer m_buffer;
  281. public:
  282. OffsetToString(offset_t offset);
  283. const char* str() { return m_buffer.str(); }
  284. };
  285. extern jlib_decl StringBuffer passwordInput(const char* prompt, StringBuffer& passwd);
  286. /**
  287. * Return a reference to a shared IProperties object representing the environment.conf settings.
  288. * The object is loaded when first needed, and freed at program termination. This function is threadsafe.
  289. *
  290. * @return The environment.conf properties
  291. *
  292. */
  293. extern jlib_decl const IProperties &queryEnvironmentConf();
  294. /**
  295. * Return an owned copy of the local environment.xml file
  296. *
  297. * @return The environment.xml property tree
  298. *
  299. */
  300. extern jlib_decl IPropertyTree *getHPCCEnvironment();
  301. extern jlib_decl bool getConfigurationDirectory(const IPropertyTree *dirtree, // NULL to use HPCC config
  302. const char *category,
  303. const char *component,
  304. const char *instance,
  305. StringBuffer &dirout);
  306. extern jlib_decl bool querySecuritySettings(DAFSConnectCfg *_connectMethod,
  307. unsigned short *_port,
  308. const char * * _certificate,
  309. const char * * _privateKey,
  310. const char * * _passPhrase);
  311. extern jlib_decl bool queryDafsSecSettings(DAFSConnectCfg *_connectMethod,
  312. unsigned short *_port,
  313. unsigned short *_sslport,
  314. const char * * _certificate,
  315. const char * * _privateKey,
  316. const char * * _passPhrase);
  317. //Queries environment.conf file
  318. extern jlib_decl bool queryHPCCPKIKeyFiles(const char * * _certificate,//HPCCCertificateFile
  319. const char * * _publicKey, //HPCCPublicKeyFile
  320. const char * * _privateKey, //HPCCPrivateKeyFile
  321. const char * * _passPhrase);//HPCCPassPhrase, encrypted
  322. extern jlib_decl const char * matchConfigurationDirectoryEntry(const char *path,const char *mask,StringBuffer &name, StringBuffer &component, StringBuffer &instance);
  323. extern jlib_decl bool replaceConfigurationDirectoryEntry(const char *path,const char *frommask,const char *tomask,StringBuffer &out);
  324. extern jlib_decl const char *queryCurrentProcessPath();
  325. /**
  326. * Locate the 'package home' directory - normally /opt/HPCCSystems - by detecting the current executable's location
  327. *
  328. * @param path Returns the package home location
  329. * @return True if the home directory was located
  330. */
  331. extern jlib_decl bool getPackageFolder(StringBuffer & path);
  332. extern jlib_decl int parseCommandLine(const char * cmdline, MemoryBuffer &mb, const char** &argvout); // parses cmdline into argvout returning arg count (mb used as buffer)
  333. extern jlib_decl bool safe_ecvt(size_t len, char * buffer, double value, int numDigits, int * decimal, int * sign);
  334. extern jlib_decl bool safe_fcvt(size_t len, char * buffer, double value, int numPlaces, int * decimal, int * sign);
  335. extern jlib_decl StringBuffer &getTempFilePath(StringBuffer & target, const char * component, IPropertyTree * pTree);
  336. interface jlib_thrown_decl ICorruptDllException: extends IException
  337. {
  338. };
  339. struct EnumMapping { int val; const char *str; };
  340. extern jlib_decl const char *getEnumText(int value, const EnumMapping *map); // fails if no match
  341. extern jlib_decl int getEnum(const char *v, const EnumMapping *map); //fails if no match
  342. extern jlib_decl const char *getEnumText(int value, const EnumMapping *map, const char * defval);
  343. extern jlib_decl int getEnum(const char *v, const EnumMapping *map, int defval);
  344. class jlib_decl QuantilePositionIterator
  345. {
  346. public:
  347. QuantilePositionIterator(size_t _numRows, unsigned _numDivisions, bool roundUp)
  348. : numRows(_numRows), numDivisions(_numDivisions)
  349. {
  350. assertex(numDivisions);
  351. step = numRows / numDivisions;
  352. stepDelta = (unsigned)(numRows % numDivisions);
  353. initialDelta = roundUp ? (numDivisions)/2 : (numDivisions-1)/2;
  354. first();
  355. }
  356. bool first()
  357. {
  358. curRow = 0;
  359. curDelta = initialDelta;
  360. curQuantile = 0;
  361. return true;
  362. }
  363. bool next()
  364. {
  365. if (curQuantile >= numDivisions)
  366. return false;
  367. curQuantile++;
  368. curRow += step;
  369. curDelta += stepDelta;
  370. if (curDelta >= numDivisions)
  371. {
  372. curRow++;
  373. curDelta -= numDivisions;
  374. }
  375. assertex(curRow <= numRows);
  376. return true;
  377. }
  378. size_t get() { return curRow; }
  379. protected:
  380. size_t numRows;
  381. size_t curRow;
  382. size_t step;
  383. unsigned numDivisions;
  384. unsigned stepDelta;
  385. unsigned curQuantile;
  386. unsigned curDelta;
  387. unsigned initialDelta;
  388. };
  389. class jlib_decl QuantileFilterIterator
  390. {
  391. public:
  392. QuantileFilterIterator(size_t _numRows, unsigned _numDivisions, bool roundUp)
  393. : numRows(_numRows), numDivisions(_numDivisions)
  394. {
  395. assertex(numDivisions);
  396. initialDelta = roundUp ? (numDivisions-1)/2 : (numDivisions)/2;
  397. first();
  398. }
  399. bool first()
  400. {
  401. curRow = 0;
  402. curDelta = initialDelta;
  403. curQuantile = 0;
  404. isQuantile = true;
  405. return true;
  406. }
  407. bool next()
  408. {
  409. if (curRow > numRows)
  410. return false;
  411. curRow++;
  412. curDelta += numDivisions;
  413. isQuantile = false;
  414. if (curDelta >= numRows)
  415. {
  416. curDelta -= numRows;
  417. isQuantile = true;
  418. }
  419. return true;
  420. }
  421. size_t get() { return isQuantile; }
  422. protected:
  423. size_t numRows;
  424. size_t curRow;
  425. size_t step;
  426. size_t curDelta;
  427. unsigned numDivisions;
  428. unsigned curQuantile;
  429. unsigned initialDelta;
  430. bool isQuantile;
  431. };
  432. #endif