util.c 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  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. # ifdef __linux
  24. # include <sys/prctl.h>
  25. # endif
  26. # include <sys/socket.h>
  27. # include <netinet/in.h>
  28. # include <netinet/tcp.h>
  29. # include <netdb.h>
  30. #else
  31. # include <winsock2.h>
  32. # include <ws2tcpip.h>
  33. #endif
  34. #include "miner.h"
  35. #include "elist.h"
  36. #include "compat.h"
  37. #include "util.h"
  38. bool successful_connect = false;
  39. struct timeval nettime;
  40. struct data_buffer {
  41. void *buf;
  42. size_t len;
  43. };
  44. struct upload_buffer {
  45. const void *buf;
  46. size_t len;
  47. };
  48. struct header_info {
  49. char *lp_path;
  50. int rolltime;
  51. char *reason;
  52. char *stratum_url;
  53. bool hadrolltime;
  54. bool canroll;
  55. bool hadexpire;
  56. };
  57. struct tq_ent {
  58. void *data;
  59. struct list_head q_node;
  60. };
  61. static void databuf_free(struct data_buffer *db)
  62. {
  63. if (!db)
  64. return;
  65. free(db->buf);
  66. memset(db, 0, sizeof(*db));
  67. }
  68. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  69. void *user_data)
  70. {
  71. struct data_buffer *db = user_data;
  72. size_t len = size * nmemb;
  73. size_t oldlen, newlen;
  74. void *newmem;
  75. static const unsigned char zero = 0;
  76. oldlen = db->len;
  77. newlen = oldlen + len;
  78. newmem = realloc(db->buf, newlen + 1);
  79. if (!newmem)
  80. return 0;
  81. db->buf = newmem;
  82. db->len = newlen;
  83. memcpy(db->buf + oldlen, ptr, len);
  84. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  85. return len;
  86. }
  87. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  88. void *user_data)
  89. {
  90. struct upload_buffer *ub = user_data;
  91. unsigned int len = size * nmemb;
  92. if (len > ub->len)
  93. len = ub->len;
  94. if (len) {
  95. memcpy(ptr, ub->buf, len);
  96. ub->buf += len;
  97. ub->len -= len;
  98. }
  99. return len;
  100. }
  101. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  102. {
  103. struct header_info *hi = user_data;
  104. size_t remlen, slen, ptrlen = size * nmemb;
  105. char *rem, *val = NULL, *key = NULL;
  106. void *tmp;
  107. val = calloc(1, ptrlen);
  108. key = calloc(1, ptrlen);
  109. if (!key || !val)
  110. goto out;
  111. tmp = memchr(ptr, ':', ptrlen);
  112. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  113. goto out;
  114. slen = tmp - ptr;
  115. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  116. goto out;
  117. memcpy(key, ptr, slen); /* store & nul term key */
  118. key[slen] = 0;
  119. rem = ptr + slen + 1; /* trim value's leading whitespace */
  120. remlen = ptrlen - slen - 1;
  121. while ((remlen > 0) && (isspace(*rem))) {
  122. remlen--;
  123. rem++;
  124. }
  125. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  126. val[remlen] = 0;
  127. while ((*val) && (isspace(val[strlen(val) - 1])))
  128. val[strlen(val) - 1] = 0;
  129. if (!*val) /* skip blank value */
  130. goto out;
  131. if (opt_protocol)
  132. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  133. if (!strcasecmp("X-Roll-Ntime", key)) {
  134. hi->hadrolltime = true;
  135. if (!strncasecmp("N", val, 1))
  136. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  137. else {
  138. hi->canroll = true;
  139. /* Check to see if expire= is supported and if not, set
  140. * the rolltime to the default scantime */
  141. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  142. sscanf(val + 7, "%d", &hi->rolltime);
  143. hi->hadexpire = true;
  144. } else
  145. hi->rolltime = opt_scantime;
  146. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  147. }
  148. }
  149. if (!strcasecmp("X-Long-Polling", key)) {
  150. hi->lp_path = val; /* steal memory reference */
  151. val = NULL;
  152. }
  153. if (!strcasecmp("X-Reject-Reason", key)) {
  154. hi->reason = val; /* steal memory reference */
  155. val = NULL;
  156. }
  157. if (!strcasecmp("X-Stratum", key)) {
  158. hi->stratum_url = val;
  159. val = NULL;
  160. }
  161. out:
  162. free(key);
  163. free(val);
  164. return ptrlen;
  165. }
  166. #if CURL_HAS_KEEPALIVE
  167. static void keep_curlalive(CURL *curl)
  168. {
  169. const int tcp_keepidle = 45;
  170. const int tcp_keepintvl = 30;
  171. const long int keepalive = 1;
  172. curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, keepalive);
  173. curl_easy_setopt(curl, CURLOPT_TCP_KEEPIDLE, tcp_keepidle);
  174. curl_easy_setopt(curl, CURLOPT_TCP_KEEPINTVL, tcp_keepintvl);
  175. }
  176. static void keep_alive(CURL *curl, __maybe_unused SOCKETTYPE fd)
  177. {
  178. keep_curlalive(curl);
  179. }
  180. #else
  181. static void keep_sockalive(SOCKETTYPE fd)
  182. {
  183. const int tcp_keepidle = 45;
  184. const int tcp_keepintvl = 30;
  185. const int keepalive = 1;
  186. const int tcp_keepcnt = 1;
  187. setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive));
  188. # ifdef __linux
  189. setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_keepcnt, sizeof(tcp_keepcnt));
  190. setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle));
  191. setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl));
  192. # endif /* __linux */
  193. # ifdef __APPLE_CC__
  194. setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl));
  195. # endif /* __APPLE_CC__ */
  196. }
  197. static void keep_curlalive(CURL *curl)
  198. {
  199. SOCKETTYPE sock;
  200. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&sock);
  201. keep_sockalive(sock);
  202. }
  203. static void keep_alive(CURL __maybe_unused *curl, SOCKETTYPE fd)
  204. {
  205. keep_sockalive(fd);
  206. }
  207. #endif
  208. static void last_nettime(struct timeval *last)
  209. {
  210. rd_lock(&netacc_lock);
  211. last->tv_sec = nettime.tv_sec;
  212. last->tv_usec = nettime.tv_usec;
  213. rd_unlock(&netacc_lock);
  214. }
  215. static void set_nettime(void)
  216. {
  217. wr_lock(&netacc_lock);
  218. gettimeofday(&nettime, NULL);
  219. wr_unlock(&netacc_lock);
  220. }
  221. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  222. __maybe_unused char *data, size_t size, void *userdata)
  223. {
  224. struct pool *pool = (struct pool *)userdata;
  225. switch(type) {
  226. case CURLINFO_HEADER_IN:
  227. case CURLINFO_DATA_IN:
  228. case CURLINFO_SSL_DATA_IN:
  229. pool->cgminer_pool_stats.net_bytes_received += size;
  230. break;
  231. case CURLINFO_HEADER_OUT:
  232. case CURLINFO_DATA_OUT:
  233. case CURLINFO_SSL_DATA_OUT:
  234. pool->cgminer_pool_stats.net_bytes_sent += size;
  235. break;
  236. case CURLINFO_TEXT:
  237. default:
  238. break;
  239. }
  240. return 0;
  241. }
  242. json_t *json_rpc_call(CURL *curl, const char *url,
  243. const char *userpass, const char *rpc_req,
  244. bool probe, bool longpoll, int *rolltime,
  245. struct pool *pool, bool share)
  246. {
  247. long timeout = longpoll ? (60 * 60) : 60;
  248. struct data_buffer all_data = {NULL, 0};
  249. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  250. char len_hdr[64], user_agent_hdr[128];
  251. char curl_err_str[CURL_ERROR_SIZE];
  252. struct curl_slist *headers = NULL;
  253. struct upload_buffer upload_data;
  254. json_t *val, *err_val, *res_val;
  255. bool probing = false;
  256. double byte_count;
  257. json_error_t err;
  258. int rc;
  259. memset(&err, 0, sizeof(err));
  260. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  261. if (probe)
  262. probing = !pool->probed;
  263. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  264. // CURLOPT_VERBOSE won't write to stderr if we use CURLOPT_DEBUGFUNCTION
  265. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  266. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  267. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  268. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  269. curl_easy_setopt(curl, CURLOPT_URL, url);
  270. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  271. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  272. /* Shares are staggered already and delays in submission can be costly
  273. * so do not delay them */
  274. if (!opt_delaynet || share)
  275. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  276. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  277. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  278. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  279. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  280. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  281. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  282. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  283. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  284. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  285. if (pool->rpc_proxy) {
  286. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  287. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  288. } else if (opt_socks_proxy) {
  289. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  290. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  291. }
  292. if (userpass) {
  293. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  294. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  295. }
  296. if (longpoll)
  297. keep_curlalive(curl);
  298. curl_easy_setopt(curl, CURLOPT_POST, 1);
  299. if (opt_protocol)
  300. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  301. upload_data.buf = rpc_req;
  302. upload_data.len = strlen(rpc_req);
  303. sprintf(len_hdr, "Content-Length: %lu",
  304. (unsigned long) upload_data.len);
  305. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  306. headers = curl_slist_append(headers,
  307. "Content-type: application/json");
  308. headers = curl_slist_append(headers,
  309. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  310. if (likely(global_hashrate)) {
  311. char ghashrate[255];
  312. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  313. headers = curl_slist_append(headers, ghashrate);
  314. }
  315. headers = curl_slist_append(headers, len_hdr);
  316. headers = curl_slist_append(headers, user_agent_hdr);
  317. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  318. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  319. if (opt_delaynet) {
  320. /* Don't delay share submission, but still track the nettime */
  321. if (!share) {
  322. long long now_msecs, last_msecs;
  323. struct timeval now, last;
  324. gettimeofday(&now, NULL);
  325. last_nettime(&last);
  326. now_msecs = (long long)now.tv_sec * 1000;
  327. now_msecs += now.tv_usec / 1000;
  328. last_msecs = (long long)last.tv_sec * 1000;
  329. last_msecs += last.tv_usec / 1000;
  330. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  331. struct timespec rgtp;
  332. rgtp.tv_sec = 0;
  333. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  334. nanosleep(&rgtp, NULL);
  335. }
  336. }
  337. set_nettime();
  338. }
  339. rc = curl_easy_perform(curl);
  340. if (rc) {
  341. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  342. goto err_out;
  343. }
  344. if (!all_data.buf) {
  345. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  346. goto err_out;
  347. }
  348. pool->cgminer_pool_stats.times_sent++;
  349. if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK)
  350. pool->cgminer_pool_stats.bytes_sent += byte_count;
  351. pool->cgminer_pool_stats.times_received++;
  352. if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK)
  353. pool->cgminer_pool_stats.bytes_received += byte_count;
  354. if (probing) {
  355. pool->probed = true;
  356. /* If X-Long-Polling was found, activate long polling */
  357. if (hi.lp_path) {
  358. if (pool->hdr_path != NULL)
  359. free(pool->hdr_path);
  360. pool->hdr_path = hi.lp_path;
  361. } else
  362. pool->hdr_path = NULL;
  363. if (hi.stratum_url) {
  364. pool->stratum_url = hi.stratum_url;
  365. hi.stratum_url = NULL;
  366. }
  367. } else {
  368. if (hi.lp_path) {
  369. free(hi.lp_path);
  370. hi.lp_path = NULL;
  371. }
  372. if (hi.stratum_url) {
  373. free(hi.stratum_url);
  374. hi.stratum_url = NULL;
  375. }
  376. }
  377. *rolltime = hi.rolltime;
  378. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  379. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  380. pool->cgminer_pool_stats.canroll = hi.canroll;
  381. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  382. val = JSON_LOADS(all_data.buf, &err);
  383. if (!val) {
  384. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  385. if (opt_protocol)
  386. applog(LOG_DEBUG, "JSON protocol response:\n%s", all_data.buf);
  387. goto err_out;
  388. }
  389. if (opt_protocol) {
  390. char *s = json_dumps(val, JSON_INDENT(3));
  391. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  392. free(s);
  393. }
  394. /* JSON-RPC valid response returns a non-null 'result',
  395. * and a null 'error'.
  396. */
  397. res_val = json_object_get(val, "result");
  398. err_val = json_object_get(val, "error");
  399. if (!res_val ||(err_val && !json_is_null(err_val))) {
  400. char *s;
  401. if (err_val)
  402. s = json_dumps(err_val, JSON_INDENT(3));
  403. else
  404. s = strdup("(unknown reason)");
  405. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  406. free(s);
  407. goto err_out;
  408. }
  409. if (hi.reason) {
  410. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  411. free(hi.reason);
  412. hi.reason = NULL;
  413. }
  414. successful_connect = true;
  415. databuf_free(&all_data);
  416. curl_slist_free_all(headers);
  417. curl_easy_reset(curl);
  418. return val;
  419. err_out:
  420. databuf_free(&all_data);
  421. curl_slist_free_all(headers);
  422. curl_easy_reset(curl);
  423. if (!successful_connect)
  424. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  425. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  426. return NULL;
  427. }
  428. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  429. static struct {
  430. const char *name;
  431. curl_proxytype proxytype;
  432. } proxynames[] = {
  433. { "http:", CURLPROXY_HTTP },
  434. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 19) || (LIBCURL_VERSION_MINOR == 19 && LIBCURL_VERSION_PATCH >= 4)
  435. { "http0:", CURLPROXY_HTTP_1_0 },
  436. #endif
  437. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR > 15) || (LIBCURL_VERSION_MINOR == 15 && LIBCURL_VERSION_PATCH >= 2)
  438. { "socks4:", CURLPROXY_SOCKS4 },
  439. #endif
  440. { "socks5:", CURLPROXY_SOCKS5 },
  441. #if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MINOR >= 18)
  442. { "socks4a:", CURLPROXY_SOCKS4A },
  443. { "socks5h:", CURLPROXY_SOCKS5_HOSTNAME },
  444. #endif
  445. { NULL, 0 }
  446. };
  447. #endif
  448. const char *proxytype(curl_proxytype proxytype)
  449. {
  450. int i;
  451. for (i = 0; proxynames[i].name; i++)
  452. if (proxynames[i].proxytype == proxytype)
  453. return proxynames[i].name;
  454. return "invalid";
  455. }
  456. char *get_proxy(char *url, struct pool *pool)
  457. {
  458. pool->rpc_proxy = NULL;
  459. #if (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 10) || (LIBCURL_VERSION_MAJOR > 7)
  460. char *split;
  461. int plen, len, i;
  462. for (i = 0; proxynames[i].name; i++) {
  463. plen = strlen(proxynames[i].name);
  464. if (strncmp(url, proxynames[i].name, plen) == 0) {
  465. if (!(split = strchr(url, '|')))
  466. return url;
  467. *split = '\0';
  468. len = split - url;
  469. pool->rpc_proxy = malloc(1 + len - plen);
  470. if (!(pool->rpc_proxy))
  471. quit(1, "Failed to malloc rpc_proxy");
  472. strcpy(pool->rpc_proxy, url + plen);
  473. pool->rpc_proxytype = proxynames[i].proxytype;
  474. url = split + 1;
  475. break;
  476. }
  477. }
  478. #endif
  479. return url;
  480. }
  481. /* Returns a malloced array string of a binary value of arbitrary length. The
  482. * array is rounded up to a 4 byte size to appease architectures that need
  483. * aligned array sizes */
  484. char *bin2hex(const unsigned char *p, size_t len)
  485. {
  486. unsigned int i;
  487. ssize_t slen;
  488. char *s;
  489. slen = len * 2 + 1;
  490. if (slen % 4)
  491. slen += 4 - (slen % 4);
  492. s = calloc(slen, 1);
  493. if (unlikely(!s))
  494. quit(1, "Failed to calloc in bin2hex");
  495. for (i = 0; i < len; i++)
  496. sprintf(s + (i * 2), "%02x", (unsigned int) p[i]);
  497. return s;
  498. }
  499. /* Does the reverse of bin2hex but does not allocate any ram */
  500. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  501. {
  502. bool ret = false;
  503. while (*hexstr && len) {
  504. char hex_byte[4];
  505. unsigned int v;
  506. if (unlikely(!hexstr[1])) {
  507. applog(LOG_ERR, "hex2bin str truncated");
  508. return ret;
  509. }
  510. memset(hex_byte, 0, 4);
  511. hex_byte[0] = hexstr[0];
  512. hex_byte[1] = hexstr[1];
  513. if (unlikely(sscanf(hex_byte, "%x", &v) != 1)) {
  514. applog(LOG_ERR, "hex2bin sscanf '%s' failed", hex_byte);
  515. return ret;
  516. }
  517. *p = (unsigned char) v;
  518. p++;
  519. hexstr += 2;
  520. len--;
  521. }
  522. if (likely(len == 0 && *hexstr == 0))
  523. ret = true;
  524. return ret;
  525. }
  526. bool fulltest(const unsigned char *hash, const unsigned char *target)
  527. {
  528. unsigned char hash_swap[32], target_swap[32];
  529. uint32_t *hash32 = (uint32_t *) hash_swap;
  530. uint32_t *target32 = (uint32_t *) target_swap;
  531. char *hash_str, *target_str;
  532. bool rc = true;
  533. int i;
  534. swap256(hash_swap, hash);
  535. swap256(target_swap, target);
  536. for (i = 0; i < 32/4; i++) {
  537. #ifdef MIPSEB
  538. uint32_t h32tmp = hash32[i];
  539. uint32_t t32tmp = swab32(target32[i]);
  540. #else
  541. uint32_t h32tmp = swab32(hash32[i]);
  542. uint32_t t32tmp = target32[i];
  543. #endif
  544. target32[i] = swab32(target32[i]); /* for printing */
  545. if (h32tmp > t32tmp) {
  546. rc = false;
  547. break;
  548. }
  549. if (h32tmp < t32tmp) {
  550. rc = true;
  551. break;
  552. }
  553. }
  554. if (opt_debug) {
  555. hash_str = bin2hex(hash_swap, 32);
  556. target_str = bin2hex(target_swap, 32);
  557. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  558. hash_str,
  559. target_str,
  560. rc ? "YES (hash < target)" :
  561. "no (false positive; hash > target)");
  562. free(hash_str);
  563. free(target_str);
  564. }
  565. return rc;
  566. }
  567. struct thread_q *tq_new(void)
  568. {
  569. struct thread_q *tq;
  570. tq = calloc(1, sizeof(*tq));
  571. if (!tq)
  572. return NULL;
  573. INIT_LIST_HEAD(&tq->q);
  574. pthread_mutex_init(&tq->mutex, NULL);
  575. pthread_cond_init(&tq->cond, NULL);
  576. return tq;
  577. }
  578. void tq_free(struct thread_q *tq)
  579. {
  580. struct tq_ent *ent, *iter;
  581. if (!tq)
  582. return;
  583. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  584. list_del(&ent->q_node);
  585. free(ent);
  586. }
  587. pthread_cond_destroy(&tq->cond);
  588. pthread_mutex_destroy(&tq->mutex);
  589. memset(tq, 0, sizeof(*tq)); /* poison */
  590. free(tq);
  591. }
  592. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  593. {
  594. mutex_lock(&tq->mutex);
  595. tq->frozen = frozen;
  596. pthread_cond_signal(&tq->cond);
  597. mutex_unlock(&tq->mutex);
  598. }
  599. void tq_freeze(struct thread_q *tq)
  600. {
  601. tq_freezethaw(tq, true);
  602. }
  603. void tq_thaw(struct thread_q *tq)
  604. {
  605. tq_freezethaw(tq, false);
  606. }
  607. bool tq_push(struct thread_q *tq, void *data)
  608. {
  609. struct tq_ent *ent;
  610. bool rc = true;
  611. ent = calloc(1, sizeof(*ent));
  612. if (!ent)
  613. return false;
  614. ent->data = data;
  615. INIT_LIST_HEAD(&ent->q_node);
  616. mutex_lock(&tq->mutex);
  617. if (!tq->frozen) {
  618. list_add_tail(&ent->q_node, &tq->q);
  619. } else {
  620. free(ent);
  621. rc = false;
  622. }
  623. pthread_cond_signal(&tq->cond);
  624. mutex_unlock(&tq->mutex);
  625. return rc;
  626. }
  627. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  628. {
  629. struct tq_ent *ent;
  630. void *rval = NULL;
  631. int rc;
  632. mutex_lock(&tq->mutex);
  633. if (!list_empty(&tq->q))
  634. goto pop;
  635. if (abstime)
  636. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  637. else
  638. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  639. if (rc)
  640. goto out;
  641. if (list_empty(&tq->q))
  642. goto out;
  643. pop:
  644. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  645. rval = ent->data;
  646. list_del(&ent->q_node);
  647. free(ent);
  648. out:
  649. mutex_unlock(&tq->mutex);
  650. return rval;
  651. }
  652. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  653. {
  654. return pthread_create(&thr->pth, attr, start, arg);
  655. }
  656. void thr_info_freeze(struct thr_info *thr)
  657. {
  658. struct tq_ent *ent, *iter;
  659. struct thread_q *tq;
  660. if (!thr)
  661. return;
  662. tq = thr->q;
  663. if (!tq)
  664. return;
  665. mutex_lock(&tq->mutex);
  666. tq->frozen = true;
  667. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  668. list_del(&ent->q_node);
  669. free(ent);
  670. }
  671. mutex_unlock(&tq->mutex);
  672. }
  673. void thr_info_cancel(struct thr_info *thr)
  674. {
  675. if (!thr)
  676. return;
  677. if (PTH(thr) != 0L) {
  678. pthread_cancel(thr->pth);
  679. PTH(thr) = 0L;
  680. }
  681. }
  682. /* Provide a ms based sleep that uses nanosleep to avoid poor usleep accuracy
  683. * on SMP machines */
  684. void nmsleep(unsigned int msecs)
  685. {
  686. struct timespec twait, tleft;
  687. int ret;
  688. ldiv_t d;
  689. d = ldiv(msecs, 1000);
  690. tleft.tv_sec = d.quot;
  691. tleft.tv_nsec = d.rem * 1000000;
  692. do {
  693. twait.tv_sec = tleft.tv_sec;
  694. twait.tv_nsec = tleft.tv_nsec;
  695. ret = nanosleep(&twait, &tleft);
  696. } while (ret == -1 && errno == EINTR);
  697. }
  698. /* Returns the microseconds difference between end and start times as a double */
  699. double us_tdiff(struct timeval *end, struct timeval *start)
  700. {
  701. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  702. }
  703. /* Returns the seconds difference between end and start times as a double */
  704. double tdiff(struct timeval *end, struct timeval *start)
  705. {
  706. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  707. }
  708. bool extract_sockaddr(struct pool *pool, char *url)
  709. {
  710. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  711. char url_address[256], port[6];
  712. int url_len, port_len = 0;
  713. pool->sockaddr_url = url;
  714. url_begin = strstr(url, "//");
  715. if (!url_begin)
  716. url_begin = url;
  717. else
  718. url_begin += 2;
  719. /* Look for numeric ipv6 entries */
  720. ipv6_begin = strstr(url_begin, "[");
  721. ipv6_end = strstr(url_begin, "]");
  722. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  723. url_end = strstr(ipv6_end, ":");
  724. else
  725. url_end = strstr(url_begin, ":");
  726. if (url_end) {
  727. url_len = url_end - url_begin;
  728. port_len = strlen(url_begin) - url_len - 1;
  729. if (port_len < 1)
  730. return false;
  731. port_start = url_end + 1;
  732. } else
  733. url_len = strlen(url_begin);
  734. if (url_len < 1)
  735. return false;
  736. sprintf(url_address, "%.*s", url_len, url_begin);
  737. if (port_len)
  738. snprintf(port, 6, "%.*s", port_len, port_start);
  739. else
  740. strcpy(port, "80");
  741. pool->stratum_port = strdup(port);
  742. pool->sockaddr_url = strdup(url_address);
  743. return true;
  744. }
  745. /* Send a single command across a socket, appending \n to it. This should all
  746. * be done under stratum lock except when first establishing the socket */
  747. static bool __stratum_send(struct pool *pool, char *s, ssize_t len)
  748. {
  749. SOCKETTYPE sock = pool->sock;
  750. ssize_t ssent = 0;
  751. if (opt_protocol)
  752. applog(LOG_DEBUG, "SEND: %s", s);
  753. strcat(s, "\n");
  754. len++;
  755. while (len > 0 ) {
  756. struct timeval timeout = {1, 0};
  757. ssize_t sent;
  758. fd_set wd;
  759. FD_ZERO(&wd);
  760. FD_SET(sock, &wd);
  761. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  762. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  763. return false;
  764. }
  765. sent = send(pool->sock, s + ssent, len, 0);
  766. if (sent < 0) {
  767. if (errno != EAGAIN && errno != EWOULDBLOCK) {
  768. applog(LOG_DEBUG, "Failed to curl_easy_send in stratum_send");
  769. return false;
  770. }
  771. sent = 0;
  772. }
  773. ssent += sent;
  774. len -= sent;
  775. }
  776. pool->cgminer_pool_stats.times_sent++;
  777. pool->cgminer_pool_stats.bytes_sent += ssent;
  778. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  779. return true;
  780. }
  781. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  782. {
  783. bool ret = false;
  784. mutex_lock(&pool->stratum_lock);
  785. if (pool->stratum_active)
  786. ret = __stratum_send(pool, s, len);
  787. else
  788. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  789. mutex_unlock(&pool->stratum_lock);
  790. return ret;
  791. }
  792. static bool socket_full(struct pool *pool, bool wait)
  793. {
  794. SOCKETTYPE sock = pool->sock;
  795. struct timeval timeout;
  796. fd_set rd;
  797. FD_ZERO(&rd);
  798. FD_SET(sock, &rd);
  799. timeout.tv_usec = 0;
  800. if (wait)
  801. timeout.tv_sec = 60;
  802. else
  803. timeout.tv_sec = 1;
  804. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  805. return true;
  806. return false;
  807. }
  808. /* Check to see if Santa's been good to you */
  809. bool sock_full(struct pool *pool)
  810. {
  811. if (strlen(pool->sockbuf))
  812. return true;
  813. return (socket_full(pool, false));
  814. }
  815. static void clear_sockbuf(struct pool *pool)
  816. {
  817. strcpy(pool->sockbuf, "");
  818. }
  819. static void clear_sock(struct pool *pool)
  820. {
  821. ssize_t n;
  822. mutex_lock(&pool->stratum_lock);
  823. do {
  824. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  825. } while (n > 0);
  826. mutex_unlock(&pool->stratum_lock);
  827. clear_sockbuf(pool);
  828. }
  829. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  830. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  831. * and zeroing the new memory */
  832. static void recalloc_sock(struct pool *pool, size_t len)
  833. {
  834. size_t old, new;
  835. old = strlen(pool->sockbuf);
  836. new = old + len + 1;
  837. if (new < pool->sockbuf_size)
  838. return;
  839. new = new + (RBUFSIZE - (new % RBUFSIZE));
  840. applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  841. pool->sockbuf = realloc(pool->sockbuf, new);
  842. if (!pool->sockbuf)
  843. quit(1, "Failed to realloc pool sockbuf in recalloc_sock");
  844. memset(pool->sockbuf + old, 0, new - old);
  845. pool->sockbuf_size = new;
  846. }
  847. /* Peeks at a socket to find the first end of line and then reads just that
  848. * from the socket and returns that as a malloced char */
  849. char *recv_line(struct pool *pool)
  850. {
  851. ssize_t len, buflen;
  852. char *tok, *sret = NULL;
  853. if (!strstr(pool->sockbuf, "\n")) {
  854. struct timeval rstart, now;
  855. gettimeofday(&rstart, NULL);
  856. if (!socket_full(pool, true)) {
  857. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  858. goto out;
  859. }
  860. mutex_lock(&pool->stratum_lock);
  861. do {
  862. char s[RBUFSIZE];
  863. size_t slen;
  864. ssize_t n;
  865. memset(s, 0, RBUFSIZE);
  866. n = recv(pool->sock, s, RECVSIZE, 0);
  867. if (!n) {
  868. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  869. break;
  870. }
  871. if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
  872. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  873. break;
  874. }
  875. slen = strlen(s);
  876. recalloc_sock(pool, slen);
  877. strcat(pool->sockbuf, s);
  878. gettimeofday(&now, NULL);
  879. } while (tdiff(&now, &rstart) < 60 && !strstr(pool->sockbuf, "\n"));
  880. mutex_unlock(&pool->stratum_lock);
  881. }
  882. buflen = strlen(pool->sockbuf);
  883. tok = strtok(pool->sockbuf, "\n");
  884. if (!tok) {
  885. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  886. goto out;
  887. }
  888. sret = strdup(tok);
  889. len = strlen(sret);
  890. /* Copy what's left in the buffer after the \n, including the
  891. * terminating \0 */
  892. if (buflen > len + 1)
  893. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  894. else
  895. strcpy(pool->sockbuf, "");
  896. pool->cgminer_pool_stats.times_received++;
  897. pool->cgminer_pool_stats.bytes_received += len;
  898. pool->cgminer_pool_stats.net_bytes_received += len;
  899. out:
  900. if (!sret)
  901. clear_sock(pool);
  902. else if (opt_protocol)
  903. applog(LOG_DEBUG, "RECVD: %s", sret);
  904. return sret;
  905. }
  906. /* Extracts a string value from a json array with error checking. To be used
  907. * when the value of the string returned is only examined and not to be stored.
  908. * See json_array_string below */
  909. static char *__json_array_string(json_t *val, unsigned int entry)
  910. {
  911. json_t *arr_entry;
  912. if (json_is_null(val))
  913. return NULL;
  914. if (!json_is_array(val))
  915. return NULL;
  916. if (entry > json_array_size(val))
  917. return NULL;
  918. arr_entry = json_array_get(val, entry);
  919. if (!json_is_string(arr_entry))
  920. return NULL;
  921. return (char *)json_string_value(arr_entry);
  922. }
  923. /* Creates a freshly malloced dup of __json_array_string */
  924. static char *json_array_string(json_t *val, unsigned int entry)
  925. {
  926. char *buf = __json_array_string(val, entry);
  927. if (buf)
  928. return strdup(buf);
  929. return NULL;
  930. }
  931. static bool parse_notify(struct pool *pool, json_t *val)
  932. {
  933. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  934. bool clean, ret = false;
  935. int merkles, i;
  936. json_t *arr;
  937. arr = json_array_get(val, 4);
  938. if (!arr || !json_is_array(arr))
  939. goto out;
  940. merkles = json_array_size(arr);
  941. job_id = json_array_string(val, 0);
  942. prev_hash = json_array_string(val, 1);
  943. coinbase1 = json_array_string(val, 2);
  944. coinbase2 = json_array_string(val, 3);
  945. bbversion = json_array_string(val, 5);
  946. nbit = json_array_string(val, 6);
  947. ntime = json_array_string(val, 7);
  948. clean = json_is_true(json_array_get(val, 8));
  949. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  950. /* Annoying but we must not leak memory */
  951. if (job_id)
  952. free(job_id);
  953. if (prev_hash)
  954. free(prev_hash);
  955. if (coinbase1)
  956. free(coinbase1);
  957. if (coinbase2)
  958. free(coinbase2);
  959. if (bbversion)
  960. free(bbversion);
  961. if (nbit)
  962. free(nbit);
  963. if (ntime)
  964. free(ntime);
  965. goto out;
  966. }
  967. cg_wlock(&pool->data_lock);
  968. free(pool->swork.job_id);
  969. free(pool->swork.prev_hash);
  970. free(pool->swork.coinbase1);
  971. free(pool->swork.coinbase2);
  972. free(pool->swork.bbversion);
  973. free(pool->swork.nbit);
  974. free(pool->swork.ntime);
  975. pool->swork.job_id = job_id;
  976. pool->swork.prev_hash = prev_hash;
  977. pool->swork.coinbase1 = coinbase1;
  978. pool->swork.cb1_len = strlen(coinbase1) / 2;
  979. pool->swork.coinbase2 = coinbase2;
  980. pool->swork.cb2_len = strlen(coinbase2) / 2;
  981. pool->swork.bbversion = bbversion;
  982. pool->swork.nbit = nbit;
  983. pool->swork.ntime = ntime;
  984. pool->swork.clean = clean;
  985. pool->swork.cb_len = pool->swork.cb1_len + pool->n1_len + pool->n2size + pool->swork.cb2_len;
  986. for (i = 0; i < pool->swork.merkles; i++)
  987. free(pool->swork.merkle[i]);
  988. if (merkles) {
  989. pool->swork.merkle = realloc(pool->swork.merkle, sizeof(char *) * merkles + 1);
  990. for (i = 0; i < merkles; i++)
  991. pool->swork.merkle[i] = json_array_string(arr, i);
  992. }
  993. pool->swork.merkles = merkles;
  994. if (clean)
  995. pool->nonce2 = 0;
  996. pool->swork.header_len = strlen(pool->swork.bbversion) +
  997. strlen(pool->swork.prev_hash) +
  998. strlen(pool->swork.ntime) +
  999. strlen(pool->swork.nbit) +
  1000. /* merkle_hash */ 32 +
  1001. /* nonce */ 8 +
  1002. /* workpadding */ 96;
  1003. pool->swork.header_len = pool->swork.header_len * 2 + 1;
  1004. align_len(&pool->swork.header_len);
  1005. cg_wunlock(&pool->data_lock);
  1006. if (opt_protocol) {
  1007. applog(LOG_DEBUG, "job_id: %s", job_id);
  1008. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1009. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1010. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1011. for (i = 0; i < merkles; i++)
  1012. applog(LOG_DEBUG, "merkle%d: %s", i, pool->swork.merkle[i]);
  1013. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1014. applog(LOG_DEBUG, "nbit: %s", nbit);
  1015. applog(LOG_DEBUG, "ntime: %s", ntime);
  1016. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1017. }
  1018. /* A notify message is the closest stratum gets to a getwork */
  1019. pool->getwork_requested++;
  1020. total_getworks++;
  1021. ret = true;
  1022. out:
  1023. return ret;
  1024. }
  1025. static bool parse_diff(struct pool *pool, json_t *val)
  1026. {
  1027. double diff;
  1028. diff = json_number_value(json_array_get(val, 0));
  1029. if (diff == 0)
  1030. return false;
  1031. cg_wlock(&pool->data_lock);
  1032. pool->swork.diff = diff;
  1033. cg_wunlock(&pool->data_lock);
  1034. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no, diff);
  1035. return true;
  1036. }
  1037. static bool parse_reconnect(struct pool *pool, json_t *val)
  1038. {
  1039. char *url, *port, address[256];
  1040. memset(address, 0, 255);
  1041. url = (char *)json_string_value(json_array_get(val, 0));
  1042. if (!url)
  1043. url = pool->sockaddr_url;
  1044. port = (char *)json_string_value(json_array_get(val, 1));
  1045. if (!port)
  1046. port = pool->stratum_port;
  1047. sprintf(address, "%s:%s", url, port);
  1048. if (!extract_sockaddr(pool, address))
  1049. return false;
  1050. pool->stratum_url = pool->sockaddr_url;
  1051. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1052. if (!restart_stratum(pool))
  1053. return false;
  1054. return true;
  1055. }
  1056. static bool send_version(struct pool *pool, json_t *val)
  1057. {
  1058. char s[RBUFSIZE];
  1059. int id = json_integer_value(json_object_get(val, "id"));
  1060. if (!id)
  1061. return false;
  1062. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  1063. if (!stratum_send(pool, s, strlen(s)))
  1064. return false;
  1065. return true;
  1066. }
  1067. static bool show_message(struct pool *pool, json_t *val)
  1068. {
  1069. char *msg;
  1070. if (!json_is_array(val))
  1071. return false;
  1072. msg = (char *)json_string_value(json_array_get(val, 0));
  1073. if (!msg)
  1074. return false;
  1075. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  1076. return true;
  1077. }
  1078. bool parse_method(struct pool *pool, char *s)
  1079. {
  1080. json_t *val = NULL, *method, *err_val, *params;
  1081. json_error_t err;
  1082. bool ret = false;
  1083. char *buf;
  1084. if (!s)
  1085. goto out;
  1086. val = JSON_LOADS(s, &err);
  1087. if (!val) {
  1088. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1089. goto out;
  1090. }
  1091. method = json_object_get(val, "method");
  1092. if (!method)
  1093. goto out;
  1094. err_val = json_object_get(val, "error");
  1095. params = json_object_get(val, "params");
  1096. if (err_val && !json_is_null(err_val)) {
  1097. char *ss;
  1098. if (err_val)
  1099. ss = json_dumps(err_val, JSON_INDENT(3));
  1100. else
  1101. ss = strdup("(unknown reason)");
  1102. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1103. free(ss);
  1104. goto out;
  1105. }
  1106. buf = (char *)json_string_value(method);
  1107. if (!buf)
  1108. goto out;
  1109. if (!strncasecmp(buf, "mining.notify", 13)) {
  1110. if (parse_notify(pool, params))
  1111. pool->stratum_notify = ret = true;
  1112. else
  1113. pool->stratum_notify = ret = false;
  1114. goto out;
  1115. }
  1116. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1117. ret = true;
  1118. goto out;
  1119. }
  1120. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1121. ret = true;
  1122. goto out;
  1123. }
  1124. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1125. ret = true;
  1126. goto out;
  1127. }
  1128. if (!strncasecmp(buf, "client.show_message", 19) && show_message(pool, params)) {
  1129. ret = true;
  1130. goto out;
  1131. }
  1132. out:
  1133. if (val)
  1134. json_decref(val);
  1135. return ret;
  1136. }
  1137. bool auth_stratum(struct pool *pool)
  1138. {
  1139. json_t *val = NULL, *res_val, *err_val;
  1140. char s[RBUFSIZE], *sret = NULL;
  1141. json_error_t err;
  1142. bool ret = false;
  1143. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1144. swork_id++, pool->rpc_user, pool->rpc_pass);
  1145. if (!stratum_send(pool, s, strlen(s)))
  1146. goto out;
  1147. /* Parse all data in the queue and anything left should be auth */
  1148. while (42) {
  1149. sret = recv_line(pool);
  1150. if (!sret)
  1151. goto out;
  1152. if (parse_method(pool, sret))
  1153. free(sret);
  1154. else
  1155. break;
  1156. }
  1157. val = JSON_LOADS(sret, &err);
  1158. free(sret);
  1159. res_val = json_object_get(val, "result");
  1160. err_val = json_object_get(val, "error");
  1161. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1162. char *ss;
  1163. if (err_val)
  1164. ss = json_dumps(err_val, JSON_INDENT(3));
  1165. else
  1166. ss = strdup("(unknown reason)");
  1167. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1168. free(ss);
  1169. goto out;
  1170. }
  1171. ret = true;
  1172. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1173. pool->probed = true;
  1174. successful_connect = true;
  1175. out:
  1176. if (val)
  1177. json_decref(val);
  1178. return ret;
  1179. }
  1180. static bool setup_stratum_curl(struct pool *pool)
  1181. {
  1182. char curl_err_str[CURL_ERROR_SIZE];
  1183. CURL *curl = NULL;
  1184. double byte_count;
  1185. char s[RBUFSIZE];
  1186. mutex_lock(&pool->stratum_lock);
  1187. pool->stratum_active = false;
  1188. if (pool->stratum_curl) {
  1189. #if CURL_HAS_KEEPALIVE
  1190. curl_easy_cleanup(pool->stratum_curl);
  1191. #else
  1192. /* See above in suspend_stratum */
  1193. CLOSESOCKET(pool->sock);
  1194. #endif
  1195. }
  1196. pool->stratum_curl = curl_easy_init();
  1197. if (unlikely(!pool->stratum_curl))
  1198. quit(1, "Failed to curl_easy_init in initiate_stratum");
  1199. mutex_unlock(&pool->stratum_lock);
  1200. curl = pool->stratum_curl;
  1201. if (!pool->sockbuf) {
  1202. pool->sockbuf = calloc(RBUFSIZE, 1);
  1203. if (!pool->sockbuf)
  1204. quit(1, "Failed to calloc pool sockbuf in initiate_stratum");
  1205. pool->sockbuf_size = RBUFSIZE;
  1206. }
  1207. /* Create a http url for use with curl */
  1208. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1209. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1210. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1211. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1212. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1213. curl_easy_setopt(curl, CURLOPT_URL, s);
  1214. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1215. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1216. if (pool->rpc_proxy) {
  1217. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1218. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  1219. } else if (opt_socks_proxy) {
  1220. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1221. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  1222. }
  1223. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1224. if (curl_easy_perform(curl)) {
  1225. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1226. return false;
  1227. }
  1228. curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, (long *)&pool->sock);
  1229. keep_alive(curl, pool->sock);
  1230. pool->cgminer_pool_stats.times_sent++;
  1231. if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK)
  1232. pool->cgminer_pool_stats.bytes_sent += byte_count;
  1233. pool->cgminer_pool_stats.times_received++;
  1234. if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK)
  1235. pool->cgminer_pool_stats.bytes_received += byte_count;
  1236. return true;
  1237. }
  1238. static char *get_sessionid(json_t *val)
  1239. {
  1240. char *ret = NULL;
  1241. json_t *arr_val;
  1242. int arrsize, i;
  1243. arr_val = json_array_get(val, 0);
  1244. if (!arr_val || !json_is_array(arr_val))
  1245. goto out;
  1246. arrsize = json_array_size(arr_val);
  1247. for (i = 0; i < arrsize; i++) {
  1248. json_t *arr = json_array_get(arr_val, i);
  1249. char *notify;
  1250. if (!arr | !json_is_array(arr))
  1251. break;
  1252. notify = __json_array_string(arr, 0);
  1253. if (!notify)
  1254. continue;
  1255. if (!strncasecmp(notify, "mining.notify", 13)) {
  1256. ret = json_array_string(arr, 1);
  1257. break;
  1258. }
  1259. }
  1260. out:
  1261. return ret;
  1262. }
  1263. void suspend_stratum(struct pool *pool)
  1264. {
  1265. clear_sockbuf(pool);
  1266. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1267. mutex_lock(&pool->stratum_lock);
  1268. pool->stratum_active = pool->stratum_notify = false;
  1269. if (pool->stratum_curl) {
  1270. #if CURL_HAS_KEEPALIVE
  1271. curl_easy_cleanup(pool->stratum_curl);
  1272. #else
  1273. /* Old versions of libcurl seem to crash occasionally on this since
  1274. * the socket is modified in keep_sockalive in ways curl does not
  1275. * know about so sacrifice the ram knowing we leak one curl handle
  1276. * every time we disconnect stratum. */
  1277. CLOSESOCKET(pool->sock);
  1278. #endif
  1279. }
  1280. pool->stratum_curl = NULL;
  1281. mutex_unlock(&pool->stratum_lock);
  1282. }
  1283. bool initiate_stratum(struct pool *pool)
  1284. {
  1285. bool ret = false, recvd = false, noresume = false, sockd = false;
  1286. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  1287. json_t *val = NULL, *res_val, *err_val;
  1288. json_error_t err;
  1289. int n2size;
  1290. resend:
  1291. if (!setup_stratum_curl(pool)) {
  1292. sockd = false;
  1293. goto out;
  1294. }
  1295. sockd = true;
  1296. if (recvd) {
  1297. /* Get rid of any crap lying around if we're resending */
  1298. clear_sock(pool);
  1299. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1300. } else {
  1301. if (pool->sessionid)
  1302. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  1303. else
  1304. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  1305. }
  1306. if (!__stratum_send(pool, s, strlen(s))) {
  1307. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1308. goto out;
  1309. }
  1310. if (!socket_full(pool, true)) {
  1311. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1312. goto out;
  1313. }
  1314. sret = recv_line(pool);
  1315. if (!sret)
  1316. goto out;
  1317. recvd = true;
  1318. val = JSON_LOADS(sret, &err);
  1319. free(sret);
  1320. if (!val) {
  1321. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1322. goto out;
  1323. }
  1324. res_val = json_object_get(val, "result");
  1325. err_val = json_object_get(val, "error");
  1326. if (!res_val || json_is_null(res_val) ||
  1327. (err_val && !json_is_null(err_val))) {
  1328. char *ss;
  1329. if (err_val)
  1330. ss = json_dumps(err_val, JSON_INDENT(3));
  1331. else
  1332. ss = strdup("(unknown reason)");
  1333. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1334. free(ss);
  1335. goto out;
  1336. }
  1337. sessionid = get_sessionid(res_val);
  1338. if (!sessionid)
  1339. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  1340. nonce1 = json_array_string(res_val, 1);
  1341. if (!nonce1) {
  1342. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1343. free(sessionid);
  1344. goto out;
  1345. }
  1346. n2size = json_integer_value(json_array_get(res_val, 2));
  1347. if (!n2size) {
  1348. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1349. free(sessionid);
  1350. free(nonce1);
  1351. goto out;
  1352. }
  1353. cg_wlock(&pool->data_lock);
  1354. pool->sessionid = sessionid;
  1355. pool->nonce1 = nonce1;
  1356. pool->n1_len = strlen(nonce1) / 2;
  1357. pool->n2size = n2size;
  1358. cg_wunlock(&pool->data_lock);
  1359. if (sessionid)
  1360. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  1361. ret = true;
  1362. out:
  1363. if (val)
  1364. json_decref(val);
  1365. if (ret) {
  1366. if (!pool->stratum_url)
  1367. pool->stratum_url = pool->sockaddr_url;
  1368. pool->stratum_active = true;
  1369. pool->swork.diff = 1;
  1370. if (opt_protocol) {
  1371. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  1372. pool->pool_no, pool->nonce1, pool->n2size);
  1373. }
  1374. } else {
  1375. if (recvd && !noresume) {
  1376. /* Reset the sessionid used for stratum resuming in case the pool
  1377. * does not support it, or does not know how to respond to the
  1378. * presence of the sessionid parameter. */
  1379. cg_wlock(&pool->data_lock);
  1380. free(pool->sessionid);
  1381. free(pool->nonce1);
  1382. pool->sessionid = pool->nonce1 = NULL;
  1383. cg_wunlock(&pool->data_lock);
  1384. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  1385. noresume = true;
  1386. goto resend;
  1387. }
  1388. applog(LOG_DEBUG, "Initiate stratum failed");
  1389. if (sockd)
  1390. suspend_stratum(pool);
  1391. }
  1392. return ret;
  1393. }
  1394. bool restart_stratum(struct pool *pool)
  1395. {
  1396. if (pool->stratum_active)
  1397. suspend_stratum(pool);
  1398. if (!initiate_stratum(pool))
  1399. return false;
  1400. if (!auth_stratum(pool))
  1401. return false;
  1402. return true;
  1403. }
  1404. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  1405. {
  1406. dev->device_last_not_well = time(NULL);
  1407. dev->device_not_well_reason = reason;
  1408. switch (reason) {
  1409. case REASON_THREAD_FAIL_INIT:
  1410. dev->thread_fail_init_count++;
  1411. break;
  1412. case REASON_THREAD_ZERO_HASH:
  1413. dev->thread_zero_hash_count++;
  1414. break;
  1415. case REASON_THREAD_FAIL_QUEUE:
  1416. dev->thread_fail_queue_count++;
  1417. break;
  1418. case REASON_DEV_SICK_IDLE_60:
  1419. dev->dev_sick_idle_60_count++;
  1420. break;
  1421. case REASON_DEV_DEAD_IDLE_600:
  1422. dev->dev_dead_idle_600_count++;
  1423. break;
  1424. case REASON_DEV_NOSTART:
  1425. dev->dev_nostart_count++;
  1426. break;
  1427. case REASON_DEV_OVER_HEAT:
  1428. dev->dev_over_heat_count++;
  1429. break;
  1430. case REASON_DEV_THERMAL_CUTOFF:
  1431. dev->dev_thermal_cutoff_count++;
  1432. break;
  1433. case REASON_DEV_COMMS_ERROR:
  1434. dev->dev_comms_error_count++;
  1435. break;
  1436. case REASON_DEV_THROTTLE:
  1437. dev->dev_throttle_count++;
  1438. break;
  1439. }
  1440. }
  1441. /* Realloc an existing string to fit an extra string s, appending s to it. */
  1442. void *realloc_strcat(char *ptr, char *s)
  1443. {
  1444. size_t old = strlen(ptr), len = strlen(s);
  1445. char *ret;
  1446. if (!len)
  1447. return ptr;
  1448. len += old + 1;
  1449. align_len(&len);
  1450. ret = malloc(len);
  1451. if (unlikely(!ret))
  1452. quit(1, "Failed to malloc in realloc_strcat");
  1453. sprintf(ret, "%s%s", ptr, s);
  1454. free(ptr);
  1455. return ret;
  1456. }
  1457. void RenameThread(const char* name)
  1458. {
  1459. #if defined(PR_SET_NAME)
  1460. // Only the first 15 characters are used (16 - NUL terminator)
  1461. prctl(PR_SET_NAME, name, 0, 0, 0);
  1462. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  1463. pthread_set_name_np(pthread_self(), name);
  1464. #elif defined(MAC_OSX)
  1465. pthread_setname_np(name);
  1466. #else
  1467. // Prevent warnings for unused parameters...
  1468. (void)name;
  1469. #endif
  1470. }