util.c 11 KB

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