util.c 56 KB

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