util.c 59 KB

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