util.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  1. /*
  2. * Copyright 2011-2012 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. * Copyright 2012 Giel van Schijndel
  5. * Copyright 2012 Gavin Andresen
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #include "config.h"
  13. #ifdef WIN32
  14. #define FD_SETSIZE 4096
  15. #endif
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <ctype.h>
  19. #include <stdarg.h>
  20. #include <string.h>
  21. #include <pthread.h>
  22. #include <jansson.h>
  23. #include <curl/curl.h>
  24. #include <time.h>
  25. #include <errno.h>
  26. #include <unistd.h>
  27. #include <sys/types.h>
  28. #ifdef HAVE_SYS_PRCTL_H
  29. # include <sys/prctl.h>
  30. #endif
  31. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  32. # include <pthread_np.h>
  33. #endif
  34. #ifndef WIN32
  35. # ifdef __linux
  36. # include <sys/prctl.h>
  37. # endif
  38. # include <sys/socket.h>
  39. # include <netinet/in.h>
  40. # include <netinet/tcp.h>
  41. # include <netdb.h>
  42. #else
  43. # include <winsock2.h>
  44. # include <mstcpip.h>
  45. # include <ws2tcpip.h>
  46. #endif
  47. #include "miner.h"
  48. #include "elist.h"
  49. #include "compat.h"
  50. #include "util.h"
  51. bool successful_connect = false;
  52. struct timeval nettime;
  53. struct data_buffer {
  54. void *buf;
  55. size_t len;
  56. curl_socket_t *idlemarker;
  57. };
  58. struct upload_buffer {
  59. const void *buf;
  60. size_t len;
  61. };
  62. struct header_info {
  63. char *lp_path;
  64. int rolltime;
  65. char *reason;
  66. char *stratum_url;
  67. bool hadrolltime;
  68. bool canroll;
  69. bool hadexpire;
  70. };
  71. struct tq_ent {
  72. void *data;
  73. struct list_head q_node;
  74. };
  75. static void databuf_free(struct data_buffer *db)
  76. {
  77. if (!db)
  78. return;
  79. free(db->buf);
  80. #ifdef DEBUG_DATABUF
  81. applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
  82. #endif
  83. memset(db, 0, sizeof(*db));
  84. }
  85. // aka data_buffer_write
  86. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  87. void *user_data)
  88. {
  89. struct data_buffer *db = user_data;
  90. size_t oldlen, newlen;
  91. oldlen = db->len;
  92. if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
  93. return 0;
  94. if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
  95. nmemb = (SIZE_MAX - oldlen) / size;
  96. size_t len = size * nmemb;
  97. void *newmem;
  98. static const unsigned char zero = 0;
  99. if (db->idlemarker) {
  100. const unsigned char *cptr = ptr;
  101. for (size_t i = 0; i < len; ++i)
  102. if (!(isspace(cptr[i]) || cptr[i] == '{')) {
  103. *db->idlemarker = CURL_SOCKET_BAD;
  104. db->idlemarker = NULL;
  105. break;
  106. }
  107. }
  108. newlen = oldlen + len;
  109. newmem = realloc(db->buf, newlen + 1);
  110. #ifdef DEBUG_DATABUF
  111. applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
  112. #endif
  113. if (!newmem)
  114. return 0;
  115. db->buf = newmem;
  116. db->len = newlen;
  117. memcpy(db->buf + oldlen, ptr, len);
  118. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  119. return nmemb;
  120. }
  121. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  122. void *user_data)
  123. {
  124. struct upload_buffer *ub = user_data;
  125. unsigned int len = size * nmemb;
  126. if (len > ub->len)
  127. len = ub->len;
  128. if (len) {
  129. memcpy(ptr, ub->buf, len);
  130. ub->buf += len;
  131. ub->len -= len;
  132. }
  133. return len;
  134. }
  135. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  136. {
  137. struct header_info *hi = user_data;
  138. size_t remlen, slen, ptrlen = size * nmemb;
  139. char *rem, *val = NULL, *key = NULL;
  140. void *tmp;
  141. val = calloc(1, ptrlen);
  142. key = calloc(1, ptrlen);
  143. if (!key || !val)
  144. goto out;
  145. tmp = memchr(ptr, ':', ptrlen);
  146. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  147. goto out;
  148. slen = tmp - ptr;
  149. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  150. goto out;
  151. memcpy(key, ptr, slen); /* store & nul term key */
  152. key[slen] = 0;
  153. rem = ptr + slen + 1; /* trim value's leading whitespace */
  154. remlen = ptrlen - slen - 1;
  155. while ((remlen > 0) && (isspace(*rem))) {
  156. remlen--;
  157. rem++;
  158. }
  159. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  160. val[remlen] = 0;
  161. while ((*val) && (isspace(val[strlen(val) - 1])))
  162. val[strlen(val) - 1] = 0;
  163. if (!*val) /* skip blank value */
  164. goto out;
  165. if (opt_protocol)
  166. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  167. if (!strcasecmp("X-Roll-Ntime", key)) {
  168. hi->hadrolltime = true;
  169. if (!strncasecmp("N", val, 1))
  170. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  171. else {
  172. hi->canroll = true;
  173. /* Check to see if expire= is supported and if not, set
  174. * the rolltime to the default scantime */
  175. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  176. sscanf(val + 7, "%d", &hi->rolltime);
  177. hi->hadexpire = true;
  178. } else
  179. hi->rolltime = opt_scantime;
  180. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  181. }
  182. }
  183. if (!strcasecmp("X-Long-Polling", key)) {
  184. hi->lp_path = val; /* steal memory reference */
  185. val = NULL;
  186. }
  187. if (!strcasecmp("X-Reject-Reason", key)) {
  188. hi->reason = val; /* steal memory reference */
  189. val = NULL;
  190. }
  191. if (!strcasecmp("X-Stratum", key)) {
  192. hi->stratum_url = val;
  193. val = NULL;
  194. }
  195. out:
  196. free(key);
  197. free(val);
  198. return ptrlen;
  199. }
  200. static int keep_sockalive(SOCKETTYPE fd)
  201. {
  202. const int tcp_keepidle = 60;
  203. const int tcp_keepintvl = 60;
  204. const int keepalive = 1;
  205. int ret = 0;
  206. #ifndef WIN32
  207. const int tcp_keepcnt = 5;
  208. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
  209. ret = 1;
  210. # ifdef __linux
  211. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
  212. ret = 1;
  213. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  214. ret = 1;
  215. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  216. ret = 1;
  217. # endif /* __linux */
  218. # ifdef __APPLE_CC__
  219. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  220. ret = 1;
  221. # endif /* __APPLE_CC__ */
  222. #else /* WIN32 */
  223. const int zero = 0;
  224. struct tcp_keepalive vals;
  225. vals.onoff = 1;
  226. vals.keepalivetime = tcp_keepidle * 1000;
  227. vals.keepaliveinterval = tcp_keepintvl * 1000;
  228. DWORD outputBytes;
  229. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&keepalive, sizeof(keepalive))))
  230. ret = 1;
  231. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  232. ret = 1;
  233. /* Windows happily submits indefinitely to the send buffer blissfully
  234. * unaware nothing is getting there without gracefully failing unless
  235. * we disable the send buffer */
  236. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  237. ret = 1;
  238. #endif /* WIN32 */
  239. return ret;
  240. }
  241. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  242. curlsocktype __maybe_unused purpose)
  243. {
  244. return keep_sockalive(fd);
  245. }
  246. static void last_nettime(struct timeval *last)
  247. {
  248. rd_lock(&netacc_lock);
  249. last->tv_sec = nettime.tv_sec;
  250. last->tv_usec = nettime.tv_usec;
  251. rd_unlock(&netacc_lock);
  252. }
  253. static void set_nettime(void)
  254. {
  255. wr_lock(&netacc_lock);
  256. gettimeofday(&nettime, NULL);
  257. wr_unlock(&netacc_lock);
  258. }
  259. static int my_curl_debug(__maybe_unused CURL *curl, curl_infotype infotype, char *data, size_t datasz, void *userdata)
  260. {
  261. struct pool *pool = userdata;
  262. switch (infotype) {
  263. case CURLINFO_TEXT:
  264. {
  265. if (!opt_protocol)
  266. break;
  267. // data is not null-terminated, so we need to copy and terminate it for applog
  268. char datacp[datasz + 1];
  269. memcpy(datacp, data, datasz);
  270. datacp[datasz] = '\0';
  271. applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
  272. break;
  273. }
  274. case CURLINFO_HEADER_IN:
  275. case CURLINFO_DATA_IN:
  276. pool->cgminer_pool_stats.bytes_received += datasz;
  277. total_bytes_xfer += datasz;
  278. break;
  279. case CURLINFO_HEADER_OUT:
  280. case CURLINFO_DATA_OUT:
  281. pool->cgminer_pool_stats.bytes_sent += datasz;
  282. total_bytes_xfer += datasz;
  283. break;
  284. default:
  285. break;
  286. }
  287. return 0;
  288. }
  289. struct json_rpc_call_state {
  290. struct data_buffer all_data;
  291. struct header_info hi;
  292. void *priv;
  293. char curl_err_str[CURL_ERROR_SIZE];
  294. struct curl_slist *headers;
  295. struct upload_buffer upload_data;
  296. struct pool *pool;
  297. };
  298. void json_rpc_call_async(CURL *curl, const char *url,
  299. const char *userpass, const char *rpc_req,
  300. bool longpoll,
  301. struct pool *pool, bool share,
  302. void *priv)
  303. {
  304. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  305. *state = (struct json_rpc_call_state){
  306. .priv = priv,
  307. .pool = pool,
  308. };
  309. long timeout = longpoll ? (60 * 60) : 60;
  310. char len_hdr[64], user_agent_hdr[128];
  311. struct curl_slist *headers = NULL;
  312. if (longpoll)
  313. state->all_data.idlemarker = &pool->lp_socket;
  314. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  315. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  316. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  317. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  318. curl_easy_setopt(curl, CURLOPT_URL, url);
  319. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  320. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  321. /* Shares are staggered already and delays in submission can be costly
  322. * so do not delay them */
  323. if (!opt_delaynet || share)
  324. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  325. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  326. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
  327. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  328. curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_data);
  329. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  330. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  331. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  332. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
  333. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  334. * to enable it */
  335. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  336. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, my_curl_debug);
  337. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, pool);
  338. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  339. if (pool->rpc_proxy) {
  340. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  341. } else if (opt_socks_proxy) {
  342. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  343. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  344. }
  345. if (userpass) {
  346. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  347. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  348. }
  349. if (longpoll)
  350. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  351. curl_easy_setopt(curl, CURLOPT_POST, 1);
  352. if (opt_protocol)
  353. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  354. state->upload_data.buf = rpc_req;
  355. state->upload_data.len = strlen(rpc_req);
  356. sprintf(len_hdr, "Content-Length: %lu",
  357. (unsigned long) state->upload_data.len);
  358. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  359. headers = curl_slist_append(headers,
  360. "Content-type: application/json");
  361. headers = curl_slist_append(headers,
  362. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  363. if (longpoll)
  364. headers = curl_slist_append(headers,
  365. "X-Minimum-Wait: 0");
  366. if (likely(global_hashrate)) {
  367. char ghashrate[255];
  368. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  369. headers = curl_slist_append(headers, ghashrate);
  370. }
  371. headers = curl_slist_append(headers, len_hdr);
  372. headers = curl_slist_append(headers, user_agent_hdr);
  373. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  374. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  375. state->headers = headers;
  376. if (opt_delaynet) {
  377. /* Don't delay share submission, but still track the nettime */
  378. if (!share) {
  379. long long now_msecs, last_msecs;
  380. struct timeval now, last;
  381. gettimeofday(&now, NULL);
  382. last_nettime(&last);
  383. now_msecs = (long long)now.tv_sec * 1000;
  384. now_msecs += now.tv_usec / 1000;
  385. last_msecs = (long long)last.tv_sec * 1000;
  386. last_msecs += last.tv_usec / 1000;
  387. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  388. struct timespec rgtp;
  389. rgtp.tv_sec = 0;
  390. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  391. nanosleep(&rgtp, NULL);
  392. }
  393. }
  394. set_nettime();
  395. }
  396. }
  397. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  398. {
  399. struct json_rpc_call_state *state;
  400. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, &state) != CURLE_OK) {
  401. applog(LOG_ERR, "Failed to get private curl data");
  402. if (out_priv)
  403. *(void**)out_priv = NULL;
  404. goto err_out;
  405. }
  406. if (out_priv)
  407. *(void**)out_priv = state->priv;
  408. json_t *val, *err_val, *res_val;
  409. json_error_t err;
  410. struct pool *pool = state->pool;
  411. bool probing = probe && !pool->probed;
  412. if (rc) {
  413. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  414. goto err_out;
  415. }
  416. if (!state->all_data.buf) {
  417. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  418. goto err_out;
  419. }
  420. pool->cgminer_pool_stats.times_sent++;
  421. pool->cgminer_pool_stats.times_received++;
  422. if (probing) {
  423. pool->probed = true;
  424. /* If X-Long-Polling was found, activate long polling */
  425. if (state->hi.lp_path) {
  426. if (pool->hdr_path != NULL)
  427. free(pool->hdr_path);
  428. pool->hdr_path = state->hi.lp_path;
  429. } else
  430. pool->hdr_path = NULL;
  431. if (state->hi.stratum_url) {
  432. pool->stratum_url = state->hi.stratum_url;
  433. state->hi.stratum_url = NULL;
  434. }
  435. } else {
  436. if (state->hi.lp_path) {
  437. free(state->hi.lp_path);
  438. state->hi.lp_path = NULL;
  439. }
  440. if (state->hi.stratum_url) {
  441. free(state->hi.stratum_url);
  442. state->hi.stratum_url = NULL;
  443. }
  444. }
  445. if (rolltime)
  446. *rolltime = state->hi.rolltime;
  447. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  448. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  449. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  450. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  451. val = JSON_LOADS(state->all_data.buf, &err);
  452. if (!val) {
  453. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  454. if (opt_protocol)
  455. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
  456. goto err_out;
  457. }
  458. if (opt_protocol) {
  459. char *s = json_dumps(val, JSON_INDENT(3));
  460. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  461. free(s);
  462. }
  463. /* JSON-RPC valid response returns a non-null 'result',
  464. * and a null 'error'.
  465. */
  466. res_val = json_object_get(val, "result");
  467. err_val = json_object_get(val, "error");
  468. if (!res_val ||(err_val && !json_is_null(err_val))) {
  469. char *s;
  470. if (err_val)
  471. s = json_dumps(err_val, JSON_INDENT(3));
  472. else
  473. s = strdup("(unknown reason)");
  474. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  475. free(s);
  476. json_decref(val);
  477. goto err_out;
  478. }
  479. if (state->hi.reason) {
  480. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  481. free(state->hi.reason);
  482. state->hi.reason = NULL;
  483. }
  484. successful_connect = true;
  485. databuf_free(&state->all_data);
  486. curl_slist_free_all(state->headers);
  487. curl_easy_reset(curl);
  488. free(state);
  489. return val;
  490. err_out:
  491. databuf_free(&state->all_data);
  492. curl_slist_free_all(state->headers);
  493. curl_easy_reset(curl);
  494. if (!successful_connect)
  495. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  496. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  497. free(state);
  498. return NULL;
  499. }
  500. json_t *json_rpc_call(CURL *curl, const char *url,
  501. const char *userpass, const char *rpc_req,
  502. bool probe, bool longpoll, int *rolltime,
  503. struct pool *pool, bool share)
  504. {
  505. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  506. int rc = curl_easy_perform(curl);
  507. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  508. }
  509. bool our_curl_supports_proxy_uris()
  510. {
  511. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  512. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  513. }
  514. /* Returns a malloced array string of a binary value of arbitrary length. The
  515. * array is rounded up to a 4 byte size to appease architectures that need
  516. * aligned array sizes */
  517. char *bin2hex(const unsigned char *p, size_t len)
  518. {
  519. unsigned int i;
  520. ssize_t slen;
  521. char *s;
  522. slen = len * 2 + 1;
  523. if (slen % 4)
  524. slen += 4 - (slen % 4);
  525. s = calloc(slen, 1);
  526. if (unlikely(!s))
  527. quit(1, "Failed to calloc in bin2hex");
  528. for (i = 0; i < len; i++)
  529. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  530. return s;
  531. }
  532. /* Does the reverse of bin2hex but does not allocate any ram */
  533. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  534. {
  535. bool ret = false;
  536. while (*hexstr && len) {
  537. char hex_byte[4];
  538. unsigned int v;
  539. if (unlikely(!hexstr[1])) {
  540. applog(LOG_ERR, "hex2bin str truncated");
  541. return ret;
  542. }
  543. memset(hex_byte, 0, 4);
  544. hex_byte[0] = hexstr[0];
  545. hex_byte[1] = hexstr[1];
  546. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  547. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  548. return ret;
  549. }
  550. *p = (unsigned char) v;
  551. p++;
  552. hexstr += 2;
  553. len--;
  554. }
  555. if (likely(len == 0 && *hexstr == 0))
  556. ret = true;
  557. return ret;
  558. }
  559. void hash_data(unsigned char *out_hash, const unsigned char *data)
  560. {
  561. unsigned char blkheader[80];
  562. // data is past the first SHA256 step (padding and interpreting as big endian on a little endian platform), so we need to flip each 32-bit chunk around to get the original input block header
  563. swap32yes(blkheader, data, 80 / 4);
  564. // double-SHA256 to get the block hash
  565. gen_hash(blkheader, out_hash, 80);
  566. }
  567. void real_block_target(unsigned char *target, const unsigned char *data)
  568. {
  569. uint8_t targetshift;
  570. targetshift = data[72] - 3;
  571. memset(target, 0, targetshift);
  572. target[targetshift++] = data[75];
  573. target[targetshift++] = data[74];
  574. target[targetshift++] = data[73];
  575. memset(&target[targetshift], 0, 0x20 - targetshift);
  576. }
  577. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  578. {
  579. const uint32_t *h32 = (uint32_t*)&hash[0];
  580. const uint32_t *t32 = (uint32_t*)&target[0];
  581. for (int i = 7; i >= 0; --i) {
  582. uint32_t h32i = le32toh(h32[i]);
  583. uint32_t t32i = le32toh(t32[i]);
  584. if (h32i > t32i)
  585. return false;
  586. if (h32i < t32i)
  587. return true;
  588. }
  589. return true;
  590. }
  591. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  592. {
  593. bool rc;
  594. rc = hash_target_check(hash, target);
  595. if (opt_debug) {
  596. unsigned char hash_swap[32], target_swap[32];
  597. char *hash_str, *target_str;
  598. for (int i = 0; i < 32; ++i) {
  599. hash_swap[i] = hash[31-i];
  600. target_swap[i] = target[31-i];
  601. }
  602. hash_str = bin2hex(hash_swap, 32);
  603. target_str = bin2hex(target_swap, 32);
  604. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  605. hash_str,
  606. target_str,
  607. rc ? "YES (hash < target)" :
  608. "no (false positive; hash > target)");
  609. free(hash_str);
  610. free(target_str);
  611. }
  612. return rc;
  613. }
  614. // DEPRECATED: This uses an input hash that has every 4 bytes flipped
  615. bool fulltest(const unsigned char *hash, const unsigned char *target)
  616. {
  617. unsigned char hash2[32];
  618. swap32yes(hash2, hash, 32 / 4);
  619. return hash_target_check_v(hash2, target);
  620. }
  621. struct thread_q *tq_new(void)
  622. {
  623. struct thread_q *tq;
  624. tq = calloc(1, sizeof(*tq));
  625. if (!tq)
  626. return NULL;
  627. INIT_LIST_HEAD(&tq->q);
  628. pthread_mutex_init(&tq->mutex, NULL);
  629. pthread_cond_init(&tq->cond, NULL);
  630. return tq;
  631. }
  632. void tq_free(struct thread_q *tq)
  633. {
  634. struct tq_ent *ent, *iter;
  635. if (!tq)
  636. return;
  637. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  638. list_del(&ent->q_node);
  639. free(ent);
  640. }
  641. pthread_cond_destroy(&tq->cond);
  642. pthread_mutex_destroy(&tq->mutex);
  643. memset(tq, 0, sizeof(*tq)); /* poison */
  644. free(tq);
  645. }
  646. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  647. {
  648. mutex_lock(&tq->mutex);
  649. tq->frozen = frozen;
  650. pthread_cond_signal(&tq->cond);
  651. mutex_unlock(&tq->mutex);
  652. }
  653. void tq_freeze(struct thread_q *tq)
  654. {
  655. tq_freezethaw(tq, true);
  656. }
  657. void tq_thaw(struct thread_q *tq)
  658. {
  659. tq_freezethaw(tq, false);
  660. }
  661. bool tq_push(struct thread_q *tq, void *data)
  662. {
  663. struct tq_ent *ent;
  664. bool rc = true;
  665. ent = calloc(1, sizeof(*ent));
  666. if (!ent)
  667. return false;
  668. ent->data = data;
  669. INIT_LIST_HEAD(&ent->q_node);
  670. mutex_lock(&tq->mutex);
  671. if (!tq->frozen) {
  672. list_add_tail(&ent->q_node, &tq->q);
  673. } else {
  674. free(ent);
  675. rc = false;
  676. }
  677. pthread_cond_signal(&tq->cond);
  678. mutex_unlock(&tq->mutex);
  679. return rc;
  680. }
  681. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  682. {
  683. struct tq_ent *ent;
  684. void *rval = NULL;
  685. int rc;
  686. mutex_lock(&tq->mutex);
  687. if (!list_empty(&tq->q))
  688. goto pop;
  689. if (abstime)
  690. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  691. else
  692. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  693. if (rc)
  694. goto out;
  695. if (list_empty(&tq->q))
  696. goto out;
  697. pop:
  698. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  699. rval = ent->data;
  700. list_del(&ent->q_node);
  701. free(ent);
  702. out:
  703. mutex_unlock(&tq->mutex);
  704. return rval;
  705. }
  706. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  707. {
  708. return pthread_create(&thr->pth, attr, start, arg);
  709. }
  710. void thr_info_freeze(struct thr_info *thr)
  711. {
  712. struct tq_ent *ent, *iter;
  713. struct thread_q *tq;
  714. if (!thr)
  715. return;
  716. tq = thr->q;
  717. if (!tq)
  718. return;
  719. mutex_lock(&tq->mutex);
  720. tq->frozen = true;
  721. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  722. list_del(&ent->q_node);
  723. free(ent);
  724. }
  725. mutex_unlock(&tq->mutex);
  726. }
  727. void thr_info_cancel(struct thr_info *thr)
  728. {
  729. if (!thr)
  730. return;
  731. if (PTH(thr) != 0L) {
  732. pthread_cancel(thr->pth);
  733. PTH(thr) = 0L;
  734. }
  735. }
  736. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  737. * on SMP machines */
  738. void nmsleep(unsigned int msecs)
  739. {
  740. struct timespec twait, tleft;
  741. int ret;
  742. ldiv_t d;
  743. d = ldiv(msecs, 1000);
  744. tleft.tv_sec = d.quot;
  745. tleft.tv_nsec = d.rem * 1000000;
  746. do {
  747. twait.tv_sec = tleft.tv_sec;
  748. twait.tv_nsec = tleft.tv_nsec;
  749. ret = nanosleep(&twait, &tleft);
  750. } while (ret == -1 && errno == EINTR);
  751. }
  752. /* Returns the microseconds difference between end and start times as a double */
  753. double us_tdiff(struct timeval *end, struct timeval *start)
  754. {
  755. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  756. }
  757. /* Returns the seconds difference between end and start times as a double */
  758. double tdiff(struct timeval *end, struct timeval *start)
  759. {
  760. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  761. }
  762. bool extract_sockaddr(struct pool *pool, char *url)
  763. {
  764. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  765. char url_address[256], port[6];
  766. int url_len, port_len = 0;
  767. url_begin = strstr(url, "//");
  768. if (!url_begin)
  769. url_begin = url;
  770. else
  771. url_begin += 2;
  772. /* Look for numeric ipv6 entries */
  773. ipv6_begin = strstr(url_begin, "[");
  774. ipv6_end = strstr(url_begin, "]");
  775. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  776. url_end = strstr(ipv6_end, ":");
  777. else
  778. url_end = strstr(url_begin, ":");
  779. if (url_end) {
  780. url_len = url_end - url_begin;
  781. port_len = strlen(url_begin) - url_len - 1;
  782. if (port_len < 1)
  783. return false;
  784. port_start = url_end + 1;
  785. } else
  786. url_len = strlen(url_begin);
  787. if (url_len < 1)
  788. return false;
  789. sprintf(url_address, "%.*s", url_len, url_begin);
  790. if (port_len)
  791. snprintf(port, 6, "%.*s", port_len, port_start);
  792. else
  793. strcpy(port, "80");
  794. free(pool->stratum_port);
  795. pool->stratum_port = strdup(port);
  796. free(pool->sockaddr_url);
  797. pool->sockaddr_url = strdup(url_address);
  798. return true;
  799. }
  800. /* Send a single command across a socket, appending \n to it. This should all
  801. * be done under stratum lock except when first establishing the socket */
  802. static bool __stratum_send(struct pool *pool, char *s, ssize_t len)
  803. {
  804. SOCKETTYPE sock = pool->sock;
  805. ssize_t ssent = 0;
  806. if (opt_protocol)
  807. applog(LOG_DEBUG, "SEND: %s", s);
  808. strcat(s, "\n");
  809. len++;
  810. while (len > 0 ) {
  811. struct timeval timeout = {0, 0};
  812. ssize_t sent;
  813. fd_set wd;
  814. FD_ZERO(&wd);
  815. FD_SET(sock, &wd);
  816. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  817. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  818. return false;
  819. }
  820. sent = send(pool->sock, s + ssent, len, 0);
  821. if (sent < 0) {
  822. if (errno != EAGAIN && errno != EWOULDBLOCK) {
  823. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  824. return false;
  825. }
  826. sent = 0;
  827. }
  828. ssent += sent;
  829. len -= ssent;
  830. }
  831. pool->cgminer_pool_stats.times_sent++;
  832. pool->cgminer_pool_stats.bytes_sent += ssent;
  833. total_bytes_xfer += ssent;
  834. return true;
  835. }
  836. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  837. {
  838. bool ret = false;
  839. mutex_lock(&pool->stratum_lock);
  840. if (pool->stratum_active)
  841. ret = __stratum_send(pool, s, len);
  842. else
  843. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  844. mutex_unlock(&pool->stratum_lock);
  845. return ret;
  846. }
  847. static bool socket_full(struct pool *pool, bool wait)
  848. {
  849. SOCKETTYPE sock = pool->sock;
  850. struct timeval timeout;
  851. fd_set rd;
  852. FD_ZERO(&rd);
  853. FD_SET(sock, &rd);
  854. timeout.tv_usec = 0;
  855. if (wait)
  856. timeout.tv_sec = 60;
  857. else
  858. timeout.tv_sec = 0;
  859. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  860. return true;
  861. return false;
  862. }
  863. /* Check to see if Santa's been good to you */
  864. bool sock_full(struct pool *pool)
  865. {
  866. if (strlen(pool->sockbuf))
  867. return true;
  868. return (socket_full(pool, false));
  869. }
  870. static void clear_sock(struct pool *pool)
  871. {
  872. ssize_t n;
  873. mutex_lock(&pool->stratum_lock);
  874. do
  875. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  876. while (n > 0);
  877. mutex_unlock(&pool->stratum_lock);
  878. strcpy(pool->sockbuf, "");
  879. }
  880. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  881. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  882. * and zeroing the new memory */
  883. static void recalloc_sock(struct pool *pool, size_t len)
  884. {
  885. size_t old, new;
  886. old = strlen(pool->sockbuf);
  887. new = old + len + 1;
  888. if (new < pool->sockbuf_size)
  889. return;
  890. new = new + (RBUFSIZE - (new % RBUFSIZE));
  891. applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  892. pool->sockbuf = realloc(pool->sockbuf, new);
  893. if (!pool->sockbuf)
  894. quit(1, "Failed to realloc pool sockbuf in recalloc_sock");
  895. memset(pool->sockbuf + old, 0, new - old);
  896. pool->sockbuf_size = new;
  897. }
  898. /* Peeks at a socket to find the first end of line and then reads just that
  899. * from the socket and returns that as a malloced char */
  900. char *recv_line(struct pool *pool)
  901. {
  902. ssize_t len, buflen;
  903. char *tok, *sret = NULL;
  904. if (!strstr(pool->sockbuf, "\n")) {
  905. struct timeval rstart, now;
  906. gettimeofday(&rstart, NULL);
  907. if (!socket_full(pool, true)) {
  908. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  909. goto out;
  910. }
  911. mutex_lock(&pool->stratum_lock);
  912. do {
  913. char s[RBUFSIZE];
  914. size_t slen, n;
  915. memset(s, 0, RBUFSIZE);
  916. n = recv(pool->sock, s, RECVSIZE, 0);
  917. if (n < 1 && errno != EAGAIN && errno != EWOULDBLOCK) {
  918. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  919. break;
  920. }
  921. slen = strlen(s);
  922. recalloc_sock(pool, slen);
  923. strcat(pool->sockbuf, s);
  924. gettimeofday(&now, NULL);
  925. } while (tdiff(&now, &rstart) < 60 && !strstr(pool->sockbuf, "\n"));
  926. mutex_unlock(&pool->stratum_lock);
  927. }
  928. buflen = strlen(pool->sockbuf);
  929. tok = strtok(pool->sockbuf, "\n");
  930. if (!tok) {
  931. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  932. goto out;
  933. }
  934. sret = strdup(tok);
  935. len = strlen(sret);
  936. /* Copy what's left in the buffer after the \n, including the
  937. * terminating \0 */
  938. if (buflen > len + 1)
  939. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  940. else
  941. strcpy(pool->sockbuf, "");
  942. pool->cgminer_pool_stats.times_received++;
  943. pool->cgminer_pool_stats.bytes_received += len;
  944. total_bytes_xfer += len;
  945. out:
  946. if (!sret)
  947. clear_sock(pool);
  948. else if (opt_protocol)
  949. applog(LOG_DEBUG, "RECVD: %s", sret);
  950. return sret;
  951. }
  952. /* Extracts a string value from a json array with error checking. To be used
  953. * when the value of the string returned is only examined and not to be stored.
  954. * See json_array_string below */
  955. static char *__json_array_string(json_t *val, unsigned int entry)
  956. {
  957. json_t *arr_entry;
  958. if (json_is_null(val))
  959. return NULL;
  960. if (!json_is_array(val))
  961. return NULL;
  962. if (entry > json_array_size(val))
  963. return NULL;
  964. arr_entry = json_array_get(val, entry);
  965. if (!json_is_string(arr_entry))
  966. return NULL;
  967. return (char *)json_string_value(arr_entry);
  968. }
  969. /* Creates a freshly malloced dup of __json_array_string */
  970. static char *json_array_string(json_t *val, unsigned int entry)
  971. {
  972. char *buf = __json_array_string(val, entry);
  973. if (buf)
  974. return strdup(buf);
  975. return NULL;
  976. }
  977. static bool parse_notify(struct pool *pool, json_t *val)
  978. {
  979. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  980. bool clean, ret = false;
  981. int merkles, i;
  982. json_t *arr;
  983. arr = json_array_get(val, 4);
  984. if (!arr || !json_is_array(arr))
  985. goto out;
  986. merkles = json_array_size(arr);
  987. job_id = json_array_string(val, 0);
  988. prev_hash = json_array_string(val, 1);
  989. coinbase1 = json_array_string(val, 2);
  990. coinbase2 = json_array_string(val, 3);
  991. bbversion = json_array_string(val, 5);
  992. nbit = json_array_string(val, 6);
  993. ntime = json_array_string(val, 7);
  994. clean = json_is_true(json_array_get(val, 8));
  995. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  996. /* Annoying but we must not leak memory */
  997. if (job_id)
  998. free(job_id);
  999. if (prev_hash)
  1000. free(prev_hash);
  1001. if (coinbase1)
  1002. free(coinbase1);
  1003. if (coinbase2)
  1004. free(coinbase2);
  1005. if (bbversion)
  1006. free(bbversion);
  1007. if (nbit)
  1008. free(nbit);
  1009. if (ntime)
  1010. free(ntime);
  1011. goto out;
  1012. }
  1013. mutex_lock(&pool->pool_lock);
  1014. free(pool->swork.job_id);
  1015. free(pool->swork.prev_hash);
  1016. free(pool->swork.coinbase1);
  1017. free(pool->swork.coinbase2);
  1018. free(pool->swork.bbversion);
  1019. free(pool->swork.nbit);
  1020. free(pool->swork.ntime);
  1021. pool->swork.job_id = job_id;
  1022. pool->swork.prev_hash = prev_hash;
  1023. pool->swork.coinbase1 = coinbase1;
  1024. pool->swork.coinbase2 = coinbase2;
  1025. pool->swork.bbversion = bbversion;
  1026. pool->swork.nbit = nbit;
  1027. pool->swork.ntime = ntime;
  1028. pool->submit_old = !clean;
  1029. pool->swork.clean = true;
  1030. for (i = 0; i < pool->swork.merkles; i++)
  1031. free(pool->swork.merkle[i]);
  1032. if (merkles) {
  1033. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  1034. for (i = 0; i < merkles; i++)
  1035. pool->swork.merkle[i] = json_array_string(arr, i);
  1036. }
  1037. pool->swork.merkles = merkles;
  1038. if (clean)
  1039. pool->nonce2 = 0;
  1040. mutex_unlock(&pool->pool_lock);
  1041. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  1042. pool->pool_no, job_id);
  1043. if (opt_protocol) {
  1044. applog(LOG_DEBUG, "job_id: %s", job_id);
  1045. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1046. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1047. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1048. for (i = 0; i < merkles; i++)
  1049. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  1050. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1051. applog(LOG_DEBUG, "nbit: %s", nbit);
  1052. applog(LOG_DEBUG, "ntime: %s", ntime);
  1053. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1054. }
  1055. /* A notify message is the closest stratum gets to a getwork */
  1056. pool->getwork_requested++;
  1057. total_getworks++;
  1058. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || pool->swork.transparency_time != (time_t)-1)
  1059. {
  1060. // Request transaction data to discourage pools from doing anything shady
  1061. char s[1024];
  1062. int sLen;
  1063. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  1064. pool->swork.job_id,
  1065. pool->swork.job_id);
  1066. stratum_send(pool, s, sLen);
  1067. if ((!pool->swork.opaque) && pool->swork.transparency_time == (time_t)-1)
  1068. pool->swork.transparency_time = time(NULL);
  1069. pool->swork.transparency_probed = true;
  1070. }
  1071. ret = true;
  1072. out:
  1073. return ret;
  1074. }
  1075. static bool parse_diff(struct pool *pool, json_t *val)
  1076. {
  1077. double diff;
  1078. diff = json_number_value(json_array_get(val, 0));
  1079. if (diff == 0)
  1080. return false;
  1081. mutex_lock(&pool->pool_lock);
  1082. pool->swork.diff = diff;
  1083. mutex_unlock(&pool->pool_lock);
  1084. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no, diff);
  1085. return true;
  1086. }
  1087. static bool parse_reconnect(struct pool *pool, json_t *val)
  1088. {
  1089. char *url, *port, address[256];
  1090. memset(address, 0, 255);
  1091. url = (char *)json_string_value(json_array_get(val, 0));
  1092. if (!url)
  1093. url = pool->sockaddr_url;
  1094. port = (char *)json_string_value(json_array_get(val, 1));
  1095. if (!port)
  1096. port = pool->stratum_port;
  1097. sprintf(address, "%s:%s", url, port);
  1098. if (!extract_sockaddr(pool, address))
  1099. return false;
  1100. pool->stratum_url = pool->sockaddr_url;
  1101. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1102. if (!initiate_stratum(pool) || !auth_stratum(pool))
  1103. return false;
  1104. return true;
  1105. }
  1106. static bool send_version(struct pool *pool, json_t *val)
  1107. {
  1108. char s[RBUFSIZE];
  1109. int id = json_integer_value(json_object_get(val, "id"));
  1110. if (!id)
  1111. return false;
  1112. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  1113. if (!stratum_send(pool, s, strlen(s)))
  1114. return false;
  1115. return true;
  1116. }
  1117. bool parse_method(struct pool *pool, char *s)
  1118. {
  1119. json_t *val = NULL, *method, *err_val, *params;
  1120. json_error_t err;
  1121. bool ret = false;
  1122. char *buf;
  1123. if (!s)
  1124. goto out;
  1125. val = JSON_LOADS(s, &err);
  1126. if (!val) {
  1127. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1128. goto out;
  1129. }
  1130. method = json_object_get(val, "method");
  1131. if (!method)
  1132. goto out;
  1133. err_val = json_object_get(val, "error");
  1134. params = json_object_get(val, "params");
  1135. if (err_val && !json_is_null(err_val)) {
  1136. char *ss;
  1137. if (err_val)
  1138. ss = json_dumps(err_val, JSON_INDENT(3));
  1139. else
  1140. ss = strdup("(unknown reason)");
  1141. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1142. free(ss);
  1143. goto out;
  1144. }
  1145. buf = (char *)json_string_value(method);
  1146. if (!buf)
  1147. goto out;
  1148. if (!strncasecmp(buf, "mining.notify", 13)) {
  1149. if (parse_notify(pool, params))
  1150. pool->stratum_notify = ret = true;
  1151. else
  1152. pool->stratum_notify = ret = false;
  1153. goto out;
  1154. }
  1155. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1156. ret = true;
  1157. goto out;
  1158. }
  1159. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1160. ret = true;
  1161. goto out;
  1162. }
  1163. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1164. ret = true;
  1165. goto out;
  1166. }
  1167. out:
  1168. if (val)
  1169. json_decref(val);
  1170. return ret;
  1171. }
  1172. extern bool parse_stratum_response(struct pool *, char *s);
  1173. bool auth_stratum(struct pool *pool)
  1174. {
  1175. json_t *val = NULL, *res_val, *err_val;
  1176. char s[RBUFSIZE], *sret = NULL;
  1177. json_error_t err;
  1178. bool ret = false;
  1179. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1180. pool->rpc_user, pool->rpc_pass);
  1181. if (!stratum_send(pool, s, strlen(s)))
  1182. goto out;
  1183. /* Parse all data in the queue and anything left should be auth */
  1184. while (42) {
  1185. sret = recv_line(pool);
  1186. if (!sret)
  1187. goto out;
  1188. if (parse_method(pool, sret))
  1189. free(sret);
  1190. else
  1191. break;
  1192. }
  1193. val = JSON_LOADS(sret, &err);
  1194. free(sret);
  1195. res_val = json_object_get(val, "result");
  1196. err_val = json_object_get(val, "error");
  1197. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1198. char *ss;
  1199. if (err_val)
  1200. ss = json_dumps(err_val, JSON_INDENT(3));
  1201. else
  1202. ss = strdup("(unknown reason)");
  1203. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  1204. free(ss);
  1205. goto out;
  1206. }
  1207. ret = true;
  1208. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1209. pool->probed = true;
  1210. pool->stratum_auth = true;
  1211. successful_connect = true;
  1212. out:
  1213. if (val)
  1214. json_decref(val);
  1215. return ret;
  1216. }
  1217. bool initiate_stratum(struct pool *pool)
  1218. {
  1219. json_t *val = NULL, *res_val, *err_val;
  1220. char curl_err_str[CURL_ERROR_SIZE];
  1221. char s[RBUFSIZE], *sret = NULL;
  1222. CURL *curl = NULL;
  1223. json_error_t err;
  1224. bool ret = false;
  1225. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  1226. mutex_lock(&pool->stratum_lock);
  1227. pool->swork.transparency_time = (time_t)-1;
  1228. pool->stratum_active = false;
  1229. pool->stratum_auth = false;
  1230. pool->swork.transparency_probed = false;
  1231. if (!pool->stratum_curl) {
  1232. pool->stratum_curl = curl_easy_init();
  1233. if (unlikely(!pool->stratum_curl))
  1234. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1235. }
  1236. if (pool->sockbuf)
  1237. pool->sockbuf[0] = '\0';
  1238. mutex_unlock(&pool->stratum_lock);
  1239. curl = pool->stratum_curl;
  1240. if (!pool->sockbuf) {
  1241. pool->sockbuf = calloc(RBUFSIZE, 1);
  1242. if (!pool->sockbuf)
  1243. quit(1, "Failed to calloc pool sockbuf in initiate_stratum");
  1244. pool->sockbuf_size = RBUFSIZE;
  1245. }
  1246. /* Create a http url for use with curl */
  1247. memset(s, 0, RBUFSIZE);
  1248. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1249. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1250. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1251. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1252. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1253. curl_easy_setopt(curl, CURLOPT_URL, s);
  1254. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1255. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  1256. * to enable it */
  1257. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1258. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, my_curl_debug);
  1259. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, pool);
  1260. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1261. if (pool->rpc_proxy) {
  1262. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1263. } else if (opt_socks_proxy) {
  1264. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1265. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1266. }
  1267. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1268. pool->sock = INVSOCK;
  1269. if (curl_easy_perform(curl)) {
  1270. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1271. goto out;
  1272. }
  1273. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&pool->sock);
  1274. keep_sockalive(pool->sock);
  1275. pool->cgminer_pool_stats.times_sent++;
  1276. pool->cgminer_pool_stats.times_received++;
  1277. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1278. if (!__stratum_send(pool, s, strlen(s))) {
  1279. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1280. goto out;
  1281. }
  1282. if (!socket_full(pool, true)) {
  1283. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1284. goto out;
  1285. }
  1286. sret = recv_line(pool);
  1287. if (!sret)
  1288. goto out;
  1289. val = JSON_LOADS(sret, &err);
  1290. free(sret);
  1291. if (!val) {
  1292. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1293. goto out;
  1294. }
  1295. res_val = json_object_get(val, "result");
  1296. err_val = json_object_get(val, "error");
  1297. if (!res_val || json_is_null(res_val) ||
  1298. (err_val && !json_is_null(err_val))) {
  1299. char *ss;
  1300. if (err_val)
  1301. ss = json_dumps(err_val, JSON_INDENT(3));
  1302. else
  1303. ss = strdup("(unknown reason)");
  1304. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1305. free(ss);
  1306. goto out;
  1307. }
  1308. free(pool->nonce1);
  1309. pool->nonce1 = json_array_string(res_val, 1);
  1310. if (!pool->nonce1) {
  1311. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1312. goto out;
  1313. }
  1314. pool->n2size = json_integer_value(json_array_get(res_val, 2));
  1315. if (!pool->n2size) {
  1316. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1317. goto out;
  1318. }
  1319. ret = true;
  1320. out:
  1321. if (val)
  1322. json_decref(val);
  1323. if (ret) {
  1324. if (!pool->stratum_url)
  1325. pool->stratum_url = pool->sockaddr_url;
  1326. pool->stratum_active = true;
  1327. pool->swork.diff = 1;
  1328. if (opt_protocol) {
  1329. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1330. pool->pool_no, pool->nonce1, pool->n2size);
  1331. }
  1332. } else
  1333. {
  1334. applog(LOG_DEBUG, "Initiate stratum failed");
  1335. if (pool->sock != INVSOCK) {
  1336. shutdown(pool->sock, SHUT_RDWR);
  1337. pool->sock = INVSOCK;
  1338. }
  1339. }
  1340. return ret;
  1341. }
  1342. void suspend_stratum(struct pool *pool)
  1343. {
  1344. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1345. mutex_lock(&pool->stratum_lock);
  1346. pool->stratum_active = false;
  1347. pool->stratum_auth = false;
  1348. mutex_unlock(&pool->stratum_lock);
  1349. CLOSESOCKET(pool->sock);
  1350. }
  1351. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1352. {
  1353. dev->device_last_not_well = time(NULL);
  1354. dev->device_not_well_reason = reason;
  1355. switch (reason) {
  1356. case REASON_THREAD_FAIL_INIT:
  1357. dev->thread_fail_init_count++;
  1358. break;
  1359. case REASON_THREAD_ZERO_HASH:
  1360. dev->thread_zero_hash_count++;
  1361. break;
  1362. case REASON_THREAD_FAIL_QUEUE:
  1363. dev->thread_fail_queue_count++;
  1364. break;
  1365. case REASON_DEV_SICK_IDLE_60:
  1366. dev->dev_sick_idle_60_count++;
  1367. break;
  1368. case REASON_DEV_DEAD_IDLE_600:
  1369. dev->dev_dead_idle_600_count++;
  1370. break;
  1371. case REASON_DEV_NOSTART:
  1372. dev->dev_nostart_count++;
  1373. break;
  1374. case REASON_DEV_OVER_HEAT:
  1375. dev->dev_over_heat_count++;
  1376. break;
  1377. case REASON_DEV_THERMAL_CUTOFF:
  1378. dev->dev_thermal_cutoff_count++;
  1379. break;
  1380. case REASON_DEV_COMMS_ERROR:
  1381. dev->dev_comms_error_count++;
  1382. break;
  1383. case REASON_DEV_THROTTLE:
  1384. dev->dev_throttle_count++;
  1385. break;
  1386. }
  1387. }
  1388. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1389. void *realloc_strcat(char *ptr, char *s)
  1390. {
  1391. size_t old = strlen(ptr), len = strlen(s);
  1392. char *ret;
  1393. if (!len)
  1394. return ptr;
  1395. len += old + 1;
  1396. if (len % 4)
  1397. len += 4 - (len % 4);
  1398. ret = malloc(len);
  1399. if (unlikely(!ret))
  1400. quit(1, "Failed to malloc in realloc_strcat");
  1401. sprintf(ret, "%s%s", ptr, s);
  1402. free(ptr);
  1403. return ret;
  1404. }
  1405. void RenameThread(const char* name)
  1406. {
  1407. #if defined(PR_SET_NAME)
  1408. // Only the first 15 characters are used (16 - NUL terminator)
  1409. prctl(PR_SET_NAME, name, 0, 0, 0);
  1410. #elif defined(__APPLE__)
  1411. pthread_setname_np(name);
  1412. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  1413. pthread_set_name_np(pthread_self(), name);
  1414. #else
  1415. // Prevent warnings for unused parameters...
  1416. (void)name;
  1417. #endif
  1418. }
  1419. #ifdef WIN32
  1420. static const char *WindowsErrorStr(DWORD dwMessageId)
  1421. {
  1422. static LPSTR msg = NULL;
  1423. if (msg)
  1424. LocalFree(msg);
  1425. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, dwMessageId, 0, (LPSTR)&msg, 0, 0))
  1426. return msg;
  1427. static const char fmt[] = "Error #%ld";
  1428. signed long ldMsgId = dwMessageId;
  1429. int sz = snprintf((char*)&sz, 0, fmt, ldMsgId) + 1;
  1430. msg = (LPTSTR)LocalAlloc(LMEM_FIXED, sz);
  1431. sprintf((char*)msg, fmt, ldMsgId);
  1432. return msg;
  1433. }
  1434. #endif
  1435. void notifier_init(int pipefd[2])
  1436. {
  1437. #ifdef WIN32
  1438. SOCKET listener, connecter, acceptor;
  1439. listener = socket(AF_INET, SOCK_STREAM, 0);
  1440. if (listener == INVALID_SOCKET)
  1441. quit(1, "Failed to create listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1442. connecter = socket(AF_INET, SOCK_STREAM, 0);
  1443. if (connecter == INVALID_SOCKET)
  1444. quit(1, "Failed to create connect socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1445. struct sockaddr_in inaddr = {
  1446. .sin_family = AF_INET,
  1447. .sin_addr = {
  1448. .s_addr = htonl(INADDR_LOOPBACK),
  1449. },
  1450. .sin_port = 0,
  1451. };
  1452. {
  1453. char reuse = 1;
  1454. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
  1455. }
  1456. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  1457. quit(1, "Failed to bind listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1458. socklen_t inaddr_sz = sizeof(inaddr);
  1459. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  1460. quit(1, "Failed to getsockname in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1461. if (listen(listener, 1) == SOCKET_ERROR)
  1462. quit(1, "Failed to listen in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1463. inaddr.sin_family = AF_INET;
  1464. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  1465. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  1466. quit(1, "Failed to connect in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1467. acceptor = accept(listener, NULL, NULL);
  1468. if (acceptor == INVALID_SOCKET)
  1469. quit(1, "Failed to accept in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1470. closesocket(listener);
  1471. pipefd[0] = connecter;
  1472. pipefd[1] = acceptor;
  1473. #else
  1474. if (pipe(pipefd))
  1475. quit(1, "Failed to create pipe in create_notifier");
  1476. #endif
  1477. }
  1478. void notifier_wake(int fd[2])
  1479. {
  1480. #ifdef WIN32
  1481. (void)send(fd[1], "\0", 1, 0);
  1482. #else
  1483. (void)write(fd[1], "\0", 1);
  1484. #endif
  1485. }
  1486. void notifier_read(int fd[2])
  1487. {
  1488. char buf[0x10];
  1489. #ifdef WIN32
  1490. (void)recv(fd[0], buf, sizeof(buf), 0);
  1491. #else
  1492. (void)read(fd[0], buf, sizeof(buf));
  1493. #endif
  1494. }