util.c 12 KB

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