util.c 12 KB

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