util.c 55 KB

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