util.c 57 KB

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