util.c 56 KB

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