util.c 11 KB

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