util.c 60 KB

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