util.c 42 KB

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