util.c 12 KB

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