util.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. /*
  2. * Copyright 2010 Jeff Garzik
  3. *
  4. * This program is free software; you can redistribute it and/or modify it
  5. * under the terms of the GNU General Public License as published by the Free
  6. * Software Foundation; either version 2 of the License, or (at your option)
  7. * any later version. See COPYING for more details.
  8. */
  9. #define _GNU_SOURCE
  10. #include "cpuminer-config.h"
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <ctype.h>
  14. #include <stdarg.h>
  15. #include <string.h>
  16. #include <jansson.h>
  17. #include <curl/curl.h>
  18. #include <time.h>
  19. #include "miner.h"
  20. #include "elist.h"
  21. struct data_buffer {
  22. void *buf;
  23. size_t len;
  24. };
  25. struct upload_buffer {
  26. const void *buf;
  27. size_t len;
  28. };
  29. struct header_info {
  30. char *lp_path;
  31. };
  32. struct tq_ent {
  33. void *data;
  34. struct list_head q_node;
  35. };
  36. struct thread_q {
  37. struct list_head q;
  38. bool frozen;
  39. pthread_mutex_t mutex;
  40. pthread_cond_t cond;
  41. };
  42. void applog(int prio, const char *fmt, ...)
  43. {
  44. va_list ap;
  45. va_start(ap, fmt);
  46. #ifdef HAVE_SYSLOG_H
  47. if (use_syslog) {
  48. vsyslog(prio, fmt, ap);
  49. }
  50. #else
  51. if (0) {}
  52. #endif
  53. else {
  54. char *f;
  55. int len;
  56. struct timeval tv = { };
  57. struct tm tm, *tm_p;
  58. gettimeofday(&tv, NULL);
  59. pthread_mutex_lock(&time_lock);
  60. tm_p = localtime(&tv.tv_sec);
  61. memcpy(&tm, tm_p, sizeof(tm));
  62. pthread_mutex_unlock(&time_lock);
  63. len = 40 + strlen(fmt) + 2;
  64. f = alloca(len);
  65. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d] %s\n",
  66. tm.tm_year + 1900,
  67. tm.tm_mon,
  68. tm.tm_mday,
  69. tm.tm_hour,
  70. tm.tm_min,
  71. tm.tm_sec,
  72. fmt);
  73. vfprintf(stderr, f, ap); /* atomic write to stderr */
  74. }
  75. va_end(ap);
  76. }
  77. static void databuf_free(struct data_buffer *db)
  78. {
  79. if (!db)
  80. return;
  81. free(db->buf);
  82. memset(db, 0, sizeof(*db));
  83. }
  84. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  85. void *user_data)
  86. {
  87. struct data_buffer *db = user_data;
  88. size_t len = size * nmemb;
  89. size_t oldlen, newlen;
  90. void *newmem;
  91. static const unsigned char zero;
  92. oldlen = db->len;
  93. newlen = oldlen + len;
  94. newmem = realloc(db->buf, newlen + 1);
  95. if (!newmem)
  96. return 0;
  97. db->buf = newmem;
  98. db->len = newlen;
  99. memcpy(db->buf + oldlen, ptr, len);
  100. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  101. return len;
  102. }
  103. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  104. void *user_data)
  105. {
  106. struct upload_buffer *ub = user_data;
  107. int len = size * nmemb;
  108. if (len > ub->len)
  109. len = ub->len;
  110. if (len) {
  111. memcpy(ptr, ub->buf, len);
  112. ub->buf += len;
  113. ub->len -= len;
  114. }
  115. return len;
  116. }
  117. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  118. {
  119. struct header_info *hi = user_data;
  120. size_t remlen, slen, ptrlen = size * nmemb;
  121. char *rem, *val = NULL, *key = NULL;
  122. void *tmp;
  123. val = calloc(1, ptrlen);
  124. key = calloc(1, ptrlen);
  125. if (!key || !val)
  126. goto out;
  127. tmp = memchr(ptr, ':', ptrlen);
  128. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  129. goto out;
  130. slen = tmp - ptr;
  131. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  132. goto out;
  133. memcpy(key, ptr, slen); /* store & nul term key */
  134. key[slen] = 0;
  135. rem = ptr + slen + 1; /* trim value's leading whitespace */
  136. remlen = ptrlen - slen - 1;
  137. while ((remlen > 0) && (isspace(*rem))) {
  138. remlen--;
  139. rem++;
  140. }
  141. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  142. val[remlen] = 0;
  143. while ((*val) && (isspace(val[strlen(val) - 1]))) {
  144. val[strlen(val) - 1] = 0;
  145. }
  146. if (!*val) /* skip blank value */
  147. goto out;
  148. if (opt_protocol)
  149. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  150. if (!strcasecmp("X-Long-Polling", key)) {
  151. hi->lp_path = val; /* steal memory reference */
  152. val = NULL;
  153. }
  154. out:
  155. free(key);
  156. free(val);
  157. return ptrlen;
  158. }
  159. json_t *json_rpc_call(CURL *curl, const char *url,
  160. const char *userpass, const char *rpc_req,
  161. bool longpoll_scan, bool longpoll)
  162. {
  163. json_t *val, *err_val, *res_val;
  164. int rc;
  165. struct data_buffer all_data = { };
  166. struct upload_buffer upload_data;
  167. json_error_t err = { };
  168. struct curl_slist *headers = NULL;
  169. char len_hdr[64];
  170. char curl_err_str[CURL_ERROR_SIZE];
  171. long timeout = longpoll ? (60 * 60) : (60 * 10);
  172. struct header_info hi = { };
  173. bool lp_scanning = false;
  174. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  175. if (longpoll_scan)
  176. lp_scanning = want_longpoll && !have_longpoll;
  177. if (opt_protocol)
  178. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  179. curl_easy_setopt(curl, CURLOPT_URL, url);
  180. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  181. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  182. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  183. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  184. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  185. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  186. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  187. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  188. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  189. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  190. if (lp_scanning) {
  191. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  192. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  193. }
  194. if (userpass) {
  195. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  196. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  197. }
  198. curl_easy_setopt(curl, CURLOPT_POST, 1);
  199. if (opt_protocol)
  200. applog(LOG_DEBUG, "JSON protocol request:\n%s\n", rpc_req);
  201. upload_data.buf = rpc_req;
  202. upload_data.len = strlen(rpc_req);
  203. sprintf(len_hdr, "Content-Length: %lu",
  204. (unsigned long) upload_data.len);
  205. headers = curl_slist_append(headers,
  206. "Content-type: application/json");
  207. headers = curl_slist_append(headers, len_hdr);
  208. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  209. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  210. rc = curl_easy_perform(curl);
  211. if (rc) {
  212. applog(LOG_ERR, "HTTP request failed: %s", curl_err_str);
  213. goto err_out;
  214. }
  215. /* If X-Long-Polling was found, activate long polling */
  216. if (hi.lp_path) {
  217. have_longpoll = true;
  218. opt_scantime = 60;
  219. tq_push(thr_info[longpoll_thr_id].q, hi.lp_path);
  220. } else
  221. free(hi.lp_path);
  222. hi.lp_path = NULL;
  223. val = json_loads(all_data.buf, &err);
  224. if (!val) {
  225. applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
  226. goto err_out;
  227. }
  228. if (opt_protocol) {
  229. char *s = json_dumps(val, JSON_INDENT(3));
  230. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  231. free(s);
  232. }
  233. /* JSON-RPC valid response returns a non-null 'result',
  234. * and a null 'error'.
  235. */
  236. res_val = json_object_get(val, "result");
  237. err_val = json_object_get(val, "error");
  238. if (!res_val || json_is_null(res_val) ||
  239. (err_val && !json_is_null(err_val))) {
  240. char *s;
  241. if (err_val)
  242. s = json_dumps(err_val, JSON_INDENT(3));
  243. else
  244. s = strdup("(unknown reason)");
  245. applog(LOG_ERR, "JSON-RPC call failed: %s", s);
  246. free(s);
  247. goto err_out;
  248. }
  249. databuf_free(&all_data);
  250. curl_slist_free_all(headers);
  251. curl_easy_reset(curl);
  252. return val;
  253. err_out:
  254. databuf_free(&all_data);
  255. curl_slist_free_all(headers);
  256. curl_easy_reset(curl);
  257. return NULL;
  258. }
  259. char *bin2hex(const unsigned char *p, size_t len)
  260. {
  261. int i;
  262. char *s = malloc((len * 2) + 1);
  263. if (!s)
  264. return NULL;
  265. for (i = 0; i < len; i++)
  266. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  267. return s;
  268. }
  269. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  270. {
  271. while (*hexstr && len) {
  272. char hex_byte[3];
  273. unsigned int v;
  274. if (!hexstr[1]) {
  275. applog(LOG_ERR, "hex2bin str truncated");
  276. return false;
  277. }
  278. hex_byte[0] = hexstr[0];
  279. hex_byte[1] = hexstr[1];
  280. hex_byte[2] = 0;
  281. if (sscanf(hex_byte, "%x", &v) != 1) {
  282. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  283. return false;
  284. }
  285. *p = (unsigned char) v;
  286. p++;
  287. hexstr += 2;
  288. len--;
  289. }
  290. return (len == 0 && *hexstr == 0) ? true : false;
  291. }
  292. /* Subtract the `struct timeval' values X and Y,
  293. storing the result in RESULT.
  294. Return 1 if the difference is negative, otherwise 0. */
  295. int
  296. timeval_subtract (
  297. struct timeval *result, struct timeval *x, struct timeval *y)
  298. {
  299. /* Perform the carry for the later subtraction by updating Y. */
  300. if (x->tv_usec < y->tv_usec) {
  301. int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
  302. y->tv_usec -= 1000000 * nsec;
  303. y->tv_sec += nsec;
  304. }
  305. if (x->tv_usec - y->tv_usec > 1000000) {
  306. int nsec = (x->tv_usec - y->tv_usec) / 1000000;
  307. y->tv_usec += 1000000 * nsec;
  308. y->tv_sec -= nsec;
  309. }
  310. /* Compute the time remaining to wait.
  311. `tv_usec' is certainly positive. */
  312. result->tv_sec = x->tv_sec - y->tv_sec;
  313. result->tv_usec = x->tv_usec - y->tv_usec;
  314. /* Return 1 if result is negative. */
  315. return x->tv_sec < y->tv_sec;
  316. }
  317. bool fulltest(const unsigned char *hash, const unsigned char *target)
  318. {
  319. unsigned char hash_swap[32], target_swap[32];
  320. uint32_t *hash32 = (uint32_t *) hash_swap;
  321. uint32_t *target32 = (uint32_t *) target_swap;
  322. int i;
  323. bool rc = true;
  324. char *hash_str, *target_str;
  325. swap256(hash_swap, hash);
  326. swap256(target_swap, target);
  327. for (i = 0; i < 32/4; i++) {
  328. uint32_t h32tmp = swab32(hash32[i]);
  329. uint32_t t32tmp = target32[i];
  330. target32[i] = swab32(target32[i]); /* for printing */
  331. if (h32tmp > t32tmp) {
  332. rc = false;
  333. break;
  334. }
  335. if (h32tmp < t32tmp) {
  336. rc = true;
  337. break;
  338. }
  339. }
  340. if (opt_debug) {
  341. hash_str = bin2hex(hash_swap, 32);
  342. target_str = bin2hex(target_swap, 32);
  343. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  344. hash_str,
  345. target_str,
  346. rc ? "YES (hash < target)" :
  347. "no (false positive; hash > target)");
  348. free(hash_str);
  349. free(target_str);
  350. }
  351. return true; /* FIXME: return rc; */
  352. }
  353. struct thread_q *tq_new(void)
  354. {
  355. struct thread_q *tq;
  356. tq = calloc(1, sizeof(*tq));
  357. if (!tq)
  358. return NULL;
  359. INIT_LIST_HEAD(&tq->q);
  360. pthread_mutex_init(&tq->mutex, NULL);
  361. pthread_cond_init(&tq->cond, NULL);
  362. return tq;
  363. }
  364. void tq_free(struct thread_q *tq)
  365. {
  366. struct tq_ent *ent, *iter;
  367. if (!tq)
  368. return;
  369. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  370. list_del(&ent->q_node);
  371. free(ent);
  372. }
  373. pthread_cond_destroy(&tq->cond);
  374. pthread_mutex_destroy(&tq->mutex);
  375. memset(tq, 0, sizeof(*tq)); /* poison */
  376. free(tq);
  377. }
  378. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  379. {
  380. pthread_mutex_lock(&tq->mutex);
  381. tq->frozen = frozen;
  382. pthread_cond_signal(&tq->cond);
  383. pthread_mutex_unlock(&tq->mutex);
  384. }
  385. void tq_freeze(struct thread_q *tq)
  386. {
  387. tq_freezethaw(tq, true);
  388. }
  389. void tq_thaw(struct thread_q *tq)
  390. {
  391. tq_freezethaw(tq, false);
  392. }
  393. bool tq_push(struct thread_q *tq, void *data)
  394. {
  395. struct tq_ent *ent;
  396. bool rc = true;
  397. ent = calloc(1, sizeof(*ent));
  398. if (!ent)
  399. return false;
  400. ent->data = data;
  401. INIT_LIST_HEAD(&ent->q_node);
  402. pthread_mutex_lock(&tq->mutex);
  403. if (!tq->frozen) {
  404. list_add_tail(&ent->q_node, &tq->q);
  405. } else {
  406. free(ent);
  407. rc = false;
  408. }
  409. pthread_cond_signal(&tq->cond);
  410. pthread_mutex_unlock(&tq->mutex);
  411. return rc;
  412. }
  413. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  414. {
  415. struct tq_ent *ent;
  416. void *rval = NULL;
  417. int rc;
  418. pthread_mutex_lock(&tq->mutex);
  419. if (!list_empty(&tq->q))
  420. goto pop;
  421. if (abstime)
  422. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  423. else
  424. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  425. if (rc)
  426. goto out;
  427. if (list_empty(&tq->q))
  428. goto out;
  429. pop:
  430. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  431. rval = ent->data;
  432. list_del(&ent->q_node);
  433. free(ent);
  434. out:
  435. pthread_mutex_unlock(&tq->mutex);
  436. return rval;
  437. }