util.c 12 KB

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