util.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. /*
  2. * Copyright 2013 Luke Dashjr
  3. * Copyright 2012-2013 Con Kolivas
  4. * Copyright 2011 Andrew Smith
  5. * Copyright 2011 Jeff Garzik
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #ifndef BFG_UTIL_H
  13. #define BFG_UTIL_H
  14. #include <stdbool.h>
  15. #include <stdint.h>
  16. #include <string.h>
  17. #include <sys/time.h>
  18. #include <curl/curl.h>
  19. #include <jansson.h>
  20. #include "compat.h"
  21. #define INVALID_TIMESTAMP ((time_t)-1)
  22. #if defined(unix) || defined(__APPLE__)
  23. #include <errno.h>
  24. #include <sys/socket.h>
  25. #include <netinet/in.h>
  26. #include <arpa/inet.h>
  27. #define SOCKETTYPE int
  28. #define SOCKETFAIL(a) ((a) < 0)
  29. #define INVSOCK -1
  30. #define INVINETADDR -1
  31. #define CLOSESOCKET close
  32. #define SOCKERR (errno)
  33. #define SOCKERRMSG bfg_strerror(errno, BST_SOCKET)
  34. static inline bool sock_blocks(void)
  35. {
  36. return (errno == EAGAIN || errno == EWOULDBLOCK);
  37. }
  38. static inline bool interrupted(void)
  39. {
  40. return (errno == EINTR);
  41. }
  42. #elif defined WIN32
  43. #include <ws2tcpip.h>
  44. #include <winsock2.h>
  45. #define SOCKETTYPE SOCKET
  46. #define SOCKETFAIL(a) ((int)(a) == SOCKET_ERROR)
  47. #define INVSOCK INVALID_SOCKET
  48. #define INVINETADDR INADDR_NONE
  49. #define CLOSESOCKET closesocket
  50. #define SOCKERR (WSAGetLastError())
  51. #define SOCKERRMSG bfg_strerror(WSAGetLastError(), BST_SOCKET)
  52. /* Check for windows variants of the errors as well as when ming
  53. * decides to wrap the error into the errno equivalent. */
  54. static inline bool sock_blocks(void)
  55. {
  56. return (WSAGetLastError() == WSAEWOULDBLOCK || errno == EAGAIN);
  57. }
  58. static inline bool interrupted(void)
  59. {
  60. return (WSAGetLastError() == WSAEINTR || errno == EINTR);
  61. }
  62. #ifndef SHUT_RDWR
  63. #define SHUT_RDWR SD_BOTH
  64. #endif
  65. #ifndef in_addr_t
  66. #define in_addr_t uint32_t
  67. #endif
  68. #endif
  69. #define IGNORE_RETURN_VALUE(expr) {if(expr);}(void)0
  70. #if JANSSON_MAJOR_VERSION >= 2
  71. #define JSON_LOADS(str, err_ptr) json_loads((str), 0, (err_ptr))
  72. #else
  73. #define JSON_LOADS(str, err_ptr) json_loads((str), (err_ptr))
  74. #endif
  75. extern char *json_dumps_ANY(json_t *, size_t flags);
  76. static inline
  77. const char *bfg_json_obj_string(json_t *json, const char *key, const char *fail)
  78. {
  79. json = json_object_get(json, key);
  80. if (!json)
  81. return fail;
  82. return json_string_value(json) ?: fail;
  83. }
  84. extern const char *__json_array_string(json_t *, unsigned int entry);
  85. extern bool isCalpha(int);
  86. static inline
  87. bool isCspace(int c)
  88. {
  89. switch (c)
  90. {
  91. case ' ': case '\f': case '\n': case '\r': case '\t': case '\v':
  92. return true;
  93. default:
  94. return false;
  95. }
  96. }
  97. extern const char *get_registered_domain(size_t *out_len, const char *, size_t len);
  98. extern const char *extract_domain(size_t *out_len, const char *uri, size_t urilen);
  99. extern bool match_domains(const char *a, size_t alen, const char *b, size_t blen);
  100. extern void test_domain_funcs();
  101. enum bfg_gpio_value {
  102. BGV_LOW = 0,
  103. BGV_HIGH = 1,
  104. BGV_ERROR = -1,
  105. };
  106. typedef struct timeval cgtimer_t;
  107. struct thr_info;
  108. struct pool;
  109. enum dev_reason;
  110. struct cgpu_info;
  111. extern void json_rpc_call_async(CURL *, const char *url, const char *userpass, const char *rpc_req, bool longpoll, struct pool *pool, bool share, void *priv);
  112. extern json_t *json_rpc_call_completed(CURL *, int rc, bool probe, int *rolltime, void *out_priv);
  113. extern char *absolute_uri(char *uri, const char *ref); // ref must be a root URI
  114. extern size_t ucs2_to_utf8(char *out, const uint16_t *in, size_t sz);
  115. extern char *ucs2_to_utf8_dup(uint16_t *in, size_t sz);
  116. #define BFGINIT(var, val) do{ \
  117. if (!(var)) \
  118. (var) = val; \
  119. }while(0)
  120. extern void gen_hash(unsigned char *data, unsigned char *hash, int len);
  121. extern void hash_data(unsigned char *out_hash, const unsigned char *data);
  122. extern void real_block_target(unsigned char *target, const unsigned char *data);
  123. extern bool hash_target_check(const unsigned char *hash, const unsigned char *target);
  124. extern bool hash_target_check_v(const unsigned char *hash, const unsigned char *target);
  125. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg);
  126. void thr_info_freeze(struct thr_info *thr);
  127. void thr_info_cancel(struct thr_info *thr);
  128. void subtime(struct timeval *a, struct timeval *b);
  129. void addtime(struct timeval *a, struct timeval *b);
  130. bool time_more(struct timeval *a, struct timeval *b);
  131. bool time_less(struct timeval *a, struct timeval *b);
  132. void copy_time(struct timeval *dest, const struct timeval *src);
  133. void timespec_to_val(struct timeval *val, const struct timespec *spec);
  134. void timeval_to_spec(struct timespec *spec, const struct timeval *val);
  135. void us_to_timeval(struct timeval *val, int64_t us);
  136. void us_to_timespec(struct timespec *spec, int64_t us);
  137. void ms_to_timespec(struct timespec *spec, int64_t ms);
  138. void timeraddspec(struct timespec *a, const struct timespec *b);
  139. void cgsleep_ms(int ms);
  140. void cgsleep_us(int64_t us);
  141. #define cgtimer_time(ts_start) timer_set_now(ts_start)
  142. #define cgsleep_prepare_r(ts_start) cgtimer_time(ts_start)
  143. void cgsleep_ms_r(cgtimer_t *ts_start, int ms);
  144. void (*cgsleep_us_r)(cgtimer_t *ts_start, int64_t us);
  145. static inline
  146. int cgtimer_to_ms(cgtimer_t *cgt)
  147. {
  148. return (cgt->tv_sec * 1000) + (cgt->tv_usec / 1000);
  149. }
  150. #define cgtimer_sub(a, b, res) timersub(a, b, res)
  151. double us_tdiff(struct timeval *end, struct timeval *start);
  152. double tdiff(struct timeval *end, struct timeval *start);
  153. bool _stratum_send(struct pool *pool, char *s, ssize_t len, bool force);
  154. #define stratum_send(pool, s, len) _stratum_send(pool, s, len, false)
  155. bool sock_full(struct pool *pool);
  156. char *recv_line(struct pool *pool);
  157. bool parse_method(struct pool *pool, char *s);
  158. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port);
  159. bool auth_stratum(struct pool *pool);
  160. bool initiate_stratum(struct pool *pool);
  161. bool restart_stratum(struct pool *pool);
  162. void suspend_stratum(struct pool *pool);
  163. extern void dev_error_update(struct cgpu_info *, enum dev_reason);
  164. void dev_error(struct cgpu_info *dev, enum dev_reason reason);
  165. void *realloc_strcat(char *ptr, char *s);
  166. extern char *sanestr(char *o, char *s);
  167. void RenameThread(const char* name);
  168. enum bfg_strerror_type {
  169. BST_ERRNO,
  170. BST_SOCKET,
  171. BST_LIBUSB,
  172. BST_SYSTEM,
  173. };
  174. extern const char *bfg_strerror(int, enum bfg_strerror_type);
  175. extern void *bfg_slurp_file(void *buf, size_t bufsz, const char *filename);
  176. typedef SOCKETTYPE notifier_t[2];
  177. extern void notifier_init(notifier_t);
  178. extern void notifier_wake(notifier_t);
  179. extern void notifier_read(notifier_t);
  180. extern void notifier_init_invalid(notifier_t);
  181. extern void notifier_destroy(notifier_t);
  182. /* Align a size_t to 4 byte boundaries for fussy arches */
  183. static inline void align_len(size_t *len)
  184. {
  185. if (*len % 4)
  186. *len += 4 - (*len % 4);
  187. }
  188. typedef struct bytes_t {
  189. uint8_t *buf;
  190. size_t sz;
  191. size_t allocsz;
  192. } bytes_t;
  193. #define BYTES_INIT ((bytes_t){.buf=NULL,})
  194. static inline
  195. void bytes_init(bytes_t *b)
  196. {
  197. *b = BYTES_INIT;
  198. }
  199. // This can't be inline without ugly const/non-const issues
  200. #define bytes_buf(b) ((b)->buf)
  201. static inline
  202. size_t bytes_len(const bytes_t *b)
  203. {
  204. return b->sz;
  205. }
  206. static inline
  207. ssize_t bytes_find(const bytes_t * const b, const uint8_t needle)
  208. {
  209. const size_t blen = bytes_len(b);
  210. const uint8_t * const buf = bytes_buf(b);
  211. for (int i = 0; i < blen; ++i)
  212. if (buf[i] == needle)
  213. return i;
  214. return -1;
  215. }
  216. extern void _bytes_alloc_failure(size_t);
  217. static inline
  218. void bytes_extend_buf(bytes_t * const b, const size_t newsz)
  219. {
  220. if (newsz <= b->allocsz)
  221. return;
  222. if (!b->allocsz)
  223. b->allocsz = 0x10;
  224. do {
  225. b->allocsz *= 2;
  226. } while (newsz > b->allocsz);
  227. b->buf = realloc(b->buf, b->allocsz);
  228. if (!b->buf)
  229. _bytes_alloc_failure(b->allocsz);
  230. }
  231. static inline
  232. void bytes_resize(bytes_t * const b, const size_t newsz)
  233. {
  234. bytes_extend_buf(b, newsz);
  235. b->sz = newsz;
  236. }
  237. static inline
  238. void *bytes_preappend(bytes_t * const b, const size_t addsz)
  239. {
  240. size_t origsz = bytes_len(b);
  241. bytes_extend_buf(b, origsz + addsz);
  242. return &bytes_buf(b)[origsz];
  243. }
  244. static inline
  245. void bytes_postappend(bytes_t * const b, const size_t addsz)
  246. {
  247. size_t origsz = bytes_len(b);
  248. bytes_resize(b, origsz + addsz);
  249. }
  250. static inline
  251. void bytes_append(bytes_t * const b, const void * const add, const size_t addsz)
  252. {
  253. void * const appendbuf = bytes_preappend(b, addsz);
  254. memcpy(appendbuf, add, addsz);
  255. bytes_postappend(b, addsz);
  256. }
  257. static inline
  258. void bytes_cat(bytes_t *b, const bytes_t *cat)
  259. {
  260. bytes_append(b, bytes_buf(cat), bytes_len(cat));
  261. }
  262. static inline
  263. void bytes_cpy(bytes_t *dst, const bytes_t *src)
  264. {
  265. dst->sz = src->sz;
  266. if (!dst->sz) {
  267. dst->allocsz = 0;
  268. dst->buf = NULL;
  269. return;
  270. }
  271. dst->allocsz = src->allocsz;
  272. size_t half;
  273. while (dst->sz <= (half = dst->allocsz / 2))
  274. dst->allocsz = half;
  275. dst->buf = malloc(dst->allocsz);
  276. memcpy(dst->buf, src->buf, dst->sz);
  277. }
  278. static inline
  279. void bytes_shift(bytes_t *b, size_t shift)
  280. {
  281. if (shift >= b->sz)
  282. {
  283. b->sz = 0;
  284. return;
  285. }
  286. b->sz -= shift;
  287. memmove(bytes_buf(b), &bytes_buf(b)[shift], bytes_len(b));
  288. }
  289. static inline
  290. void bytes_reset(bytes_t *b)
  291. {
  292. b->sz = 0;
  293. }
  294. static inline
  295. void bytes_nullterminate(bytes_t *b)
  296. {
  297. bytes_append(b, "", 1);
  298. --b->sz;
  299. }
  300. static inline
  301. void bytes_free(bytes_t *b)
  302. {
  303. free(b->buf);
  304. b->sz = b->allocsz = 0;
  305. }
  306. static inline
  307. void set_maxfd(int *p_maxfd, int fd)
  308. {
  309. if (fd > *p_maxfd)
  310. *p_maxfd = fd;
  311. }
  312. static inline
  313. void timer_unset(struct timeval *tvp)
  314. {
  315. tvp->tv_sec = -1;
  316. }
  317. static inline
  318. bool timer_isset(const struct timeval *tvp)
  319. {
  320. return tvp->tv_sec != -1;
  321. }
  322. extern void (*timer_set_now)(struct timeval *);
  323. #define cgtime(tvp) timer_set_now(tvp)
  324. #define TIMEVAL_USECS(usecs) ( \
  325. (struct timeval){ \
  326. .tv_sec = (usecs) / 1000000, \
  327. .tv_usec = (usecs) % 1000000, \
  328. } \
  329. )
  330. static inline
  331. long timeval_to_us(const struct timeval *tvp)
  332. {
  333. return ((long)tvp->tv_sec * 1000000) + tvp->tv_usec;
  334. }
  335. #define timer_set_delay(tvp_timer, tvp_now, usecs) do { \
  336. struct timeval tv_add = TIMEVAL_USECS(usecs); \
  337. timeradd(&tv_add, tvp_now, tvp_timer); \
  338. } while(0)
  339. #define timer_set_delay_from_now(tvp_timer, usecs) do { \
  340. struct timeval tv_now; \
  341. timer_set_now(&tv_now); \
  342. timer_set_delay(tvp_timer, &tv_now, usecs); \
  343. } while(0)
  344. static inline
  345. const struct timeval *_bfg_nullisnow(const struct timeval *tvp, struct timeval *tvp_buf)
  346. {
  347. if (tvp)
  348. return tvp;
  349. cgtime(tvp_buf);
  350. return tvp_buf;
  351. }
  352. static inline
  353. long timer_elapsed_us(const struct timeval *tvp_timer, const struct timeval *tvp_now)
  354. {
  355. struct timeval tv;
  356. const struct timeval *_tvp_now = _bfg_nullisnow(tvp_now, &tv);
  357. timersub(_tvp_now, tvp_timer, &tv);
  358. return timeval_to_us(&tv);
  359. }
  360. #define ms_tdiff(end, start) (timer_elapsed_us(start, end) / 1000)
  361. static inline
  362. int timer_elapsed(const struct timeval *tvp_timer, const struct timeval *tvp_now)
  363. {
  364. struct timeval tv;
  365. const struct timeval *_tvp_now = _bfg_nullisnow(tvp_now, &tv);
  366. timersub(_tvp_now, tvp_timer, &tv);
  367. return tv.tv_sec;
  368. }
  369. static inline
  370. bool timer_passed(const struct timeval *tvp_timer, const struct timeval *tvp_now)
  371. {
  372. if (!timer_isset(tvp_timer))
  373. return false;
  374. struct timeval tv;
  375. const struct timeval *_tvp_now = _bfg_nullisnow(tvp_now, &tv);
  376. return timercmp(tvp_timer, _tvp_now, <);
  377. }
  378. #if defined(WIN32) && !defined(HAVE_POOR_GETTIMEOFDAY)
  379. #define HAVE_POOR_GETTIMEOFDAY
  380. #endif
  381. #ifdef HAVE_POOR_GETTIMEOFDAY
  382. extern void bfg_gettimeofday(struct timeval *);
  383. #else
  384. #define bfg_gettimeofday(out) gettimeofday(out, NULL)
  385. #endif
  386. static inline
  387. void reduce_timeout_to(struct timeval *tvp_timeout, struct timeval *tvp_time)
  388. {
  389. if (!timer_isset(tvp_time))
  390. return;
  391. if ((!timer_isset(tvp_timeout)) || timercmp(tvp_time, tvp_timeout, <))
  392. *tvp_timeout = *tvp_time;
  393. }
  394. static inline
  395. struct timeval *select_timeout(struct timeval *tvp_timeout, struct timeval *tvp_now)
  396. {
  397. if (!timer_isset(tvp_timeout))
  398. return NULL;
  399. if (timercmp(tvp_timeout, tvp_now, <))
  400. timerclear(tvp_timeout);
  401. else
  402. timersub(tvp_timeout, tvp_now, tvp_timeout);
  403. return tvp_timeout;
  404. }
  405. #define _SNP2(fn, ...) do{ \
  406. int __n42 = fn(s, sz, __VA_ARGS__); \
  407. s += __n42; \
  408. sz = (sz <= __n42) ? 0 : (sz - __n42); \
  409. rv += __n42; \
  410. }while(0)
  411. #define _SNP(...) _SNP2(snprintf, __VA_ARGS__)
  412. #define REPLACEMENT_CHAR (0xFFFD)
  413. #define U8_DEGREE "\xc2\xb0"
  414. #define U8_MICRO "\xc2\xb5"
  415. #define U8_HLINE "\xe2\x94\x80"
  416. #define U8_BTEE "\xe2\x94\xb4"
  417. extern int utf8_len(uint8_t);
  418. extern int32_t utf8_decode(const void *, int *out_len);
  419. extern size_t utf8_strlen(const void *);
  420. extern void utf8_test();
  421. #define RUNONCE(rv) do { \
  422. static bool _runonce = false; \
  423. if (_runonce) \
  424. return rv; \
  425. _runonce = true; \
  426. } while(0)
  427. static inline
  428. char *maybe_strdup(const char *s)
  429. {
  430. return s ? strdup(s) : NULL;
  431. }
  432. static inline
  433. void maybe_strdup_if_null(const char **p, const char *s)
  434. {
  435. if (!*p)
  436. *p = maybe_strdup(s);
  437. }
  438. extern char *trimmed_strdup(const char *);
  439. extern void run_cmd(const char *cmd);
  440. extern uint8_t crc5usb(unsigned char *ptr, uint8_t len);
  441. extern void bfg_init_checksums(void);
  442. extern uint8_t crc8ccitt(const void *, size_t);
  443. #endif /* __UTIL_H__ */