util.c 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2013 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. * Copyright 2012 Giel van Schijndel
  6. * Copyright 2012 Gavin Andresen
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by the Free
  10. * Software Foundation; either version 3 of the License, or (at your option)
  11. * any later version. See COPYING for more details.
  12. */
  13. #include "config.h"
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <ctype.h>
  17. #include <stdarg.h>
  18. #include <string.h>
  19. #include <pthread.h>
  20. #include <jansson.h>
  21. #include <curl/curl.h>
  22. #include <time.h>
  23. #include <errno.h>
  24. #include <unistd.h>
  25. #include <sys/types.h>
  26. #ifdef HAVE_SYS_PRCTL_H
  27. # include <sys/prctl.h>
  28. #endif
  29. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  30. # include <pthread_np.h>
  31. #endif
  32. #ifndef WIN32
  33. # ifdef __linux
  34. # include <sys/prctl.h>
  35. # endif
  36. # include <sys/socket.h>
  37. # include <netinet/in.h>
  38. # include <netinet/tcp.h>
  39. # include <netdb.h>
  40. #else
  41. # include <winsock2.h>
  42. # include <mstcpip.h>
  43. # include <ws2tcpip.h>
  44. #endif
  45. #include "miner.h"
  46. #include "elist.h"
  47. #include "compat.h"
  48. #include "util.h"
  49. bool successful_connect = false;
  50. struct timeval nettime;
  51. struct data_buffer {
  52. void *buf;
  53. size_t len;
  54. curl_socket_t *idlemarker;
  55. };
  56. struct upload_buffer {
  57. const void *buf;
  58. size_t len;
  59. };
  60. struct header_info {
  61. char *lp_path;
  62. int rolltime;
  63. char *reason;
  64. char *stratum_url;
  65. bool hadrolltime;
  66. bool canroll;
  67. bool hadexpire;
  68. };
  69. struct tq_ent {
  70. void *data;
  71. struct list_head q_node;
  72. };
  73. static void databuf_free(struct data_buffer *db)
  74. {
  75. if (!db)
  76. return;
  77. free(db->buf);
  78. #ifdef DEBUG_DATABUF
  79. applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
  80. #endif
  81. memset(db, 0, sizeof(*db));
  82. }
  83. // aka data_buffer_write
  84. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  85. void *user_data)
  86. {
  87. struct data_buffer *db = user_data;
  88. size_t oldlen, newlen;
  89. oldlen = db->len;
  90. if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
  91. return 0;
  92. if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
  93. nmemb = (SIZE_MAX - oldlen) / size;
  94. size_t len = size * nmemb;
  95. void *newmem;
  96. static const unsigned char zero = 0;
  97. if (db->idlemarker) {
  98. const unsigned char *cptr = ptr;
  99. for (size_t i = 0; i < len; ++i)
  100. if (!(isspace(cptr[i]) || cptr[i] == '{')) {
  101. *db->idlemarker = CURL_SOCKET_BAD;
  102. db->idlemarker = NULL;
  103. break;
  104. }
  105. }
  106. newlen = oldlen + len;
  107. newmem = realloc(db->buf, newlen + 1);
  108. #ifdef DEBUG_DATABUF
  109. applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
  110. #endif
  111. if (!newmem)
  112. return 0;
  113. db->buf = newmem;
  114. db->len = newlen;
  115. memcpy(db->buf + oldlen, ptr, len);
  116. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  117. return nmemb;
  118. }
  119. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  120. void *user_data)
  121. {
  122. struct upload_buffer *ub = user_data;
  123. unsigned int len = size * nmemb;
  124. if (len > ub->len)
  125. len = ub->len;
  126. if (len) {
  127. memcpy(ptr, ub->buf, len);
  128. ub->buf += len;
  129. ub->len -= len;
  130. }
  131. return len;
  132. }
  133. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  134. {
  135. struct header_info *hi = user_data;
  136. size_t remlen, slen, ptrlen = size * nmemb;
  137. char *rem, *val = NULL, *key = NULL;
  138. void *tmp;
  139. val = calloc(1, ptrlen);
  140. key = calloc(1, ptrlen);
  141. if (!key || !val)
  142. goto out;
  143. tmp = memchr(ptr, ':', ptrlen);
  144. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  145. goto out;
  146. slen = tmp - ptr;
  147. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  148. goto out;
  149. memcpy(key, ptr, slen); /* store & nul term key */
  150. key[slen] = 0;
  151. rem = ptr + slen + 1; /* trim value's leading whitespace */
  152. remlen = ptrlen - slen - 1;
  153. while ((remlen > 0) && (isspace(*rem))) {
  154. remlen--;
  155. rem++;
  156. }
  157. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  158. val[remlen] = 0;
  159. while ((*val) && (isspace(val[strlen(val) - 1])))
  160. val[strlen(val) - 1] = 0;
  161. if (!*val) /* skip blank value */
  162. goto out;
  163. if (opt_protocol)
  164. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  165. if (!strcasecmp("X-Roll-Ntime", key)) {
  166. hi->hadrolltime = true;
  167. if (!strncasecmp("N", val, 1))
  168. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  169. else {
  170. hi->canroll = true;
  171. /* Check to see if expire= is supported and if not, set
  172. * the rolltime to the default scantime */
  173. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  174. sscanf(val + 7, "%d", &hi->rolltime);
  175. hi->hadexpire = true;
  176. } else
  177. hi->rolltime = opt_scantime;
  178. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  179. }
  180. }
  181. if (!strcasecmp("X-Long-Polling", key)) {
  182. hi->lp_path = val; /* steal memory reference */
  183. val = NULL;
  184. }
  185. if (!strcasecmp("X-Reject-Reason", key)) {
  186. hi->reason = val; /* steal memory reference */
  187. val = NULL;
  188. }
  189. if (!strcasecmp("X-Stratum", key)) {
  190. hi->stratum_url = val;
  191. val = NULL;
  192. }
  193. out:
  194. free(key);
  195. free(val);
  196. return ptrlen;
  197. }
  198. static int keep_sockalive(SOCKETTYPE fd)
  199. {
  200. const int tcp_keepidle = 45;
  201. const int tcp_keepintvl = 30;
  202. const int keepalive = 1;
  203. int ret = 0;
  204. #ifndef WIN32
  205. const int tcp_keepcnt = 1;
  206. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive))))
  207. ret = 1;
  208. # ifdef __linux
  209. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt))))
  210. ret = 1;
  211. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  212. ret = 1;
  213. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  214. ret = 1;
  215. # endif /* __linux */
  216. # ifdef __APPLE_CC__
  217. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  218. ret = 1;
  219. # endif /* __APPLE_CC__ */
  220. #else /* WIN32 */
  221. const int zero = 0;
  222. struct tcp_keepalive vals;
  223. vals.onoff = 1;
  224. vals.keepalivetime = tcp_keepidle * 1000;
  225. vals.keepaliveinterval = tcp_keepintvl * 1000;
  226. DWORD outputBytes;
  227. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&keepalive, sizeof(keepalive))))
  228. ret = 1;
  229. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  230. ret = 1;
  231. /* Windows happily submits indefinitely to the send buffer blissfully
  232. * unaware nothing is getting there without gracefully failing unless
  233. * we disable the send buffer */
  234. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  235. ret = 1;
  236. #endif /* WIN32 */
  237. return ret;
  238. }
  239. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  240. curlsocktype __maybe_unused purpose)
  241. {
  242. return keep_sockalive(fd);
  243. }
  244. static void last_nettime(struct timeval *last)
  245. {
  246. rd_lock(&netacc_lock);
  247. last->tv_sec = nettime.tv_sec;
  248. last->tv_usec = nettime.tv_usec;
  249. rd_unlock(&netacc_lock);
  250. }
  251. static void set_nettime(void)
  252. {
  253. wr_lock(&netacc_lock);
  254. gettimeofday(&nettime, NULL);
  255. wr_unlock(&netacc_lock);
  256. }
  257. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  258. char *data, size_t size,
  259. void *userdata)
  260. {
  261. struct pool *pool = (struct pool *)userdata;
  262. switch(type) {
  263. case CURLINFO_HEADER_IN:
  264. case CURLINFO_DATA_IN:
  265. case CURLINFO_SSL_DATA_IN:
  266. pool->cgminer_pool_stats.bytes_received += size;
  267. total_bytes_xfer += size;
  268. pool->cgminer_pool_stats.net_bytes_received += size;
  269. break;
  270. case CURLINFO_HEADER_OUT:
  271. case CURLINFO_DATA_OUT:
  272. case CURLINFO_SSL_DATA_OUT:
  273. pool->cgminer_pool_stats.bytes_sent += size;
  274. total_bytes_xfer += size;
  275. pool->cgminer_pool_stats.net_bytes_sent += size;
  276. break;
  277. case CURLINFO_TEXT:
  278. {
  279. if (!opt_protocol)
  280. break;
  281. // data is not null-terminated, so we need to copy and terminate it for applog
  282. char datacp[size + 1];
  283. memcpy(datacp, data, size);
  284. while (likely(size) && unlikely(isspace(datacp[size-1])))
  285. --size;
  286. if (unlikely(!size))
  287. break;
  288. datacp[size] = '\0';
  289. applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
  290. break;
  291. }
  292. default:
  293. break;
  294. }
  295. return 0;
  296. }
  297. struct json_rpc_call_state {
  298. struct data_buffer all_data;
  299. struct header_info hi;
  300. void *priv;
  301. char curl_err_str[CURL_ERROR_SIZE];
  302. struct curl_slist *headers;
  303. struct upload_buffer upload_data;
  304. struct pool *pool;
  305. };
  306. void json_rpc_call_async(CURL *curl, const char *url,
  307. const char *userpass, const char *rpc_req,
  308. bool longpoll,
  309. struct pool *pool, bool share,
  310. void *priv)
  311. {
  312. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  313. *state = (struct json_rpc_call_state){
  314. .priv = priv,
  315. .pool = pool,
  316. };
  317. long timeout = longpoll ? (60 * 60) : 60;
  318. char len_hdr[64], user_agent_hdr[128];
  319. struct curl_slist *headers = NULL;
  320. if (longpoll)
  321. state->all_data.idlemarker = &pool->lp_socket;
  322. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  323. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  324. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  325. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  326. * to enable it */
  327. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  328. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  329. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  330. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  331. curl_easy_setopt(curl, CURLOPT_URL, url);
  332. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  333. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  334. /* Shares are staggered already and delays in submission can be costly
  335. * so do not delay them */
  336. if (!opt_delaynet || share)
  337. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  338. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  339. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
  340. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  341. curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_data);
  342. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  343. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  344. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  345. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
  346. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  347. if (pool->rpc_proxy) {
  348. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  349. } else if (opt_socks_proxy) {
  350. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  351. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  352. }
  353. if (userpass) {
  354. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  355. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  356. }
  357. if (longpoll)
  358. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  359. curl_easy_setopt(curl, CURLOPT_POST, 1);
  360. if (opt_protocol)
  361. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  362. state->upload_data.buf = rpc_req;
  363. state->upload_data.len = strlen(rpc_req);
  364. sprintf(len_hdr, "Content-Length: %lu",
  365. (unsigned long) state->upload_data.len);
  366. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE"/"VERSION);
  367. headers = curl_slist_append(headers,
  368. "Content-type: application/json");
  369. headers = curl_slist_append(headers,
  370. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  371. if (longpoll)
  372. headers = curl_slist_append(headers,
  373. "X-Minimum-Wait: 0");
  374. if (likely(global_hashrate)) {
  375. char ghashrate[255];
  376. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, (uint64_t)global_hashrate);
  377. headers = curl_slist_append(headers, ghashrate);
  378. }
  379. headers = curl_slist_append(headers, len_hdr);
  380. headers = curl_slist_append(headers, user_agent_hdr);
  381. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  382. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  383. state->headers = headers;
  384. if (opt_delaynet) {
  385. /* Don't delay share submission, but still track the nettime */
  386. if (!share) {
  387. long long now_msecs, last_msecs;
  388. struct timeval now, last;
  389. gettimeofday(&now, NULL);
  390. last_nettime(&last);
  391. now_msecs = (long long)now.tv_sec * 1000;
  392. now_msecs += now.tv_usec / 1000;
  393. last_msecs = (long long)last.tv_sec * 1000;
  394. last_msecs += last.tv_usec / 1000;
  395. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  396. struct timespec rgtp;
  397. rgtp.tv_sec = 0;
  398. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  399. nanosleep(&rgtp, NULL);
  400. }
  401. }
  402. set_nettime();
  403. }
  404. }
  405. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  406. {
  407. struct json_rpc_call_state *state;
  408. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, &state) != CURLE_OK) {
  409. applog(LOG_ERR, "Failed to get private curl data");
  410. if (out_priv)
  411. *(void**)out_priv = NULL;
  412. goto err_out;
  413. }
  414. if (out_priv)
  415. *(void**)out_priv = state->priv;
  416. json_t *val, *err_val, *res_val;
  417. json_error_t err;
  418. struct pool *pool = state->pool;
  419. bool probing = probe && !pool->probed;
  420. if (rc) {
  421. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  422. goto err_out;
  423. }
  424. if (!state->all_data.buf) {
  425. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  426. goto err_out;
  427. }
  428. pool->cgminer_pool_stats.times_sent++;
  429. pool->cgminer_pool_stats.times_received++;
  430. if (probing) {
  431. pool->probed = true;
  432. /* If X-Long-Polling was found, activate long polling */
  433. if (state->hi.lp_path) {
  434. if (pool->hdr_path != NULL)
  435. free(pool->hdr_path);
  436. pool->hdr_path = state->hi.lp_path;
  437. } else
  438. pool->hdr_path = NULL;
  439. if (state->hi.stratum_url) {
  440. pool->stratum_url = state->hi.stratum_url;
  441. state->hi.stratum_url = NULL;
  442. }
  443. } else {
  444. if (state->hi.lp_path) {
  445. free(state->hi.lp_path);
  446. state->hi.lp_path = NULL;
  447. }
  448. if (state->hi.stratum_url) {
  449. free(state->hi.stratum_url);
  450. state->hi.stratum_url = NULL;
  451. }
  452. }
  453. if (pool->force_rollntime)
  454. {
  455. state->hi.canroll = true;
  456. state->hi.hadexpire = true;
  457. state->hi.rolltime = pool->force_rollntime;
  458. }
  459. if (rolltime)
  460. *rolltime = state->hi.rolltime;
  461. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  462. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  463. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  464. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  465. val = JSON_LOADS(state->all_data.buf, &err);
  466. if (!val) {
  467. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  468. if (opt_protocol)
  469. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
  470. goto err_out;
  471. }
  472. if (opt_protocol) {
  473. char *s = json_dumps(val, JSON_INDENT(3));
  474. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  475. free(s);
  476. }
  477. /* JSON-RPC valid response returns a non-null 'result',
  478. * and a null 'error'.
  479. */
  480. res_val = json_object_get(val, "result");
  481. err_val = json_object_get(val, "error");
  482. if (!res_val ||(err_val && !json_is_null(err_val))) {
  483. char *s;
  484. if (err_val)
  485. s = json_dumps(err_val, JSON_INDENT(3));
  486. else
  487. s = strdup("(unknown reason)");
  488. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  489. free(s);
  490. json_decref(val);
  491. goto err_out;
  492. }
  493. if (state->hi.reason) {
  494. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  495. free(state->hi.reason);
  496. state->hi.reason = NULL;
  497. }
  498. successful_connect = true;
  499. databuf_free(&state->all_data);
  500. curl_slist_free_all(state->headers);
  501. curl_easy_reset(curl);
  502. free(state);
  503. return val;
  504. err_out:
  505. databuf_free(&state->all_data);
  506. curl_slist_free_all(state->headers);
  507. curl_easy_reset(curl);
  508. if (!successful_connect)
  509. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  510. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  511. free(state);
  512. return NULL;
  513. }
  514. json_t *json_rpc_call(CURL *curl, const char *url,
  515. const char *userpass, const char *rpc_req,
  516. bool probe, bool longpoll, int *rolltime,
  517. struct pool *pool, bool share)
  518. {
  519. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  520. int rc = curl_easy_perform(curl);
  521. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  522. }
  523. bool our_curl_supports_proxy_uris()
  524. {
  525. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  526. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  527. }
  528. // NOTE: This assumes reference URI is a root
  529. char *absolute_uri(char *uri, const char *ref)
  530. {
  531. if (strstr(uri, "://"))
  532. return strdup(uri);
  533. char *copy_start, *abs;
  534. bool need_slash = false;
  535. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  536. if (ref[strlen(ref) - 1] != '/')
  537. need_slash = true;
  538. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  539. if (!abs) {
  540. applog(LOG_ERR, "Malloc failure in absolute_uri");
  541. return NULL;
  542. }
  543. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  544. return abs;
  545. }
  546. /* Returns a malloced array string of a binary value of arbitrary length. The
  547. * array is rounded up to a 4 byte size to appease architectures that need
  548. * aligned array sizes */
  549. char *bin2hex(const unsigned char *p, size_t len)
  550. {
  551. unsigned int i;
  552. ssize_t slen;
  553. char *s;
  554. slen = len * 2 + 1;
  555. if (slen % 4)
  556. slen += 4 - (slen % 4);
  557. s = calloc(slen, 1);
  558. if (unlikely(!s))
  559. quit(1, "Failed to calloc in bin2hex");
  560. for (i = 0; i < len; i++)
  561. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  562. return s;
  563. }
  564. /* Does the reverse of bin2hex but does not allocate any ram */
  565. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  566. {
  567. bool ret = false;
  568. while (*hexstr && len) {
  569. char hex_byte[4];
  570. unsigned int v;
  571. if (unlikely(!hexstr[1])) {
  572. applog(LOG_ERR, "hex2bin str truncated");
  573. return ret;
  574. }
  575. memset(hex_byte, 0, 4);
  576. hex_byte[0] = hexstr[0];
  577. hex_byte[1] = hexstr[1];
  578. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  579. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  580. return ret;
  581. }
  582. *p = (unsigned char) v;
  583. p++;
  584. hexstr += 2;
  585. len--;
  586. }
  587. if (likely(len == 0 && *hexstr == 0))
  588. ret = true;
  589. return ret;
  590. }
  591. void hash_data(unsigned char *out_hash, const unsigned char *data)
  592. {
  593. unsigned char blkheader[80];
  594. // 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
  595. swap32yes(blkheader, data, 80 / 4);
  596. // double-SHA256 to get the block hash
  597. gen_hash(blkheader, out_hash, 80);
  598. }
  599. // Example output: 0000000000000000000000000000000000000000000000000000ffff00000000 (bdiff 1)
  600. void real_block_target(unsigned char *target, const unsigned char *data)
  601. {
  602. uint8_t targetshift;
  603. if (unlikely(data[72] < 3 || data[72] > 0x20))
  604. {
  605. // Invalid (out of bounds) target
  606. memset(target, 0xff, 32);
  607. return;
  608. }
  609. targetshift = data[72] - 3;
  610. memset(target, 0, targetshift);
  611. target[targetshift++] = data[75];
  612. target[targetshift++] = data[74];
  613. target[targetshift++] = data[73];
  614. memset(&target[targetshift], 0, 0x20 - targetshift);
  615. }
  616. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  617. {
  618. const uint32_t *h32 = (uint32_t*)&hash[0];
  619. const uint32_t *t32 = (uint32_t*)&target[0];
  620. for (int i = 7; i >= 0; --i) {
  621. uint32_t h32i = le32toh(h32[i]);
  622. uint32_t t32i = le32toh(t32[i]);
  623. if (h32i > t32i)
  624. return false;
  625. if (h32i < t32i)
  626. return true;
  627. }
  628. return true;
  629. }
  630. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  631. {
  632. bool rc;
  633. rc = hash_target_check(hash, target);
  634. if (opt_debug) {
  635. unsigned char hash_swap[32], target_swap[32];
  636. char *hash_str, *target_str;
  637. for (int i = 0; i < 32; ++i) {
  638. hash_swap[i] = hash[31-i];
  639. target_swap[i] = target[31-i];
  640. }
  641. hash_str = bin2hex(hash_swap, 32);
  642. target_str = bin2hex(target_swap, 32);
  643. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  644. hash_str,
  645. target_str,
  646. rc ? "YES (hash < target)" :
  647. "no (false positive; hash > target)");
  648. free(hash_str);
  649. free(target_str);
  650. }
  651. return rc;
  652. }
  653. // This operates on a native-endian SHA256 state
  654. // In other words, on little endian platforms, every 4 bytes are in reverse order
  655. bool fulltest(const unsigned char *hash, const unsigned char *target)
  656. {
  657. unsigned char hash2[32];
  658. swap32tobe(hash2, hash, 32 / 4);
  659. return hash_target_check_v(hash2, target);
  660. }
  661. struct thread_q *tq_new(void)
  662. {
  663. struct thread_q *tq;
  664. tq = calloc(1, sizeof(*tq));
  665. if (!tq)
  666. return NULL;
  667. INIT_LIST_HEAD(&tq->q);
  668. pthread_mutex_init(&tq->mutex, NULL);
  669. pthread_cond_init(&tq->cond, NULL);
  670. return tq;
  671. }
  672. void tq_free(struct thread_q *tq)
  673. {
  674. struct tq_ent *ent, *iter;
  675. if (!tq)
  676. return;
  677. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  678. list_del(&ent->q_node);
  679. free(ent);
  680. }
  681. pthread_cond_destroy(&tq->cond);
  682. pthread_mutex_destroy(&tq->mutex);
  683. memset(tq, 0, sizeof(*tq)); /* poison */
  684. free(tq);
  685. }
  686. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  687. {
  688. mutex_lock(&tq->mutex);
  689. tq->frozen = frozen;
  690. pthread_cond_signal(&tq->cond);
  691. mutex_unlock(&tq->mutex);
  692. }
  693. void tq_freeze(struct thread_q *tq)
  694. {
  695. tq_freezethaw(tq, true);
  696. }
  697. void tq_thaw(struct thread_q *tq)
  698. {
  699. tq_freezethaw(tq, false);
  700. }
  701. bool tq_push(struct thread_q *tq, void *data)
  702. {
  703. struct tq_ent *ent;
  704. bool rc = true;
  705. ent = calloc(1, sizeof(*ent));
  706. if (!ent)
  707. return false;
  708. ent->data = data;
  709. INIT_LIST_HEAD(&ent->q_node);
  710. mutex_lock(&tq->mutex);
  711. if (!tq->frozen) {
  712. list_add_tail(&ent->q_node, &tq->q);
  713. } else {
  714. free(ent);
  715. rc = false;
  716. }
  717. pthread_cond_signal(&tq->cond);
  718. mutex_unlock(&tq->mutex);
  719. return rc;
  720. }
  721. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  722. {
  723. struct tq_ent *ent;
  724. void *rval = NULL;
  725. int rc;
  726. mutex_lock(&tq->mutex);
  727. if (!list_empty(&tq->q))
  728. goto pop;
  729. if (abstime)
  730. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  731. else
  732. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  733. if (rc)
  734. goto out;
  735. if (list_empty(&tq->q))
  736. goto out;
  737. pop:
  738. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  739. rval = ent->data;
  740. list_del(&ent->q_node);
  741. free(ent);
  742. out:
  743. mutex_unlock(&tq->mutex);
  744. return rval;
  745. }
  746. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  747. {
  748. return pthread_create(&thr->pth, attr, start, arg);
  749. }
  750. void thr_info_freeze(struct thr_info *thr)
  751. {
  752. struct tq_ent *ent, *iter;
  753. struct thread_q *tq;
  754. if (!thr)
  755. return;
  756. tq = thr->q;
  757. if (!tq)
  758. return;
  759. mutex_lock(&tq->mutex);
  760. tq->frozen = true;
  761. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  762. list_del(&ent->q_node);
  763. free(ent);
  764. }
  765. mutex_unlock(&tq->mutex);
  766. }
  767. void thr_info_cancel(struct thr_info *thr)
  768. {
  769. if (!thr)
  770. return;
  771. if (PTH(thr) != 0L) {
  772. pthread_cancel(thr->pth);
  773. PTH(thr) = 0L;
  774. }
  775. }
  776. #ifndef HAVE_PTHREAD_CANCEL
  777. // Bionic (Android) is intentionally missing pthread_cancel, so it is implemented using pthread_kill
  778. enum pthread_cancel_workaround_mode {
  779. PCWM_DEFAULT = 0,
  780. PCWM_TERMINATE = 1,
  781. PCWM_ASYNC = 2,
  782. PCWM_DISABLED = 4,
  783. PCWM_CANCELLED = 8,
  784. };
  785. static pthread_key_t key_pcwm;
  786. struct sigaction pcwm_orig_term_handler;
  787. static
  788. void do_pthread_cancel_exit(int flags)
  789. {
  790. if (!(flags & PCWM_ASYNC))
  791. // NOTE: Logging disables cancel while mutex held, so this is safe
  792. applog(LOG_WARNING, "pthread_cancel workaround: Cannot defer cancellation, terminating thread NOW");
  793. pthread_exit(PTHREAD_CANCELED);
  794. }
  795. static
  796. void sighandler_pthread_cancel(int sig)
  797. {
  798. int flags = (int)pthread_getspecific(key_pcwm);
  799. if (flags & PCWM_TERMINATE) // Main thread
  800. {
  801. // Restore original handler and call it
  802. if (sigaction(sig, &pcwm_orig_term_handler, NULL))
  803. quit(1, "pthread_cancel workaround: Failed to restore original handler");
  804. raise(SIGTERM);
  805. quit(1, "pthread_cancel workaround: Original handler returned");
  806. }
  807. if (flags & PCWM_CANCELLED) // Already pending cancel
  808. return;
  809. if (flags & PCWM_DISABLED)
  810. {
  811. flags |= PCWM_CANCELLED;
  812. if (pthread_setspecific(key_pcwm, (void*)flags))
  813. quit(1, "pthread_cancel workaround: pthread_setspecific failed (setting PCWM_CANCELLED)");
  814. return;
  815. }
  816. do_pthread_cancel_exit(flags);
  817. }
  818. int pthread_setcancelstate(int state, int *oldstate)
  819. {
  820. int flags = (int)pthread_getspecific(key_pcwm);
  821. if (oldstate)
  822. *oldstate = (flags & PCWM_DISABLED) ? PTHREAD_CANCEL_DISABLE : PTHREAD_CANCEL_ENABLE;
  823. if (state == PTHREAD_CANCEL_DISABLE)
  824. flags |= PCWM_DISABLED;
  825. else
  826. {
  827. if (flags & PCWM_CANCELLED)
  828. do_pthread_cancel_exit(flags);
  829. flags &= ~PCWM_DISABLED;
  830. }
  831. if (pthread_setspecific(key_pcwm, (void*)flags))
  832. return -1;
  833. return 0;
  834. }
  835. int pthread_setcanceltype(int type, int *oldtype)
  836. {
  837. int flags = (int)pthread_getspecific(key_pcwm);
  838. if (oldtype)
  839. *oldtype = (flags & PCWM_ASYNC) ? PTHREAD_CANCEL_ASYNCHRONOUS : PTHREAD_CANCEL_DEFERRED;
  840. if (type == PTHREAD_CANCEL_ASYNCHRONOUS)
  841. flags |= PCWM_ASYNC;
  842. else
  843. flags &= ~PCWM_ASYNC;
  844. if (pthread_setspecific(key_pcwm, (void*)flags))
  845. return -1;
  846. return 0;
  847. }
  848. void setup_pthread_cancel_workaround()
  849. {
  850. if (pthread_key_create(&key_pcwm, NULL))
  851. quit(1, "pthread_cancel workaround: pthread_key_create failed");
  852. if (pthread_setspecific(key_pcwm, (void*)PCWM_TERMINATE))
  853. quit(1, "pthread_cancel workaround: pthread_setspecific failed");
  854. struct sigaction new_sigact = {
  855. .sa_handler = sighandler_pthread_cancel,
  856. };
  857. if (sigaction(SIGTERM, &new_sigact, &pcwm_orig_term_handler))
  858. quit(1, "pthread_cancel workaround: Failed to install SIGTERM handler");
  859. }
  860. #endif
  861. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  862. * on SMP machines */
  863. void nmsleep(unsigned int msecs)
  864. {
  865. struct timespec twait, tleft;
  866. int ret;
  867. ldiv_t d;
  868. d = ldiv(msecs, 1000);
  869. tleft.tv_sec = d.quot;
  870. tleft.tv_nsec = d.rem * 1000000;
  871. do {
  872. twait.tv_sec = tleft.tv_sec;
  873. twait.tv_nsec = tleft.tv_nsec;
  874. ret = nanosleep(&twait, &tleft);
  875. } while (ret == -1 && errno == EINTR);
  876. }
  877. /* Returns the microseconds difference between end and start times as a double */
  878. double us_tdiff(struct timeval *end, struct timeval *start)
  879. {
  880. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  881. }
  882. /* Returns the seconds difference between end and start times as a double */
  883. double tdiff(struct timeval *end, struct timeval *start)
  884. {
  885. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  886. }
  887. bool extract_sockaddr(struct pool *pool, char *url)
  888. {
  889. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  890. char url_address[256], port[6];
  891. int url_len, port_len = 0;
  892. url_begin = strstr(url, "//");
  893. if (!url_begin)
  894. url_begin = url;
  895. else
  896. url_begin += 2;
  897. /* Look for numeric ipv6 entries */
  898. ipv6_begin = strstr(url_begin, "[");
  899. ipv6_end = strstr(url_begin, "]");
  900. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  901. url_end = strstr(ipv6_end, ":");
  902. else
  903. url_end = strstr(url_begin, ":");
  904. if (url_end) {
  905. url_len = url_end - url_begin;
  906. port_len = strlen(url_begin) - url_len - 1;
  907. if (port_len < 1)
  908. return false;
  909. port_start = url_end + 1;
  910. } else
  911. url_len = strlen(url_begin);
  912. if (url_len < 1)
  913. return false;
  914. sprintf(url_address, "%.*s", url_len, url_begin);
  915. if (port_len)
  916. snprintf(port, 6, "%.*s", port_len, port_start);
  917. else
  918. strcpy(port, "80");
  919. free(pool->stratum_port);
  920. pool->stratum_port = strdup(port);
  921. free(pool->sockaddr_url);
  922. pool->sockaddr_url = strdup(url_address);
  923. return true;
  924. }
  925. enum send_ret {
  926. SEND_OK,
  927. SEND_SELECTFAIL,
  928. SEND_SENDFAIL,
  929. SEND_INACTIVE
  930. };
  931. /* Send a single command across a socket, appending \n to it. This should all
  932. * be done under stratum lock except when first establishing the socket */
  933. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  934. {
  935. SOCKETTYPE sock = pool->sock;
  936. ssize_t ssent = 0;
  937. strcat(s, "\n");
  938. len++;
  939. while (len > 0 ) {
  940. struct timeval timeout = {0, 0};
  941. ssize_t sent;
  942. fd_set wd;
  943. FD_ZERO(&wd);
  944. FD_SET(sock, &wd);
  945. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  946. return SEND_SELECTFAIL;
  947. sent = send(pool->sock, s + ssent, len, 0);
  948. if (sent < 0) {
  949. if (!sock_blocks())
  950. return SEND_SENDFAIL;
  951. sent = 0;
  952. }
  953. ssent += sent;
  954. len -= sent;
  955. }
  956. pool->cgminer_pool_stats.times_sent++;
  957. pool->cgminer_pool_stats.bytes_sent += ssent;
  958. total_bytes_xfer += ssent;
  959. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  960. return SEND_OK;
  961. }
  962. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  963. {
  964. enum send_ret ret = SEND_INACTIVE;
  965. if (opt_protocol)
  966. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  967. mutex_lock(&pool->stratum_lock);
  968. if (pool->stratum_active)
  969. ret = __stratum_send(pool, s, len);
  970. mutex_unlock(&pool->stratum_lock);
  971. /* This is to avoid doing applog under stratum_lock */
  972. switch (ret) {
  973. default:
  974. case SEND_OK:
  975. break;
  976. case SEND_SELECTFAIL:
  977. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  978. break;
  979. case SEND_SENDFAIL:
  980. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  981. break;
  982. case SEND_INACTIVE:
  983. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  984. break;
  985. }
  986. return (ret == SEND_OK);
  987. }
  988. static bool socket_full(struct pool *pool, bool wait)
  989. {
  990. SOCKETTYPE sock = pool->sock;
  991. struct timeval timeout;
  992. fd_set rd;
  993. FD_ZERO(&rd);
  994. FD_SET(sock, &rd);
  995. timeout.tv_usec = 0;
  996. if (wait)
  997. timeout.tv_sec = 60;
  998. else
  999. timeout.tv_sec = 0;
  1000. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1001. return true;
  1002. return false;
  1003. }
  1004. /* Check to see if Santa's been good to you */
  1005. bool sock_full(struct pool *pool)
  1006. {
  1007. if (strlen(pool->sockbuf))
  1008. return true;
  1009. return (socket_full(pool, false));
  1010. }
  1011. static void clear_sockbuf(struct pool *pool)
  1012. {
  1013. strcpy(pool->sockbuf, "");
  1014. }
  1015. static void clear_sock(struct pool *pool)
  1016. {
  1017. ssize_t n;
  1018. mutex_lock(&pool->stratum_lock);
  1019. do {
  1020. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1021. } while (n > 0);
  1022. mutex_unlock(&pool->stratum_lock);
  1023. clear_sockbuf(pool);
  1024. }
  1025. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1026. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1027. * and zeroing the new memory */
  1028. static void recalloc_sock(struct pool *pool, size_t len)
  1029. {
  1030. size_t old, new;
  1031. old = strlen(pool->sockbuf);
  1032. new = old + len + 1;
  1033. if (new < pool->sockbuf_size)
  1034. return;
  1035. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1036. applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  1037. pool->sockbuf = realloc(pool->sockbuf, new);
  1038. if (!pool->sockbuf)
  1039. quit(1, "Failed to realloc pool sockbuf in recalloc_sock");
  1040. memset(pool->sockbuf + old, 0, new - old);
  1041. pool->sockbuf_size = new;
  1042. }
  1043. enum recv_ret {
  1044. RECV_OK,
  1045. RECV_CLOSED,
  1046. RECV_RECVFAIL
  1047. };
  1048. /* Peeks at a socket to find the first end of line and then reads just that
  1049. * from the socket and returns that as a malloced char */
  1050. char *recv_line(struct pool *pool)
  1051. {
  1052. ssize_t len, buflen;
  1053. char *tok, *sret = NULL;
  1054. if (!strstr(pool->sockbuf, "\n")) {
  1055. enum recv_ret ret = RECV_OK;
  1056. struct timeval rstart, now;
  1057. gettimeofday(&rstart, NULL);
  1058. if (!socket_full(pool, true)) {
  1059. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1060. goto out;
  1061. }
  1062. mutex_lock(&pool->stratum_lock);
  1063. do {
  1064. char s[RBUFSIZE];
  1065. size_t slen;
  1066. ssize_t n;
  1067. memset(s, 0, RBUFSIZE);
  1068. n = recv(pool->sock, s, RECVSIZE, 0);
  1069. if (!n) {
  1070. ret = RECV_CLOSED;
  1071. break;
  1072. }
  1073. if (n < 0) {
  1074. if (!sock_blocks()) {
  1075. ret = RECV_RECVFAIL;
  1076. break;
  1077. }
  1078. } else {
  1079. slen = strlen(s);
  1080. recalloc_sock(pool, slen);
  1081. strcat(pool->sockbuf, s);
  1082. }
  1083. gettimeofday(&now, NULL);
  1084. } while (tdiff(&now, &rstart) < 60 && !strstr(pool->sockbuf, "\n"));
  1085. mutex_unlock(&pool->stratum_lock);
  1086. switch (ret) {
  1087. default:
  1088. case RECV_OK:
  1089. break;
  1090. case RECV_CLOSED:
  1091. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1092. goto out;
  1093. case RECV_RECVFAIL:
  1094. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1095. goto out;
  1096. }
  1097. }
  1098. buflen = strlen(pool->sockbuf);
  1099. tok = strtok(pool->sockbuf, "\n");
  1100. if (!tok) {
  1101. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1102. goto out;
  1103. }
  1104. sret = strdup(tok);
  1105. len = strlen(sret);
  1106. /* Copy what's left in the buffer after the \n, including the
  1107. * terminating \0 */
  1108. if (buflen > len + 1)
  1109. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1110. else
  1111. strcpy(pool->sockbuf, "");
  1112. pool->cgminer_pool_stats.times_received++;
  1113. pool->cgminer_pool_stats.bytes_received += len;
  1114. total_bytes_xfer += len;
  1115. pool->cgminer_pool_stats.net_bytes_received += len;
  1116. out:
  1117. if (!sret)
  1118. clear_sock(pool);
  1119. else if (opt_protocol)
  1120. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1121. return sret;
  1122. }
  1123. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1124. * flag, but this is compatible with 2.0. */
  1125. char *json_dumps_ANY(json_t *json, size_t flags)
  1126. {
  1127. switch (json_typeof(json))
  1128. {
  1129. case JSON_ARRAY:
  1130. case JSON_OBJECT:
  1131. return json_dumps(json, flags);
  1132. default:
  1133. break;
  1134. }
  1135. char *rv;
  1136. #ifdef JSON_ENCODE_ANY
  1137. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1138. if (rv)
  1139. return rv;
  1140. #endif
  1141. json_t *tmp = json_array();
  1142. char *s;
  1143. int i;
  1144. size_t len;
  1145. if (!tmp)
  1146. quit(1, "json_dumps_ANY failed to allocate json array");
  1147. if (json_array_append(tmp, json))
  1148. quit(1, "json_dumps_ANY failed to append temporary array");
  1149. s = json_dumps(tmp, flags);
  1150. if (!s)
  1151. return NULL;
  1152. for (i = 0; s[i] != '['; ++i)
  1153. if (unlikely(!(s[i] && isspace(s[i]))))
  1154. quit(1, "json_dumps_ANY failed to find opening bracket in array dump");
  1155. len = strlen(&s[++i]) - 1;
  1156. if (unlikely(s[i+len] != ']'))
  1157. quit(1, "json_dumps_ANY failed to find closing bracket in array dump");
  1158. rv = malloc(len + 1);
  1159. memcpy(rv, &s[i], len);
  1160. rv[len] = '\0';
  1161. free(s);
  1162. json_decref(tmp);
  1163. return rv;
  1164. }
  1165. /* Extracts a string value from a json array with error checking. To be used
  1166. * when the value of the string returned is only examined and not to be stored.
  1167. * See json_array_string below */
  1168. static char *__json_array_string(json_t *val, unsigned int entry)
  1169. {
  1170. json_t *arr_entry;
  1171. if (json_is_null(val))
  1172. return NULL;
  1173. if (!json_is_array(val))
  1174. return NULL;
  1175. if (entry > json_array_size(val))
  1176. return NULL;
  1177. arr_entry = json_array_get(val, entry);
  1178. if (!json_is_string(arr_entry))
  1179. return NULL;
  1180. return (char *)json_string_value(arr_entry);
  1181. }
  1182. /* Creates a freshly malloced dup of __json_array_string */
  1183. static char *json_array_string(json_t *val, unsigned int entry)
  1184. {
  1185. char *buf = __json_array_string(val, entry);
  1186. if (buf)
  1187. return strdup(buf);
  1188. return NULL;
  1189. }
  1190. void stratum_probe_transparency(struct pool *pool)
  1191. {
  1192. // Request transaction data to discourage pools from doing anything shady
  1193. char s[1024];
  1194. int sLen;
  1195. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  1196. pool->swork.job_id,
  1197. pool->swork.job_id);
  1198. stratum_send(pool, s, sLen);
  1199. if ((!pool->swork.opaque) && pool->swork.transparency_time == (time_t)-1)
  1200. pool->swork.transparency_time = time(NULL);
  1201. pool->swork.transparency_probed = true;
  1202. }
  1203. static bool parse_notify(struct pool *pool, json_t *val)
  1204. {
  1205. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  1206. bool clean, ret = false;
  1207. int merkles, i;
  1208. json_t *arr;
  1209. arr = json_array_get(val, 4);
  1210. if (!arr || !json_is_array(arr))
  1211. goto out;
  1212. merkles = json_array_size(arr);
  1213. job_id = json_array_string(val, 0);
  1214. prev_hash = json_array_string(val, 1);
  1215. coinbase1 = json_array_string(val, 2);
  1216. coinbase2 = json_array_string(val, 3);
  1217. bbversion = json_array_string(val, 5);
  1218. nbit = json_array_string(val, 6);
  1219. ntime = json_array_string(val, 7);
  1220. clean = json_is_true(json_array_get(val, 8));
  1221. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  1222. /* Annoying but we must not leak memory */
  1223. if (job_id)
  1224. free(job_id);
  1225. if (prev_hash)
  1226. free(prev_hash);
  1227. if (coinbase1)
  1228. free(coinbase1);
  1229. if (coinbase2)
  1230. free(coinbase2);
  1231. if (bbversion)
  1232. free(bbversion);
  1233. if (nbit)
  1234. free(nbit);
  1235. if (ntime)
  1236. free(ntime);
  1237. goto out;
  1238. }
  1239. mutex_lock(&pool->pool_lock);
  1240. free(pool->swork.job_id);
  1241. free(pool->swork.prev_hash);
  1242. free(pool->swork.coinbase1);
  1243. free(pool->swork.coinbase2);
  1244. free(pool->swork.bbversion);
  1245. free(pool->swork.nbit);
  1246. free(pool->swork.ntime);
  1247. pool->swork.job_id = job_id;
  1248. pool->swork.prev_hash = prev_hash;
  1249. pool->swork.coinbase1 = coinbase1;
  1250. pool->swork.cb1_len = strlen(coinbase1) / 2;
  1251. pool->swork.coinbase2 = coinbase2;
  1252. pool->swork.cb2_len = strlen(coinbase2) / 2;
  1253. pool->swork.bbversion = bbversion;
  1254. pool->swork.nbit = nbit;
  1255. pool->swork.ntime = ntime;
  1256. pool->submit_old = !clean;
  1257. pool->swork.clean = true;
  1258. pool->swork.cb_len = pool->swork.cb1_len + pool->n1_len + pool->n2size + pool->swork.cb2_len;
  1259. for (i = 0; i < pool->swork.merkles; i++)
  1260. free(pool->swork.merkle[i]);
  1261. if (merkles) {
  1262. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  1263. for (i = 0; i < merkles; i++)
  1264. pool->swork.merkle[i] = json_array_string(arr, i);
  1265. }
  1266. pool->swork.merkles = merkles;
  1267. if (clean)
  1268. pool->nonce2 = 0;
  1269. pool->swork.header_len = strlen(pool->swork.bbversion) +
  1270. strlen(pool->swork.prev_hash) +
  1271. strlen(pool->swork.ntime) +
  1272. strlen(pool->swork.nbit) +
  1273. /* merkle_hash */ 32 +
  1274. /* nonce */ 8 +
  1275. /* workpadding */ 96;
  1276. pool->swork.header_len = pool->swork.header_len * 2 + 1;
  1277. align_len(&pool->swork.header_len);
  1278. mutex_unlock(&pool->pool_lock);
  1279. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  1280. pool->pool_no, job_id);
  1281. if (opt_protocol) {
  1282. applog(LOG_DEBUG, "job_id: %s", job_id);
  1283. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1284. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1285. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1286. for (i = 0; i < merkles; i++)
  1287. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  1288. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1289. applog(LOG_DEBUG, "nbit: %s", nbit);
  1290. applog(LOG_DEBUG, "ntime: %s", ntime);
  1291. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1292. }
  1293. /* A notify message is the closest stratum gets to a getwork */
  1294. pool->getwork_requested++;
  1295. total_getworks++;
  1296. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || pool->swork.transparency_time != (time_t)-1)
  1297. if (pool->stratum_init)
  1298. stratum_probe_transparency(pool);
  1299. ret = true;
  1300. out:
  1301. return ret;
  1302. }
  1303. static bool parse_diff(struct pool *pool, json_t *val)
  1304. {
  1305. double diff;
  1306. diff = json_number_value(json_array_get(val, 0));
  1307. if (diff == 0)
  1308. return false;
  1309. mutex_lock(&pool->pool_lock);
  1310. pool->swork.diff = diff;
  1311. mutex_unlock(&pool->pool_lock);
  1312. applog(LOG_DEBUG, "Pool %d stratum bdifficulty set to %f", pool->pool_no, diff);
  1313. return true;
  1314. }
  1315. static bool parse_reconnect(struct pool *pool, json_t *val)
  1316. {
  1317. char *url, *port, address[256];
  1318. memset(address, 0, 255);
  1319. url = (char *)json_string_value(json_array_get(val, 0));
  1320. if (!url)
  1321. url = pool->sockaddr_url;
  1322. port = (char *)json_string_value(json_array_get(val, 1));
  1323. if (!port)
  1324. port = pool->stratum_port;
  1325. sprintf(address, "%s:%s", url, port);
  1326. if (!extract_sockaddr(pool, address))
  1327. return false;
  1328. pool->stratum_url = pool->sockaddr_url;
  1329. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1330. if (!restart_stratum(pool))
  1331. return false;
  1332. return true;
  1333. }
  1334. static bool send_version(struct pool *pool, json_t *val)
  1335. {
  1336. char s[RBUFSIZE], *idstr;
  1337. json_t *id = json_object_get(val, "id");
  1338. if (!(id && !json_is_null(id)))
  1339. return false;
  1340. idstr = json_dumps_ANY(id, 0);
  1341. sprintf(s, "{\"id\": %s, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  1342. free(idstr);
  1343. if (!stratum_send(pool, s, strlen(s)))
  1344. return false;
  1345. return true;
  1346. }
  1347. static bool stratum_show_message(struct pool *pool, json_t *val, json_t *params)
  1348. {
  1349. char *msg;
  1350. char s[RBUFSIZE], *idstr;
  1351. json_t *id = json_object_get(val, "id");
  1352. msg = json_array_string(params, 0);
  1353. if (likely(msg))
  1354. {
  1355. free(pool->admin_msg);
  1356. pool->admin_msg = msg;
  1357. applog(LOG_NOTICE, "Message from pool %u: %s", pool->pool_no, msg);
  1358. }
  1359. if (!(id && !json_is_null(id)))
  1360. return true;
  1361. idstr = json_dumps_ANY(id, 0);
  1362. if (likely(msg))
  1363. sprintf(s, "{\"id\": %s, \"result\": true, \"error\": null}", idstr);
  1364. else
  1365. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [-1, \"Failed to parse message\", null]}", idstr);
  1366. free(idstr);
  1367. if (!stratum_send(pool, s, strlen(s)))
  1368. return false;
  1369. return true;
  1370. }
  1371. bool parse_method(struct pool *pool, char *s)
  1372. {
  1373. json_t *val = NULL, *method, *err_val, *params;
  1374. json_error_t err;
  1375. bool ret = false;
  1376. char *buf;
  1377. if (!s)
  1378. goto out;
  1379. val = JSON_LOADS(s, &err);
  1380. if (!val) {
  1381. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1382. goto out;
  1383. }
  1384. method = json_object_get(val, "method");
  1385. if (!method)
  1386. goto out;
  1387. err_val = json_object_get(val, "error");
  1388. params = json_object_get(val, "params");
  1389. if (err_val && !json_is_null(err_val)) {
  1390. char *ss;
  1391. if (err_val)
  1392. ss = json_dumps(err_val, JSON_INDENT(3));
  1393. else
  1394. ss = strdup("(unknown reason)");
  1395. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1396. free(ss);
  1397. goto out;
  1398. }
  1399. buf = (char *)json_string_value(method);
  1400. if (!buf)
  1401. goto out;
  1402. if (!strncasecmp(buf, "mining.notify", 13)) {
  1403. if (parse_notify(pool, params))
  1404. pool->stratum_notify = ret = true;
  1405. else
  1406. pool->stratum_notify = ret = false;
  1407. goto out;
  1408. }
  1409. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1410. ret = true;
  1411. goto out;
  1412. }
  1413. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1414. ret = true;
  1415. goto out;
  1416. }
  1417. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1418. ret = true;
  1419. goto out;
  1420. }
  1421. if (!strncasecmp(buf, "client.show_message", 19) && stratum_show_message(pool, val, params)) {
  1422. ret = true;
  1423. goto out;
  1424. }
  1425. out:
  1426. if (val)
  1427. json_decref(val);
  1428. return ret;
  1429. }
  1430. extern bool parse_stratum_response(struct pool *, char *s);
  1431. bool auth_stratum(struct pool *pool)
  1432. {
  1433. json_t *val = NULL, *res_val, *err_val;
  1434. char s[RBUFSIZE], *sret = NULL;
  1435. json_error_t err;
  1436. bool ret = false;
  1437. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1438. pool->rpc_user, pool->rpc_pass);
  1439. if (!stratum_send(pool, s, strlen(s)))
  1440. goto out;
  1441. /* Parse all data in the queue and anything left should be auth */
  1442. while (42) {
  1443. sret = recv_line(pool);
  1444. if (!sret)
  1445. goto out;
  1446. if (parse_method(pool, sret))
  1447. free(sret);
  1448. else
  1449. break;
  1450. }
  1451. val = JSON_LOADS(sret, &err);
  1452. free(sret);
  1453. res_val = json_object_get(val, "result");
  1454. err_val = json_object_get(val, "error");
  1455. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1456. char *ss;
  1457. if (err_val)
  1458. ss = json_dumps(err_val, JSON_INDENT(3));
  1459. else
  1460. ss = strdup("(unknown reason)");
  1461. applog(LOG_WARNING, "JSON stratum auth failed: %s", ss);
  1462. free(ss);
  1463. goto out;
  1464. }
  1465. ret = true;
  1466. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1467. pool->probed = true;
  1468. successful_connect = true;
  1469. out:
  1470. if (val)
  1471. json_decref(val);
  1472. if (pool->stratum_notify)
  1473. stratum_probe_transparency(pool);
  1474. return ret;
  1475. }
  1476. curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
  1477. {
  1478. struct pool *pool = clientp;
  1479. curl_socket_t sck = socket(addr->family, addr->socktype, addr->protocol);
  1480. pool->sock = sck;
  1481. return sck;
  1482. }
  1483. static bool setup_stratum_curl(struct pool *pool)
  1484. {
  1485. char curl_err_str[CURL_ERROR_SIZE];
  1486. CURL *curl = NULL;
  1487. char s[RBUFSIZE];
  1488. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  1489. mutex_lock(&pool->stratum_lock);
  1490. pool->swork.transparency_time = (time_t)-1;
  1491. pool->stratum_active = false;
  1492. pool->stratum_notify = false;
  1493. pool->swork.transparency_probed = false;
  1494. if (pool->stratum_curl)
  1495. curl_easy_cleanup(pool->stratum_curl);
  1496. pool->stratum_curl = curl_easy_init();
  1497. if (unlikely(!pool->stratum_curl))
  1498. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1499. if (pool->sockbuf)
  1500. pool->sockbuf[0] = '\0';
  1501. mutex_unlock(&pool->stratum_lock);
  1502. curl = pool->stratum_curl;
  1503. if (!pool->sockbuf) {
  1504. pool->sockbuf = calloc(RBUFSIZE, 1);
  1505. if (!pool->sockbuf)
  1506. quit(1, "Failed to calloc pool sockbuf in initiate_stratum");
  1507. pool->sockbuf_size = RBUFSIZE;
  1508. }
  1509. /* Create a http url for use with curl */
  1510. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1511. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1512. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1513. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1514. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1515. curl_easy_setopt(curl, CURLOPT_URL, s);
  1516. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1517. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  1518. * to enable it */
  1519. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  1520. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  1521. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1522. // CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
  1523. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
  1524. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  1525. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1526. if (pool->rpc_proxy) {
  1527. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1528. } else if (opt_socks_proxy) {
  1529. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1530. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1531. }
  1532. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1533. pool->sock = INVSOCK;
  1534. if (curl_easy_perform(curl)) {
  1535. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1536. curl_easy_cleanup(curl);
  1537. pool->stratum_curl = NULL;
  1538. return false;
  1539. }
  1540. if (pool->sock == INVSOCK)
  1541. {
  1542. pool->stratum_curl = NULL;
  1543. curl_easy_cleanup(curl);
  1544. applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
  1545. return false;
  1546. }
  1547. keep_sockalive(pool->sock);
  1548. pool->cgminer_pool_stats.times_sent++;
  1549. pool->cgminer_pool_stats.times_received++;
  1550. return true;
  1551. }
  1552. static char *get_sessionid(json_t *val)
  1553. {
  1554. char *ret = NULL;
  1555. json_t *arr_val;
  1556. int arrsize, i;
  1557. arr_val = json_array_get(val, 0);
  1558. if (!arr_val || !json_is_array(arr_val))
  1559. goto out;
  1560. arrsize = json_array_size(arr_val);
  1561. for (i = 0; i < arrsize; i++) {
  1562. json_t *arr = json_array_get(arr_val, i);
  1563. char *notify;
  1564. if (!arr | !json_is_array(arr))
  1565. break;
  1566. notify = __json_array_string(arr, 0);
  1567. if (!notify)
  1568. continue;
  1569. if (!strncasecmp(notify, "mining.notify", 13)) {
  1570. ret = json_array_string(arr, 1);
  1571. break;
  1572. }
  1573. }
  1574. out:
  1575. return ret;
  1576. }
  1577. void suspend_stratum(struct pool *pool)
  1578. {
  1579. clear_sockbuf(pool);
  1580. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1581. mutex_lock(&pool->stratum_lock);
  1582. pool->stratum_active = pool->stratum_notify = false;
  1583. curl_easy_cleanup(pool->stratum_curl);
  1584. pool->stratum_curl = NULL;
  1585. pool->sock = INVSOCK;
  1586. mutex_unlock(&pool->stratum_lock);
  1587. }
  1588. bool initiate_stratum(struct pool *pool)
  1589. {
  1590. bool ret = false, recvd = false, noresume = false, sockd = false;
  1591. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  1592. json_t *val = NULL, *res_val, *err_val;
  1593. json_error_t err;
  1594. int n2size;
  1595. if (!setup_stratum_curl(pool))
  1596. goto out;
  1597. sockd = true;
  1598. resend:
  1599. if (noresume) {
  1600. /* Get rid of any crap lying around if we're resending */
  1601. clear_sock(pool);
  1602. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1603. } else {
  1604. if (pool->sessionid)
  1605. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  1606. else
  1607. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  1608. }
  1609. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  1610. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1611. goto out;
  1612. }
  1613. if (!socket_full(pool, true)) {
  1614. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1615. goto out;
  1616. }
  1617. sret = recv_line(pool);
  1618. if (!sret)
  1619. goto out;
  1620. recvd = true;
  1621. val = JSON_LOADS(sret, &err);
  1622. free(sret);
  1623. if (!val) {
  1624. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1625. goto out;
  1626. }
  1627. res_val = json_object_get(val, "result");
  1628. err_val = json_object_get(val, "error");
  1629. if (!res_val || json_is_null(res_val) ||
  1630. (err_val && !json_is_null(err_val))) {
  1631. char *ss;
  1632. if (err_val)
  1633. ss = json_dumps(err_val, JSON_INDENT(3));
  1634. else
  1635. ss = strdup("(unknown reason)");
  1636. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1637. free(ss);
  1638. goto out;
  1639. }
  1640. sessionid = get_sessionid(res_val);
  1641. if (!sessionid)
  1642. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  1643. nonce1 = json_array_string(res_val, 1);
  1644. if (!nonce1) {
  1645. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1646. free(sessionid);
  1647. goto out;
  1648. }
  1649. n2size = json_integer_value(json_array_get(res_val, 2));
  1650. if (!n2size) {
  1651. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1652. free(sessionid);
  1653. free(nonce1);
  1654. goto out;
  1655. }
  1656. mutex_lock(&pool->pool_lock);
  1657. free(pool->sessionid);
  1658. pool->sessionid = sessionid;
  1659. free(pool->nonce1);
  1660. pool->nonce1 = nonce1;
  1661. pool->n1_len = strlen(nonce1) / 2;
  1662. pool->n2size = n2size;
  1663. mutex_unlock(&pool->pool_lock);
  1664. if (sessionid)
  1665. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  1666. ret = true;
  1667. out:
  1668. if (val)
  1669. json_decref(val);
  1670. if (ret) {
  1671. if (!pool->stratum_url)
  1672. pool->stratum_url = pool->sockaddr_url;
  1673. pool->stratum_active = true;
  1674. pool->swork.diff = 1;
  1675. if (opt_protocol) {
  1676. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1677. pool->pool_no, pool->nonce1, pool->n2size);
  1678. }
  1679. } else {
  1680. if (recvd && !noresume) {
  1681. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  1682. noresume = true;
  1683. goto resend;
  1684. }
  1685. applog(LOG_DEBUG, "Initiate stratum failed");
  1686. if (sockd)
  1687. suspend_stratum(pool);
  1688. }
  1689. return ret;
  1690. }
  1691. bool restart_stratum(struct pool *pool)
  1692. {
  1693. if (pool->stratum_active)
  1694. suspend_stratum(pool);
  1695. if (!initiate_stratum(pool))
  1696. return false;
  1697. if (!auth_stratum(pool))
  1698. return false;
  1699. return true;
  1700. }
  1701. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1702. {
  1703. dev->device_last_not_well = time(NULL);
  1704. dev->device_not_well_reason = reason;
  1705. switch (reason) {
  1706. case REASON_THREAD_FAIL_INIT:
  1707. dev->thread_fail_init_count++;
  1708. break;
  1709. case REASON_THREAD_ZERO_HASH:
  1710. dev->thread_zero_hash_count++;
  1711. break;
  1712. case REASON_THREAD_FAIL_QUEUE:
  1713. dev->thread_fail_queue_count++;
  1714. break;
  1715. case REASON_DEV_SICK_IDLE_60:
  1716. dev->dev_sick_idle_60_count++;
  1717. break;
  1718. case REASON_DEV_DEAD_IDLE_600:
  1719. dev->dev_dead_idle_600_count++;
  1720. break;
  1721. case REASON_DEV_NOSTART:
  1722. dev->dev_nostart_count++;
  1723. break;
  1724. case REASON_DEV_OVER_HEAT:
  1725. dev->dev_over_heat_count++;
  1726. break;
  1727. case REASON_DEV_THERMAL_CUTOFF:
  1728. dev->dev_thermal_cutoff_count++;
  1729. break;
  1730. case REASON_DEV_COMMS_ERROR:
  1731. dev->dev_comms_error_count++;
  1732. break;
  1733. case REASON_DEV_THROTTLE:
  1734. dev->dev_throttle_count++;
  1735. break;
  1736. }
  1737. }
  1738. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1739. void *realloc_strcat(char *ptr, char *s)
  1740. {
  1741. size_t old = strlen(ptr), len = strlen(s);
  1742. char *ret;
  1743. if (!len)
  1744. return ptr;
  1745. len += old + 1;
  1746. align_len(&len);
  1747. ret = malloc(len);
  1748. if (unlikely(!ret))
  1749. quit(1, "Failed to malloc in realloc_strcat");
  1750. sprintf(ret, "%s%s", ptr, s);
  1751. free(ptr);
  1752. return ret;
  1753. }
  1754. static
  1755. bool sanechars[] = {
  1756. false, false, false, false, false, false, false, false,
  1757. false, false, false, false, false, false, false, false,
  1758. false, false, false, false, false, false, false, false,
  1759. false, false, false, false, false, false, false, false,
  1760. false, false, false, false, false, false, false, false,
  1761. false, false, false, false, false, false, false, false,
  1762. true , true , true , true , true , true , true , true ,
  1763. true , true , false, false, false, false, false, false,
  1764. false, true , true , true , true , true , true , true ,
  1765. true , true , true , true , true , true , true , true ,
  1766. true , true , true , true , true , true , true , true ,
  1767. true , true , true , false, false, false, false, false,
  1768. false, true , true , true , true , true , true , true ,
  1769. true , true , true , true , true , true , true , true ,
  1770. true , true , true , true , true , true , true , true ,
  1771. true , true , true , false, false, false, false, false,
  1772. };
  1773. char *sanestr(char *o, char *s)
  1774. {
  1775. char *rv = o;
  1776. bool br = false;
  1777. for ( ; s[0]; ++s)
  1778. {
  1779. if (sanechars[s[0] & 0x7f])
  1780. {
  1781. if (br)
  1782. {
  1783. br = false;
  1784. if (s[0] >= '0' && s[0] <= '9')
  1785. (o++)[0] = '_';
  1786. }
  1787. (o++)[0] = s[0];
  1788. }
  1789. else
  1790. if (o != s && o[-1] >= '0' && o[-1] <= '9')
  1791. br = true;
  1792. }
  1793. o[0] = '\0';
  1794. return rv;
  1795. }
  1796. void RenameThread(const char* name)
  1797. {
  1798. #if defined(PR_SET_NAME)
  1799. // Only the first 15 characters are used (16 - NUL terminator)
  1800. prctl(PR_SET_NAME, name, 0, 0, 0);
  1801. #elif defined(__APPLE__)
  1802. pthread_setname_np(name);
  1803. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  1804. pthread_set_name_np(pthread_self(), name);
  1805. #else
  1806. // Prevent warnings for unused parameters...
  1807. (void)name;
  1808. #endif
  1809. }
  1810. #ifdef WIN32
  1811. static const char *WindowsErrorStr(DWORD dwMessageId)
  1812. {
  1813. static LPSTR msg = NULL;
  1814. if (msg)
  1815. LocalFree(msg);
  1816. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, dwMessageId, 0, (LPSTR)&msg, 0, 0))
  1817. return msg;
  1818. static const char fmt[] = "Error #%ld";
  1819. signed long ldMsgId = dwMessageId;
  1820. int sz = snprintf((char*)&sz, 0, fmt, ldMsgId) + 1;
  1821. msg = (LPTSTR)LocalAlloc(LMEM_FIXED, sz);
  1822. sprintf((char*)msg, fmt, ldMsgId);
  1823. return msg;
  1824. }
  1825. #endif
  1826. void notifier_init(notifier_t pipefd)
  1827. {
  1828. #ifdef WIN32
  1829. SOCKET listener, connecter, acceptor;
  1830. listener = socket(AF_INET, SOCK_STREAM, 0);
  1831. if (listener == INVALID_SOCKET)
  1832. quit(1, "Failed to create listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1833. connecter = socket(AF_INET, SOCK_STREAM, 0);
  1834. if (connecter == INVALID_SOCKET)
  1835. quit(1, "Failed to create connect socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1836. struct sockaddr_in inaddr = {
  1837. .sin_family = AF_INET,
  1838. .sin_addr = {
  1839. .s_addr = htonl(INADDR_LOOPBACK),
  1840. },
  1841. .sin_port = 0,
  1842. };
  1843. {
  1844. char reuse = 1;
  1845. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
  1846. }
  1847. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  1848. quit(1, "Failed to bind listener socket in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1849. socklen_t inaddr_sz = sizeof(inaddr);
  1850. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  1851. quit(1, "Failed to getsockname in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1852. if (listen(listener, 1) == SOCKET_ERROR)
  1853. quit(1, "Failed to listen in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1854. inaddr.sin_family = AF_INET;
  1855. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  1856. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  1857. quit(1, "Failed to connect in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1858. acceptor = accept(listener, NULL, NULL);
  1859. if (acceptor == INVALID_SOCKET)
  1860. quit(1, "Failed to accept in create_notifier: %s", WindowsErrorStr(WSAGetLastError()));
  1861. closesocket(listener);
  1862. pipefd[0] = connecter;
  1863. pipefd[1] = acceptor;
  1864. #else
  1865. if (pipe(pipefd))
  1866. quit(1, "Failed to create pipe in create_notifier");
  1867. #endif
  1868. }
  1869. void notifier_wake(notifier_t fd)
  1870. {
  1871. if (fd[1] == INVSOCK)
  1872. return;
  1873. #ifdef WIN32
  1874. (void)send(fd[1], "\0", 1, 0);
  1875. #else
  1876. (void)write(fd[1], "\0", 1);
  1877. #endif
  1878. }
  1879. void notifier_read(notifier_t fd)
  1880. {
  1881. char buf[0x10];
  1882. #ifdef WIN32
  1883. (void)recv(fd[0], buf, sizeof(buf), 0);
  1884. #else
  1885. (void)read(fd[0], buf, sizeof(buf));
  1886. #endif
  1887. }
  1888. void notifier_destroy(notifier_t fd)
  1889. {
  1890. #ifdef WIN32
  1891. closesocket(fd[0]);
  1892. closesocket(fd[1]);
  1893. #else
  1894. close(fd[0]);
  1895. close(fd[1]);
  1896. #endif
  1897. fd[0] = fd[1] = INVSOCK;
  1898. }