util.c 41 KB

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