util.c 13 KB

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