util.c 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678
  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. /* Adequate size s==len*2 + 1 must be alloced to use this variant */
  496. void __bin2hex(char *s, const unsigned char *p, size_t len)
  497. {
  498. int i;
  499. static const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  500. for (i = 0; i < (int)len; i++) {
  501. *s++ = hex[p[i] >> 4];
  502. *s++ = hex[p[i] & 0xF];
  503. }
  504. *s++ = '\0';
  505. }
  506. /* Returns a malloced array string of a binary value of arbitrary length. The
  507. * array is rounded up to a 4 byte size to appease architectures that need
  508. * aligned array sizes */
  509. char *bin2hex(const unsigned char *p, size_t len)
  510. {
  511. ssize_t slen;
  512. char *s;
  513. slen = len * 2 + 1;
  514. if (slen % 4)
  515. slen += 4 - (slen % 4);
  516. s = calloc(slen, 1);
  517. if (unlikely(!s))
  518. quithere(1, "Failed to calloc");
  519. __bin2hex(s, p, len);
  520. return s;
  521. }
  522. /* Does the reverse of bin2hex but does not allocate any ram */
  523. static const int hex2bin_tbl[256] = {
  524. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  525. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  526. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  527. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  528. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  529. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  530. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  531. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  532. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  533. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  534. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  535. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  536. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  537. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  538. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  539. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  540. };
  541. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  542. {
  543. int nibble1, nibble2;
  544. unsigned char idx;
  545. bool ret = false;
  546. while (*hexstr && len) {
  547. if (unlikely(!hexstr[1])) {
  548. applog(LOG_ERR, "hex2bin str truncated");
  549. return ret;
  550. }
  551. idx = *hexstr++;
  552. nibble1 = hex2bin_tbl[idx];
  553. idx = *hexstr++;
  554. nibble2 = hex2bin_tbl[idx];
  555. if (unlikely((nibble1 < 0) || (nibble2 < 0))) {
  556. applog(LOG_ERR, "hex2bin scan failed");
  557. return ret;
  558. }
  559. *p++ = (((unsigned char)nibble1) << 4) | ((unsigned char)nibble2);
  560. --len;
  561. }
  562. if (likely(len == 0 && *hexstr == 0))
  563. ret = true;
  564. return ret;
  565. }
  566. bool fulltest(const unsigned char *hash, const unsigned char *target)
  567. {
  568. unsigned char hash_swap[32], target_swap[32];
  569. uint32_t *hash32 = (uint32_t *) hash_swap;
  570. uint32_t *target32 = (uint32_t *) target_swap;
  571. char *hash_str, *target_str;
  572. bool rc = true;
  573. int i;
  574. swap256(hash_swap, hash);
  575. swap256(target_swap, target);
  576. for (i = 0; i < 32/4; i++) {
  577. uint32_t h32tmp = htobe32(hash32[i]);
  578. uint32_t t32tmp = htole32(target32[i]);
  579. target32[i] = swab32(target32[i]); /* for printing */
  580. if (h32tmp > t32tmp) {
  581. rc = false;
  582. break;
  583. }
  584. if (h32tmp < t32tmp) {
  585. rc = true;
  586. break;
  587. }
  588. }
  589. if (opt_debug) {
  590. hash_str = bin2hex(hash_swap, 32);
  591. target_str = bin2hex(target_swap, 32);
  592. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  593. hash_str,
  594. target_str,
  595. rc ? "YES (hash <= target)" :
  596. "no (false positive; hash > target)");
  597. free(hash_str);
  598. free(target_str);
  599. }
  600. return rc;
  601. }
  602. struct thread_q *tq_new(void)
  603. {
  604. struct thread_q *tq;
  605. tq = calloc(1, sizeof(*tq));
  606. if (!tq)
  607. return NULL;
  608. INIT_LIST_HEAD(&tq->q);
  609. pthread_mutex_init(&tq->mutex, NULL);
  610. pthread_cond_init(&tq->cond, NULL);
  611. return tq;
  612. }
  613. void tq_free(struct thread_q *tq)
  614. {
  615. struct tq_ent *ent, *iter;
  616. if (!tq)
  617. return;
  618. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  619. list_del(&ent->q_node);
  620. free(ent);
  621. }
  622. pthread_cond_destroy(&tq->cond);
  623. pthread_mutex_destroy(&tq->mutex);
  624. memset(tq, 0, sizeof(*tq)); /* poison */
  625. free(tq);
  626. }
  627. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  628. {
  629. mutex_lock(&tq->mutex);
  630. tq->frozen = frozen;
  631. pthread_cond_signal(&tq->cond);
  632. mutex_unlock(&tq->mutex);
  633. }
  634. void tq_freeze(struct thread_q *tq)
  635. {
  636. tq_freezethaw(tq, true);
  637. }
  638. void tq_thaw(struct thread_q *tq)
  639. {
  640. tq_freezethaw(tq, false);
  641. }
  642. bool tq_push(struct thread_q *tq, void *data)
  643. {
  644. struct tq_ent *ent;
  645. bool rc = true;
  646. ent = calloc(1, sizeof(*ent));
  647. if (!ent)
  648. return false;
  649. ent->data = data;
  650. INIT_LIST_HEAD(&ent->q_node);
  651. mutex_lock(&tq->mutex);
  652. if (!tq->frozen) {
  653. list_add_tail(&ent->q_node, &tq->q);
  654. } else {
  655. free(ent);
  656. rc = false;
  657. }
  658. pthread_cond_signal(&tq->cond);
  659. mutex_unlock(&tq->mutex);
  660. return rc;
  661. }
  662. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  663. {
  664. struct tq_ent *ent;
  665. void *rval = NULL;
  666. int rc;
  667. mutex_lock(&tq->mutex);
  668. if (!list_empty(&tq->q))
  669. goto pop;
  670. if (abstime)
  671. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  672. else
  673. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  674. if (rc)
  675. goto out;
  676. if (list_empty(&tq->q))
  677. goto out;
  678. pop:
  679. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  680. rval = ent->data;
  681. list_del(&ent->q_node);
  682. free(ent);
  683. out:
  684. mutex_unlock(&tq->mutex);
  685. return rval;
  686. }
  687. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  688. {
  689. cgsem_init(&thr->sem);
  690. return pthread_create(&thr->pth, attr, start, arg);
  691. }
  692. void thr_info_cancel(struct thr_info *thr)
  693. {
  694. if (!thr)
  695. return;
  696. if (PTH(thr) != 0L) {
  697. pthread_cancel(thr->pth);
  698. PTH(thr) = 0L;
  699. }
  700. cgsem_destroy(&thr->sem);
  701. }
  702. void subtime(struct timeval *a, struct timeval *b)
  703. {
  704. timersub(a, b, b);
  705. }
  706. void addtime(struct timeval *a, struct timeval *b)
  707. {
  708. timeradd(a, b, b);
  709. }
  710. bool time_more(struct timeval *a, struct timeval *b)
  711. {
  712. return timercmp(a, b, >);
  713. }
  714. bool time_less(struct timeval *a, struct timeval *b)
  715. {
  716. return timercmp(a, b, <);
  717. }
  718. void copy_time(struct timeval *dest, const struct timeval *src)
  719. {
  720. memcpy(dest, src, sizeof(struct timeval));
  721. }
  722. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  723. {
  724. val->tv_sec = spec->tv_sec;
  725. val->tv_usec = spec->tv_nsec / 1000;
  726. }
  727. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  728. {
  729. spec->tv_sec = val->tv_sec;
  730. spec->tv_nsec = val->tv_usec * 1000;
  731. }
  732. void us_to_timeval(struct timeval *val, int64_t us)
  733. {
  734. lldiv_t tvdiv = lldiv(us, 1000000);
  735. val->tv_sec = tvdiv.quot;
  736. val->tv_usec = tvdiv.rem;
  737. }
  738. void us_to_timespec(struct timespec *spec, int64_t us)
  739. {
  740. lldiv_t tvdiv = lldiv(us, 1000000);
  741. spec->tv_sec = tvdiv.quot;
  742. spec->tv_nsec = tvdiv.rem * 1000;
  743. }
  744. void ms_to_timespec(struct timespec *spec, int64_t ms)
  745. {
  746. lldiv_t tvdiv = lldiv(ms, 1000);
  747. spec->tv_sec = tvdiv.quot;
  748. spec->tv_nsec = tvdiv.rem * 1000000;
  749. }
  750. void ms_to_timeval(struct timeval *val, int64_t ms)
  751. {
  752. lldiv_t tvdiv = lldiv(ms, 1000);
  753. val->tv_sec = tvdiv.quot;
  754. val->tv_usec = tvdiv.rem * 1000;
  755. }
  756. void timeraddspec(struct timespec *a, const struct timespec *b)
  757. {
  758. a->tv_sec += b->tv_sec;
  759. a->tv_nsec += b->tv_nsec;
  760. if (a->tv_nsec >= 1000000000) {
  761. a->tv_nsec -= 1000000000;
  762. a->tv_sec++;
  763. }
  764. }
  765. static int __maybe_unused timespec_to_ms(struct timespec *ts)
  766. {
  767. return ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
  768. }
  769. /* Subtract b from a */
  770. static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b)
  771. {
  772. a->tv_sec -= b->tv_sec;
  773. a->tv_nsec -= b->tv_nsec;
  774. if (a->tv_nsec < 0) {
  775. a->tv_nsec += 1000000000;
  776. a->tv_sec--;
  777. }
  778. }
  779. /* These are cgminer specific sleep functions that use an absolute nanosecond
  780. * resolution timer to avoid poor usleep accuracy and overruns. */
  781. #ifdef WIN32
  782. /* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */
  783. #define EPOCHFILETIME (116444736000000000LL)
  784. /* Return the system time as an lldiv_t in decimicroseconds. */
  785. static void decius_time(lldiv_t *lidiv)
  786. {
  787. FILETIME ft;
  788. LARGE_INTEGER li;
  789. GetSystemTimeAsFileTime(&ft);
  790. li.LowPart = ft.dwLowDateTime;
  791. li.HighPart = ft.dwHighDateTime;
  792. li.QuadPart -= EPOCHFILETIME;
  793. /* SystemTime is in decimicroseconds so divide by an unusual number */
  794. *lidiv = lldiv(li.QuadPart, 10000000);
  795. }
  796. /* This is a cgminer gettimeofday wrapper. Since we always call gettimeofday
  797. * with tz set to NULL, and windows' default resolution is only 15ms, this
  798. * gives us higher resolution times on windows. */
  799. void cgtime(struct timeval *tv)
  800. {
  801. lldiv_t lidiv;
  802. decius_time(&lidiv);
  803. tv->tv_sec = lidiv.quot;
  804. tv->tv_usec = lidiv.rem / 10;
  805. }
  806. #else /* WIN32 */
  807. void cgtime(struct timeval *tv)
  808. {
  809. gettimeofday(tv, NULL);
  810. }
  811. int cgtimer_to_ms(cgtimer_t *cgt)
  812. {
  813. return timespec_to_ms(cgt);
  814. }
  815. /* Subtracts b from a and stores it in res. */
  816. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  817. {
  818. res->tv_sec = a->tv_sec - b->tv_sec;
  819. res->tv_nsec = a->tv_nsec - b->tv_nsec;
  820. if (res->tv_nsec < 0) {
  821. res->tv_nsec += 1000000000;
  822. res->tv_sec--;
  823. }
  824. }
  825. #endif /* WIN32 */
  826. #ifdef CLOCK_MONOTONIC /* Essentially just linux */
  827. void cgtimer_time(cgtimer_t *ts_start)
  828. {
  829. clock_gettime(CLOCK_MONOTONIC, ts_start);
  830. }
  831. static void nanosleep_abstime(struct timespec *ts_end)
  832. {
  833. int ret;
  834. do {
  835. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  836. } while (ret == EINTR);
  837. }
  838. /* Reentrant version of cgsleep functions allow start time to be set separately
  839. * from the beginning of the actual sleep, allowing scheduling delays to be
  840. * counted in the sleep. */
  841. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  842. {
  843. struct timespec ts_end;
  844. ms_to_timespec(&ts_end, ms);
  845. timeraddspec(&ts_end, ts_start);
  846. nanosleep_abstime(&ts_end);
  847. }
  848. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  849. {
  850. struct timespec ts_end;
  851. us_to_timespec(&ts_end, us);
  852. timeraddspec(&ts_end, ts_start);
  853. nanosleep_abstime(&ts_end);
  854. }
  855. #else /* CLOCK_MONOTONIC */
  856. #ifdef __MACH__
  857. #include <mach/clock.h>
  858. #include <mach/mach.h>
  859. void cgtimer_time(cgtimer_t *ts_start)
  860. {
  861. clock_serv_t cclock;
  862. mach_timespec_t mts;
  863. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  864. clock_get_time(cclock, &mts);
  865. mach_port_deallocate(mach_task_self(), cclock);
  866. ts_start->tv_sec = mts.tv_sec;
  867. ts_start->tv_nsec = mts.tv_nsec;
  868. }
  869. #elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */
  870. void cgtimer_time(cgtimer_t *ts_start)
  871. {
  872. struct timeval tv;
  873. cgtime(&tv);
  874. ts_start->tv_sec = tv->tv_sec;
  875. ts_start->tv_nsec = tv->tv_usec * 1000;
  876. }
  877. #endif /* __MACH__ */
  878. #ifdef WIN32
  879. /* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t
  880. * typedef, allowing us to have sub-microsecond resolution for times, do simple
  881. * arithmetic for timer calculations, and use windows' own hTimers to get
  882. * accurate absolute timeouts. */
  883. int cgtimer_to_ms(cgtimer_t *cgt)
  884. {
  885. return (int)(cgt->QuadPart / 10000LL);
  886. }
  887. /* Subtracts b from a and stores it in res. */
  888. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  889. {
  890. res->QuadPart = a->QuadPart - b->QuadPart;
  891. }
  892. /* Note that cgtimer time is NOT offset by the unix epoch since we use absolute
  893. * timeouts with hTimers. */
  894. void cgtimer_time(cgtimer_t *ts_start)
  895. {
  896. FILETIME ft;
  897. GetSystemTimeAsFileTime(&ft);
  898. ts_start->LowPart = ft.dwLowDateTime;
  899. ts_start->HighPart = ft.dwHighDateTime;
  900. }
  901. static void liSleep(LARGE_INTEGER *li, int timeout)
  902. {
  903. HANDLE hTimer;
  904. DWORD ret;
  905. if (unlikely(timeout <= 0))
  906. return;
  907. hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
  908. if (unlikely(!hTimer))
  909. quit(1, "Failed to create hTimer in liSleep");
  910. ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0);
  911. if (unlikely(!ret))
  912. quit(1, "Failed to SetWaitableTimer in liSleep");
  913. /* We still use a timeout as a sanity check in case the system time
  914. * is changed while we're running */
  915. ret = WaitForSingleObject(hTimer, timeout);
  916. if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT))
  917. quit(1, "Failed to WaitForSingleObject in liSleep");
  918. CloseHandle(hTimer);
  919. }
  920. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  921. {
  922. LARGE_INTEGER li;
  923. li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL;
  924. liSleep(&li, ms);
  925. }
  926. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  927. {
  928. LARGE_INTEGER li;
  929. int ms;
  930. li.QuadPart = ts_start->QuadPart + us * 10LL;
  931. ms = us / 1000;
  932. if (!ms)
  933. ms = 1;
  934. liSleep(&li, ms);
  935. }
  936. #else /* WIN32 */
  937. static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start)
  938. {
  939. struct timespec now;
  940. timeraddspec(ts_diff, ts_start);
  941. cgtimer_time(&now);
  942. timersubspec(ts_diff, &now);
  943. if (unlikely(ts_diff->tv_sec < 0))
  944. return;
  945. nanosleep(ts_diff, NULL);
  946. }
  947. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  948. {
  949. struct timespec ts_diff;
  950. ms_to_timespec(&ts_diff, ms);
  951. cgsleep_spec(&ts_diff, ts_start);
  952. }
  953. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  954. {
  955. struct timespec ts_diff;
  956. us_to_timespec(&ts_diff, us);
  957. cgsleep_spec(&ts_diff, ts_start);
  958. }
  959. #endif /* WIN32 */
  960. #endif /* CLOCK_MONOTONIC */
  961. void cgsleep_ms(int ms)
  962. {
  963. cgtimer_t ts_start;
  964. cgsleep_prepare_r(&ts_start);
  965. cgsleep_ms_r(&ts_start, ms);
  966. }
  967. void cgsleep_us(int64_t us)
  968. {
  969. cgtimer_t ts_start;
  970. cgsleep_prepare_r(&ts_start);
  971. cgsleep_us_r(&ts_start, us);
  972. }
  973. /* Returns the microseconds difference between end and start times as a double */
  974. double us_tdiff(struct timeval *end, struct timeval *start)
  975. {
  976. /* Sanity check. We should only be using this for small differences so
  977. * limit the max to 60 seconds. */
  978. if (unlikely(end->tv_sec - start->tv_sec > 60))
  979. return 60000000;
  980. return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec);
  981. }
  982. /* Returns the milliseconds difference between end and start times */
  983. int ms_tdiff(struct timeval *end, struct timeval *start)
  984. {
  985. /* Like us_tdiff, limit to 1 hour. */
  986. if (unlikely(end->tv_sec - start->tv_sec > 3600))
  987. return 3600000;
  988. return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000;
  989. }
  990. /* Returns the seconds difference between end and start times as a double */
  991. double tdiff(struct timeval *end, struct timeval *start)
  992. {
  993. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  994. }
  995. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  996. {
  997. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  998. char url_address[256], port[6];
  999. int url_len, port_len = 0;
  1000. *sockaddr_url = url;
  1001. url_begin = strstr(url, "//");
  1002. if (!url_begin)
  1003. url_begin = url;
  1004. else
  1005. url_begin += 2;
  1006. /* Look for numeric ipv6 entries */
  1007. ipv6_begin = strstr(url_begin, "[");
  1008. ipv6_end = strstr(url_begin, "]");
  1009. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1010. url_end = strstr(ipv6_end, ":");
  1011. else
  1012. url_end = strstr(url_begin, ":");
  1013. if (url_end) {
  1014. url_len = url_end - url_begin;
  1015. port_len = strlen(url_begin) - url_len - 1;
  1016. if (port_len < 1)
  1017. return false;
  1018. port_start = url_end + 1;
  1019. } else
  1020. url_len = strlen(url_begin);
  1021. if (url_len < 1)
  1022. return false;
  1023. sprintf(url_address, "%.*s", url_len, url_begin);
  1024. if (port_len) {
  1025. char *slash;
  1026. snprintf(port, 6, "%.*s", port_len, port_start);
  1027. slash = strchr(port, '/');
  1028. if (slash)
  1029. *slash = '\0';
  1030. } else
  1031. strcpy(port, "80");
  1032. *sockaddr_port = strdup(port);
  1033. *sockaddr_url = strdup(url_address);
  1034. return true;
  1035. }
  1036. enum send_ret {
  1037. SEND_OK,
  1038. SEND_SELECTFAIL,
  1039. SEND_SENDFAIL,
  1040. SEND_INACTIVE
  1041. };
  1042. /* Send a single command across a socket, appending \n to it. This should all
  1043. * be done under stratum lock except when first establishing the socket */
  1044. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1045. {
  1046. SOCKETTYPE sock = pool->sock;
  1047. ssize_t ssent = 0;
  1048. strcat(s, "\n");
  1049. len++;
  1050. while (len > 0 ) {
  1051. struct timeval timeout = {1, 0};
  1052. ssize_t sent;
  1053. fd_set wd;
  1054. FD_ZERO(&wd);
  1055. FD_SET(sock, &wd);
  1056. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  1057. return SEND_SELECTFAIL;
  1058. #ifdef __APPLE__
  1059. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1060. #elif WIN32
  1061. sent = send(pool->sock, s + ssent, len, 0);
  1062. #else
  1063. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1064. #endif
  1065. if (sent < 0) {
  1066. if (!sock_blocks())
  1067. return SEND_SENDFAIL;
  1068. sent = 0;
  1069. }
  1070. ssent += sent;
  1071. len -= sent;
  1072. }
  1073. pool->cgminer_pool_stats.times_sent++;
  1074. pool->cgminer_pool_stats.bytes_sent += ssent;
  1075. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1076. return SEND_OK;
  1077. }
  1078. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  1079. {
  1080. enum send_ret ret = SEND_INACTIVE;
  1081. if (opt_protocol)
  1082. applog(LOG_DEBUG, "SEND: %s", s);
  1083. mutex_lock(&pool->stratum_lock);
  1084. if (pool->stratum_active)
  1085. ret = __stratum_send(pool, s, len);
  1086. mutex_unlock(&pool->stratum_lock);
  1087. /* This is to avoid doing applog under stratum_lock */
  1088. switch (ret) {
  1089. default:
  1090. case SEND_OK:
  1091. break;
  1092. case SEND_SELECTFAIL:
  1093. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1094. suspend_stratum(pool);
  1095. break;
  1096. case SEND_SENDFAIL:
  1097. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1098. suspend_stratum(pool);
  1099. break;
  1100. case SEND_INACTIVE:
  1101. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1102. break;
  1103. }
  1104. return (ret == SEND_OK);
  1105. }
  1106. static bool socket_full(struct pool *pool, int wait)
  1107. {
  1108. SOCKETTYPE sock = pool->sock;
  1109. struct timeval timeout;
  1110. fd_set rd;
  1111. if (unlikely(wait < 0))
  1112. wait = 0;
  1113. FD_ZERO(&rd);
  1114. FD_SET(sock, &rd);
  1115. timeout.tv_usec = 0;
  1116. timeout.tv_sec = wait;
  1117. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1118. return true;
  1119. return false;
  1120. }
  1121. /* Check to see if Santa's been good to you */
  1122. bool sock_full(struct pool *pool)
  1123. {
  1124. if (strlen(pool->sockbuf))
  1125. return true;
  1126. return (socket_full(pool, 0));
  1127. }
  1128. static void clear_sockbuf(struct pool *pool)
  1129. {
  1130. strcpy(pool->sockbuf, "");
  1131. }
  1132. static void clear_sock(struct pool *pool)
  1133. {
  1134. ssize_t n;
  1135. mutex_lock(&pool->stratum_lock);
  1136. do {
  1137. if (pool->sock)
  1138. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1139. else
  1140. n = 0;
  1141. } while (n > 0);
  1142. mutex_unlock(&pool->stratum_lock);
  1143. clear_sockbuf(pool);
  1144. }
  1145. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1146. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1147. * and zeroing the new memory */
  1148. static void recalloc_sock(struct pool *pool, size_t len)
  1149. {
  1150. size_t old, new;
  1151. old = strlen(pool->sockbuf);
  1152. new = old + len + 1;
  1153. if (new < pool->sockbuf_size)
  1154. return;
  1155. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1156. // Avoid potentially recursive locking
  1157. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  1158. pool->sockbuf = realloc(pool->sockbuf, new);
  1159. if (!pool->sockbuf)
  1160. quithere(1, "Failed to realloc pool sockbuf");
  1161. memset(pool->sockbuf + old, 0, new - old);
  1162. pool->sockbuf_size = new;
  1163. }
  1164. /* Peeks at a socket to find the first end of line and then reads just that
  1165. * from the socket and returns that as a malloced char */
  1166. char *recv_line(struct pool *pool)
  1167. {
  1168. char *tok, *sret = NULL;
  1169. ssize_t len, buflen;
  1170. int waited = 0;
  1171. if (!strstr(pool->sockbuf, "\n")) {
  1172. struct timeval rstart, now;
  1173. cgtime(&rstart);
  1174. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1175. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1176. goto out;
  1177. }
  1178. do {
  1179. char s[RBUFSIZE];
  1180. size_t slen;
  1181. ssize_t n;
  1182. memset(s, 0, RBUFSIZE);
  1183. n = recv(pool->sock, s, RECVSIZE, 0);
  1184. if (!n) {
  1185. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1186. suspend_stratum(pool);
  1187. break;
  1188. }
  1189. cgtime(&now);
  1190. waited = tdiff(&now, &rstart);
  1191. if (n < 0) {
  1192. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1193. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1194. suspend_stratum(pool);
  1195. break;
  1196. }
  1197. } else {
  1198. slen = strlen(s);
  1199. recalloc_sock(pool, slen);
  1200. strcat(pool->sockbuf, s);
  1201. }
  1202. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1203. }
  1204. buflen = strlen(pool->sockbuf);
  1205. tok = strtok(pool->sockbuf, "\n");
  1206. if (!tok) {
  1207. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1208. goto out;
  1209. }
  1210. sret = strdup(tok);
  1211. len = strlen(sret);
  1212. /* Copy what's left in the buffer after the \n, including the
  1213. * terminating \0 */
  1214. if (buflen > len + 1)
  1215. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1216. else
  1217. strcpy(pool->sockbuf, "");
  1218. pool->cgminer_pool_stats.times_received++;
  1219. pool->cgminer_pool_stats.bytes_received += len;
  1220. pool->cgminer_pool_stats.net_bytes_received += len;
  1221. out:
  1222. if (!sret)
  1223. clear_sock(pool);
  1224. else if (opt_protocol)
  1225. applog(LOG_DEBUG, "RECVD: %s", sret);
  1226. return sret;
  1227. }
  1228. /* Extracts a string value from a json array with error checking. To be used
  1229. * when the value of the string returned is only examined and not to be stored.
  1230. * See json_array_string below */
  1231. static char *__json_array_string(json_t *val, unsigned int entry)
  1232. {
  1233. json_t *arr_entry;
  1234. if (json_is_null(val))
  1235. return NULL;
  1236. if (!json_is_array(val))
  1237. return NULL;
  1238. if (entry > json_array_size(val))
  1239. return NULL;
  1240. arr_entry = json_array_get(val, entry);
  1241. if (!json_is_string(arr_entry))
  1242. return NULL;
  1243. return (char *)json_string_value(arr_entry);
  1244. }
  1245. /* Creates a freshly malloced dup of __json_array_string */
  1246. static char *json_array_string(json_t *val, unsigned int entry)
  1247. {
  1248. char *buf = __json_array_string(val, entry);
  1249. if (buf)
  1250. return strdup(buf);
  1251. return NULL;
  1252. }
  1253. static char *blank_merkel = "0000000000000000000000000000000000000000000000000000000000000000";
  1254. static bool parse_notify(struct pool *pool, json_t *val)
  1255. {
  1256. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
  1257. *ntime, *header;
  1258. size_t cb1_len, cb2_len, alloc_len;
  1259. unsigned char *cb1, *cb2;
  1260. bool clean, ret = false;
  1261. int merkles, i;
  1262. json_t *arr;
  1263. arr = json_array_get(val, 4);
  1264. if (!arr || !json_is_array(arr))
  1265. goto out;
  1266. merkles = json_array_size(arr);
  1267. job_id = json_array_string(val, 0);
  1268. prev_hash = json_array_string(val, 1);
  1269. coinbase1 = json_array_string(val, 2);
  1270. coinbase2 = json_array_string(val, 3);
  1271. bbversion = json_array_string(val, 5);
  1272. nbit = json_array_string(val, 6);
  1273. ntime = json_array_string(val, 7);
  1274. clean = json_is_true(json_array_get(val, 8));
  1275. if (!job_id || !prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime) {
  1276. /* Annoying but we must not leak memory */
  1277. if (job_id)
  1278. free(job_id);
  1279. if (prev_hash)
  1280. free(prev_hash);
  1281. if (coinbase1)
  1282. free(coinbase1);
  1283. if (coinbase2)
  1284. free(coinbase2);
  1285. if (bbversion)
  1286. free(bbversion);
  1287. if (nbit)
  1288. free(nbit);
  1289. if (ntime)
  1290. free(ntime);
  1291. goto out;
  1292. }
  1293. cg_wlock(&pool->data_lock);
  1294. free(pool->swork.job_id);
  1295. free(pool->swork.prev_hash);
  1296. free(pool->swork.bbversion);
  1297. free(pool->swork.nbit);
  1298. free(pool->swork.ntime);
  1299. pool->swork.job_id = job_id;
  1300. pool->swork.prev_hash = prev_hash;
  1301. cb1_len = strlen(coinbase1) / 2;
  1302. cb2_len = strlen(coinbase2) / 2;
  1303. pool->swork.bbversion = bbversion;
  1304. pool->swork.nbit = nbit;
  1305. pool->swork.ntime = ntime;
  1306. pool->swork.clean = clean;
  1307. alloc_len = pool->swork.cb_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
  1308. pool->nonce2_offset = cb1_len + pool->n1_len;
  1309. for (i = 0; i < pool->swork.merkles; i++)
  1310. free(pool->swork.merkle_bin[i]);
  1311. if (merkles) {
  1312. pool->swork.merkle_bin = realloc(pool->swork.merkle_bin,
  1313. sizeof(char *) * merkles + 1);
  1314. for (i = 0; i < merkles; i++) {
  1315. char *merkle = json_array_string(arr, i);
  1316. pool->swork.merkle_bin[i] = malloc(32);
  1317. if (unlikely(!pool->swork.merkle_bin[i]))
  1318. quit(1, "Failed to malloc pool swork merkle_bin");
  1319. hex2bin(pool->swork.merkle_bin[i], merkle, 32);
  1320. free(merkle);
  1321. }
  1322. }
  1323. pool->swork.merkles = merkles;
  1324. if (clean)
  1325. pool->nonce2 = 0;
  1326. pool->merkle_offset = strlen(pool->swork.bbversion) +
  1327. strlen(pool->swork.prev_hash);
  1328. pool->swork.header_len = pool->merkle_offset +
  1329. /* merkle_hash */ 32 +
  1330. strlen(pool->swork.ntime) +
  1331. strlen(pool->swork.nbit) +
  1332. /* nonce */ 8 +
  1333. /* workpadding */ 96;
  1334. pool->merkle_offset /= 2;
  1335. pool->swork.header_len = pool->swork.header_len * 2 + 1;
  1336. align_len(&pool->swork.header_len);
  1337. header = alloca(pool->swork.header_len);
  1338. snprintf(header, pool->swork.header_len,
  1339. "%s%s%s%s%s%s%s",
  1340. pool->swork.bbversion,
  1341. pool->swork.prev_hash,
  1342. blank_merkel,
  1343. pool->swork.ntime,
  1344. pool->swork.nbit,
  1345. "00000000", /* nonce */
  1346. workpadding);
  1347. if (unlikely(!hex2bin(pool->header_bin, header, 128)))
  1348. quit(1, "Failed to convert header to header_bin in parse_notify");
  1349. cb1 = calloc(cb1_len, 1);
  1350. if (unlikely(!cb1))
  1351. quithere(1, "Failed to calloc cb1 in parse_notify");
  1352. hex2bin(cb1, coinbase1, cb1_len);
  1353. cb2 = calloc(cb2_len, 1);
  1354. if (unlikely(!cb2))
  1355. quithere(1, "Failed to calloc cb2 in parse_notify");
  1356. hex2bin(cb2, coinbase2, cb2_len);
  1357. free(pool->coinbase);
  1358. align_len(&alloc_len);
  1359. pool->coinbase = calloc(alloc_len, 1);
  1360. if (unlikely(!pool->coinbase))
  1361. quit(1, "Failed to calloc pool coinbase in parse_notify");
  1362. memcpy(pool->coinbase, cb1, cb1_len);
  1363. memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
  1364. memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
  1365. cg_wunlock(&pool->data_lock);
  1366. if (opt_protocol) {
  1367. applog(LOG_DEBUG, "job_id: %s", job_id);
  1368. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1369. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1370. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1371. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1372. applog(LOG_DEBUG, "nbit: %s", nbit);
  1373. applog(LOG_DEBUG, "ntime: %s", ntime);
  1374. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1375. }
  1376. free(coinbase1);
  1377. free(coinbase2);
  1378. free(cb1);
  1379. free(cb2);
  1380. /* A notify message is the closest stratum gets to a getwork */
  1381. pool->getwork_requested++;
  1382. total_getworks++;
  1383. ret = true;
  1384. if (pool == current_pool())
  1385. opt_work_update = true;
  1386. out:
  1387. return ret;
  1388. }
  1389. static bool parse_diff(struct pool *pool, json_t *val)
  1390. {
  1391. double old_diff, diff;
  1392. diff = json_number_value(json_array_get(val, 0));
  1393. if (diff == 0)
  1394. return false;
  1395. cg_wlock(&pool->data_lock);
  1396. old_diff = pool->swork.diff;
  1397. pool->swork.diff = diff;
  1398. cg_wunlock(&pool->data_lock);
  1399. if (old_diff != diff) {
  1400. int idiff = diff;
  1401. if ((double)idiff == diff)
  1402. applog(LOG_NOTICE, "Pool %d difficulty changed to %d",
  1403. pool->pool_no, idiff);
  1404. else
  1405. applog(LOG_NOTICE, "Pool %d difficulty changed to %f",
  1406. pool->pool_no, diff);
  1407. } else
  1408. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no,
  1409. diff);
  1410. return true;
  1411. }
  1412. static bool parse_reconnect(struct pool *pool, json_t *val)
  1413. {
  1414. char *url, *port, address[256];
  1415. memset(address, 0, 255);
  1416. url = (char *)json_string_value(json_array_get(val, 0));
  1417. if (!url)
  1418. url = pool->sockaddr_url;
  1419. port = (char *)json_string_value(json_array_get(val, 1));
  1420. if (!port)
  1421. port = pool->stratum_port;
  1422. sprintf(address, "%s:%s", url, port);
  1423. if (!extract_sockaddr(address, &pool->sockaddr_url, &pool->stratum_port))
  1424. return false;
  1425. pool->stratum_url = pool->sockaddr_url;
  1426. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1427. if (!restart_stratum(pool))
  1428. return false;
  1429. return true;
  1430. }
  1431. static bool send_version(struct pool *pool, json_t *val)
  1432. {
  1433. char s[RBUFSIZE];
  1434. int id = json_integer_value(json_object_get(val, "id"));
  1435. if (!id)
  1436. return false;
  1437. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  1438. if (!stratum_send(pool, s, strlen(s)))
  1439. return false;
  1440. return true;
  1441. }
  1442. static bool show_message(struct pool *pool, json_t *val)
  1443. {
  1444. char *msg;
  1445. if (!json_is_array(val))
  1446. return false;
  1447. msg = (char *)json_string_value(json_array_get(val, 0));
  1448. if (!msg)
  1449. return false;
  1450. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  1451. return true;
  1452. }
  1453. bool parse_method(struct pool *pool, char *s)
  1454. {
  1455. json_t *val = NULL, *method, *err_val, *params;
  1456. json_error_t err;
  1457. bool ret = false;
  1458. char *buf;
  1459. if (!s)
  1460. return ret;
  1461. val = JSON_LOADS(s, &err);
  1462. if (!val) {
  1463. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1464. return ret;
  1465. }
  1466. method = json_object_get(val, "method");
  1467. if (!method)
  1468. return ret;
  1469. err_val = json_object_get(val, "error");
  1470. params = json_object_get(val, "params");
  1471. if (err_val && !json_is_null(err_val)) {
  1472. char *ss;
  1473. if (err_val)
  1474. ss = json_dumps(err_val, JSON_INDENT(3));
  1475. else
  1476. ss = strdup("(unknown reason)");
  1477. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1478. free(ss);
  1479. return ret;
  1480. }
  1481. buf = (char *)json_string_value(method);
  1482. if (!buf)
  1483. return ret;
  1484. if (!strncasecmp(buf, "mining.notify", 13)) {
  1485. if (parse_notify(pool, params))
  1486. pool->stratum_notify = ret = true;
  1487. else
  1488. pool->stratum_notify = ret = false;
  1489. return ret;
  1490. }
  1491. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1492. ret = true;
  1493. return ret;
  1494. }
  1495. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1496. ret = true;
  1497. return ret;
  1498. }
  1499. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1500. ret = true;
  1501. return ret;
  1502. }
  1503. if (!strncasecmp(buf, "client.show_message", 19) && show_message(pool, params)) {
  1504. ret = true;
  1505. return ret;
  1506. }
  1507. return ret;
  1508. }
  1509. bool auth_stratum(struct pool *pool)
  1510. {
  1511. json_t *val = NULL, *res_val, *err_val;
  1512. char s[RBUFSIZE], *sret = NULL;
  1513. json_error_t err;
  1514. bool ret = false;
  1515. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1516. swork_id++, pool->rpc_user, pool->rpc_pass);
  1517. if (!stratum_send(pool, s, strlen(s)))
  1518. return ret;
  1519. /* Parse all data in the queue and anything left should be auth */
  1520. while (42) {
  1521. sret = recv_line(pool);
  1522. if (!sret)
  1523. return ret;
  1524. if (parse_method(pool, sret))
  1525. free(sret);
  1526. else
  1527. break;
  1528. }
  1529. val = JSON_LOADS(sret, &err);
  1530. free(sret);
  1531. res_val = json_object_get(val, "result");
  1532. err_val = json_object_get(val, "error");
  1533. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1534. char *ss;
  1535. if (err_val)
  1536. ss = json_dumps(err_val, JSON_INDENT(3));
  1537. else
  1538. ss = strdup("(unknown reason)");
  1539. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1540. free(ss);
  1541. return ret;
  1542. }
  1543. ret = true;
  1544. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1545. pool->probed = true;
  1546. successful_connect = true;
  1547. return ret;
  1548. }
  1549. static int recv_byte(int sockd)
  1550. {
  1551. char c;
  1552. if (recv(sockd, &c, 1, 0) != -1)
  1553. return c;
  1554. return -1;
  1555. }
  1556. static bool http_negotiate(struct pool *pool, int sockd, bool http0)
  1557. {
  1558. char buf[1024];
  1559. int i, len;
  1560. if (http0) {
  1561. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n",
  1562. pool->sockaddr_url, pool->stratum_port);
  1563. } else {
  1564. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n",
  1565. pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url,
  1566. pool->stratum_port);
  1567. }
  1568. applog(LOG_DEBUG, "Sending proxy %s:%s - %s",
  1569. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  1570. send(sockd, buf, strlen(buf), 0);
  1571. len = recv(sockd, buf, 12, 0);
  1572. if (len <= 0) {
  1573. applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT",
  1574. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1575. return false;
  1576. }
  1577. buf[len] = '\0';
  1578. applog(LOG_DEBUG, "Received from proxy %s:%s - %s",
  1579. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  1580. if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) {
  1581. applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s",
  1582. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  1583. return false;
  1584. }
  1585. /* Ignore unwanted headers till we get desired response */
  1586. for (i = 0; i < 4; i++) {
  1587. buf[i] = recv_byte(sockd);
  1588. if (buf[i] == (char)-1) {
  1589. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  1590. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1591. return false;
  1592. }
  1593. }
  1594. while (strncmp(buf, "\r\n\r\n", 4)) {
  1595. for (i = 0; i < 3; i++)
  1596. buf[i] = buf[i + 1];
  1597. buf[3] = recv_byte(sockd);
  1598. if (buf[3] == (char)-1) {
  1599. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  1600. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1601. return false;
  1602. }
  1603. }
  1604. applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy",
  1605. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1606. return true;
  1607. }
  1608. static bool socks5_negotiate(struct pool *pool, int sockd)
  1609. {
  1610. unsigned char atyp, uclen;
  1611. unsigned short port;
  1612. char buf[515];
  1613. int i, len;
  1614. buf[0] = 0x05;
  1615. buf[1] = 0x01;
  1616. buf[2] = 0x00;
  1617. applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy",
  1618. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1619. send(sockd, buf, 3, 0);
  1620. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) {
  1621. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  1622. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1623. return false;
  1624. }
  1625. buf[0] = 0x05;
  1626. buf[1] = 0x01;
  1627. buf[2] = 0x00;
  1628. buf[3] = 0x03;
  1629. len = (strlen(pool->sockaddr_url));
  1630. if (len > 255)
  1631. len = 255;
  1632. uclen = len;
  1633. buf[4] = (uclen & 0xff);
  1634. memcpy(buf + 5, pool->sockaddr_url, len);
  1635. port = atoi(pool->stratum_port);
  1636. buf[5 + len] = (port >> 8);
  1637. buf[6 + len] = (port & 0xff);
  1638. send(sockd, buf, (7 + len), 0);
  1639. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) {
  1640. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  1641. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1642. return false;
  1643. }
  1644. recv_byte(sockd);
  1645. atyp = recv_byte(sockd);
  1646. if (atyp == 0x01) {
  1647. for (i = 0; i < 4; i++)
  1648. recv_byte(sockd);
  1649. } else if (atyp == 0x03) {
  1650. len = recv_byte(sockd);
  1651. for (i = 0; i < len; i++)
  1652. recv_byte(sockd);
  1653. } else {
  1654. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  1655. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1656. return false;
  1657. }
  1658. for (i = 0; i < 2; i++)
  1659. recv_byte(sockd);
  1660. applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy",
  1661. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1662. return true;
  1663. }
  1664. static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
  1665. {
  1666. unsigned short port;
  1667. in_addr_t inp;
  1668. char buf[515];
  1669. int i, len;
  1670. buf[0] = 0x04;
  1671. buf[1] = 0x01;
  1672. port = atoi(pool->stratum_port);
  1673. buf[2] = port >> 8;
  1674. buf[3] = port & 0xff;
  1675. sprintf(&buf[8], "CGMINER");
  1676. /* See if we've been given an IP address directly to avoid needing to
  1677. * resolve it. */
  1678. inp = inet_addr(pool->sockaddr_url);
  1679. inp = ntohl(inp);
  1680. if ((int)inp != -1)
  1681. socks4a = false;
  1682. else {
  1683. /* Try to extract the IP address ourselves first */
  1684. struct addrinfo servinfobase, *servinfo, hints;
  1685. servinfo = &servinfobase;
  1686. memset(&hints, 0, sizeof(struct addrinfo));
  1687. hints.ai_family = AF_INET; /* IPV4 only */
  1688. if (!getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo)) {
  1689. struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr;
  1690. inp = ntohl(saddr_in->sin_addr.s_addr);
  1691. socks4a = false;
  1692. freeaddrinfo(servinfo);
  1693. }
  1694. }
  1695. if (!socks4a) {
  1696. if ((int)inp == -1) {
  1697. applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s",
  1698. pool->sockaddr_url);
  1699. return false;
  1700. }
  1701. buf[4] = (inp >> 24) & 0xFF;
  1702. buf[5] = (inp >> 16) & 0xFF;
  1703. buf[6] = (inp >> 8) & 0xFF;
  1704. buf[7] = (inp >> 0) & 0xFF;
  1705. send(sockd, buf, 16, 0);
  1706. } else {
  1707. /* This appears to not be working but hopefully most will be
  1708. * able to resolve IP addresses themselves. */
  1709. buf[4] = 0;
  1710. buf[5] = 0;
  1711. buf[6] = 0;
  1712. buf[7] = 1;
  1713. len = strlen(pool->sockaddr_url);
  1714. if (len > 255)
  1715. len = 255;
  1716. memcpy(&buf[16], pool->sockaddr_url, len);
  1717. len += 16;
  1718. buf[len++] = '\0';
  1719. send(sockd, buf, len, 0);
  1720. }
  1721. if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) {
  1722. applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server",
  1723. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1724. return false;
  1725. }
  1726. for (i = 0; i < 6; i++)
  1727. recv_byte(sockd);
  1728. return true;
  1729. }
  1730. static void noblock_socket(SOCKETTYPE fd)
  1731. {
  1732. #ifndef WIN32
  1733. int flags = fcntl(fd, F_GETFL, 0);
  1734. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  1735. #else
  1736. u_long flags = 1;
  1737. ioctlsocket(fd, FIONBIO, &flags);
  1738. #endif
  1739. }
  1740. static void block_socket(SOCKETTYPE fd)
  1741. {
  1742. #ifndef WIN32
  1743. int flags = fcntl(fd, F_GETFL, 0);
  1744. fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
  1745. #else
  1746. u_long flags = 0;
  1747. ioctlsocket(fd, FIONBIO, &flags);
  1748. #endif
  1749. }
  1750. static bool sock_connecting(void)
  1751. {
  1752. #ifndef WIN32
  1753. return errno == EINPROGRESS;
  1754. #else
  1755. return WSAGetLastError() == WSAEWOULDBLOCK;
  1756. #endif
  1757. }
  1758. static bool setup_stratum_socket(struct pool *pool)
  1759. {
  1760. struct addrinfo servinfobase, *servinfo, *hints, *p;
  1761. char *sockaddr_url, *sockaddr_port;
  1762. int sockd;
  1763. mutex_lock(&pool->stratum_lock);
  1764. pool->stratum_active = false;
  1765. if (pool->sock)
  1766. CLOSESOCKET(pool->sock);
  1767. pool->sock = 0;
  1768. mutex_unlock(&pool->stratum_lock);
  1769. hints = &pool->stratum_hints;
  1770. memset(hints, 0, sizeof(struct addrinfo));
  1771. hints->ai_family = AF_UNSPEC;
  1772. hints->ai_socktype = SOCK_STREAM;
  1773. servinfo = &servinfobase;
  1774. if (!pool->rpc_proxy && opt_socks_proxy) {
  1775. pool->rpc_proxy = opt_socks_proxy;
  1776. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  1777. pool->rpc_proxytype = PROXY_SOCKS5;
  1778. }
  1779. if (pool->rpc_proxy) {
  1780. sockaddr_url = pool->sockaddr_proxy_url;
  1781. sockaddr_port = pool->sockaddr_proxy_port;
  1782. } else {
  1783. sockaddr_url = pool->sockaddr_url;
  1784. sockaddr_port = pool->stratum_port;
  1785. }
  1786. if (getaddrinfo(sockaddr_url, sockaddr_port, hints, &servinfo) != 0) {
  1787. if (!pool->probed) {
  1788. applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s",
  1789. sockaddr_url, sockaddr_port);
  1790. pool->probed = true;
  1791. } else {
  1792. applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
  1793. sockaddr_url, sockaddr_port);
  1794. }
  1795. return false;
  1796. }
  1797. for (p = servinfo; p != NULL; p = p->ai_next) {
  1798. sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
  1799. if (sockd == -1) {
  1800. applog(LOG_DEBUG, "Failed socket");
  1801. continue;
  1802. }
  1803. /* Iterate non blocking over entries returned by getaddrinfo
  1804. * to cope with round robin DNS entries, finding the first one
  1805. * we can connect to quickly. */
  1806. noblock_socket(sockd);
  1807. if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
  1808. struct timeval tv_timeout = {1, 0};
  1809. int selret;
  1810. fd_set rw;
  1811. if (!sock_connecting()) {
  1812. CLOSESOCKET(sockd);
  1813. applog(LOG_DEBUG, "Failed sock connect");
  1814. continue;
  1815. }
  1816. FD_ZERO(&rw);
  1817. FD_SET(sockd, &rw);
  1818. selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout);
  1819. if (selret > 0 && FD_ISSET(sockd, &rw)) {
  1820. socklen_t len;
  1821. int err, n;
  1822. len = sizeof(err);
  1823. n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (void *)&err, &len);
  1824. if (!n && !err) {
  1825. applog(LOG_DEBUG, "Succeeded delayed connect");
  1826. block_socket(sockd);
  1827. break;
  1828. }
  1829. }
  1830. CLOSESOCKET(sockd);
  1831. applog(LOG_DEBUG, "Select timeout/failed connect");
  1832. continue;
  1833. }
  1834. applog(LOG_WARNING, "Succeeded immediate connect");
  1835. block_socket(sockd);
  1836. break;
  1837. }
  1838. if (p == NULL) {
  1839. applog(LOG_INFO, "Failed to connect to stratum on %s:%s",
  1840. sockaddr_url, sockaddr_port);
  1841. freeaddrinfo(servinfo);
  1842. return false;
  1843. }
  1844. freeaddrinfo(servinfo);
  1845. if (pool->rpc_proxy) {
  1846. switch (pool->rpc_proxytype) {
  1847. case PROXY_HTTP_1_0:
  1848. if (!http_negotiate(pool, sockd, true))
  1849. return false;
  1850. break;
  1851. case PROXY_HTTP:
  1852. if (!http_negotiate(pool, sockd, false))
  1853. return false;
  1854. break;
  1855. case PROXY_SOCKS5:
  1856. case PROXY_SOCKS5H:
  1857. if (!socks5_negotiate(pool, sockd))
  1858. return false;
  1859. break;
  1860. case PROXY_SOCKS4:
  1861. if (!socks4_negotiate(pool, sockd, false))
  1862. return false;
  1863. break;
  1864. case PROXY_SOCKS4A:
  1865. if (!socks4_negotiate(pool, sockd, true))
  1866. return false;
  1867. break;
  1868. default:
  1869. applog(LOG_WARNING, "Unsupported proxy type for %s:%s",
  1870. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1871. return false;
  1872. break;
  1873. }
  1874. }
  1875. if (!pool->sockbuf) {
  1876. pool->sockbuf = calloc(RBUFSIZE, 1);
  1877. if (!pool->sockbuf)
  1878. quithere(1, "Failed to calloc pool sockbuf");
  1879. pool->sockbuf_size = RBUFSIZE;
  1880. }
  1881. pool->sock = sockd;
  1882. keep_sockalive(sockd);
  1883. return true;
  1884. }
  1885. static char *get_sessionid(json_t *val)
  1886. {
  1887. char *ret = NULL;
  1888. json_t *arr_val;
  1889. int arrsize, i;
  1890. arr_val = json_array_get(val, 0);
  1891. if (!arr_val || !json_is_array(arr_val))
  1892. goto out;
  1893. arrsize = json_array_size(arr_val);
  1894. for (i = 0; i < arrsize; i++) {
  1895. json_t *arr = json_array_get(arr_val, i);
  1896. char *notify;
  1897. if (!arr | !json_is_array(arr))
  1898. break;
  1899. notify = __json_array_string(arr, 0);
  1900. if (!notify)
  1901. continue;
  1902. if (!strncasecmp(notify, "mining.notify", 13)) {
  1903. ret = json_array_string(arr, 1);
  1904. break;
  1905. }
  1906. }
  1907. out:
  1908. return ret;
  1909. }
  1910. void suspend_stratum(struct pool *pool)
  1911. {
  1912. clear_sockbuf(pool);
  1913. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  1914. mutex_lock(&pool->stratum_lock);
  1915. pool->stratum_active = pool->stratum_notify = false;
  1916. if (pool->sock)
  1917. CLOSESOCKET(pool->sock);
  1918. pool->sock = 0;
  1919. mutex_unlock(&pool->stratum_lock);
  1920. }
  1921. bool initiate_stratum(struct pool *pool)
  1922. {
  1923. bool ret = false, recvd = false, noresume = false, sockd = false;
  1924. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  1925. json_t *val = NULL, *res_val, *err_val;
  1926. json_error_t err;
  1927. int n2size;
  1928. resend:
  1929. if (!setup_stratum_socket(pool)) {
  1930. sockd = false;
  1931. goto out;
  1932. }
  1933. sockd = true;
  1934. if (recvd) {
  1935. /* Get rid of any crap lying around if we're resending */
  1936. clear_sock(pool);
  1937. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  1938. } else {
  1939. if (pool->sessionid)
  1940. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  1941. else
  1942. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  1943. }
  1944. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  1945. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  1946. goto out;
  1947. }
  1948. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1949. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  1950. goto out;
  1951. }
  1952. sret = recv_line(pool);
  1953. if (!sret)
  1954. goto out;
  1955. recvd = true;
  1956. val = JSON_LOADS(sret, &err);
  1957. free(sret);
  1958. if (!val) {
  1959. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1960. goto out;
  1961. }
  1962. res_val = json_object_get(val, "result");
  1963. err_val = json_object_get(val, "error");
  1964. if (!res_val || json_is_null(res_val) ||
  1965. (err_val && !json_is_null(err_val))) {
  1966. char *ss;
  1967. if (err_val)
  1968. ss = json_dumps(err_val, JSON_INDENT(3));
  1969. else
  1970. ss = strdup("(unknown reason)");
  1971. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  1972. free(ss);
  1973. goto out;
  1974. }
  1975. sessionid = get_sessionid(res_val);
  1976. if (!sessionid)
  1977. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  1978. nonce1 = json_array_string(res_val, 1);
  1979. if (!nonce1) {
  1980. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  1981. free(sessionid);
  1982. goto out;
  1983. }
  1984. n2size = json_integer_value(json_array_get(res_val, 2));
  1985. if (!n2size) {
  1986. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  1987. free(sessionid);
  1988. free(nonce1);
  1989. goto out;
  1990. }
  1991. cg_wlock(&pool->data_lock);
  1992. pool->sessionid = sessionid;
  1993. pool->nonce1 = nonce1;
  1994. pool->n1_len = strlen(nonce1) / 2;
  1995. free(pool->nonce1bin);
  1996. pool->nonce1bin = calloc(pool->n1_len, 1);
  1997. if (unlikely(!pool->nonce1bin))
  1998. quithere(1, "Failed to calloc pool->nonce1bin");
  1999. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  2000. pool->n2size = n2size;
  2001. cg_wunlock(&pool->data_lock);
  2002. if (sessionid)
  2003. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2004. ret = true;
  2005. out:
  2006. if (ret) {
  2007. if (!pool->stratum_url)
  2008. pool->stratum_url = pool->sockaddr_url;
  2009. pool->stratum_active = true;
  2010. pool->swork.diff = 1;
  2011. if (opt_protocol) {
  2012. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2013. pool->pool_no, pool->nonce1, pool->n2size);
  2014. }
  2015. } else {
  2016. if (recvd && !noresume) {
  2017. /* Reset the sessionid used for stratum resuming in case the pool
  2018. * does not support it, or does not know how to respond to the
  2019. * presence of the sessionid parameter. */
  2020. cg_wlock(&pool->data_lock);
  2021. free(pool->sessionid);
  2022. free(pool->nonce1);
  2023. pool->sessionid = pool->nonce1 = NULL;
  2024. cg_wunlock(&pool->data_lock);
  2025. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2026. noresume = true;
  2027. goto resend;
  2028. }
  2029. applog(LOG_DEBUG, "Initiate stratum failed");
  2030. if (sockd)
  2031. suspend_stratum(pool);
  2032. }
  2033. return ret;
  2034. }
  2035. bool restart_stratum(struct pool *pool)
  2036. {
  2037. if (pool->stratum_active)
  2038. suspend_stratum(pool);
  2039. if (!initiate_stratum(pool))
  2040. return false;
  2041. if (!auth_stratum(pool))
  2042. return false;
  2043. return true;
  2044. }
  2045. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  2046. {
  2047. dev->device_last_not_well = time(NULL);
  2048. dev->device_not_well_reason = reason;
  2049. switch (reason) {
  2050. case REASON_THREAD_FAIL_INIT:
  2051. dev->thread_fail_init_count++;
  2052. break;
  2053. case REASON_THREAD_ZERO_HASH:
  2054. dev->thread_zero_hash_count++;
  2055. break;
  2056. case REASON_THREAD_FAIL_QUEUE:
  2057. dev->thread_fail_queue_count++;
  2058. break;
  2059. case REASON_DEV_SICK_IDLE_60:
  2060. dev->dev_sick_idle_60_count++;
  2061. break;
  2062. case REASON_DEV_DEAD_IDLE_600:
  2063. dev->dev_dead_idle_600_count++;
  2064. break;
  2065. case REASON_DEV_NOSTART:
  2066. dev->dev_nostart_count++;
  2067. break;
  2068. case REASON_DEV_OVER_HEAT:
  2069. dev->dev_over_heat_count++;
  2070. break;
  2071. case REASON_DEV_THERMAL_CUTOFF:
  2072. dev->dev_thermal_cutoff_count++;
  2073. break;
  2074. case REASON_DEV_COMMS_ERROR:
  2075. dev->dev_comms_error_count++;
  2076. break;
  2077. case REASON_DEV_THROTTLE:
  2078. dev->dev_throttle_count++;
  2079. break;
  2080. }
  2081. }
  2082. /* Realloc an existing string to fit an extra string s, appending s to it. */
  2083. void *realloc_strcat(char *ptr, char *s)
  2084. {
  2085. size_t old = strlen(ptr), len = strlen(s);
  2086. char *ret;
  2087. if (!len)
  2088. return ptr;
  2089. len += old + 1;
  2090. align_len(&len);
  2091. ret = malloc(len);
  2092. if (unlikely(!ret))
  2093. quithere(1, "Failed to malloc");
  2094. sprintf(ret, "%s%s", ptr, s);
  2095. free(ptr);
  2096. return ret;
  2097. }
  2098. /* Make a text readable version of a string using 0xNN for < ' ' or > '~'
  2099. * Including 0x00 at the end
  2100. * You must free the result yourself */
  2101. void *str_text(char *ptr)
  2102. {
  2103. unsigned char *uptr;
  2104. char *ret, *txt;
  2105. if (ptr == NULL) {
  2106. ret = strdup("(null)");
  2107. if (unlikely(!ret))
  2108. quithere(1, "Failed to malloc null");
  2109. }
  2110. uptr = (unsigned char *)ptr;
  2111. ret = txt = malloc(strlen(ptr)*4+5); // Guaranteed >= needed
  2112. if (unlikely(!txt))
  2113. quithere(1, "Failed to malloc txt");
  2114. do {
  2115. if (*uptr < ' ' || *uptr > '~') {
  2116. sprintf(txt, "0x%02x", *uptr);
  2117. txt += 4;
  2118. } else
  2119. *(txt++) = *uptr;
  2120. } while (*(uptr++));
  2121. *txt = '\0';
  2122. return ret;
  2123. }
  2124. void RenameThread(const char* name)
  2125. {
  2126. #if defined(PR_SET_NAME)
  2127. // Only the first 15 characters are used (16 - NUL terminator)
  2128. prctl(PR_SET_NAME, name, 0, 0, 0);
  2129. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  2130. pthread_set_name_np(pthread_self(), name);
  2131. #elif defined(MAC_OSX)
  2132. pthread_setname_np(name);
  2133. #else
  2134. // Prevent warnings for unused parameters...
  2135. (void)name;
  2136. #endif
  2137. }
  2138. /* cgminer specific wrappers for true unnamed semaphore usage on platforms
  2139. * that support them and for apple which does not. We use a single byte across
  2140. * a pipe to emulate semaphore behaviour there. */
  2141. #ifdef __APPLE__
  2142. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2143. {
  2144. int flags, fd, i;
  2145. if (pipe(cgsem->pipefd) == -1)
  2146. quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
  2147. /* Make the pipes FD_CLOEXEC to allow them to close should we call
  2148. * execv on restart. */
  2149. for (i = 0; i < 2; i++) {
  2150. fd = cgsem->pipefd[i];
  2151. flags = fcntl(fd, F_GETFD, 0);
  2152. flags |= FD_CLOEXEC;
  2153. if (fcntl(fd, F_SETFD, flags) == -1)
  2154. quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
  2155. }
  2156. }
  2157. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2158. {
  2159. const char buf = 1;
  2160. int ret;
  2161. ret = write(cgsem->pipefd[1], &buf, 1);
  2162. if (unlikely(ret == 0))
  2163. applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
  2164. }
  2165. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2166. {
  2167. char buf;
  2168. int ret;
  2169. ret = read(cgsem->pipefd[0], &buf, 1);
  2170. if (unlikely(ret == 0))
  2171. applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
  2172. }
  2173. void cgsem_destroy(cgsem_t *cgsem)
  2174. {
  2175. close(cgsem->pipefd[1]);
  2176. close(cgsem->pipefd[0]);
  2177. }
  2178. /* This is similar to sem_timedwait but takes a millisecond value */
  2179. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  2180. {
  2181. struct timeval timeout;
  2182. int ret, fd;
  2183. fd_set rd;
  2184. char buf;
  2185. fd = cgsem->pipefd[0];
  2186. FD_ZERO(&rd);
  2187. FD_SET(fd, &rd);
  2188. ms_to_timeval(&timeout, ms);
  2189. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  2190. if (ret > 0) {
  2191. ret = read(fd, &buf, 1);
  2192. return 0;
  2193. }
  2194. if (likely(!ret))
  2195. return ETIMEDOUT;
  2196. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  2197. /* We don't reach here */
  2198. return 0;
  2199. }
  2200. #else
  2201. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2202. {
  2203. int ret;
  2204. if ((ret = sem_init(cgsem, 0, 0)))
  2205. quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
  2206. }
  2207. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2208. {
  2209. if (unlikely(sem_post(cgsem)))
  2210. quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
  2211. }
  2212. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2213. {
  2214. if (unlikely(sem_wait(cgsem)))
  2215. quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
  2216. }
  2217. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  2218. {
  2219. struct timespec abs_timeout, ts_now;
  2220. struct timeval tv_now;
  2221. int ret;
  2222. cgtime(&tv_now);
  2223. timeval_to_spec(&ts_now, &tv_now);
  2224. ms_to_timespec(&abs_timeout, ms);
  2225. timeraddspec(&abs_timeout, &ts_now);
  2226. ret = sem_timedwait(cgsem, &abs_timeout);
  2227. if (ret) {
  2228. if (likely(sock_timeout()))
  2229. return ETIMEDOUT;
  2230. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  2231. }
  2232. return 0;
  2233. }
  2234. void cgsem_destroy(cgsem_t *cgsem)
  2235. {
  2236. sem_destroy(cgsem);
  2237. }
  2238. #endif
  2239. /* Provide a completion_timeout helper function for unreliable functions that
  2240. * may die due to driver issues etc that time out if the function fails and
  2241. * can then reliably return. */
  2242. struct cg_completion {
  2243. cgsem_t cgsem;
  2244. void (*fn)(void *fnarg);
  2245. void *fnarg;
  2246. };
  2247. void *completion_thread(void *arg)
  2248. {
  2249. struct cg_completion *cgc = (struct cg_completion *)arg;
  2250. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2251. cgc->fn(cgc->fnarg);
  2252. cgsem_post(&cgc->cgsem);
  2253. return NULL;
  2254. }
  2255. bool cg_completion_timeout(void *fn, void *fnarg, int timeout)
  2256. {
  2257. struct cg_completion *cgc;
  2258. pthread_t pthread;
  2259. bool ret = false;
  2260. cgc = malloc(sizeof(struct cg_completion));
  2261. if (unlikely(!cgc))
  2262. return ret;
  2263. cgsem_init(&cgc->cgsem);
  2264. cgc->fn = fn;
  2265. cgc->fnarg = fnarg;
  2266. pthread_create(&pthread, NULL, completion_thread, (void *)cgc);
  2267. ret = cgsem_mswait(&cgc->cgsem, timeout);
  2268. if (!ret) {
  2269. pthread_join(pthread, NULL);
  2270. free(cgc);
  2271. } else
  2272. pthread_cancel(pthread);
  2273. return !ret;
  2274. }