util.c 10 KB

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