util.c 11 KB

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