util.c 11 KB

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