util.c 55 KB

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