util.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. 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. if (!comms_error)
  232. applog(LOG_ERR, "HTTP request failed: %s", curl_err_str);
  233. comms_error = true;
  234. goto err_out;
  235. }
  236. /* If X-Long-Polling was found, activate long polling */
  237. if (hi.lp_path) {
  238. have_longpoll = true;
  239. tq_push(thr_info[longpoll_thr_id].q, hi.lp_path);
  240. } else
  241. free(hi.lp_path);
  242. hi.lp_path = NULL;
  243. val = JSON_LOADS(all_data.buf, &err);
  244. if (!val) {
  245. if (!comms_error)
  246. applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
  247. comms_error = true;
  248. if (opt_protocol)
  249. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  250. goto err_out;
  251. }
  252. if (opt_protocol) {
  253. char *s = json_dumps(val, JSON_INDENT(3));
  254. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  255. free(s);
  256. }
  257. /* JSON-RPC valid response returns a non-null 'result',
  258. * and a null 'error'.
  259. */
  260. res_val = json_object_get(val, "result");
  261. err_val = json_object_get(val, "error");
  262. if (!res_val || json_is_null(res_val) ||
  263. (err_val && !json_is_null(err_val))) {
  264. char *s;
  265. if (err_val)
  266. s = json_dumps(err_val, JSON_INDENT(3));
  267. else
  268. s = strdup("(unknown reason)");
  269. if (!comms_error)
  270. applog(LOG_ERR, "JSON-RPC call failed: %s", s);
  271. comms_error = true;
  272. free(s);
  273. goto err_out;
  274. }
  275. comms_error = false;
  276. databuf_free(&all_data);
  277. curl_slist_free_all(headers);
  278. curl_easy_reset(curl);
  279. return val;
  280. err_out:
  281. databuf_free(&all_data);
  282. curl_slist_free_all(headers);
  283. curl_easy_reset(curl);
  284. return NULL;
  285. }
  286. char *bin2hex(const unsigned char *p, size_t len)
  287. {
  288. int i;
  289. char *s = malloc((len * 2) + 1);
  290. if (!s)
  291. return NULL;
  292. for (i = 0; i < len; i++)
  293. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  294. return s;
  295. }
  296. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  297. {
  298. while (*hexstr && len) {
  299. char hex_byte[3];
  300. unsigned int v;
  301. if (!hexstr[1]) {
  302. applog(LOG_ERR, "hex2bin str truncated");
  303. return false;
  304. }
  305. hex_byte[0] = hexstr[0];
  306. hex_byte[1] = hexstr[1];
  307. hex_byte[2] = 0;
  308. if (sscanf(hex_byte, "%x", &v) != 1) {
  309. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  310. return false;
  311. }
  312. *p = (unsigned char) v;
  313. p++;
  314. hexstr += 2;
  315. len--;
  316. }
  317. return (len == 0 && *hexstr == 0) ? true : false;
  318. }
  319. /* Subtract the `struct timeval' values X and Y,
  320. storing the result in RESULT.
  321. Return 1 if the difference is negative, otherwise 0. */
  322. int
  323. timeval_subtract (
  324. struct timeval *result, struct timeval *x, struct timeval *y)
  325. {
  326. /* Perform the carry for the later subtraction by updating Y. */
  327. if (x->tv_usec < y->tv_usec) {
  328. int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
  329. y->tv_usec -= 1000000 * nsec;
  330. y->tv_sec += nsec;
  331. }
  332. if (x->tv_usec - y->tv_usec > 1000000) {
  333. int nsec = (x->tv_usec - y->tv_usec) / 1000000;
  334. y->tv_usec += 1000000 * nsec;
  335. y->tv_sec -= nsec;
  336. }
  337. /* Compute the time remaining to wait.
  338. `tv_usec' is certainly positive. */
  339. result->tv_sec = x->tv_sec - y->tv_sec;
  340. result->tv_usec = x->tv_usec - y->tv_usec;
  341. /* Return 1 if result is negative. */
  342. return x->tv_sec < y->tv_sec;
  343. }
  344. bool fulltest(const unsigned char *hash, const unsigned char *target)
  345. {
  346. unsigned char hash_swap[32], target_swap[32];
  347. uint32_t *hash32 = (uint32_t *) hash_swap;
  348. uint32_t *target32 = (uint32_t *) target_swap;
  349. int i;
  350. bool rc = true;
  351. char *hash_str, *target_str;
  352. swap256(hash_swap, hash);
  353. swap256(target_swap, target);
  354. for (i = 0; i < 32/4; i++) {
  355. uint32_t h32tmp = swab32(hash32[i]);
  356. uint32_t t32tmp = target32[i];
  357. target32[i] = swab32(target32[i]); /* for printing */
  358. if (h32tmp > t32tmp) {
  359. rc = false;
  360. break;
  361. }
  362. if (h32tmp < t32tmp) {
  363. rc = true;
  364. break;
  365. }
  366. }
  367. if (opt_debug) {
  368. hash_str = bin2hex(hash_swap, 32);
  369. target_str = bin2hex(target_swap, 32);
  370. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  371. hash_str,
  372. target_str,
  373. rc ? "YES (hash < target)" :
  374. "no (false positive; hash > target)");
  375. free(hash_str);
  376. free(target_str);
  377. }
  378. return true; /* FIXME: return rc; */
  379. }
  380. struct thread_q *tq_new(void)
  381. {
  382. struct thread_q *tq;
  383. tq = calloc(1, sizeof(*tq));
  384. if (!tq)
  385. return NULL;
  386. INIT_LIST_HEAD(&tq->q);
  387. pthread_mutex_init(&tq->mutex, NULL);
  388. pthread_cond_init(&tq->cond, NULL);
  389. return tq;
  390. }
  391. void tq_free(struct thread_q *tq)
  392. {
  393. struct tq_ent *ent, *iter;
  394. if (!tq)
  395. return;
  396. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  397. list_del(&ent->q_node);
  398. free(ent);
  399. }
  400. pthread_cond_destroy(&tq->cond);
  401. pthread_mutex_destroy(&tq->mutex);
  402. memset(tq, 0, sizeof(*tq)); /* poison */
  403. free(tq);
  404. }
  405. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  406. {
  407. pthread_mutex_lock(&tq->mutex);
  408. tq->frozen = frozen;
  409. pthread_cond_signal(&tq->cond);
  410. pthread_mutex_unlock(&tq->mutex);
  411. }
  412. void tq_freeze(struct thread_q *tq)
  413. {
  414. tq_freezethaw(tq, true);
  415. }
  416. void tq_thaw(struct thread_q *tq)
  417. {
  418. tq_freezethaw(tq, false);
  419. }
  420. bool tq_push(struct thread_q *tq, void *data)
  421. {
  422. struct tq_ent *ent;
  423. bool rc = true;
  424. ent = calloc(1, sizeof(*ent));
  425. if (!ent)
  426. return false;
  427. ent->data = data;
  428. INIT_LIST_HEAD(&ent->q_node);
  429. pthread_mutex_lock(&tq->mutex);
  430. if (!tq->frozen) {
  431. list_add_tail(&ent->q_node, &tq->q);
  432. } else {
  433. free(ent);
  434. rc = false;
  435. }
  436. pthread_cond_signal(&tq->cond);
  437. pthread_mutex_unlock(&tq->mutex);
  438. return rc;
  439. }
  440. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  441. {
  442. struct tq_ent *ent;
  443. void *rval = NULL;
  444. int rc;
  445. pthread_mutex_lock(&tq->mutex);
  446. if (!list_empty(&tq->q))
  447. goto pop;
  448. if (abstime)
  449. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  450. else
  451. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  452. if (rc)
  453. goto out;
  454. if (list_empty(&tq->q))
  455. goto out;
  456. pop:
  457. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  458. rval = ent->data;
  459. list_del(&ent->q_node);
  460. free(ent);
  461. out:
  462. pthread_mutex_unlock(&tq->mutex);
  463. return rval;
  464. }