util.c 55 KB

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