util.c 57 KB

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