util.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 3 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <ctype.h>
  14. #include <stdarg.h>
  15. #include <string.h>
  16. #include <jansson.h>
  17. #include <curl/curl.h>
  18. #include <time.h>
  19. #include <errno.h>
  20. #include <unistd.h>
  21. #include <sys/types.h>
  22. #ifndef WIN32
  23. #include <fcntl.h>
  24. # ifdef __linux
  25. # include <sys/prctl.h>
  26. # endif
  27. # include <sys/socket.h>
  28. # include <netinet/in.h>
  29. # include <netinet/tcp.h>
  30. # include <netdb.h>
  31. #else
  32. # include <windows.h>
  33. # include <winsock2.h>
  34. # include <ws2tcpip.h>
  35. # include <mmsystem.h>
  36. #endif
  37. #include "miner.h"
  38. #include "elist.h"
  39. #include "compat.h"
  40. #include "util.h"
  41. #define DEFAULT_SOCKWAIT 60
  42. bool successful_connect = false;
  43. struct timeval nettime;
  44. struct data_buffer {
  45. void *buf;
  46. size_t len;
  47. };
  48. struct upload_buffer {
  49. const void *buf;
  50. size_t len;
  51. };
  52. struct header_info {
  53. char *lp_path;
  54. int rolltime;
  55. char *reason;
  56. char *stratum_url;
  57. bool hadrolltime;
  58. bool canroll;
  59. bool hadexpire;
  60. };
  61. struct tq_ent {
  62. void *data;
  63. struct list_head q_node;
  64. };
  65. static void databuf_free(struct data_buffer *db)
  66. {
  67. if (!db)
  68. return;
  69. free(db->buf);
  70. memset(db, 0, sizeof(*db));
  71. }
  72. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  73. void *user_data)
  74. {
  75. struct data_buffer *db = user_data;
  76. size_t len = size * nmemb;
  77. size_t oldlen, newlen;
  78. void *newmem;
  79. static const unsigned char zero = 0;
  80. oldlen = db->len;
  81. newlen = oldlen + len;
  82. newmem = realloc(db->buf, newlen + 1);
  83. if (!newmem)
  84. return 0;
  85. db->buf = newmem;
  86. db->len = newlen;
  87. memcpy(db->buf + oldlen, ptr, len);
  88. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  89. return len;
  90. }
  91. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  92. void *user_data)
  93. {
  94. struct upload_buffer *ub = user_data;
  95. unsigned int len = size * nmemb;
  96. if (len > ub->len)
  97. len = ub->len;
  98. if (len) {
  99. memcpy(ptr, ub->buf, len);
  100. ub->buf += len;
  101. ub->len -= len;
  102. }
  103. return len;
  104. }
  105. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  106. {
  107. struct header_info *hi = user_data;
  108. size_t remlen, slen, ptrlen = size * nmemb;
  109. char *rem, *val = NULL, *key = NULL;
  110. void *tmp;
  111. val = calloc(1, ptrlen);
  112. key = calloc(1, ptrlen);
  113. if (!key || !val)
  114. goto out;
  115. tmp = memchr(ptr, ':', ptrlen);
  116. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  117. goto out;
  118. slen = tmp - ptr;
  119. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  120. goto out;
  121. memcpy(key, ptr, slen); /* store & nul term key */
  122. key[slen] = 0;
  123. rem = ptr + slen + 1; /* trim value's leading whitespace */
  124. remlen = ptrlen - slen - 1;
  125. while ((remlen > 0) && (isspace(*rem))) {
  126. remlen--;
  127. rem++;
  128. }
  129. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  130. val[remlen] = 0;
  131. while ((*val) && (isspace(val[strlen(val) - 1])))
  132. val[strlen(val) - 1] = 0;
  133. if (!*val) /* skip blank value */
  134. goto out;
  135. if (opt_protocol)
  136. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  137. if (!strcasecmp("X-Roll-Ntime", key)) {
  138. hi->hadrolltime = true;
  139. if (!strncasecmp("N", val, 1))
  140. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  141. else {
  142. hi->canroll = true;
  143. /* Check to see if expire= is supported and if not, set
  144. * the rolltime to the default scantime */
  145. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  146. sscanf(val + 7, "%d", &hi->rolltime);
  147. hi->hadexpire = true;
  148. } else
  149. hi->rolltime = opt_scantime;
  150. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  151. }
  152. }
  153. if (!strcasecmp("X-Long-Polling", key)) {
  154. hi->lp_path = val; /* steal memory reference */
  155. val = NULL;
  156. }
  157. if (!strcasecmp("X-Reject-Reason", key)) {
  158. hi->reason = val; /* steal memory reference */
  159. val = NULL;
  160. }
  161. if (!strcasecmp("X-Stratum", key)) {
  162. hi->stratum_url = val;
  163. val = NULL;
  164. }
  165. out:
  166. free(key);
  167. free(val);
  168. return ptrlen;
  169. }
  170. static void keep_sockalive(SOCKETTYPE fd)
  171. {
  172. const int tcp_one = 1;
  173. #ifndef WIN32
  174. const int tcp_keepidle = 45;
  175. const int tcp_keepintvl = 30;
  176. int flags = fcntl(fd, F_GETFL, 0);
  177. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  178. #else
  179. u_long flags = 1;
  180. ioctlsocket(fd, FIONBIO, &flags);
  181. #endif
  182. setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const void *)&tcp_one, sizeof(tcp_one));
  183. if (!opt_delaynet)
  184. #ifndef __linux
  185. setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
  186. #else /* __linux */
  187. setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one));
  188. setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one));
  189. setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle));
  190. setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl));
  191. #endif /* __linux */
  192. #ifdef __APPLE_CC__
  193. setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl));
  194. #endif /* __APPLE_CC__ */
  195. }
  196. #if CURL_HAS_KEEPALIVE
  197. static void keep_curlalive(CURL *curl)
  198. {
  199. const int tcp_keepidle = 45;
  200. const int tcp_keepintvl = 30;
  201. const long int keepalive = 1;
  202. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keepalive);
  203. curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, tcp_keepidle);
  204. curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, tcp_keepintvl);
  205. }
  206. #else
  207. static void keep_curlalive(CURL *curl)
  208. {
  209. SOCKETTYPE sock;
  210. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock);
  211. keep_sockalive(sock);
  212. }
  213. #endif
  214. static void last_nettime(struct timeval *last)
  215. {
  216. rd_lock(&netacc_lock);
  217. last->tv_sec = nettime.tv_sec;
  218. last->tv_usec = nettime.tv_usec;
  219. rd_unlock(&netacc_lock);
  220. }
  221. static void set_nettime(void)
  222. {
  223. wr_lock(&netacc_lock);
  224. cgtime(&nettime);
  225. wr_unlock(&netacc_lock);
  226. }
  227. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  228. __maybe_unused char *data, size_t size, void *userdata)
  229. {
  230. struct pool *pool = (struct pool *)userdata;
  231. switch(type) {
  232. case CURLINFO_HEADER_IN:
  233. case CURLINFO_DATA_IN:
  234. case CURLINFO_SSL_DATA_IN:
  235. pool->cgminer_pool_stats.net_bytes_received += size;
  236. break;
  237. case CURLINFO_HEADER_OUT:
  238. case CURLINFO_DATA_OUT:
  239. case CURLINFO_SSL_DATA_OUT:
  240. pool->cgminer_pool_stats.net_bytes_sent += size;
  241. break;
  242. case CURLINFO_TEXT:
  243. default:
  244. break;
  245. }
  246. return 0;
  247. }
  248. json_t *json_rpc_call(CURL *curl, const char *url,
  249. const char *userpass, const char *rpc_req,
  250. bool probe, bool longpoll, int *rolltime,
  251. struct pool *pool, bool share)
  252. {
  253. long timeout = longpoll ? (60 * 60) : 60;
  254. struct data_buffer all_data = {NULL, 0};
  255. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  256. char len_hdr[64], user_agent_hdr[128];
  257. char curl_err_str[CURL_ERROR_SIZE];
  258. struct curl_slist *headers = NULL;
  259. struct upload_buffer upload_data;
  260. json_t *val, *err_val, *res_val;
  261. bool probing = false;
  262. double byte_count;
  263. json_error_t err;
  264. int rc;
  265. memset(&err, 0, sizeof(err));
  266. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  267. if (probe)
  268. probing = !pool->probed;
  269. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  270. // CURLOPT_VERBOSE won't write to stderr if we use CURLOPT_DEBUGFUNCTION
  271. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  272. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  273. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  274. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  275. curl_easy_setopt(curl, CURLOPT_URL, url);
  276. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  277. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  278. /* Shares are staggered already and delays in submission can be costly
  279. * so do not delay them */
  280. if (!opt_delaynet || share)
  281. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  282. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  283. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  284. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  285. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  286. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  287. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  288. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  289. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  290. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  291. if (pool->rpc_proxy) {
  292. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  293. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  294. } else if (opt_socks_proxy) {
  295. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  296. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  297. }
  298. if (userpass) {
  299. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  300. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  301. }
  302. if (longpoll)
  303. keep_curlalive(curl);
  304. curl_easy_setopt(curl, CURLOPT_POST, 1);
  305. if (opt_protocol)
  306. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  307. upload_data.buf = rpc_req;
  308. upload_data.len = strlen(rpc_req);
  309. sprintf(len_hdr, "Content-Length: %lu",
  310. (unsigned long) upload_data.len);
  311. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  312. headers = curl_slist_append(headers,
  313. "Content-type: application/json");
  314. headers = curl_slist_append(headers,
  315. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  316. if (likely(global_hashrate)) {
  317. char ghashrate[255];
  318. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  319. headers = curl_slist_append(headers, ghashrate);
  320. }
  321. headers = curl_slist_append(headers, len_hdr);
  322. headers = curl_slist_append(headers, user_agent_hdr);
  323. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  324. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  325. if (opt_delaynet) {
  326. /* Don't delay share submission, but still track the nettime */
  327. if (!share) {
  328. long long now_msecs, last_msecs;
  329. struct timeval now, last;
  330. cgtime(&now);
  331. last_nettime(&last);
  332. now_msecs = (long long)now.tv_sec * 1000;
  333. now_msecs += now.tv_usec / 1000;
  334. last_msecs = (long long)last.tv_sec * 1000;
  335. last_msecs += last.tv_usec / 1000;
  336. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  337. struct timespec rgtp;
  338. rgtp.tv_sec = 0;
  339. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  340. nanosleep(&rgtp, NULL);
  341. }
  342. }
  343. set_nettime();
  344. }
  345. rc = curl_easy_perform(curl);
  346. if (rc) {
  347. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  348. goto err_out;
  349. }
  350. if (!all_data.buf) {
  351. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  352. goto err_out;
  353. }
  354. pool->cgminer_pool_stats.times_sent++;
  355. if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK)
  356. pool->cgminer_pool_stats.bytes_sent += byte_count;
  357. pool->cgminer_pool_stats.times_received++;
  358. if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK)
  359. pool->cgminer_pool_stats.bytes_received += byte_count;
  360. if (probing) {
  361. pool->probed = true;
  362. /* If X-Long-Polling was found, activate long polling */
  363. if (hi.lp_path) {
  364. if (pool->hdr_path != NULL)
  365. free(pool->hdr_path);
  366. pool->hdr_path = hi.lp_path;
  367. } else
  368. pool->hdr_path = NULL;
  369. if (hi.stratum_url) {
  370. pool->stratum_url = hi.stratum_url;
  371. hi.stratum_url = NULL;
  372. }
  373. } else {
  374. if (hi.lp_path) {
  375. free(hi.lp_path);
  376. hi.lp_path = NULL;
  377. }
  378. if (hi.stratum_url) {
  379. free(hi.stratum_url);
  380. hi.stratum_url = NULL;
  381. }
  382. }
  383. *rolltime = hi.rolltime;
  384. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  385. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  386. pool->cgminer_pool_stats.canroll = hi.canroll;
  387. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  388. val = JSON_LOADS(all_data.buf, &err);
  389. if (!val) {
  390. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  391. if (opt_protocol)
  392. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char *)(all_data.buf));
  393. goto err_out;
  394. }
  395. if (opt_protocol) {
  396. char *s = json_dumps(val, JSON_INDENT(3));
  397. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  398. free(s);
  399. }
  400. /* JSON-RPC valid response returns a non-null 'result',
  401. * and a null 'error'.
  402. */
  403. res_val = json_object_get(val, "result");
  404. err_val = json_object_get(val, "error");
  405. if (!res_val ||(err_val && !json_is_null(err_val))) {
  406. char *s;
  407. if (err_val)
  408. s = json_dumps(err_val, JSON_INDENT(3));
  409. else
  410. s = strdup("(unknown reason)");
  411. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  412. free(s);
  413. goto err_out;
  414. }
  415. if (hi.reason) {
  416. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  417. free(hi.reason);
  418. hi.reason = NULL;
  419. }
  420. successful_connect = true;
  421. databuf_free(&all_data);
  422. curl_slist_free_all(headers);
  423. curl_easy_reset(curl);
  424. return val;
  425. err_out:
  426. databuf_free(&all_data);
  427. curl_slist_free_all(headers);
  428. curl_easy_reset(curl);
  429. if (!successful_connect)
  430. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  431. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  432. return NULL;
  433. }
  434. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  435. static struct {
  436. const char *name;
  437. curl_proxytype proxytype;
  438. } proxynames[] = {
  439. { "http:", CURLPROXY_HTTP },
  440. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 19) || (LIBCURL_VERSION_MINOR == 19 && LIBCURL_VERSION_PATCH >= 4)
  441. { "http0:", CURLPROXY_HTTP_1_0 },
  442. #endif
  443. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 15) || (LIBCURL_VERSION_MINOR == 15 && LIBCURL_VERSION_PATCH >= 2)
  444. { "socks4:", CURLPROXY_SOCKS4 },
  445. #endif
  446. { "socks5:", CURLPROXY_SOCKS5 },
  447. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR >= 18)
  448. { "socks4a:", CURLPROXY_SOCKS4A },
  449. { "socks5h:", CURLPROXY_SOCKS5_HOSTNAME },
  450. #endif
  451. { NULL, 0 }
  452. };
  453. #endif
  454. const char *proxytype(curl_proxytype proxytype)
  455. {
  456. int i;
  457. for (i = 0; proxynames[i].name; i++)
  458. if (proxynames[i].proxytype == proxytype)
  459. return proxynames[i].name;
  460. return "invalid";
  461. }
  462. char *get_proxy(char *url, struct pool *pool)
  463. {
  464. pool->rpc_proxy = NULL;
  465. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  466. char *split;
  467. int plen, len, i;
  468. for (i = 0; proxynames[i].name; i++) {
  469. plen = strlen(proxynames[i].name);
  470. if (strncmp(url, proxynames[i].name, plen) == 0) {
  471. if (!(split = strchr(url, '|')))
  472. return url;
  473. *split = '\0';
  474. len = split - url;
  475. pool->rpc_proxy = malloc(1 + len - plen);
  476. if (!(pool->rpc_proxy))
  477. quithere(1, "Failed to malloc rpc_proxy");
  478. strcpy(pool->rpc_proxy, url + plen);
  479. pool->rpc_proxytype = proxynames[i].proxytype;
  480. url = split + 1;
  481. break;
  482. }
  483. }
  484. #endif
  485. return url;
  486. }
  487. /* Returns a malloced array string of a binary value of arbitrary length. The
  488. * array is rounded up to a 4 byte size to appease architectures that need
  489. * aligned array sizes */
  490. char *bin2hex(const unsigned char *p, size_t len)
  491. {
  492. ssize_t slen;
  493. char *s;
  494. int i;
  495. slen = len * 2 + 1;
  496. if (slen % 4)
  497. slen += 4 - (slen % 4);
  498. s = calloc(slen, 1);
  499. if (unlikely(!s))
  500. quithere(1, "Failed to calloc");
  501. for (i = 0; i < (int)len; i++)
  502. sprintf(s + (i * 2), "%02x", (unsigned int)p[i]);
  503. return s;
  504. }
  505. /* Does the reverse of bin2hex but does not allocate any ram */
  506. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  507. {
  508. bool ret = false;
  509. while (*hexstr && len) {
  510. char hex_byte[4];
  511. unsigned int v;
  512. if (unlikely(!hexstr[1])) {
  513. applog(LOG_ERR, "hex2bin str truncated");
  514. return ret;
  515. }
  516. memset(hex_byte, 0, 4);
  517. hex_byte[0] = hexstr[0];
  518. hex_byte[1] = hexstr[1];
  519. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  520. applog(LOG_INFO, "hex2bin sscanf '%s' failed", hex_byte);
  521. return ret;
  522. }
  523. *p = (unsigned char) v;
  524. p++;
  525. hexstr += 2;
  526. len--;
  527. }
  528. if (likely(len == 0 && *hexstr == 0))
  529. ret = true;
  530. return ret;
  531. }
  532. bool fulltest(const unsigned char *hash, const unsigned char *target)
  533. {
  534. unsigned char hash_swap[32], target_swap[32];
  535. uint32_t *hash32 = (uint32_t *) hash_swap;
  536. uint32_t *target32 = (uint32_t *) target_swap;
  537. char *hash_str, *target_str;
  538. bool rc = true;
  539. int i;
  540. swap256(hash_swap, hash);
  541. swap256(target_swap, target);
  542. for (i = 0; i < 32/4; i++) {
  543. uint32_t h32tmp = htobe32(hash32[i]);
  544. uint32_t t32tmp = htole32(target32[i]);
  545. target32[i] = swab32(target32[i]); /* for printing */
  546. if (h32tmp > t32tmp) {
  547. rc = false;
  548. break;
  549. }
  550. if (h32tmp < t32tmp) {
  551. rc = true;
  552. break;
  553. }
  554. }
  555. if (opt_debug) {
  556. hash_str = bin2hex(hash_swap, 32);
  557. target_str = bin2hex(target_swap, 32);
  558. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  559. hash_str,
  560. target_str,
  561. rc ? "YES (hash <= target)" :
  562. "no (false positive; hash > target)");
  563. free(hash_str);
  564. free(target_str);
  565. }
  566. return rc;
  567. }
  568. struct thread_q *tq_new(void)
  569. {
  570. struct thread_q *tq;
  571. tq = calloc(1, sizeof(*tq));
  572. if (!tq)
  573. return NULL;
  574. INIT_LIST_HEAD(&tq->q);
  575. pthread_mutex_init(&tq->mutex, NULL);
  576. pthread_cond_init(&tq->cond, NULL);
  577. return tq;
  578. }
  579. void tq_free(struct thread_q *tq)
  580. {
  581. struct tq_ent *ent, *iter;
  582. if (!tq)
  583. return;
  584. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  585. list_del(&ent->q_node);
  586. free(ent);
  587. }
  588. pthread_cond_destroy(&tq->cond);
  589. pthread_mutex_destroy(&tq->mutex);
  590. memset(tq, 0, sizeof(*tq)); /* poison */
  591. free(tq);
  592. }
  593. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  594. {
  595. mutex_lock(&tq->mutex);
  596. tq->frozen = frozen;
  597. pthread_cond_signal(&tq->cond);
  598. mutex_unlock(&tq->mutex);
  599. }
  600. void tq_freeze(struct thread_q *tq)
  601. {
  602. tq_freezethaw(tq, true);
  603. }
  604. void tq_thaw(struct thread_q *tq)
  605. {
  606. tq_freezethaw(tq, false);
  607. }
  608. bool tq_push(struct thread_q *tq, void *data)
  609. {
  610. struct tq_ent *ent;
  611. bool rc = true;
  612. ent = calloc(1, sizeof(*ent));
  613. if (!ent)
  614. return false;
  615. ent->data = data;
  616. INIT_LIST_HEAD(&ent->q_node);
  617. mutex_lock(&tq->mutex);
  618. if (!tq->frozen) {
  619. list_add_tail(&ent->q_node, &tq->q);
  620. } else {
  621. free(ent);
  622. rc = false;
  623. }
  624. pthread_cond_signal(&tq->cond);
  625. mutex_unlock(&tq->mutex);
  626. return rc;
  627. }
  628. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  629. {
  630. struct tq_ent *ent;
  631. void *rval = NULL;
  632. int rc;
  633. mutex_lock(&tq->mutex);
  634. if (!list_empty(&tq->q))
  635. goto pop;
  636. if (abstime)
  637. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  638. else
  639. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  640. if (rc)
  641. goto out;
  642. if (list_empty(&tq->q))
  643. goto out;
  644. pop:
  645. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  646. rval = ent->data;
  647. list_del(&ent->q_node);
  648. free(ent);
  649. out:
  650. mutex_unlock(&tq->mutex);
  651. return rval;
  652. }
  653. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  654. {
  655. cgsem_init(&thr->sem);
  656. return pthread_create(&thr->pth, attr, start, arg);
  657. }
  658. void thr_info_cancel(struct thr_info *thr)
  659. {
  660. if (!thr)
  661. return;
  662. if (PTH(thr) != 0L) {
  663. pthread_cancel(thr->pth);
  664. PTH(thr) = 0L;
  665. }
  666. cgsem_destroy(&thr->sem);
  667. }
  668. void subtime(struct timeval *a, struct timeval *b)
  669. {
  670. timersub(a, b, b);
  671. }
  672. void addtime(struct timeval *a, struct timeval *b)
  673. {
  674. timeradd(a, b, b);
  675. }
  676. bool time_more(struct timeval *a, struct timeval *b)
  677. {
  678. return timercmp(a, b, >);
  679. }
  680. bool time_less(struct timeval *a, struct timeval *b)
  681. {
  682. return timercmp(a, b, <);
  683. }
  684. void copy_time(struct timeval *dest, const struct timeval *src)
  685. {
  686. memcpy(dest, src, sizeof(struct timeval));
  687. }
  688. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  689. {
  690. val->tv_sec = spec->tv_sec;
  691. val->tv_usec = spec->tv_nsec / 1000;
  692. }
  693. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  694. {
  695. spec->tv_sec = val->tv_sec;
  696. spec->tv_nsec = val->tv_usec * 1000;
  697. }
  698. void us_to_timeval(struct timeval *val, int64_t us)
  699. {
  700. lldiv_t tvdiv = lldiv(us, 1000000);
  701. val->tv_sec = tvdiv.quot;
  702. val->tv_usec = tvdiv.rem;
  703. }
  704. void us_to_timespec(struct timespec *spec, int64_t us)
  705. {
  706. lldiv_t tvdiv = lldiv(us, 1000000);
  707. spec->tv_sec = tvdiv.quot;
  708. spec->tv_nsec = tvdiv.rem * 1000;
  709. }
  710. void ms_to_timespec(struct timespec *spec, int64_t ms)
  711. {
  712. lldiv_t tvdiv = lldiv(ms, 1000);
  713. spec->tv_sec = tvdiv.quot;
  714. spec->tv_nsec = tvdiv.rem * 1000000;
  715. }
  716. void timeraddspec(struct timespec *a, const struct timespec *b)
  717. {
  718. a->tv_sec += b->tv_sec;
  719. a->tv_nsec += b->tv_nsec;
  720. if (a->tv_nsec >= 1000000000) {
  721. a->tv_nsec -= 1000000000;
  722. a->tv_sec++;
  723. }
  724. }
  725. static int timespec_to_ms(struct timespec *ts)
  726. {
  727. return ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
  728. }
  729. /* Subtracts b from a and stores it in res. */
  730. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  731. {
  732. res->tv_sec = a->tv_sec - b->tv_sec;
  733. res->tv_nsec = a->tv_nsec - b->tv_nsec;
  734. if (res->tv_nsec < 0) {
  735. res->tv_nsec += 1000000000;
  736. res->tv_sec--;
  737. }
  738. }
  739. /* Subtract b from a */
  740. static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b)
  741. {
  742. a->tv_sec -= b->tv_sec;
  743. a->tv_nsec -= b->tv_nsec;
  744. if (a->tv_nsec < 0) {
  745. a->tv_nsec += 1000000000;
  746. a->tv_sec--;
  747. }
  748. }
  749. static void __maybe_unused cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start)
  750. {
  751. struct timespec now;
  752. timeraddspec(ts_diff, ts_start);
  753. cgtimer_time(&now);
  754. timersubspec(ts_diff, &now);
  755. if (unlikely(ts_diff->tv_sec < 0))
  756. return;
  757. nanosleep(ts_diff, NULL);
  758. }
  759. int cgtimer_to_ms(cgtimer_t *cgt)
  760. {
  761. return timespec_to_ms(cgt);
  762. }
  763. /* These are cgminer specific sleep functions that use an absolute nanosecond
  764. * resolution timer to avoid poor usleep accuracy and overruns. */
  765. #ifdef WIN32
  766. /* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */
  767. #define EPOCHFILETIME (116444736000000000LL)
  768. /* Return the system time as an lldiv_t in decimicroseconds. */
  769. static void decius_time(lldiv_t *lidiv)
  770. {
  771. FILETIME ft;
  772. LARGE_INTEGER li;
  773. GetSystemTimeAsFileTime(&ft);
  774. li.LowPart = ft.dwLowDateTime;
  775. li.HighPart = ft.dwHighDateTime;
  776. li.QuadPart -= EPOCHFILETIME;
  777. /* SystemTime is in decimicroseconds so divide by an unusual number */
  778. *lidiv = lldiv(li.QuadPart, 10000000);
  779. }
  780. /* This is a cgminer gettimeofday wrapper. Since we always call gettimeofday
  781. * with tz set to NULL, and windows' default resolution is only 15ms, this
  782. * gives us higher resolution times on windows. */
  783. void cgtime(struct timeval *tv)
  784. {
  785. lldiv_t lidiv;
  786. decius_time(&lidiv);
  787. tv->tv_sec = lidiv.quot;
  788. tv->tv_usec = lidiv.rem / 10;
  789. }
  790. void cgtimer_time(cgtimer_t *ts_start)
  791. {
  792. lldiv_t lidiv;;
  793. decius_time(&lidiv);
  794. ts_start->tv_sec = lidiv.quot;
  795. ts_start->tv_nsec = lidiv.quot * 100;
  796. }
  797. #else /* WIN32 */
  798. void cgtime(struct timeval *tv)
  799. {
  800. gettimeofday(tv, NULL);
  801. }
  802. #endif /* WIN32 */
  803. #ifdef CLOCK_MONOTONIC /* Essentially just linux */
  804. void cgtimer_time(cgtimer_t *ts_start)
  805. {
  806. clock_gettime(CLOCK_MONOTONIC, ts_start);
  807. }
  808. static void nanosleep_abstime(struct timespec *ts_end)
  809. {
  810. int ret;
  811. do {
  812. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  813. } while (ret == EINTR);
  814. }
  815. /* Reentrant version of cgsleep functions allow start time to be set separately
  816. * from the beginning of the actual sleep, allowing scheduling delays to be
  817. * counted in the sleep. */
  818. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  819. {
  820. struct timespec ts_end;
  821. ms_to_timespec(&ts_end, ms);
  822. timeraddspec(&ts_end, ts_start);
  823. nanosleep_abstime(&ts_end);
  824. }
  825. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  826. {
  827. struct timespec ts_end;
  828. us_to_timespec(&ts_end, us);
  829. timeraddspec(&ts_end, ts_start);
  830. nanosleep_abstime(&ts_end);
  831. }
  832. #else /* CLOCK_MONOTONIC */
  833. #ifdef __MACH__
  834. #include <mach/clock.h>
  835. #include <mach/mach.h>
  836. void cgtimer_time(cgtimer_t *ts_start)
  837. {
  838. clock_serv_t cclock;
  839. mach_timespec_t mts;
  840. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  841. clock_get_time(cclock, &mts);
  842. mach_port_deallocate(mach_task_self(), cclock);
  843. ts_start->tv_sec = mts.tv_sec;
  844. ts_start->tv_nsec = mts.tv_nsec;
  845. }
  846. #elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */
  847. void cgtimer_time(cgtimer_t *ts_start)
  848. {
  849. struct timeval tv;
  850. cgtime(&tv);
  851. ts_start->tv_sec = tv->tv_sec;
  852. ts_start->tv_nsec = tv->tv_usec * 1000;
  853. }
  854. #endif /* __MACH__ */
  855. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  856. {
  857. struct timespec ts_diff;
  858. ms_to_timespec(&ts_diff, ms);
  859. cgsleep_spec(&ts_diff, ts_start);
  860. }
  861. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  862. {
  863. struct timespec ts_diff;
  864. us_to_timespec(&ts_diff, us);
  865. cgsleep_spec(&ts_diff, ts_start);
  866. }
  867. #endif /* CLOCK_MONOTONIC */
  868. void cgsleep_ms(int ms)
  869. {
  870. cgtimer_t ts_start;
  871. cgsleep_prepare_r(&ts_start);
  872. cgsleep_ms_r(&ts_start, ms);
  873. }
  874. void cgsleep_us(int64_t us)
  875. {
  876. cgtimer_t ts_start;
  877. cgsleep_prepare_r(&ts_start);
  878. cgsleep_us_r(&ts_start, us);
  879. }
  880. /* Returns the microseconds difference between end and start times as a double */
  881. double us_tdiff(struct timeval *end, struct timeval *start)
  882. {
  883. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  884. }
  885. /* Returns the seconds difference between end and start times as a double */
  886. double tdiff(struct timeval *end, struct timeval *start)
  887. {
  888. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  889. }
  890. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  891. {
  892. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  893. char url_address[256], port[6];
  894. int url_len, port_len = 0;
  895. *sockaddr_url = url;
  896. url_begin = strstr(url, "//");
  897. if (!url_begin)
  898. url_begin = url;
  899. else
  900. url_begin += 2;
  901. /* Look for numeric ipv6 entries */
  902. ipv6_begin = strstr(url_begin, "[");
  903. ipv6_end = strstr(url_begin, "]");
  904. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  905. url_end = strstr(ipv6_end, ":");
  906. else
  907. url_end = strstr(url_begin, ":");
  908. if (url_end) {
  909. url_len = url_end - url_begin;
  910. port_len = strlen(url_begin) - url_len - 1;
  911. if (port_len < 1)
  912. return false;
  913. port_start = url_end + 1;
  914. } else
  915. url_len = strlen(url_begin);
  916. if (url_len < 1)
  917. return false;
  918. sprintf(url_address, "%.*s", url_len, url_begin);
  919. if (port_len)
  920. snprintf(port, 6, "%.*s", port_len, port_start);
  921. else
  922. strcpy(port, "80");
  923. *sockaddr_port = strdup(port);
  924. *sockaddr_url = strdup(url_address);
  925. return true;
  926. }
  927. enum send_ret {
  928. SEND_OK,
  929. SEND_SELECTFAIL,
  930. SEND_SENDFAIL,
  931. SEND_INACTIVE
  932. };
  933. /* Send a single command across a socket, appending \n to it. This should all
  934. * be done under stratum lock except when first establishing the socket */
  935. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  936. {
  937. SOCKETTYPE sock = pool->sock;
  938. ssize_t ssent = 0;
  939. strcat(s, "\n");
  940. len++;
  941. while (len > 0 ) {
  942. struct timeval timeout = {1, 0};
  943. ssize_t sent;
  944. fd_set wd;
  945. FD_ZERO(&wd);
  946. FD_SET(sock, &wd);
  947. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  948. return SEND_SELECTFAIL;
  949. #ifdef __APPLE__
  950. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  951. #elif WIN32
  952. sent = send(pool->sock, s + ssent, len, 0);
  953. #else
  954. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  955. #endif
  956. if (sent < 0) {
  957. if (!sock_blocks())
  958. return SEND_SENDFAIL;
  959. sent = 0;
  960. }
  961. ssent += sent;
  962. len -= sent;
  963. }
  964. pool->cgminer_pool_stats.times_sent++;
  965. pool->cgminer_pool_stats.bytes_sent += ssent;
  966. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  967. return SEND_OK;
  968. }
  969. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  970. {
  971. enum send_ret ret = SEND_INACTIVE;
  972. if (opt_protocol)
  973. applog(LOG_DEBUG, "SEND: %s", s);
  974. mutex_lock(&pool->stratum_lock);
  975. if (pool->stratum_active)
  976. ret = __stratum_send(pool, s, len);
  977. mutex_unlock(&pool->stratum_lock);
  978. /* This is to avoid doing applog under stratum_lock */
  979. switch (ret) {
  980. default:
  981. case SEND_OK:
  982. break;
  983. case SEND_SELECTFAIL:
  984. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  985. suspend_stratum(pool);
  986. break;
  987. case SEND_SENDFAIL:
  988. applog(LOG_DEBUG, "Failed to send in stratum_send");
  989. suspend_stratum(pool);
  990. break;
  991. case SEND_INACTIVE:
  992. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  993. break;
  994. }
  995. return (ret == SEND_OK);
  996. }
  997. static bool socket_full(struct pool *pool, int wait)
  998. {
  999. SOCKETTYPE sock = pool->sock;
  1000. struct timeval timeout;
  1001. fd_set rd;
  1002. if (unlikely(wait < 0))
  1003. wait = 0;
  1004. FD_ZERO(&rd);
  1005. FD_SET(sock, &rd);
  1006. timeout.tv_usec = 0;
  1007. timeout.tv_sec = wait;
  1008. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1009. return true;
  1010. return false;
  1011. }
  1012. /* Check to see if Santa's been good to you */
  1013. bool sock_full(struct pool *pool)
  1014. {
  1015. if (strlen(pool->sockbuf))
  1016. return true;
  1017. return (socket_full(pool, 0));
  1018. }
  1019. static void clear_sockbuf(struct pool *pool)
  1020. {
  1021. strcpy(pool->sockbuf, "");
  1022. }
  1023. static void clear_sock(struct pool *pool)
  1024. {
  1025. ssize_t n;
  1026. mutex_lock(&pool->stratum_lock);
  1027. do {
  1028. if (pool->sock)
  1029. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1030. else
  1031. n = 0;
  1032. } while (n > 0);
  1033. mutex_unlock(&pool->stratum_lock);
  1034. clear_sockbuf(pool);
  1035. }
  1036. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1037. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1038. * and zeroing the new memory */
  1039. static void recalloc_sock(struct pool *pool, size_t len)
  1040. {
  1041. size_t old, new;
  1042. old = strlen(pool->sockbuf);
  1043. new = old + len + 1;
  1044. if (new < pool->sockbuf_size)
  1045. return;
  1046. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1047. // Avoid potentially recursive locking
  1048. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  1049. pool->sockbuf = realloc(pool->sockbuf, new);
  1050. if (!pool->sockbuf)
  1051. quithere(1, "Failed to realloc pool sockbuf");
  1052. memset(pool->sockbuf + old, 0, new - old);
  1053. pool->sockbuf_size = new;
  1054. }
  1055. /* Peeks at a socket to find the first end of line and then reads just that
  1056. * from the socket and returns that as a malloced char */
  1057. char *recv_line(struct pool *pool)
  1058. {
  1059. char *tok, *sret = NULL;
  1060. ssize_t len, buflen;
  1061. int waited = 0;
  1062. if (!strstr(pool->sockbuf, "\n")) {
  1063. struct timeval rstart, now;
  1064. cgtime(&rstart);
  1065. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1066. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1067. goto out;
  1068. }
  1069. do {
  1070. char s[RBUFSIZE];
  1071. size_t slen;
  1072. ssize_t n;
  1073. memset(s, 0, RBUFSIZE);
  1074. n = recv(pool->sock, s, RECVSIZE, 0);
  1075. if (!n) {
  1076. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1077. suspend_stratum(pool);
  1078. break;
  1079. }
  1080. cgtime(&now);
  1081. waited = tdiff(&now, &rstart);
  1082. if (n < 0) {
  1083. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1084. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1085. suspend_stratum(pool);
  1086. break;
  1087. }
  1088. } else {
  1089. slen = strlen(s);
  1090. recalloc_sock(pool, slen);
  1091. strcat(pool->sockbuf, s);
  1092. }
  1093. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1094. }
  1095. buflen = strlen(pool->sockbuf);
  1096. tok = strtok(pool->sockbuf, "\n");
  1097. if (!tok) {
  1098. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1099. goto out;
  1100. }
  1101. sret = strdup(tok);
  1102. len = strlen(sret);
  1103. /* Copy what's left in the buffer after the \n, including the
  1104. * terminating \0 */
  1105. if (buflen > len + 1)
  1106. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1107. else
  1108. strcpy(pool->sockbuf, "");
  1109. pool->cgminer_pool_stats.times_received++;
  1110. pool->cgminer_pool_stats.bytes_received += len;
  1111. pool->cgminer_pool_stats.net_bytes_received += len;
  1112. out:
  1113. if (!sret)
  1114. clear_sock(pool);
  1115. else if (opt_protocol)
  1116. applog(LOG_DEBUG, "RECVD: %s", sret);
  1117. return sret;
  1118. }
  1119. /* Extracts a string value from a json array with error checking. To be used
  1120. * when the value of the string returned is only examined and not to be stored.
  1121. * See json_array_string below */
  1122. static char *__json_array_string(json_t *val, unsigned int entry)
  1123. {
  1124. json_t *arr_entry;
  1125. if (json_is_null(val))
  1126. return NULL;
  1127. if (!json_is_array(val))
  1128. return NULL;
  1129. if (entry > json_array_size(val))
  1130. return NULL;
  1131. arr_entry = json_array_get(val, entry);
  1132. if (!json_is_string(arr_entry))
  1133. return NULL;
  1134. return (char *)json_string_value(arr_entry);
  1135. }
  1136. /* Creates a freshly malloced dup of __json_array_string */
  1137. static char *json_array_string(json_t *val, unsigned int entry)
  1138. {
  1139. char *buf = __json_array_string(val, entry);
  1140. if (buf)
  1141. return strdup(buf);
  1142. return NULL;
  1143. }
  1144. static char *blank_merkel = "0000000000000000000000000000000000000000000000000000000000000000";
  1145. static bool parse_notify(struct pool *pool, json_t *val)
  1146. {
  1147. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
  1148. *ntime, *header;
  1149. size_t cb1_len, cb2_len, alloc_len;
  1150. unsigned char *cb1, *cb2;
  1151. bool clean, ret = false;
  1152. int merkles, i;
  1153. json_t *arr;
  1154. arr = json_array_get(val, 4);
  1155. if (!arr || !json_is_array(arr))
  1156. goto out;
  1157. merkles = json_array_size(arr);
  1158. job_id = json_array_string(val, 0);
  1159. prev_hash = json_array_string(val, 1);
  1160. coinbase1 = json_array_string(val, 2);
  1161. coinbase2 = json_array_string(val, 3);
  1162. bbversion = json_array_string(val, 5);
  1163. nbit = json_array_string(val, 6);
  1164. ntime = json_array_string(val, 7);
  1165. clean = json_is_true(json_array_get(val, 8));
  1166. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  1167. /* Annoying but we must not leak memory */
  1168. if (job_id)
  1169. free(job_id);
  1170. if (prev_hash)
  1171. free(prev_hash);
  1172. if (coinbase1)
  1173. free(coinbase1);
  1174. if (coinbase2)
  1175. free(coinbase2);
  1176. if (bbversion)
  1177. free(bbversion);
  1178. if (nbit)
  1179. free(nbit);
  1180. if (ntime)
  1181. free(ntime);
  1182. goto out;
  1183. }
  1184. cg_wlock(&pool->data_lock);
  1185. free(pool->swork.job_id);
  1186. free(pool->swork.prev_hash);
  1187. free(pool->swork.bbversion);
  1188. free(pool->swork.nbit);
  1189. free(pool->swork.ntime);
  1190. pool->swork.job_id = job_id;
  1191. pool->swork.prev_hash = prev_hash;
  1192. cb1_len = strlen(coinbase1) / 2;
  1193. cb2_len = strlen(coinbase2) / 2;
  1194. pool->swork.bbversion = bbversion;
  1195. pool->swork.nbit = nbit;
  1196. pool->swork.ntime = ntime;
  1197. pool->swork.clean = clean;
  1198. alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
  1199. pool->nonce2_offset = cb1_len + pool->n1_len;
  1200. for (i = 0; i < pool->swork.merkles; i++)
  1201. free(pool->swork.merkle_bin[i]);
  1202. if (merkles) {
  1203. pool->swork.merkle_bin = realloc(pool->swork.merkle_bin,
  1204. sizeof(char *) * merkles + 1);
  1205. for (i = 0; i < merkles; i++) {
  1206. char *merkle = json_array_string(arr, i);
  1207. pool->swork.merkle_bin[i] = malloc(32);
  1208. if (unlikely(!pool->swork.merkle_bin[i]))
  1209. quit(1, "Failed to malloc pool swork merkle_bin");
  1210. hex2bin(pool->swork.merkle_bin[i], merkle, 32);
  1211. free(merkle);
  1212. }
  1213. }
  1214. pool->swork.merkles = merkles;
  1215. if (clean)
  1216. pool->nonce2 = 0;
  1217. pool->merkle_offset = strlen(pool->swork.bbversion) +
  1218. strlen(pool->swork.prev_hash);
  1219. pool->swork.header_len = pool->merkle_offset +
  1220. /* merkle_hash */ 32 +
  1221. strlen(pool->swork.ntime) +
  1222. strlen(pool->swork.nbit) +
  1223. /* nonce */ 8 +
  1224. /* workpadding */ 96;
  1225. pool->merkle_offset /= 2;
  1226. pool->swork.header_len = pool->swork.header_len * 2 + 1;
  1227. align_len(&pool->swork.header_len);
  1228. header = alloca(pool->swork.header_len);
  1229. snprintf(header, pool->swork.header_len,
  1230. "%s%s%s%s%s%s%s",
  1231. pool->swork.bbversion,
  1232. pool->swork.prev_hash,
  1233. blank_merkel,
  1234. pool->swork.ntime,
  1235. pool->swork.nbit,
  1236. "00000000", /* nonce */
  1237. workpadding);
  1238. if (unlikely(!hex2bin(pool->header_bin, header, 128)))
  1239. quit(1, "Failed to convert header to header_bin in parse_notify");
  1240. cb1 = calloc(cb1_len, 1);
  1241. if (unlikely(!cb1))
  1242. quithere(1, "Failed to calloc cb1 in parse_notify");
  1243. hex2bin(cb1, coinbase1, cb1_len);
  1244. cb2 = calloc(cb2_len, 1);
  1245. if (unlikely(!cb2))
  1246. quithere(1, "Failed to calloc cb2 in parse_notify");
  1247. hex2bin(cb2, coinbase2, cb2_len);
  1248. free(pool->coinbase);
  1249. align_len(&alloc_len);
  1250. pool->coinbase = calloc(alloc_len, 1);
  1251. if (unlikely(!pool->coinbase))
  1252. quit(1, "Failed to calloc pool coinbase in parse_notify");
  1253. memcpy(pool->coinbase, cb1, cb1_len);
  1254. memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
  1255. memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
  1256. cg_wunlock(&pool->data_lock);
  1257. if (opt_protocol) {
  1258. applog(LOG_DEBUG, "job_id: %s", job_id);
  1259. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1260. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1261. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1262. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1263. applog(LOG_DEBUG, "nbit: %s", nbit);
  1264. applog(LOG_DEBUG, "ntime: %s", ntime);
  1265. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1266. }
  1267. free(coinbase1);
  1268. free(coinbase2);
  1269. free(cb1);
  1270. free(cb2);
  1271. /* A notify message is the closest stratum gets to a getwork */
  1272. pool->getwork_requested++;
  1273. total_getworks++;
  1274. ret = true;
  1275. out:
  1276. return ret;
  1277. }
  1278. static bool parse_diff(struct pool *pool, json_t *val)
  1279. {
  1280. double old_diff, diff;
  1281. diff = json_number_value(json_array_get(val, 0));
  1282. if (diff == 0)
  1283. return false;
  1284. cg_wlock(&pool->data_lock);
  1285. old_diff = pool->swork.diff;
  1286. pool->swork.diff = diff;
  1287. cg_wunlock(&pool->data_lock);
  1288. if (old_diff != diff) {
  1289. int idiff = diff;
  1290. if ((double)idiff == diff)
  1291. applog(LOG_NOTICE, "Pool %d difficulty changed to %d",
  1292. pool->pool_no, idiff);
  1293. else
  1294. applog(LOG_NOTICE, "Pool %d difficulty changed to %f",
  1295. pool->pool_no, diff);
  1296. } else
  1297. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no,
  1298. diff);
  1299. return true;
  1300. }
  1301. static bool parse_reconnect(struct pool *pool, json_t *val)
  1302. {
  1303. char *url, *port, address[256];
  1304. memset(address, 0, 255);
  1305. url = (char *)json_string_value(json_array_get(val, 0));
  1306. if (!url)
  1307. url = pool->sockaddr_url;
  1308. port = (char *)json_string_value(json_array_get(val, 1));
  1309. if (!port)
  1310. port = pool->stratum_port;
  1311. sprintf(address, "%s:%s", url, port);
  1312. if (!extract_sockaddr(address, &pool->sockaddr_url, &pool->stratum_port))
  1313. return false;
  1314. pool->stratum_url = pool->sockaddr_url;
  1315. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1316. if (!restart_stratum(pool))
  1317. return false;
  1318. return true;
  1319. }
  1320. static bool send_version(struct pool *pool, json_t *val)
  1321. {
  1322. char s[RBUFSIZE];
  1323. int id = json_integer_value(json_object_get(val, "id"));
  1324. if (!id)
  1325. return false;
  1326. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  1327. if (!stratum_send(pool, s, strlen(s)))
  1328. return false;
  1329. return true;
  1330. }
  1331. static bool show_message(struct pool *pool, json_t *val)
  1332. {
  1333. char *msg;
  1334. if (!json_is_array(val))
  1335. return false;
  1336. msg = (char *)json_string_value(json_array_get(val, 0));
  1337. if (!msg)
  1338. return false;
  1339. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  1340. return true;
  1341. }
  1342. bool parse_method(struct pool *pool, char *s)
  1343. {
  1344. json_t *val = NULL, *method, *err_val, *params;
  1345. json_error_t err;
  1346. bool ret = false;
  1347. char *buf;
  1348. if (!s)
  1349. return ret;
  1350. val = JSON_LOADS(s, &err);
  1351. if (!val) {
  1352. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1353. return ret;
  1354. }
  1355. method = json_object_get(val, "method");
  1356. if (!method)
  1357. return ret;
  1358. err_val = json_object_get(val, "error");
  1359. params = json_object_get(val, "params");
  1360. if (err_val && !json_is_null(err_val)) {
  1361. char *ss;
  1362. if (err_val)
  1363. ss = json_dumps(err_val, JSON_INDENT(3));
  1364. else
  1365. ss = strdup("(unknown reason)");
  1366. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1367. free(ss);
  1368. return ret;
  1369. }
  1370. buf = (char *)json_string_value(method);
  1371. if (!buf)
  1372. return ret;
  1373. if (!strncasecmp(buf, "mining.notify", 13)) {
  1374. if (parse_notify(pool, params))
  1375. pool->stratum_notify = ret = true;
  1376. else
  1377. pool->stratum_notify = ret = false;
  1378. return ret;
  1379. }
  1380. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1381. ret = true;
  1382. return ret;
  1383. }
  1384. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1385. ret = true;
  1386. return ret;
  1387. }
  1388. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1389. ret = true;
  1390. return ret;
  1391. }
  1392. if (!strncasecmp(buf, "client.show_message", 19) && show_message(pool, params)) {
  1393. ret = true;
  1394. return ret;
  1395. }
  1396. return ret;
  1397. }
  1398. bool auth_stratum(struct pool *pool)
  1399. {
  1400. json_t *val = NULL, *res_val, *err_val;
  1401. char s[RBUFSIZE], *sret = NULL;
  1402. json_error_t err;
  1403. bool ret = false;
  1404. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1405. swork_id++, pool->rpc_user, pool->rpc_pass);
  1406. if (!stratum_send(pool, s, strlen(s)))
  1407. return ret;
  1408. /* Parse all data in the queue and anything left should be auth */
  1409. while (42) {
  1410. sret = recv_line(pool);
  1411. if (!sret)
  1412. return ret;
  1413. if (parse_method(pool, sret))
  1414. free(sret);
  1415. else
  1416. break;
  1417. }
  1418. val = JSON_LOADS(sret, &err);
  1419. free(sret);
  1420. res_val = json_object_get(val, "result");
  1421. err_val = json_object_get(val, "error");
  1422. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1423. char *ss;
  1424. if (err_val)
  1425. ss = json_dumps(err_val, JSON_INDENT(3));
  1426. else
  1427. ss = strdup("(unknown reason)");
  1428. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1429. free(ss);
  1430. return ret;
  1431. }
  1432. ret = true;
  1433. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1434. pool->probed = true;
  1435. successful_connect = true;
  1436. return ret;
  1437. }
  1438. static bool setup_stratum_socket(struct pool *pool)
  1439. {
  1440. struct addrinfo servinfobase, *servinfo, *hints, pbase, *p;
  1441. int sockd;
  1442. mutex_lock(&pool->stratum_lock);
  1443. pool->stratum_active = false;
  1444. if (pool->sock)
  1445. CLOSESOCKET(pool->sock);
  1446. pool->sock = 0;
  1447. mutex_unlock(&pool->stratum_lock);
  1448. hints = &pool->stratum_hints;
  1449. memset(hints, 0, sizeof(struct addrinfo));
  1450. hints->ai_family = AF_UNSPEC;
  1451. hints->ai_socktype = SOCK_STREAM;
  1452. servinfo = &servinfobase;
  1453. p = &pbase;
  1454. if (getaddrinfo(pool->sockaddr_url, pool->stratum_port, hints, &servinfo) != 0) {
  1455. if (!pool->probed) {
  1456. applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s",
  1457. pool->sockaddr_url, pool->stratum_port);
  1458. pool->probed = true;
  1459. } else {
  1460. applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
  1461. pool->sockaddr_url, pool->stratum_port);
  1462. }
  1463. return false;
  1464. }
  1465. for (p = servinfo; p != NULL; p = p->ai_next) {
  1466. sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
  1467. if (sockd == -1) {
  1468. applog(LOG_DEBUG, "Failed socket");
  1469. continue;
  1470. }
  1471. if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
  1472. CLOSESOCKET(sockd);
  1473. applog(LOG_DEBUG, "Failed connect");
  1474. continue;
  1475. }
  1476. break;
  1477. }
  1478. if (p == NULL) {
  1479. applog(LOG_INFO, "Failed to find a stratum servinfo on %s:%s",
  1480. pool->sockaddr_url, pool->stratum_port);
  1481. freeaddrinfo(servinfo);
  1482. return false;
  1483. }
  1484. freeaddrinfo(servinfo);
  1485. if (!pool->sockbuf) {
  1486. pool->sockbuf = calloc(RBUFSIZE, 1);
  1487. if (!pool->sockbuf)
  1488. quithere(1, "Failed to calloc pool sockbuf");
  1489. pool->sockbuf_size = RBUFSIZE;
  1490. }
  1491. pool->sock = sockd;
  1492. keep_sockalive(sockd);
  1493. return true;
  1494. }
  1495. static char *get_sessionid(json_t *val)
  1496. {
  1497. char *ret = NULL;
  1498. json_t *arr_val;
  1499. int arrsize, i;
  1500. arr_val = json_array_get(val, 0);
  1501. if (!arr_val || !json_is_array(arr_val))
  1502. goto out;
  1503. arrsize = json_array_size(arr_val);
  1504. for (i = 0; i < arrsize; i++) {
  1505. json_t *arr = json_array_get(arr_val, i);
  1506. char *notify;
  1507. if (!arr | !json_is_array(arr))
  1508. break;
  1509. notify = __json_array_string(arr, 0);
  1510. if (!notify)
  1511. continue;
  1512. if (!strncasecmp(notify, "mining.notify", 13)) {
  1513. ret = json_array_string(arr, 1);
  1514. break;
  1515. }
  1516. }
  1517. out:
  1518. return ret;
  1519. }
  1520. void suspend_stratum(struct pool *pool)
  1521. {
  1522. clear_sockbuf(pool);
  1523. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1524. mutex_lock(&pool->stratum_lock);
  1525. pool->stratum_active = pool->stratum_notify = false;
  1526. if (pool->sock)
  1527. CLOSESOCKET(pool->sock);
  1528. pool->sock = 0;
  1529. mutex_unlock(&pool->stratum_lock);
  1530. }
  1531. bool initiate_stratum(struct pool *pool)
  1532. {
  1533. bool ret = false, recvd = false, noresume = false, sockd = false;
  1534. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  1535. json_t *val = NULL, *res_val, *err_val;
  1536. json_error_t err;
  1537. int n2size;
  1538. resend:
  1539. if (!setup_stratum_socket(pool)) {
  1540. sockd = false;
  1541. goto out;
  1542. }
  1543. sockd = true;
  1544. if (recvd) {
  1545. /* Get rid of any crap lying around if we're resending */
  1546. clear_sock(pool);
  1547. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1548. } else {
  1549. if (pool->sessionid)
  1550. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  1551. else
  1552. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  1553. }
  1554. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  1555. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1556. goto out;
  1557. }
  1558. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1559. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1560. goto out;
  1561. }
  1562. sret = recv_line(pool);
  1563. if (!sret)
  1564. goto out;
  1565. recvd = true;
  1566. val = JSON_LOADS(sret, &err);
  1567. free(sret);
  1568. if (!val) {
  1569. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1570. goto out;
  1571. }
  1572. res_val = json_object_get(val, "result");
  1573. err_val = json_object_get(val, "error");
  1574. if (!res_val || json_is_null(res_val) ||
  1575. (err_val && !json_is_null(err_val))) {
  1576. char *ss;
  1577. if (err_val)
  1578. ss = json_dumps(err_val, JSON_INDENT(3));
  1579. else
  1580. ss = strdup("(unknown reason)");
  1581. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1582. free(ss);
  1583. goto out;
  1584. }
  1585. sessionid = get_sessionid(res_val);
  1586. if (!sessionid)
  1587. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  1588. nonce1 = json_array_string(res_val, 1);
  1589. if (!nonce1) {
  1590. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1591. free(sessionid);
  1592. goto out;
  1593. }
  1594. n2size = json_integer_value(json_array_get(res_val, 2));
  1595. if (!n2size) {
  1596. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1597. free(sessionid);
  1598. free(nonce1);
  1599. goto out;
  1600. }
  1601. cg_wlock(&pool->data_lock);
  1602. pool->sessionid = sessionid;
  1603. pool->nonce1 = nonce1;
  1604. pool->n1_len = strlen(nonce1) / 2;
  1605. free(pool->nonce1bin);
  1606. pool->nonce1bin = calloc(pool->n1_len, 1);
  1607. if (unlikely(!pool->nonce1bin))
  1608. quithere(1, "Failed to calloc pool->nonce1bin");
  1609. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  1610. pool->n2size = n2size;
  1611. cg_wunlock(&pool->data_lock);
  1612. if (sessionid)
  1613. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  1614. ret = true;
  1615. out:
  1616. if (ret) {
  1617. if (!pool->stratum_url)
  1618. pool->stratum_url = pool->sockaddr_url;
  1619. pool->stratum_active = true;
  1620. pool->swork.diff = 1;
  1621. if (opt_protocol) {
  1622. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1623. pool->pool_no, pool->nonce1, pool->n2size);
  1624. }
  1625. } else {
  1626. if (recvd && !noresume) {
  1627. /* Reset the sessionid used for stratum resuming in case the pool
  1628. * does not support it, or does not know how to respond to the
  1629. * presence of the sessionid parameter. */
  1630. cg_wlock(&pool->data_lock);
  1631. free(pool->sessionid);
  1632. free(pool->nonce1);
  1633. pool->sessionid = pool->nonce1 = NULL;
  1634. cg_wunlock(&pool->data_lock);
  1635. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  1636. noresume = true;
  1637. goto resend;
  1638. }
  1639. applog(LOG_DEBUG, "Initiate stratum failed");
  1640. if (sockd)
  1641. suspend_stratum(pool);
  1642. }
  1643. return ret;
  1644. }
  1645. bool restart_stratum(struct pool *pool)
  1646. {
  1647. if (pool->stratum_active)
  1648. suspend_stratum(pool);
  1649. if (!initiate_stratum(pool))
  1650. return false;
  1651. if (!auth_stratum(pool))
  1652. return false;
  1653. return true;
  1654. }
  1655. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1656. {
  1657. dev->device_last_not_well = time(NULL);
  1658. dev->device_not_well_reason = reason;
  1659. switch (reason) {
  1660. case REASON_THREAD_FAIL_INIT:
  1661. dev->thread_fail_init_count++;
  1662. break;
  1663. case REASON_THREAD_ZERO_HASH:
  1664. dev->thread_zero_hash_count++;
  1665. break;
  1666. case REASON_THREAD_FAIL_QUEUE:
  1667. dev->thread_fail_queue_count++;
  1668. break;
  1669. case REASON_DEV_SICK_IDLE_60:
  1670. dev->dev_sick_idle_60_count++;
  1671. break;
  1672. case REASON_DEV_DEAD_IDLE_600:
  1673. dev->dev_dead_idle_600_count++;
  1674. break;
  1675. case REASON_DEV_NOSTART:
  1676. dev->dev_nostart_count++;
  1677. break;
  1678. case REASON_DEV_OVER_HEAT:
  1679. dev->dev_over_heat_count++;
  1680. break;
  1681. case REASON_DEV_THERMAL_CUTOFF:
  1682. dev->dev_thermal_cutoff_count++;
  1683. break;
  1684. case REASON_DEV_COMMS_ERROR:
  1685. dev->dev_comms_error_count++;
  1686. break;
  1687. case REASON_DEV_THROTTLE:
  1688. dev->dev_throttle_count++;
  1689. break;
  1690. }
  1691. }
  1692. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1693. void *realloc_strcat(char *ptr, char *s)
  1694. {
  1695. size_t old = strlen(ptr), len = strlen(s);
  1696. char *ret;
  1697. if (!len)
  1698. return ptr;
  1699. len += old + 1;
  1700. align_len(&len);
  1701. ret = malloc(len);
  1702. if (unlikely(!ret))
  1703. quithere(1, "Failed to malloc");
  1704. sprintf(ret, "%s%s", ptr, s);
  1705. free(ptr);
  1706. return ret;
  1707. }
  1708. /* Make a text readable version of a string using 0xNN for < ' ' or > '~'
  1709. * Including 0x00 at the end
  1710. * You must free the result yourself */
  1711. void *str_text(char *ptr)
  1712. {
  1713. unsigned char *uptr;
  1714. char *ret, *txt;
  1715. if (ptr == NULL) {
  1716. ret = strdup("(null)");
  1717. if (unlikely(!ret))
  1718. quithere(1, "Failed to malloc null");
  1719. }
  1720. uptr = (unsigned char *)ptr;
  1721. ret = txt = malloc(strlen(ptr)*4+5); // Guaranteed >= needed
  1722. if (unlikely(!txt))
  1723. quithere(1, "Failed to malloc txt");
  1724. do {
  1725. if (*uptr < ' ' || *uptr > '~') {
  1726. sprintf(txt, "0x%02x", *uptr);
  1727. txt += 4;
  1728. } else
  1729. *(txt++) = *uptr;
  1730. } while (*(uptr++));
  1731. *txt = '\0';
  1732. return ret;
  1733. }
  1734. void RenameThread(const char* name)
  1735. {
  1736. #if defined(PR_SET_NAME)
  1737. // Only the first 15 characters are used (16 - NUL terminator)
  1738. prctl(PR_SET_NAME, name, 0, 0, 0);
  1739. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  1740. pthread_set_name_np(pthread_self(), name);
  1741. #elif defined(MAC_OSX)
  1742. pthread_setname_np(name);
  1743. #else
  1744. // Prevent warnings for unused parameters...
  1745. (void)name;
  1746. #endif
  1747. }
  1748. /* cgminer specific wrappers for true unnamed semaphore usage on platforms
  1749. * that support them and for apple which does not. We use a single byte across
  1750. * a pipe to emulate semaphore behaviour there. */
  1751. #ifdef __APPLE__
  1752. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1753. {
  1754. int flags, fd, i;
  1755. if (pipe(cgsem->pipefd) == -1)
  1756. quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
  1757. /* Make the pipes FD_CLOEXEC to allow them to close should we call
  1758. * execv on restart. */
  1759. for (i = 0; i < 2; i++) {
  1760. fd = cgsem->pipefd[i];
  1761. flags = fcntl(fd, F_GETFD, 0);
  1762. flags |= FD_CLOEXEC;
  1763. if (fcntl(fd, F_SETFD, flags) == -1)
  1764. quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
  1765. }
  1766. }
  1767. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1768. {
  1769. const char buf = 1;
  1770. int ret;
  1771. ret = write(cgsem->pipefd[1], &buf, 1);
  1772. if (unlikely(ret == 0))
  1773. applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
  1774. }
  1775. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1776. {
  1777. char buf;
  1778. int ret;
  1779. ret = read(cgsem->pipefd[0], &buf, 1);
  1780. if (unlikely(ret == 0))
  1781. applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
  1782. }
  1783. void _cgsem_destroy(cgsem_t *cgsem)
  1784. {
  1785. close(cgsem->pipefd[1]);
  1786. close(cgsem->pipefd[0]);
  1787. }
  1788. #else
  1789. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1790. {
  1791. int ret;
  1792. if ((ret = sem_init(cgsem, 0, 0)))
  1793. quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
  1794. }
  1795. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1796. {
  1797. if (unlikely(sem_post(cgsem)))
  1798. quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
  1799. }
  1800. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  1801. {
  1802. if (unlikely(sem_wait(cgsem)))
  1803. quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
  1804. }
  1805. void _cgsem_destroy(cgsem_t *cgsem)
  1806. {
  1807. sem_destroy(cgsem);
  1808. }
  1809. #endif