util.c 12 KB

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