util.c 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086
  1. /*
  2. * Copyright 2011-2014 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 <winsock2.h>
  35. # include <ws2tcpip.h>
  36. # include <mmsystem.h>
  37. #endif
  38. #include <sched.h>
  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_web_config(const char *url)
  252. {
  253. struct data_buffer all_data = {NULL, 0};
  254. char curl_err_str[CURL_ERROR_SIZE];
  255. long timeout = 60;
  256. json_error_t err;
  257. json_t *val;
  258. CURL *curl;
  259. int rc;
  260. memset(&err, 0, sizeof(err));
  261. curl = curl_easy_init();
  262. if (unlikely(!curl))
  263. quithere(1, "CURL initialisation failed");
  264. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  265. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  266. curl_easy_setopt(curl, CURLOPT_URL, url);
  267. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  268. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  269. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  270. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  271. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  272. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  273. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  274. val = NULL;
  275. rc = curl_easy_perform(curl);
  276. curl_easy_cleanup(curl);
  277. if (rc) {
  278. applog(LOG_ERR, "HTTP config request of '%s' failed: %s", url, curl_err_str);
  279. goto c_out;
  280. }
  281. if (!all_data.buf) {
  282. applog(LOG_ERR, "Empty config data received from '%s'", url);
  283. goto c_out;
  284. }
  285. val = JSON_LOADS(all_data.buf, &err);
  286. if (!val) {
  287. applog(LOG_ERR, "JSON config decode of '%s' failed(%d): %s", url,
  288. err.line, err.text);
  289. }
  290. databuf_free(&all_data);
  291. c_out:
  292. return val;
  293. }
  294. json_t *json_rpc_call(CURL *curl, const char *url,
  295. const char *userpass, const char *rpc_req,
  296. bool probe, bool longpoll, int *rolltime,
  297. struct pool *pool, bool share)
  298. {
  299. long timeout = longpoll ? (60 * 60) : 60;
  300. struct data_buffer all_data = {NULL, 0};
  301. struct header_info hi = {NULL, 0, NULL, NULL, false, false, false};
  302. char len_hdr[64], user_agent_hdr[128];
  303. char curl_err_str[CURL_ERROR_SIZE];
  304. struct curl_slist *headers = NULL;
  305. struct upload_buffer upload_data;
  306. json_t *val, *err_val, *res_val;
  307. bool probing = false;
  308. double byte_count;
  309. json_error_t err;
  310. int rc;
  311. memset(&err, 0, sizeof(err));
  312. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  313. if (probe)
  314. probing = !pool->probed;
  315. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  316. // CURLOPT_VERBOSE won't write to stderr if we use CURLOPT_DEBUGFUNCTION
  317. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  318. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  319. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  320. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  321. curl_easy_setopt(curl, CURLOPT_URL, url);
  322. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  323. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  324. /* Shares are staggered already and delays in submission can be costly
  325. * so do not delay them */
  326. if (!opt_delaynet || share)
  327. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  328. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  329. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
  330. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  331. curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
  332. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  333. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  334. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  335. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
  336. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  337. if (pool->rpc_proxy) {
  338. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  339. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, pool->rpc_proxytype);
  340. } else if (opt_socks_proxy) {
  341. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  342. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  343. }
  344. if (userpass) {
  345. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  346. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  347. }
  348. if (longpoll)
  349. keep_curlalive(curl);
  350. curl_easy_setopt(curl, CURLOPT_POST, 1);
  351. if (opt_protocol)
  352. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  353. upload_data.buf = rpc_req;
  354. upload_data.len = strlen(rpc_req);
  355. sprintf(len_hdr, "Content-Length: %lu",
  356. (unsigned long) upload_data.len);
  357. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE_STRING);
  358. headers = curl_slist_append(headers,
  359. "Content-type: application/json");
  360. headers = curl_slist_append(headers,
  361. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  362. if (likely(global_hashrate)) {
  363. char ghashrate[255];
  364. sprintf(ghashrate, "X-Mining-Hashrate: %llu", global_hashrate);
  365. headers = curl_slist_append(headers, ghashrate);
  366. }
  367. headers = curl_slist_append(headers, len_hdr);
  368. headers = curl_slist_append(headers, user_agent_hdr);
  369. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  370. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  371. if (opt_delaynet) {
  372. /* Don't delay share submission, but still track the nettime */
  373. if (!share) {
  374. long long now_msecs, last_msecs;
  375. struct timeval now, last;
  376. cgtime(&now);
  377. last_nettime(&last);
  378. now_msecs = (long long)now.tv_sec * 1000;
  379. now_msecs += now.tv_usec / 1000;
  380. last_msecs = (long long)last.tv_sec * 1000;
  381. last_msecs += last.tv_usec / 1000;
  382. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  383. struct timespec rgtp;
  384. rgtp.tv_sec = 0;
  385. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  386. nanosleep(&rgtp, NULL);
  387. }
  388. }
  389. set_nettime();
  390. }
  391. rc = curl_easy_perform(curl);
  392. if (rc) {
  393. applog(LOG_INFO, "HTTP request failed: %s", curl_err_str);
  394. goto err_out;
  395. }
  396. if (!all_data.buf) {
  397. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  398. goto err_out;
  399. }
  400. pool->cgminer_pool_stats.times_sent++;
  401. if (curl_easy_getinfo(curl, CURLINFO_SIZE_UPLOAD, &byte_count) == CURLE_OK)
  402. pool->cgminer_pool_stats.bytes_sent += byte_count;
  403. pool->cgminer_pool_stats.times_received++;
  404. if (curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &byte_count) == CURLE_OK)
  405. pool->cgminer_pool_stats.bytes_received += byte_count;
  406. if (probing) {
  407. pool->probed = true;
  408. /* If X-Long-Polling was found, activate long polling */
  409. if (hi.lp_path) {
  410. if (pool->hdr_path != NULL)
  411. free(pool->hdr_path);
  412. pool->hdr_path = hi.lp_path;
  413. } else
  414. pool->hdr_path = NULL;
  415. if (hi.stratum_url) {
  416. pool->stratum_url = hi.stratum_url;
  417. hi.stratum_url = NULL;
  418. }
  419. } else {
  420. if (hi.lp_path) {
  421. free(hi.lp_path);
  422. hi.lp_path = NULL;
  423. }
  424. if (hi.stratum_url) {
  425. free(hi.stratum_url);
  426. hi.stratum_url = NULL;
  427. }
  428. }
  429. *rolltime = hi.rolltime;
  430. pool->cgminer_pool_stats.rolltime = hi.rolltime;
  431. pool->cgminer_pool_stats.hadrolltime = hi.hadrolltime;
  432. pool->cgminer_pool_stats.canroll = hi.canroll;
  433. pool->cgminer_pool_stats.hadexpire = hi.hadexpire;
  434. val = JSON_LOADS(all_data.buf, &err);
  435. if (!val) {
  436. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  437. if (opt_protocol)
  438. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char *)(all_data.buf));
  439. goto err_out;
  440. }
  441. if (opt_protocol) {
  442. char *s = json_dumps(val, JSON_INDENT(3));
  443. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  444. free(s);
  445. }
  446. /* JSON-RPC valid response returns a non-null 'result',
  447. * and a null 'error'.
  448. */
  449. res_val = json_object_get(val, "result");
  450. err_val = json_object_get(val, "error");
  451. if (!res_val ||(err_val && !json_is_null(err_val))) {
  452. char *s;
  453. if (err_val)
  454. s = json_dumps(err_val, JSON_INDENT(3));
  455. else
  456. s = strdup("(unknown reason)");
  457. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  458. free(s);
  459. goto err_out;
  460. }
  461. if (hi.reason) {
  462. json_object_set_new(val, "reject-reason", json_string(hi.reason));
  463. free(hi.reason);
  464. hi.reason = NULL;
  465. }
  466. successful_connect = true;
  467. databuf_free(&all_data);
  468. curl_slist_free_all(headers);
  469. curl_easy_reset(curl);
  470. return val;
  471. err_out:
  472. databuf_free(&all_data);
  473. curl_slist_free_all(headers);
  474. curl_easy_reset(curl);
  475. if (!successful_connect)
  476. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  477. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  478. return NULL;
  479. }
  480. #define PROXY_HTTP CURLPROXY_HTTP
  481. #define PROXY_HTTP_1_0 CURLPROXY_HTTP_1_0
  482. #define PROXY_SOCKS4 CURLPROXY_SOCKS4
  483. #define PROXY_SOCKS5 CURLPROXY_SOCKS5
  484. #define PROXY_SOCKS4A CURLPROXY_SOCKS4A
  485. #define PROXY_SOCKS5H CURLPROXY_SOCKS5_HOSTNAME
  486. #else /* HAVE_LIBCURL */
  487. #define PROXY_HTTP 0
  488. #define PROXY_HTTP_1_0 1
  489. #define PROXY_SOCKS4 2
  490. #define PROXY_SOCKS5 3
  491. #define PROXY_SOCKS4A 4
  492. #define PROXY_SOCKS5H 5
  493. #endif /* HAVE_LIBCURL */
  494. static struct {
  495. const char *name;
  496. proxytypes_t proxytype;
  497. } proxynames[] = {
  498. { "http:", PROXY_HTTP },
  499. { "http0:", PROXY_HTTP_1_0 },
  500. { "socks4:", PROXY_SOCKS4 },
  501. { "socks5:", PROXY_SOCKS5 },
  502. { "socks4a:", PROXY_SOCKS4A },
  503. { "socks5h:", PROXY_SOCKS5H },
  504. { NULL, 0 }
  505. };
  506. const char *proxytype(proxytypes_t proxytype)
  507. {
  508. int i;
  509. for (i = 0; proxynames[i].name; i++)
  510. if (proxynames[i].proxytype == proxytype)
  511. return proxynames[i].name;
  512. return "invalid";
  513. }
  514. char *get_proxy(char *url, struct pool *pool)
  515. {
  516. pool->rpc_proxy = NULL;
  517. char *split;
  518. int plen, len, i;
  519. for (i = 0; proxynames[i].name; i++) {
  520. plen = strlen(proxynames[i].name);
  521. if (strncmp(url, proxynames[i].name, plen) == 0) {
  522. if (!(split = strchr(url, '|')))
  523. return url;
  524. *split = '\0';
  525. len = split - url;
  526. pool->rpc_proxy = malloc(1 + len - plen);
  527. if (!(pool->rpc_proxy))
  528. quithere(1, "Failed to malloc rpc_proxy");
  529. strcpy(pool->rpc_proxy, url + plen);
  530. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  531. pool->rpc_proxytype = proxynames[i].proxytype;
  532. url = split + 1;
  533. break;
  534. }
  535. }
  536. return url;
  537. }
  538. /* Adequate size s==len*2 + 1 must be alloced to use this variant */
  539. void __bin2hex(char *s, const unsigned char *p, size_t len)
  540. {
  541. int i;
  542. static const char hex[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  543. for (i = 0; i < (int)len; i++) {
  544. *s++ = hex[p[i] >> 4];
  545. *s++ = hex[p[i] & 0xF];
  546. }
  547. *s++ = '\0';
  548. }
  549. /* Returns a malloced array string of a binary value of arbitrary length. The
  550. * array is rounded up to a 4 byte size to appease architectures that need
  551. * aligned array sizes */
  552. char *bin2hex(const unsigned char *p, size_t len)
  553. {
  554. ssize_t slen;
  555. char *s;
  556. slen = len * 2 + 1;
  557. if (slen % 4)
  558. slen += 4 - (slen % 4);
  559. s = calloc(slen, 1);
  560. if (unlikely(!s))
  561. quithere(1, "Failed to calloc");
  562. __bin2hex(s, p, len);
  563. return s;
  564. }
  565. static const int hex2bin_tbl[256] = {
  566. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  567. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  568. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  569. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
  570. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  571. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  572. -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  573. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  574. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  575. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  576. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  577. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  578. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  579. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  580. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  581. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  582. };
  583. /* Does the reverse of bin2hex but does not allocate any ram */
  584. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  585. {
  586. int nibble1, nibble2;
  587. unsigned char idx;
  588. bool ret = false;
  589. while (*hexstr && len) {
  590. if (unlikely(!hexstr[1])) {
  591. applog(LOG_ERR, "hex2bin str truncated");
  592. return ret;
  593. }
  594. idx = *hexstr++;
  595. nibble1 = hex2bin_tbl[idx];
  596. idx = *hexstr++;
  597. nibble2 = hex2bin_tbl[idx];
  598. if (unlikely((nibble1 < 0) || (nibble2 < 0))) {
  599. applog(LOG_ERR, "hex2bin scan failed");
  600. return ret;
  601. }
  602. *p++ = (((unsigned char)nibble1) << 4) | ((unsigned char)nibble2);
  603. --len;
  604. }
  605. if (likely(len == 0 && *hexstr == 0))
  606. ret = true;
  607. return ret;
  608. }
  609. static bool _valid_hex(char *s, const char *file, const char *func, const int line)
  610. {
  611. bool ret = false;
  612. int i, len;
  613. if (unlikely(!s)) {
  614. applog(LOG_ERR, "Null string passed to valid_hex from"IN_FMT_FFL, file, func, line);
  615. return ret;
  616. }
  617. len = strlen(s);
  618. for (i = 0; i < len; i++) {
  619. unsigned char idx = s[i];
  620. if (unlikely(hex2bin_tbl[idx] < 0)) {
  621. applog(LOG_ERR, "Invalid char 0x%x passed to valid_hex from"IN_FMT_FFL, idx, file, func, line);
  622. return ret;
  623. }
  624. }
  625. ret = true;
  626. return ret;
  627. }
  628. #define valid_hex(s) _valid_hex(s, __FILE__, __func__, __LINE__)
  629. static bool _valid_ascii(char *s, const char *file, const char *func, const int line)
  630. {
  631. bool ret = false;
  632. int i, len;
  633. if (unlikely(!s)) {
  634. applog(LOG_ERR, "Null string passed to valid_ascii from"IN_FMT_FFL, file, func, line);
  635. return ret;
  636. }
  637. len = strlen(s);
  638. if (unlikely(!len)) {
  639. applog(LOG_ERR, "Zero length string passed to valid_ascii from"IN_FMT_FFL, file, func, line);
  640. return ret;
  641. }
  642. for (i = 0; i < len; i++) {
  643. unsigned char idx = s[i];
  644. if (unlikely(idx < 32 || idx > 126)) {
  645. applog(LOG_ERR, "Invalid char 0x%x passed to valid_ascii from"IN_FMT_FFL, idx, file, func, line);
  646. return ret;
  647. }
  648. }
  649. ret = true;
  650. return ret;
  651. }
  652. #define valid_ascii(s) _valid_ascii(s, __FILE__, __func__, __LINE__)
  653. static const int b58tobin_tbl[] = {
  654. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  655. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  656. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  657. -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, -1, -1, -1, -1, -1, -1,
  658. -1, 9, 10, 11, 12, 13, 14, 15, 16, -1, 17, 18, 19, 20, 21, -1,
  659. 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1,
  660. -1, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46,
  661. 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57
  662. };
  663. /* b58bin should always be at least 25 bytes long and already checked to be
  664. * valid. */
  665. void b58tobin(unsigned char *b58bin, const char *b58)
  666. {
  667. uint32_t c, bin32[7];
  668. int len, i, j;
  669. uint64_t t;
  670. memset(bin32, 0, 7 * sizeof(uint32_t));
  671. len = strlen(b58);
  672. for (i = 0; i < len; i++) {
  673. c = b58[i];
  674. c = b58tobin_tbl[c];
  675. for (j = 6; j >= 0; j--) {
  676. t = ((uint64_t)bin32[j]) * 58 + c;
  677. c = (t & 0x3f00000000ull) >> 32;
  678. bin32[j] = t & 0xffffffffull;
  679. }
  680. }
  681. *(b58bin++) = bin32[0] & 0xff;
  682. for (i = 1; i < 7; i++) {
  683. *((uint32_t *)b58bin) = htobe32(bin32[i]);
  684. b58bin += sizeof(uint32_t);
  685. }
  686. }
  687. void address_to_pubkeyhash(unsigned char *pkh, const char *addr)
  688. {
  689. unsigned char b58bin[25];
  690. memset(b58bin, 0, 25);
  691. b58tobin(b58bin, addr);
  692. pkh[0] = 0x76;
  693. pkh[1] = 0xa9;
  694. pkh[2] = 0x14;
  695. memcpy(&pkh[3], &b58bin[1], 20);
  696. pkh[23] = 0x88;
  697. pkh[24] = 0xac;
  698. }
  699. /* For encoding nHeight into coinbase, return how many bytes were used */
  700. int ser_number(unsigned char *s, int32_t val)
  701. {
  702. int32_t *i32 = (int32_t *)&s[1];
  703. int len;
  704. if (val < 128)
  705. len = 1;
  706. else if (val < 16512)
  707. len = 2;
  708. else if (val < 2113664)
  709. len = 3;
  710. else
  711. len = 4;
  712. *i32 = htole32(val);
  713. s[0] = len++;
  714. return len;
  715. }
  716. /* For encoding variable length strings */
  717. unsigned char *ser_string(char *s, int *slen)
  718. {
  719. size_t len = strlen(s);
  720. unsigned char *ret;
  721. ret = malloc(1 + len + 8); // Leave room for largest size
  722. if (unlikely(!ret))
  723. quit(1, "Failed to malloc ret in ser_string");
  724. if (len < 253) {
  725. ret[0] = len;
  726. memcpy(ret + 1, s, len);
  727. *slen = len + 1;
  728. } else if (len < 0x10000) {
  729. uint16_t *u16 = (uint16_t *)&ret[1];
  730. ret[0] = 253;
  731. *u16 = htobe16(len);
  732. memcpy(ret + 3, s, len);
  733. *slen = len + 3;
  734. } else {
  735. /* size_t is only 32 bit on many platforms anyway */
  736. uint32_t *u32 = (uint32_t *)&ret[1];
  737. ret[0] = 254;
  738. *u32 = htobe32(len);
  739. memcpy(ret + 5, s, len);
  740. *slen = len + 5;
  741. }
  742. return ret;
  743. }
  744. bool fulltest(const unsigned char *hash, const unsigned char *target)
  745. {
  746. uint32_t *hash32 = (uint32_t *)hash;
  747. uint32_t *target32 = (uint32_t *)target;
  748. bool rc = true;
  749. int i;
  750. for (i = 28 / 4; i >= 0; i--) {
  751. uint32_t h32tmp = le32toh(hash32[i]);
  752. uint32_t t32tmp = le32toh(target32[i]);
  753. if (h32tmp > t32tmp) {
  754. rc = false;
  755. break;
  756. }
  757. if (h32tmp < t32tmp) {
  758. rc = true;
  759. break;
  760. }
  761. }
  762. if (opt_debug) {
  763. unsigned char hash_swap[32], target_swap[32];
  764. char *hash_str, *target_str;
  765. swab256(hash_swap, hash);
  766. swab256(target_swap, target);
  767. hash_str = bin2hex(hash_swap, 32);
  768. target_str = bin2hex(target_swap, 32);
  769. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  770. hash_str,
  771. target_str,
  772. rc ? "YES (hash <= target)" :
  773. "no (false positive; hash > target)");
  774. free(hash_str);
  775. free(target_str);
  776. }
  777. return rc;
  778. }
  779. struct thread_q *tq_new(void)
  780. {
  781. struct thread_q *tq;
  782. tq = calloc(1, sizeof(*tq));
  783. if (!tq)
  784. return NULL;
  785. INIT_LIST_HEAD(&tq->q);
  786. pthread_mutex_init(&tq->mutex, NULL);
  787. pthread_cond_init(&tq->cond, NULL);
  788. return tq;
  789. }
  790. void tq_free(struct thread_q *tq)
  791. {
  792. struct tq_ent *ent, *iter;
  793. if (!tq)
  794. return;
  795. list_for_each_entry_safe(ent, iter, &tq->q, q_node) {
  796. list_del(&ent->q_node);
  797. free(ent);
  798. }
  799. pthread_cond_destroy(&tq->cond);
  800. pthread_mutex_destroy(&tq->mutex);
  801. memset(tq, 0, sizeof(*tq)); /* poison */
  802. free(tq);
  803. }
  804. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  805. {
  806. mutex_lock(&tq->mutex);
  807. tq->frozen = frozen;
  808. pthread_cond_signal(&tq->cond);
  809. mutex_unlock(&tq->mutex);
  810. }
  811. void tq_freeze(struct thread_q *tq)
  812. {
  813. tq_freezethaw(tq, true);
  814. }
  815. void tq_thaw(struct thread_q *tq)
  816. {
  817. tq_freezethaw(tq, false);
  818. }
  819. bool tq_push(struct thread_q *tq, void *data)
  820. {
  821. struct tq_ent *ent;
  822. bool rc = true;
  823. ent = calloc(1, sizeof(*ent));
  824. if (!ent)
  825. return false;
  826. ent->data = data;
  827. INIT_LIST_HEAD(&ent->q_node);
  828. mutex_lock(&tq->mutex);
  829. if (!tq->frozen) {
  830. list_add_tail(&ent->q_node, &tq->q);
  831. } else {
  832. free(ent);
  833. rc = false;
  834. }
  835. pthread_cond_signal(&tq->cond);
  836. mutex_unlock(&tq->mutex);
  837. return rc;
  838. }
  839. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  840. {
  841. struct tq_ent *ent;
  842. void *rval = NULL;
  843. int rc;
  844. mutex_lock(&tq->mutex);
  845. if (!list_empty(&tq->q))
  846. goto pop;
  847. if (abstime)
  848. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  849. else
  850. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  851. if (rc)
  852. goto out;
  853. if (list_empty(&tq->q))
  854. goto out;
  855. pop:
  856. ent = list_entry(tq->q.next, struct tq_ent, q_node);
  857. rval = ent->data;
  858. list_del(&ent->q_node);
  859. free(ent);
  860. out:
  861. mutex_unlock(&tq->mutex);
  862. return rval;
  863. }
  864. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  865. {
  866. cgsem_init(&thr->sem);
  867. return pthread_create(&thr->pth, attr, start, arg);
  868. }
  869. void thr_info_cancel(struct thr_info *thr)
  870. {
  871. if (!thr)
  872. return;
  873. if (PTH(thr) != 0L) {
  874. pthread_cancel(thr->pth);
  875. PTH(thr) = 0L;
  876. }
  877. cgsem_destroy(&thr->sem);
  878. }
  879. void subtime(struct timeval *a, struct timeval *b)
  880. {
  881. timersub(a, b, b);
  882. }
  883. void addtime(struct timeval *a, struct timeval *b)
  884. {
  885. timeradd(a, b, b);
  886. }
  887. bool time_more(struct timeval *a, struct timeval *b)
  888. {
  889. return timercmp(a, b, >);
  890. }
  891. bool time_less(struct timeval *a, struct timeval *b)
  892. {
  893. return timercmp(a, b, <);
  894. }
  895. void copy_time(struct timeval *dest, const struct timeval *src)
  896. {
  897. memcpy(dest, src, sizeof(struct timeval));
  898. }
  899. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  900. {
  901. val->tv_sec = spec->tv_sec;
  902. val->tv_usec = spec->tv_nsec / 1000;
  903. }
  904. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  905. {
  906. spec->tv_sec = val->tv_sec;
  907. spec->tv_nsec = val->tv_usec * 1000;
  908. }
  909. void us_to_timeval(struct timeval *val, int64_t us)
  910. {
  911. lldiv_t tvdiv = lldiv(us, 1000000);
  912. val->tv_sec = tvdiv.quot;
  913. val->tv_usec = tvdiv.rem;
  914. }
  915. void us_to_timespec(struct timespec *spec, int64_t us)
  916. {
  917. lldiv_t tvdiv = lldiv(us, 1000000);
  918. spec->tv_sec = tvdiv.quot;
  919. spec->tv_nsec = tvdiv.rem * 1000;
  920. }
  921. void ms_to_timespec(struct timespec *spec, int64_t ms)
  922. {
  923. lldiv_t tvdiv = lldiv(ms, 1000);
  924. spec->tv_sec = tvdiv.quot;
  925. spec->tv_nsec = tvdiv.rem * 1000000;
  926. }
  927. void ms_to_timeval(struct timeval *val, int64_t ms)
  928. {
  929. lldiv_t tvdiv = lldiv(ms, 1000);
  930. val->tv_sec = tvdiv.quot;
  931. val->tv_usec = tvdiv.rem * 1000;
  932. }
  933. void timeraddspec(struct timespec *a, const struct timespec *b)
  934. {
  935. a->tv_sec += b->tv_sec;
  936. a->tv_nsec += b->tv_nsec;
  937. if (a->tv_nsec >= 1000000000) {
  938. a->tv_nsec -= 1000000000;
  939. a->tv_sec++;
  940. }
  941. }
  942. static int __maybe_unused timespec_to_ms(struct timespec *ts)
  943. {
  944. return ts->tv_sec * 1000 + ts->tv_nsec / 1000000;
  945. }
  946. /* Subtract b from a */
  947. static void __maybe_unused timersubspec(struct timespec *a, const struct timespec *b)
  948. {
  949. a->tv_sec -= b->tv_sec;
  950. a->tv_nsec -= b->tv_nsec;
  951. if (a->tv_nsec < 0) {
  952. a->tv_nsec += 1000000000;
  953. a->tv_sec--;
  954. }
  955. }
  956. /* These are cgminer specific sleep functions that use an absolute nanosecond
  957. * resolution timer to avoid poor usleep accuracy and overruns. */
  958. #ifdef WIN32
  959. /* Windows start time is since 1601 LOL so convert it to unix epoch 1970. */
  960. #define EPOCHFILETIME (116444736000000000LL)
  961. /* Return the system time as an lldiv_t in decimicroseconds. */
  962. static void decius_time(lldiv_t *lidiv)
  963. {
  964. FILETIME ft;
  965. LARGE_INTEGER li;
  966. GetSystemTimeAsFileTime(&ft);
  967. li.LowPart = ft.dwLowDateTime;
  968. li.HighPart = ft.dwHighDateTime;
  969. li.QuadPart -= EPOCHFILETIME;
  970. /* SystemTime is in decimicroseconds so divide by an unusual number */
  971. *lidiv = lldiv(li.QuadPart, 10000000);
  972. }
  973. /* This is a cgminer gettimeofday wrapper. Since we always call gettimeofday
  974. * with tz set to NULL, and windows' default resolution is only 15ms, this
  975. * gives us higher resolution times on windows. */
  976. void cgtime(struct timeval *tv)
  977. {
  978. lldiv_t lidiv;
  979. decius_time(&lidiv);
  980. tv->tv_sec = lidiv.quot;
  981. tv->tv_usec = lidiv.rem / 10;
  982. }
  983. #else /* WIN32 */
  984. void cgtime(struct timeval *tv)
  985. {
  986. gettimeofday(tv, NULL);
  987. }
  988. int cgtimer_to_ms(cgtimer_t *cgt)
  989. {
  990. return timespec_to_ms(cgt);
  991. }
  992. /* Subtracts b from a and stores it in res. */
  993. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  994. {
  995. res->tv_sec = a->tv_sec - b->tv_sec;
  996. res->tv_nsec = a->tv_nsec - b->tv_nsec;
  997. if (res->tv_nsec < 0) {
  998. res->tv_nsec += 1000000000;
  999. res->tv_sec--;
  1000. }
  1001. }
  1002. #endif /* WIN32 */
  1003. #ifdef CLOCK_MONOTONIC /* Essentially just linux */
  1004. void cgtimer_time(cgtimer_t *ts_start)
  1005. {
  1006. clock_gettime(CLOCK_MONOTONIC, ts_start);
  1007. }
  1008. static void nanosleep_abstime(struct timespec *ts_end)
  1009. {
  1010. int ret;
  1011. do {
  1012. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  1013. } while (ret == EINTR);
  1014. }
  1015. /* Reentrant version of cgsleep functions allow start time to be set separately
  1016. * from the beginning of the actual sleep, allowing scheduling delays to be
  1017. * counted in the sleep. */
  1018. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1019. {
  1020. struct timespec ts_end;
  1021. ms_to_timespec(&ts_end, ms);
  1022. timeraddspec(&ts_end, ts_start);
  1023. nanosleep_abstime(&ts_end);
  1024. }
  1025. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1026. {
  1027. struct timespec ts_end;
  1028. us_to_timespec(&ts_end, us);
  1029. timeraddspec(&ts_end, ts_start);
  1030. nanosleep_abstime(&ts_end);
  1031. }
  1032. #else /* CLOCK_MONOTONIC */
  1033. #ifdef __MACH__
  1034. #include <mach/clock.h>
  1035. #include <mach/mach.h>
  1036. void cgtimer_time(cgtimer_t *ts_start)
  1037. {
  1038. clock_serv_t cclock;
  1039. mach_timespec_t mts;
  1040. host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  1041. clock_get_time(cclock, &mts);
  1042. mach_port_deallocate(mach_task_self(), cclock);
  1043. ts_start->tv_sec = mts.tv_sec;
  1044. ts_start->tv_nsec = mts.tv_nsec;
  1045. }
  1046. #elif !defined(WIN32) /* __MACH__ - Everything not linux/macosx/win32 */
  1047. void cgtimer_time(cgtimer_t *ts_start)
  1048. {
  1049. struct timeval tv;
  1050. cgtime(&tv);
  1051. ts_start->tv_sec = tv->tv_sec;
  1052. ts_start->tv_nsec = tv->tv_usec * 1000;
  1053. }
  1054. #endif /* __MACH__ */
  1055. #ifdef WIN32
  1056. /* For windows we use the SystemTime stored as a LARGE_INTEGER as the cgtimer_t
  1057. * typedef, allowing us to have sub-microsecond resolution for times, do simple
  1058. * arithmetic for timer calculations, and use windows' own hTimers to get
  1059. * accurate absolute timeouts. */
  1060. int cgtimer_to_ms(cgtimer_t *cgt)
  1061. {
  1062. return (int)(cgt->QuadPart / 10000LL);
  1063. }
  1064. /* Subtracts b from a and stores it in res. */
  1065. void cgtimer_sub(cgtimer_t *a, cgtimer_t *b, cgtimer_t *res)
  1066. {
  1067. res->QuadPart = a->QuadPart - b->QuadPart;
  1068. }
  1069. /* Note that cgtimer time is NOT offset by the unix epoch since we use absolute
  1070. * timeouts with hTimers. */
  1071. void cgtimer_time(cgtimer_t *ts_start)
  1072. {
  1073. FILETIME ft;
  1074. GetSystemTimeAsFileTime(&ft);
  1075. ts_start->LowPart = ft.dwLowDateTime;
  1076. ts_start->HighPart = ft.dwHighDateTime;
  1077. }
  1078. static void liSleep(LARGE_INTEGER *li, int timeout)
  1079. {
  1080. HANDLE hTimer;
  1081. DWORD ret;
  1082. if (unlikely(timeout <= 0))
  1083. return;
  1084. hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
  1085. if (unlikely(!hTimer))
  1086. quit(1, "Failed to create hTimer in liSleep");
  1087. ret = SetWaitableTimer(hTimer, li, 0, NULL, NULL, 0);
  1088. if (unlikely(!ret))
  1089. quit(1, "Failed to SetWaitableTimer in liSleep");
  1090. /* We still use a timeout as a sanity check in case the system time
  1091. * is changed while we're running */
  1092. ret = WaitForSingleObject(hTimer, timeout);
  1093. if (unlikely(ret != WAIT_OBJECT_0 && ret != WAIT_TIMEOUT))
  1094. quit(1, "Failed to WaitForSingleObject in liSleep");
  1095. CloseHandle(hTimer);
  1096. }
  1097. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1098. {
  1099. LARGE_INTEGER li;
  1100. li.QuadPart = ts_start->QuadPart + (int64_t)ms * 10000LL;
  1101. liSleep(&li, ms);
  1102. }
  1103. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1104. {
  1105. LARGE_INTEGER li;
  1106. int ms;
  1107. li.QuadPart = ts_start->QuadPart + us * 10LL;
  1108. ms = us / 1000;
  1109. if (!ms)
  1110. ms = 1;
  1111. liSleep(&li, ms);
  1112. }
  1113. #else /* WIN32 */
  1114. static void cgsleep_spec(struct timespec *ts_diff, const struct timespec *ts_start)
  1115. {
  1116. struct timespec now;
  1117. timeraddspec(ts_diff, ts_start);
  1118. cgtimer_time(&now);
  1119. timersubspec(ts_diff, &now);
  1120. if (unlikely(ts_diff->tv_sec < 0))
  1121. return;
  1122. nanosleep(ts_diff, NULL);
  1123. }
  1124. void cgsleep_ms_r(cgtimer_t *ts_start, int ms)
  1125. {
  1126. struct timespec ts_diff;
  1127. ms_to_timespec(&ts_diff, ms);
  1128. cgsleep_spec(&ts_diff, ts_start);
  1129. }
  1130. void cgsleep_us_r(cgtimer_t *ts_start, int64_t us)
  1131. {
  1132. struct timespec ts_diff;
  1133. us_to_timespec(&ts_diff, us);
  1134. cgsleep_spec(&ts_diff, ts_start);
  1135. }
  1136. #endif /* WIN32 */
  1137. #endif /* CLOCK_MONOTONIC */
  1138. void cgsleep_ms(int ms)
  1139. {
  1140. cgtimer_t ts_start;
  1141. cgsleep_prepare_r(&ts_start);
  1142. cgsleep_ms_r(&ts_start, ms);
  1143. }
  1144. void cgsleep_us(int64_t us)
  1145. {
  1146. cgtimer_t ts_start;
  1147. cgsleep_prepare_r(&ts_start);
  1148. cgsleep_us_r(&ts_start, us);
  1149. }
  1150. /* Returns the microseconds difference between end and start times as a double */
  1151. double us_tdiff(struct timeval *end, struct timeval *start)
  1152. {
  1153. /* Sanity check. We should only be using this for small differences so
  1154. * limit the max to 60 seconds. */
  1155. if (unlikely(end->tv_sec - start->tv_sec > 60))
  1156. return 60000000;
  1157. return (end->tv_sec - start->tv_sec) * 1000000 + (end->tv_usec - start->tv_usec);
  1158. }
  1159. /* Returns the milliseconds difference between end and start times */
  1160. int ms_tdiff(struct timeval *end, struct timeval *start)
  1161. {
  1162. /* Like us_tdiff, limit to 1 hour. */
  1163. if (unlikely(end->tv_sec - start->tv_sec > 3600))
  1164. return 3600000;
  1165. return (end->tv_sec - start->tv_sec) * 1000 + (end->tv_usec - start->tv_usec) / 1000;
  1166. }
  1167. /* Returns the seconds difference between end and start times as a double */
  1168. double tdiff(struct timeval *end, struct timeval *start)
  1169. {
  1170. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1171. }
  1172. void check_extranonce_option(struct pool *pool, char * url)
  1173. {
  1174. char extra_op[16], *extra_op_loc;
  1175. extra_op_loc = strstr(url, "#");
  1176. if (extra_op_loc && !pool->extranonce_subscribe)
  1177. {
  1178. strncpy(extra_op, extra_op_loc, sizeof(extra_op));
  1179. extra_op[sizeof(extra_op) - 1] = '\0';
  1180. *extra_op_loc = '\0';
  1181. if (!strcmp(extra_op, "#xnsub"))
  1182. {
  1183. pool->extranonce_subscribe = true;
  1184. applog(LOG_DEBUG, "Pool %d extranonce subscribe enabled.", pool->pool_no);
  1185. }
  1186. }
  1187. return;
  1188. }
  1189. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1190. {
  1191. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1192. char url_address[256], port[6];
  1193. int url_len, port_len = 0;
  1194. *sockaddr_url = url;
  1195. url_begin = strstr(url, "//");
  1196. if (!url_begin)
  1197. url_begin = url;
  1198. else
  1199. url_begin += 2;
  1200. /* Look for numeric ipv6 entries */
  1201. ipv6_begin = strstr(url_begin, "[");
  1202. ipv6_end = strstr(url_begin, "]");
  1203. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1204. url_end = strstr(ipv6_end, ":");
  1205. else
  1206. url_end = strstr(url_begin, ":");
  1207. if (url_end) {
  1208. url_len = url_end - url_begin;
  1209. port_len = strlen(url_begin) - url_len - 1;
  1210. if (port_len < 1)
  1211. return false;
  1212. port_start = url_end + 1;
  1213. } else
  1214. url_len = strlen(url_begin);
  1215. if (url_len < 1)
  1216. return false;
  1217. snprintf(url_address, 254, "%.*s", url_len, url_begin);
  1218. if (port_len) {
  1219. char *slash;
  1220. snprintf(port, 6, "%.*s", port_len, port_start);
  1221. slash = strchr(port, '/');
  1222. if (slash)
  1223. *slash = '\0';
  1224. } else
  1225. strcpy(port, "80");
  1226. *sockaddr_port = strdup(port);
  1227. *sockaddr_url = strdup(url_address);
  1228. return true;
  1229. }
  1230. enum send_ret {
  1231. SEND_OK,
  1232. SEND_SELECTFAIL,
  1233. SEND_SENDFAIL,
  1234. SEND_INACTIVE
  1235. };
  1236. /* Send a single command across a socket, appending \n to it. This should all
  1237. * be done under stratum lock except when first establishing the socket */
  1238. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1239. {
  1240. SOCKETTYPE sock = pool->sock;
  1241. ssize_t ssent = 0;
  1242. strcat(s, "\n");
  1243. len++;
  1244. while (len > 0 ) {
  1245. struct timeval timeout = {1, 0};
  1246. ssize_t sent;
  1247. fd_set wd;
  1248. retry:
  1249. FD_ZERO(&wd);
  1250. FD_SET(sock, &wd);
  1251. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1) {
  1252. if (interrupted())
  1253. goto retry;
  1254. return SEND_SELECTFAIL;
  1255. }
  1256. #ifdef __APPLE__
  1257. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1258. #elif WIN32
  1259. sent = send(pool->sock, s + ssent, len, 0);
  1260. #else
  1261. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1262. #endif
  1263. if (sent < 0) {
  1264. if (!sock_blocks())
  1265. return SEND_SENDFAIL;
  1266. sent = 0;
  1267. }
  1268. ssent += sent;
  1269. len -= sent;
  1270. }
  1271. pool->cgminer_pool_stats.times_sent++;
  1272. pool->cgminer_pool_stats.bytes_sent += ssent;
  1273. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1274. return SEND_OK;
  1275. }
  1276. bool stratum_send(struct pool *pool, char *s, ssize_t len)
  1277. {
  1278. enum send_ret ret = SEND_INACTIVE;
  1279. if (opt_protocol)
  1280. applog(LOG_DEBUG, "SEND: %s", s);
  1281. mutex_lock(&pool->stratum_lock);
  1282. if (pool->stratum_active)
  1283. ret = __stratum_send(pool, s, len);
  1284. mutex_unlock(&pool->stratum_lock);
  1285. /* This is to avoid doing applog under stratum_lock */
  1286. switch (ret) {
  1287. default:
  1288. case SEND_OK:
  1289. break;
  1290. case SEND_SELECTFAIL:
  1291. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1292. suspend_stratum(pool);
  1293. break;
  1294. case SEND_SENDFAIL:
  1295. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1296. suspend_stratum(pool);
  1297. break;
  1298. case SEND_INACTIVE:
  1299. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1300. break;
  1301. }
  1302. return (ret == SEND_OK);
  1303. }
  1304. static bool socket_full(struct pool *pool, int wait)
  1305. {
  1306. SOCKETTYPE sock = pool->sock;
  1307. struct timeval timeout;
  1308. fd_set rd;
  1309. if (unlikely(wait < 0))
  1310. wait = 0;
  1311. FD_ZERO(&rd);
  1312. FD_SET(sock, &rd);
  1313. timeout.tv_usec = 0;
  1314. timeout.tv_sec = wait;
  1315. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1316. return true;
  1317. return false;
  1318. }
  1319. /* Check to see if Santa's been good to you */
  1320. bool sock_full(struct pool *pool)
  1321. {
  1322. if (strlen(pool->sockbuf))
  1323. return true;
  1324. return (socket_full(pool, 0));
  1325. }
  1326. static void clear_sockbuf(struct pool *pool)
  1327. {
  1328. strcpy(pool->sockbuf, "");
  1329. }
  1330. static void clear_sock(struct pool *pool)
  1331. {
  1332. ssize_t n;
  1333. mutex_lock(&pool->stratum_lock);
  1334. do {
  1335. if (pool->sock)
  1336. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1337. else
  1338. n = 0;
  1339. } while (n > 0);
  1340. mutex_unlock(&pool->stratum_lock);
  1341. clear_sockbuf(pool);
  1342. }
  1343. /* Realloc memory to new size and zero any extra memory added */
  1344. void _recalloc(void **ptr, size_t old, size_t new, const char *file, const char *func, const int line)
  1345. {
  1346. if (new == old)
  1347. return;
  1348. *ptr = realloc(*ptr, new);
  1349. if (unlikely(!*ptr))
  1350. quitfrom(1, file, func, line, "Failed to realloc");
  1351. if (new > old)
  1352. memset(*ptr + old, 0, new - old);
  1353. }
  1354. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1355. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1356. * and zeroing the new memory */
  1357. static void recalloc_sock(struct pool *pool, size_t len)
  1358. {
  1359. size_t old, new;
  1360. old = strlen(pool->sockbuf);
  1361. new = old + len + 1;
  1362. if (new < pool->sockbuf_size)
  1363. return;
  1364. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1365. // Avoid potentially recursive locking
  1366. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %d", new);
  1367. pool->sockbuf = realloc(pool->sockbuf, new);
  1368. if (!pool->sockbuf)
  1369. quithere(1, "Failed to realloc pool sockbuf");
  1370. memset(pool->sockbuf + old, 0, new - old);
  1371. pool->sockbuf_size = new;
  1372. }
  1373. /* Peeks at a socket to find the first end of line and then reads just that
  1374. * from the socket and returns that as a malloced char */
  1375. char *recv_line(struct pool *pool)
  1376. {
  1377. char *tok, *sret = NULL;
  1378. ssize_t len, buflen;
  1379. int waited = 0;
  1380. if (!strstr(pool->sockbuf, "\n")) {
  1381. struct timeval rstart, now;
  1382. cgtime(&rstart);
  1383. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1384. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1385. goto out;
  1386. }
  1387. do {
  1388. char s[RBUFSIZE];
  1389. size_t slen;
  1390. ssize_t n;
  1391. memset(s, 0, RBUFSIZE);
  1392. n = recv(pool->sock, s, RECVSIZE, 0);
  1393. if (!n) {
  1394. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1395. suspend_stratum(pool);
  1396. break;
  1397. }
  1398. cgtime(&now);
  1399. waited = tdiff(&now, &rstart);
  1400. if (n < 0) {
  1401. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1402. applog(LOG_DEBUG, "Failed to recv sock in recv_line");
  1403. suspend_stratum(pool);
  1404. break;
  1405. }
  1406. } else {
  1407. slen = strlen(s);
  1408. recalloc_sock(pool, slen);
  1409. strcat(pool->sockbuf, s);
  1410. }
  1411. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1412. }
  1413. buflen = strlen(pool->sockbuf);
  1414. tok = strtok(pool->sockbuf, "\n");
  1415. if (!tok) {
  1416. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1417. goto out;
  1418. }
  1419. sret = strdup(tok);
  1420. len = strlen(sret);
  1421. /* Copy what's left in the buffer after the \n, including the
  1422. * terminating \0 */
  1423. if (buflen > len + 1)
  1424. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1425. else
  1426. strcpy(pool->sockbuf, "");
  1427. pool->cgminer_pool_stats.times_received++;
  1428. pool->cgminer_pool_stats.bytes_received += len;
  1429. pool->cgminer_pool_stats.net_bytes_received += len;
  1430. out:
  1431. if (!sret)
  1432. clear_sock(pool);
  1433. else if (opt_protocol)
  1434. applog(LOG_DEBUG, "RECVD: %s", sret);
  1435. return sret;
  1436. }
  1437. /* Extracts a string value from a json array with error checking. To be used
  1438. * when the value of the string returned is only examined and not to be stored.
  1439. * See json_array_string below */
  1440. static char *__json_array_string(json_t *val, unsigned int entry)
  1441. {
  1442. json_t *arr_entry;
  1443. if (json_is_null(val))
  1444. return NULL;
  1445. if (!json_is_array(val))
  1446. return NULL;
  1447. if (entry > json_array_size(val))
  1448. return NULL;
  1449. arr_entry = json_array_get(val, entry);
  1450. if (!json_is_string(arr_entry))
  1451. return NULL;
  1452. return (char *)json_string_value(arr_entry);
  1453. }
  1454. /* Creates a freshly malloced dup of __json_array_string */
  1455. static char *json_array_string(json_t *val, unsigned int entry)
  1456. {
  1457. char *buf = __json_array_string(val, entry);
  1458. if (buf)
  1459. return strdup(buf);
  1460. return NULL;
  1461. }
  1462. static char *blank_merkle = "0000000000000000000000000000000000000000000000000000000000000000";
  1463. static bool parse_notify(struct pool *pool, json_t *val)
  1464. {
  1465. char *job_id, *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit,
  1466. *ntime, header[228];
  1467. unsigned char *cb1 = NULL, *cb2 = NULL;
  1468. size_t cb1_len, cb2_len, alloc_len;
  1469. bool clean, ret = false;
  1470. int merkles, i;
  1471. json_t *arr;
  1472. arr = json_array_get(val, 4);
  1473. if (!arr || !json_is_array(arr))
  1474. goto out;
  1475. merkles = json_array_size(arr);
  1476. job_id = json_array_string(val, 0);
  1477. prev_hash = __json_array_string(val, 1);
  1478. coinbase1 = json_array_string(val, 2);
  1479. coinbase2 = json_array_string(val, 3);
  1480. bbversion = __json_array_string(val, 5);
  1481. nbit = __json_array_string(val, 6);
  1482. ntime = __json_array_string(val, 7);
  1483. clean = json_is_true(json_array_get(val, 8));
  1484. if (!valid_ascii(job_id) || !valid_hex(prev_hash) || !valid_hex(coinbase1) ||
  1485. !valid_hex(coinbase2) || !valid_hex(bbversion) || !valid_hex(nbit) ||
  1486. !valid_hex(ntime)) {
  1487. /* Annoying but we must not leak memory */
  1488. free(job_id);
  1489. free(coinbase1);
  1490. free(coinbase2);
  1491. goto out;
  1492. }
  1493. cg_wlock(&pool->data_lock);
  1494. free(pool->swork.job_id);
  1495. pool->swork.job_id = job_id;
  1496. snprintf(pool->prev_hash, 65, "%s", prev_hash);
  1497. cb1_len = strlen(coinbase1) / 2;
  1498. cb2_len = strlen(coinbase2) / 2;
  1499. snprintf(pool->bbversion, 9, "%s", bbversion);
  1500. snprintf(pool->nbit, 9, "%s", nbit);
  1501. snprintf(pool->ntime, 9, "%s", ntime);
  1502. pool->swork.clean = clean;
  1503. alloc_len = pool->coinbase_len = cb1_len + pool->n1_len + pool->n2size + cb2_len;
  1504. pool->nonce2_offset = cb1_len + pool->n1_len;
  1505. for (i = 0; i < pool->merkles; i++)
  1506. free(pool->swork.merkle_bin[i]);
  1507. if (merkles) {
  1508. pool->swork.merkle_bin = realloc(pool->swork.merkle_bin,
  1509. sizeof(char *) * merkles + 1);
  1510. for (i = 0; i < merkles; i++) {
  1511. char *merkle = json_array_string(arr, i);
  1512. pool->swork.merkle_bin[i] = malloc(32);
  1513. if (unlikely(!pool->swork.merkle_bin[i]))
  1514. quit(1, "Failed to malloc pool swork merkle_bin");
  1515. if (opt_protocol)
  1516. applog(LOG_DEBUG, "merkle %d: %s", i, merkle);
  1517. ret = hex2bin(pool->swork.merkle_bin[i], merkle, 32);
  1518. free(merkle);
  1519. if (unlikely(!ret)) {
  1520. applog(LOG_ERR, "Failed to convert merkle to merkle_bin in parse_notify");
  1521. goto out_unlock;
  1522. }
  1523. }
  1524. }
  1525. pool->merkles = merkles;
  1526. if (clean)
  1527. pool->nonce2 = 0;
  1528. #if 0
  1529. header_len = strlen(pool->bbversion) +
  1530. strlen(pool->prev_hash);
  1531. /* merkle_hash */ 32 +
  1532. strlen(pool->ntime) +
  1533. strlen(pool->nbit) +
  1534. /* nonce */ 8 +
  1535. /* workpadding */ 96;
  1536. #endif
  1537. snprintf(header, 225,
  1538. "%s%s%s%s%s%s%s",
  1539. pool->bbversion,
  1540. pool->prev_hash,
  1541. blank_merkle,
  1542. pool->ntime,
  1543. pool->nbit,
  1544. "00000000", /* nonce */
  1545. workpadding);
  1546. ret = hex2bin(pool->header_bin, header, 112);
  1547. if (unlikely(!ret)) {
  1548. applog(LOG_ERR, "Failed to convert header to header_bin in parse_notify");
  1549. goto out_unlock;
  1550. }
  1551. cb1 = alloca(cb1_len);
  1552. ret = hex2bin(cb1, coinbase1, cb1_len);
  1553. if (unlikely(!ret)) {
  1554. applog(LOG_ERR, "Failed to convert cb1 to cb1_bin in parse_notify");
  1555. goto out_unlock;
  1556. }
  1557. cb2 = alloca(cb2_len);
  1558. ret = hex2bin(cb2, coinbase2, cb2_len);
  1559. if (unlikely(!ret)) {
  1560. applog(LOG_ERR, "Failed to convert cb2 to cb2_bin in parse_notify");
  1561. goto out_unlock;
  1562. }
  1563. free(pool->coinbase);
  1564. align_len(&alloc_len);
  1565. pool->coinbase = calloc(alloc_len, 1);
  1566. if (unlikely(!pool->coinbase))
  1567. quit(1, "Failed to calloc pool coinbase in parse_notify");
  1568. memcpy(pool->coinbase, cb1, cb1_len);
  1569. memcpy(pool->coinbase + cb1_len, pool->nonce1bin, pool->n1_len);
  1570. memcpy(pool->coinbase + cb1_len + pool->n1_len + pool->n2size, cb2, cb2_len);
  1571. if (opt_debug) {
  1572. char *cb = bin2hex(pool->coinbase, pool->coinbase_len);
  1573. applog(LOG_DEBUG, "Pool %d coinbase %s", pool->pool_no, cb);
  1574. free(cb);
  1575. }
  1576. out_unlock:
  1577. cg_wunlock(&pool->data_lock);
  1578. if (opt_protocol) {
  1579. applog(LOG_DEBUG, "job_id: %s", job_id);
  1580. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1581. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1582. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1583. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1584. applog(LOG_DEBUG, "nbit: %s", nbit);
  1585. applog(LOG_DEBUG, "ntime: %s", ntime);
  1586. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1587. }
  1588. free(coinbase1);
  1589. free(coinbase2);
  1590. /* A notify message is the closest stratum gets to a getwork */
  1591. pool->getwork_requested++;
  1592. total_getworks++;
  1593. if (pool == current_pool())
  1594. opt_work_update = true;
  1595. out:
  1596. return ret;
  1597. }
  1598. static bool parse_diff(struct pool *pool, json_t *val)
  1599. {
  1600. double old_diff, diff;
  1601. diff = json_number_value(json_array_get(val, 0));
  1602. if (diff == 0)
  1603. return false;
  1604. cg_wlock(&pool->data_lock);
  1605. old_diff = pool->sdiff;
  1606. pool->sdiff = diff;
  1607. cg_wunlock(&pool->data_lock);
  1608. if (old_diff != diff) {
  1609. int idiff = diff;
  1610. if ((double)idiff == diff)
  1611. applog(LOG_NOTICE, "Pool %d difficulty changed to %d",
  1612. pool->pool_no, idiff);
  1613. else
  1614. applog(LOG_NOTICE, "Pool %d difficulty changed to %.1f",
  1615. pool->pool_no, diff);
  1616. } else
  1617. applog(LOG_DEBUG, "Pool %d difficulty set to %f", pool->pool_no,
  1618. diff);
  1619. return true;
  1620. }
  1621. static bool parse_extranonce(struct pool *pool, json_t *val)
  1622. {
  1623. int n2size;
  1624. char* nonce1;
  1625. nonce1 = json_array_string(val, 0);
  1626. if (!valid_hex(nonce1)) {
  1627. applog(LOG_INFO, "Failed to get valid nonce1 in parse_extranonce");
  1628. goto out;
  1629. }
  1630. n2size = json_integer_value(json_array_get(val, 1));
  1631. if (n2size < 2 || n2size > 16) {
  1632. applog(LOG_INFO, "Failed to get valid n2size in parse_extranonce");
  1633. free(nonce1);
  1634. goto out;
  1635. }
  1636. cg_wlock(&pool->data_lock);
  1637. pool->nonce1 = nonce1;
  1638. pool->n1_len = strlen(nonce1) / 2;
  1639. free(pool->nonce1bin);
  1640. pool->nonce1bin = calloc(pool->n1_len, 1);
  1641. if (unlikely(!pool->nonce1bin))
  1642. quithere(1, "Failed to calloc pool->nonce1bin");
  1643. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  1644. pool->n2size = n2size;
  1645. applog(LOG_NOTICE, "Pool %d confirmed mining.extranonce.subscribe with extranonce1 %s extran2size %d",
  1646. pool->pool_no, pool->nonce1, pool->n2size);
  1647. cg_wunlock(&pool->data_lock);
  1648. return true;
  1649. out:
  1650. return false;
  1651. }
  1652. static void __suspend_stratum(struct pool *pool)
  1653. {
  1654. clear_sockbuf(pool);
  1655. pool->stratum_active = pool->stratum_notify = false;
  1656. if (pool->sock)
  1657. CLOSESOCKET(pool->sock);
  1658. pool->sock = 0;
  1659. }
  1660. static bool parse_reconnect(struct pool *pool, json_t *val)
  1661. {
  1662. char *sockaddr_url, *stratum_port, *tmp;
  1663. char *url, *port, address[256];
  1664. memset(address, 0, 255);
  1665. url = (char *)json_string_value(json_array_get(val, 0));
  1666. if (!url)
  1667. url = pool->sockaddr_url;
  1668. else {
  1669. char *dot_pool, *dot_reconnect;
  1670. dot_pool = strchr(pool->sockaddr_url, '.');
  1671. if (!dot_pool) {
  1672. applog(LOG_ERR, "Denied stratum reconnect request for pool without domain '%s'",
  1673. pool->sockaddr_url);
  1674. return false;
  1675. }
  1676. dot_reconnect = strchr(url, '.');
  1677. if (!dot_reconnect) {
  1678. applog(LOG_ERR, "Denied stratum reconnect request to url without domain '%s'",
  1679. url);
  1680. return false;
  1681. }
  1682. if (strcmp(dot_pool, dot_reconnect)) {
  1683. applog(LOG_ERR, "Denied stratum reconnect request to non-matching domain url '%s'",
  1684. pool->sockaddr_url);
  1685. return false;
  1686. }
  1687. }
  1688. port = (char *)json_string_value(json_array_get(val, 1));
  1689. if (!port)
  1690. port = pool->stratum_port;
  1691. snprintf(address, 254, "%s:%s", url, port);
  1692. if (!extract_sockaddr(address, &sockaddr_url, &stratum_port))
  1693. return false;
  1694. applog(LOG_WARNING, "Stratum reconnect requested from pool %d to %s", pool->pool_no, address);
  1695. clear_pool_work(pool);
  1696. mutex_lock(&pool->stratum_lock);
  1697. __suspend_stratum(pool);
  1698. tmp = pool->sockaddr_url;
  1699. pool->sockaddr_url = sockaddr_url;
  1700. pool->stratum_url = pool->sockaddr_url;
  1701. free(tmp);
  1702. tmp = pool->stratum_port;
  1703. pool->stratum_port = stratum_port;
  1704. free(tmp);
  1705. mutex_unlock(&pool->stratum_lock);
  1706. if (!restart_stratum(pool)) {
  1707. pool_failed(pool);
  1708. return false;
  1709. }
  1710. return true;
  1711. }
  1712. static bool send_version(struct pool *pool, json_t *val)
  1713. {
  1714. char s[RBUFSIZE];
  1715. int id = json_integer_value(json_object_get(val, "id"));
  1716. if (!id)
  1717. return false;
  1718. sprintf(s, "{\"id\": %d, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", id);
  1719. if (!stratum_send(pool, s, strlen(s)))
  1720. return false;
  1721. return true;
  1722. }
  1723. static bool show_message(struct pool *pool, json_t *val)
  1724. {
  1725. char *msg;
  1726. if (!json_is_array(val))
  1727. return false;
  1728. msg = (char *)json_string_value(json_array_get(val, 0));
  1729. if (!msg)
  1730. return false;
  1731. applog(LOG_NOTICE, "Pool %d message: %s", pool->pool_no, msg);
  1732. return true;
  1733. }
  1734. bool parse_method(struct pool *pool, char *s)
  1735. {
  1736. json_t *val = NULL, *method, *err_val, *params;
  1737. json_error_t err;
  1738. bool ret = false;
  1739. char *buf;
  1740. if (!s)
  1741. goto out;
  1742. val = JSON_LOADS(s, &err);
  1743. if (!val) {
  1744. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1745. goto out;
  1746. }
  1747. method = json_object_get(val, "method");
  1748. if (!method)
  1749. goto out_decref;
  1750. err_val = json_object_get(val, "error");
  1751. params = json_object_get(val, "params");
  1752. if (err_val && !json_is_null(err_val)) {
  1753. char *ss;
  1754. if (err_val)
  1755. ss = json_dumps(err_val, JSON_INDENT(3));
  1756. else
  1757. ss = strdup("(unknown reason)");
  1758. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1759. free(ss);
  1760. goto out_decref;
  1761. }
  1762. buf = (char *)json_string_value(method);
  1763. if (!buf)
  1764. goto out_decref;
  1765. if (!strncasecmp(buf, "mining.notify", 13)) {
  1766. if (parse_notify(pool, params))
  1767. pool->stratum_notify = ret = true;
  1768. else
  1769. pool->stratum_notify = ret = false;
  1770. goto out_decref;
  1771. }
  1772. if (!strncasecmp(buf, "mining.set_difficulty", 21)) {
  1773. ret = parse_diff(pool, params);
  1774. goto out_decref;
  1775. }
  1776. if(!strncasecmp(buf, "mining.set_extranonce", 21)) {
  1777. ret = parse_extranonce(pool, params);
  1778. goto out_decref;
  1779. }
  1780. if (!strncasecmp(buf, "client.reconnect", 16)) {
  1781. ret = parse_reconnect(pool, params);
  1782. goto out_decref;
  1783. }
  1784. if (!strncasecmp(buf, "client.get_version", 18)) {
  1785. ret = send_version(pool, val);
  1786. goto out_decref;
  1787. }
  1788. if (!strncasecmp(buf, "client.show_message", 19)) {
  1789. ret = show_message(pool, params);
  1790. goto out_decref;
  1791. }
  1792. out_decref:
  1793. json_decref(val);
  1794. out:
  1795. return ret;
  1796. }
  1797. bool auth_stratum(struct pool *pool)
  1798. {
  1799. json_t *val = NULL, *res_val, *err_val;
  1800. char s[RBUFSIZE], *sret = NULL;
  1801. json_error_t err;
  1802. bool ret = false;
  1803. sprintf(s, "{\"id\": %d, \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1804. swork_id++, pool->rpc_user, pool->rpc_pass);
  1805. if (!stratum_send(pool, s, strlen(s)))
  1806. return ret;
  1807. /* Parse all data in the queue and anything left should be auth */
  1808. while (42) {
  1809. sret = recv_line(pool);
  1810. if (!sret)
  1811. return ret;
  1812. if (parse_method(pool, sret))
  1813. free(sret);
  1814. else
  1815. break;
  1816. }
  1817. val = JSON_LOADS(sret, &err);
  1818. free(sret);
  1819. res_val = json_object_get(val, "result");
  1820. err_val = json_object_get(val, "error");
  1821. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1822. char *ss;
  1823. if (err_val)
  1824. ss = json_dumps(err_val, JSON_INDENT(3));
  1825. else
  1826. ss = strdup("(unknown reason)");
  1827. applog(LOG_INFO, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1828. free(ss);
  1829. suspend_stratum(pool);
  1830. goto out;
  1831. }
  1832. ret = true;
  1833. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1834. pool->probed = true;
  1835. successful_connect = true;
  1836. out:
  1837. json_decref(val);
  1838. return ret;
  1839. }
  1840. static int recv_byte(int sockd)
  1841. {
  1842. char c;
  1843. if (recv(sockd, &c, 1, 0) != -1)
  1844. return c;
  1845. return -1;
  1846. }
  1847. static bool http_negotiate(struct pool *pool, int sockd, bool http0)
  1848. {
  1849. char buf[1024];
  1850. int i, len;
  1851. if (http0) {
  1852. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.0\r\n\r\n",
  1853. pool->sockaddr_url, pool->stratum_port);
  1854. } else {
  1855. snprintf(buf, 1024, "CONNECT %s:%s HTTP/1.1\r\nHost: %s:%s\r\n\r\n",
  1856. pool->sockaddr_url, pool->stratum_port, pool->sockaddr_url,
  1857. pool->stratum_port);
  1858. }
  1859. applog(LOG_DEBUG, "Sending proxy %s:%s - %s",
  1860. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  1861. send(sockd, buf, strlen(buf), 0);
  1862. len = recv(sockd, buf, 12, 0);
  1863. if (len <= 0) {
  1864. applog(LOG_WARNING, "Couldn't read from proxy %s:%s after sending CONNECT",
  1865. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1866. return false;
  1867. }
  1868. buf[len] = '\0';
  1869. applog(LOG_DEBUG, "Received from proxy %s:%s - %s",
  1870. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  1871. if (strcmp(buf, "HTTP/1.1 200") && strcmp(buf, "HTTP/1.0 200")) {
  1872. applog(LOG_WARNING, "HTTP Error from proxy %s:%s - %s",
  1873. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port, buf);
  1874. return false;
  1875. }
  1876. /* Ignore unwanted headers till we get desired response */
  1877. for (i = 0; i < 4; i++) {
  1878. buf[i] = recv_byte(sockd);
  1879. if (buf[i] == (char)-1) {
  1880. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  1881. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1882. return false;
  1883. }
  1884. }
  1885. while (strncmp(buf, "\r\n\r\n", 4)) {
  1886. for (i = 0; i < 3; i++)
  1887. buf[i] = buf[i + 1];
  1888. buf[3] = recv_byte(sockd);
  1889. if (buf[3] == (char)-1) {
  1890. applog(LOG_WARNING, "Couldn't read HTTP byte from proxy %s:%s",
  1891. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1892. return false;
  1893. }
  1894. }
  1895. applog(LOG_DEBUG, "Success negotiating with %s:%s HTTP proxy",
  1896. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1897. return true;
  1898. }
  1899. static bool socks5_negotiate(struct pool *pool, int sockd)
  1900. {
  1901. unsigned char atyp, uclen;
  1902. unsigned short port;
  1903. char buf[515];
  1904. int i, len;
  1905. buf[0] = 0x05;
  1906. buf[1] = 0x01;
  1907. buf[2] = 0x00;
  1908. applog(LOG_DEBUG, "Attempting to negotiate with %s:%s SOCKS5 proxy",
  1909. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1910. send(sockd, buf, 3, 0);
  1911. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != buf[2]) {
  1912. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  1913. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1914. return false;
  1915. }
  1916. buf[0] = 0x05;
  1917. buf[1] = 0x01;
  1918. buf[2] = 0x00;
  1919. buf[3] = 0x03;
  1920. len = (strlen(pool->sockaddr_url));
  1921. if (len > 255)
  1922. len = 255;
  1923. uclen = len;
  1924. buf[4] = (uclen & 0xff);
  1925. memcpy(buf + 5, pool->sockaddr_url, len);
  1926. port = atoi(pool->stratum_port);
  1927. buf[5 + len] = (port >> 8);
  1928. buf[6 + len] = (port & 0xff);
  1929. send(sockd, buf, (7 + len), 0);
  1930. if (recv_byte(sockd) != 0x05 || recv_byte(sockd) != 0x00) {
  1931. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  1932. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1933. return false;
  1934. }
  1935. recv_byte(sockd);
  1936. atyp = recv_byte(sockd);
  1937. if (atyp == 0x01) {
  1938. for (i = 0; i < 4; i++)
  1939. recv_byte(sockd);
  1940. } else if (atyp == 0x03) {
  1941. len = recv_byte(sockd);
  1942. for (i = 0; i < len; i++)
  1943. recv_byte(sockd);
  1944. } else {
  1945. applog(LOG_WARNING, "Bad response from %s:%s SOCKS5 server",
  1946. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port );
  1947. return false;
  1948. }
  1949. for (i = 0; i < 2; i++)
  1950. recv_byte(sockd);
  1951. applog(LOG_DEBUG, "Success negotiating with %s:%s SOCKS5 proxy",
  1952. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  1953. return true;
  1954. }
  1955. static bool socks4_negotiate(struct pool *pool, int sockd, bool socks4a)
  1956. {
  1957. unsigned short port;
  1958. in_addr_t inp;
  1959. char buf[515];
  1960. int i, len;
  1961. buf[0] = 0x04;
  1962. buf[1] = 0x01;
  1963. port = atoi(pool->stratum_port);
  1964. buf[2] = port >> 8;
  1965. buf[3] = port & 0xff;
  1966. sprintf(&buf[8], "CGMINER");
  1967. /* See if we've been given an IP address directly to avoid needing to
  1968. * resolve it. */
  1969. inp = inet_addr(pool->sockaddr_url);
  1970. inp = ntohl(inp);
  1971. if ((int)inp != -1)
  1972. socks4a = false;
  1973. else {
  1974. /* Try to extract the IP address ourselves first */
  1975. struct addrinfo servinfobase, *servinfo, hints;
  1976. servinfo = &servinfobase;
  1977. memset(&hints, 0, sizeof(struct addrinfo));
  1978. hints.ai_family = AF_INET; /* IPV4 only */
  1979. if (!getaddrinfo(pool->sockaddr_url, NULL, &hints, &servinfo)) {
  1980. struct sockaddr_in *saddr_in = (struct sockaddr_in *)servinfo->ai_addr;
  1981. inp = ntohl(saddr_in->sin_addr.s_addr);
  1982. socks4a = false;
  1983. freeaddrinfo(servinfo);
  1984. }
  1985. }
  1986. if (!socks4a) {
  1987. if ((int)inp == -1) {
  1988. applog(LOG_WARNING, "Invalid IP address specified for socks4 proxy: %s",
  1989. pool->sockaddr_url);
  1990. return false;
  1991. }
  1992. buf[4] = (inp >> 24) & 0xFF;
  1993. buf[5] = (inp >> 16) & 0xFF;
  1994. buf[6] = (inp >> 8) & 0xFF;
  1995. buf[7] = (inp >> 0) & 0xFF;
  1996. send(sockd, buf, 16, 0);
  1997. } else {
  1998. /* This appears to not be working but hopefully most will be
  1999. * able to resolve IP addresses themselves. */
  2000. buf[4] = 0;
  2001. buf[5] = 0;
  2002. buf[6] = 0;
  2003. buf[7] = 1;
  2004. len = strlen(pool->sockaddr_url);
  2005. if (len > 255)
  2006. len = 255;
  2007. memcpy(&buf[16], pool->sockaddr_url, len);
  2008. len += 16;
  2009. buf[len++] = '\0';
  2010. send(sockd, buf, len, 0);
  2011. }
  2012. if (recv_byte(sockd) != 0x00 || recv_byte(sockd) != 0x5a) {
  2013. applog(LOG_WARNING, "Bad response from %s:%s SOCKS4 server",
  2014. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2015. return false;
  2016. }
  2017. for (i = 0; i < 6; i++)
  2018. recv_byte(sockd);
  2019. return true;
  2020. }
  2021. static void noblock_socket(SOCKETTYPE fd)
  2022. {
  2023. #ifndef WIN32
  2024. int flags = fcntl(fd, F_GETFL, 0);
  2025. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  2026. #else
  2027. u_long flags = 1;
  2028. ioctlsocket(fd, FIONBIO, &flags);
  2029. #endif
  2030. }
  2031. static void block_socket(SOCKETTYPE fd)
  2032. {
  2033. #ifndef WIN32
  2034. int flags = fcntl(fd, F_GETFL, 0);
  2035. fcntl(fd, F_SETFL, flags & ~O_NONBLOCK);
  2036. #else
  2037. u_long flags = 0;
  2038. ioctlsocket(fd, FIONBIO, &flags);
  2039. #endif
  2040. }
  2041. static bool sock_connecting(void)
  2042. {
  2043. #ifndef WIN32
  2044. return errno == EINPROGRESS;
  2045. #else
  2046. return WSAGetLastError() == WSAEWOULDBLOCK;
  2047. #endif
  2048. }
  2049. static bool setup_stratum_socket(struct pool *pool)
  2050. {
  2051. struct addrinfo servinfobase, *servinfo, *hints, *p;
  2052. char *sockaddr_url, *sockaddr_port;
  2053. int sockd;
  2054. mutex_lock(&pool->stratum_lock);
  2055. pool->stratum_active = false;
  2056. if (pool->sock)
  2057. CLOSESOCKET(pool->sock);
  2058. pool->sock = 0;
  2059. mutex_unlock(&pool->stratum_lock);
  2060. hints = &pool->stratum_hints;
  2061. memset(hints, 0, sizeof(struct addrinfo));
  2062. hints->ai_family = AF_UNSPEC;
  2063. hints->ai_socktype = SOCK_STREAM;
  2064. servinfo = &servinfobase;
  2065. if (!pool->rpc_proxy && opt_socks_proxy) {
  2066. pool->rpc_proxy = opt_socks_proxy;
  2067. extract_sockaddr(pool->rpc_proxy, &pool->sockaddr_proxy_url, &pool->sockaddr_proxy_port);
  2068. pool->rpc_proxytype = PROXY_SOCKS5;
  2069. }
  2070. if (pool->rpc_proxy) {
  2071. sockaddr_url = pool->sockaddr_proxy_url;
  2072. sockaddr_port = pool->sockaddr_proxy_port;
  2073. } else {
  2074. sockaddr_url = pool->sockaddr_url;
  2075. sockaddr_port = pool->stratum_port;
  2076. }
  2077. if (getaddrinfo(sockaddr_url, sockaddr_port, hints, &servinfo) != 0) {
  2078. if (!pool->probed) {
  2079. applog(LOG_WARNING, "Failed to resolve (?wrong URL) %s:%s",
  2080. sockaddr_url, sockaddr_port);
  2081. pool->probed = true;
  2082. } else {
  2083. applog(LOG_INFO, "Failed to getaddrinfo for %s:%s",
  2084. sockaddr_url, sockaddr_port);
  2085. }
  2086. return false;
  2087. }
  2088. for (p = servinfo; p != NULL; p = p->ai_next) {
  2089. sockd = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
  2090. if (sockd == -1) {
  2091. applog(LOG_DEBUG, "Failed socket");
  2092. continue;
  2093. }
  2094. /* Iterate non blocking over entries returned by getaddrinfo
  2095. * to cope with round robin DNS entries, finding the first one
  2096. * we can connect to quickly. */
  2097. noblock_socket(sockd);
  2098. if (connect(sockd, p->ai_addr, p->ai_addrlen) == -1) {
  2099. struct timeval tv_timeout = {1, 0};
  2100. int selret;
  2101. fd_set rw;
  2102. if (!sock_connecting()) {
  2103. CLOSESOCKET(sockd);
  2104. applog(LOG_DEBUG, "Failed sock connect");
  2105. continue;
  2106. }
  2107. retry:
  2108. FD_ZERO(&rw);
  2109. FD_SET(sockd, &rw);
  2110. selret = select(sockd + 1, NULL, &rw, NULL, &tv_timeout);
  2111. if (selret > 0 && FD_ISSET(sockd, &rw)) {
  2112. socklen_t len;
  2113. int err, n;
  2114. len = sizeof(err);
  2115. n = getsockopt(sockd, SOL_SOCKET, SO_ERROR, (void *)&err, &len);
  2116. if (!n && !err) {
  2117. applog(LOG_DEBUG, "Succeeded delayed connect");
  2118. block_socket(sockd);
  2119. break;
  2120. }
  2121. }
  2122. if (selret < 0 && interrupted())
  2123. goto retry;
  2124. CLOSESOCKET(sockd);
  2125. applog(LOG_DEBUG, "Select timeout/failed connect");
  2126. continue;
  2127. }
  2128. applog(LOG_WARNING, "Succeeded immediate connect");
  2129. block_socket(sockd);
  2130. break;
  2131. }
  2132. if (p == NULL) {
  2133. applog(LOG_INFO, "Failed to connect to stratum on %s:%s",
  2134. sockaddr_url, sockaddr_port);
  2135. freeaddrinfo(servinfo);
  2136. return false;
  2137. }
  2138. freeaddrinfo(servinfo);
  2139. if (pool->rpc_proxy) {
  2140. switch (pool->rpc_proxytype) {
  2141. case PROXY_HTTP_1_0:
  2142. if (!http_negotiate(pool, sockd, true))
  2143. return false;
  2144. break;
  2145. case PROXY_HTTP:
  2146. if (!http_negotiate(pool, sockd, false))
  2147. return false;
  2148. break;
  2149. case PROXY_SOCKS5:
  2150. case PROXY_SOCKS5H:
  2151. if (!socks5_negotiate(pool, sockd))
  2152. return false;
  2153. break;
  2154. case PROXY_SOCKS4:
  2155. if (!socks4_negotiate(pool, sockd, false))
  2156. return false;
  2157. break;
  2158. case PROXY_SOCKS4A:
  2159. if (!socks4_negotiate(pool, sockd, true))
  2160. return false;
  2161. break;
  2162. default:
  2163. applog(LOG_WARNING, "Unsupported proxy type for %s:%s",
  2164. pool->sockaddr_proxy_url, pool->sockaddr_proxy_port);
  2165. return false;
  2166. break;
  2167. }
  2168. }
  2169. if (!pool->sockbuf) {
  2170. pool->sockbuf = calloc(RBUFSIZE, 1);
  2171. if (!pool->sockbuf)
  2172. quithere(1, "Failed to calloc pool sockbuf");
  2173. pool->sockbuf_size = RBUFSIZE;
  2174. }
  2175. pool->sock = sockd;
  2176. keep_sockalive(sockd);
  2177. return true;
  2178. }
  2179. static char *get_sessionid(json_t *val)
  2180. {
  2181. char *ret = NULL;
  2182. json_t *arr_val;
  2183. int arrsize, i;
  2184. arr_val = json_array_get(val, 0);
  2185. if (!arr_val || !json_is_array(arr_val))
  2186. goto out;
  2187. arrsize = json_array_size(arr_val);
  2188. for (i = 0; i < arrsize; i++) {
  2189. json_t *arr = json_array_get(arr_val, i);
  2190. char *notify;
  2191. if (!arr | !json_is_array(arr))
  2192. break;
  2193. notify = __json_array_string(arr, 0);
  2194. if (!notify)
  2195. continue;
  2196. if (!strncasecmp(notify, "mining.notify", 13)) {
  2197. ret = json_array_string(arr, 1);
  2198. break;
  2199. }
  2200. }
  2201. out:
  2202. return ret;
  2203. }
  2204. void suspend_stratum(struct pool *pool)
  2205. {
  2206. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  2207. mutex_lock(&pool->stratum_lock);
  2208. __suspend_stratum(pool);
  2209. mutex_unlock(&pool->stratum_lock);
  2210. }
  2211. void extranonce_subscribe_stratum(struct pool *pool)
  2212. {
  2213. char s[RBUFSIZE];
  2214. if(pool->extranonce_subscribe)
  2215. {
  2216. sprintf(s,"{\"id\": %d, \"method\": \"mining.extranonce.subscribe\", \"params\": []}", swork_id++);
  2217. applog(LOG_INFO, "Send extranonce.subscribe for stratum pool %d", pool->pool_no);
  2218. stratum_send(pool, s, strlen(s));
  2219. }
  2220. }
  2221. bool initiate_stratum(struct pool *pool)
  2222. {
  2223. bool ret = false, recvd = false, noresume = false, sockd = false;
  2224. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  2225. json_t *val = NULL, *res_val, *err_val;
  2226. json_error_t err;
  2227. int n2size;
  2228. resend:
  2229. if (!setup_stratum_socket(pool)) {
  2230. sockd = false;
  2231. goto out;
  2232. }
  2233. sockd = true;
  2234. if (recvd) {
  2235. /* Get rid of any crap lying around if we're resending */
  2236. clear_sock(pool);
  2237. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  2238. } else {
  2239. if (pool->sessionid)
  2240. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  2241. else
  2242. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  2243. }
  2244. if (__stratum_send(pool, s, strlen(s)) != SEND_OK) {
  2245. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2246. goto out;
  2247. }
  2248. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  2249. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  2250. goto out;
  2251. }
  2252. sret = recv_line(pool);
  2253. if (!sret)
  2254. goto out;
  2255. recvd = true;
  2256. val = JSON_LOADS(sret, &err);
  2257. free(sret);
  2258. if (!val) {
  2259. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2260. goto out;
  2261. }
  2262. res_val = json_object_get(val, "result");
  2263. err_val = json_object_get(val, "error");
  2264. if (!res_val || json_is_null(res_val) ||
  2265. (err_val && !json_is_null(err_val))) {
  2266. char *ss;
  2267. if (err_val)
  2268. ss = json_dumps(err_val, JSON_INDENT(3));
  2269. else
  2270. ss = strdup("(unknown reason)");
  2271. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  2272. free(ss);
  2273. goto out;
  2274. }
  2275. sessionid = get_sessionid(res_val);
  2276. if (!sessionid)
  2277. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2278. nonce1 = json_array_string(res_val, 1);
  2279. if (!valid_hex(nonce1)) {
  2280. applog(LOG_INFO, "Failed to get valid nonce1 in initiate_stratum");
  2281. free(sessionid);
  2282. goto out;
  2283. }
  2284. n2size = json_integer_value(json_array_get(res_val, 2));
  2285. if (n2size < 2 || n2size > 16) {
  2286. applog(LOG_INFO, "Failed to get valid n2size in initiate_stratum");
  2287. free(sessionid);
  2288. free(nonce1);
  2289. goto out;
  2290. }
  2291. cg_wlock(&pool->data_lock);
  2292. pool->sessionid = sessionid;
  2293. pool->nonce1 = nonce1;
  2294. pool->n1_len = strlen(nonce1) / 2;
  2295. free(pool->nonce1bin);
  2296. pool->nonce1bin = calloc(pool->n1_len, 1);
  2297. if (unlikely(!pool->nonce1bin))
  2298. quithere(1, "Failed to calloc pool->nonce1bin");
  2299. hex2bin(pool->nonce1bin, pool->nonce1, pool->n1_len);
  2300. pool->n2size = n2size;
  2301. cg_wunlock(&pool->data_lock);
  2302. if (sessionid)
  2303. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2304. ret = true;
  2305. out:
  2306. if (ret) {
  2307. if (!pool->stratum_url)
  2308. pool->stratum_url = pool->sockaddr_url;
  2309. pool->stratum_active = true;
  2310. pool->sdiff = 1;
  2311. if (opt_protocol) {
  2312. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2313. pool->pool_no, pool->nonce1, pool->n2size);
  2314. }
  2315. } else {
  2316. if (recvd && !noresume) {
  2317. /* Reset the sessionid used for stratum resuming in case the pool
  2318. * does not support it, or does not know how to respond to the
  2319. * presence of the sessionid parameter. */
  2320. cg_wlock(&pool->data_lock);
  2321. free(pool->sessionid);
  2322. free(pool->nonce1);
  2323. pool->sessionid = pool->nonce1 = NULL;
  2324. cg_wunlock(&pool->data_lock);
  2325. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2326. noresume = true;
  2327. json_decref(val);
  2328. goto resend;
  2329. }
  2330. applog(LOG_DEBUG, "Initiate stratum failed");
  2331. if (sockd)
  2332. suspend_stratum(pool);
  2333. }
  2334. json_decref(val);
  2335. return ret;
  2336. }
  2337. bool restart_stratum(struct pool *pool)
  2338. {
  2339. if (pool->stratum_active)
  2340. suspend_stratum(pool);
  2341. if (!initiate_stratum(pool))
  2342. return false;
  2343. if (!auth_stratum(pool))
  2344. return false;
  2345. extranonce_subscribe_stratum(pool);
  2346. return true;
  2347. }
  2348. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  2349. {
  2350. dev->device_last_not_well = time(NULL);
  2351. dev->device_not_well_reason = reason;
  2352. switch (reason) {
  2353. case REASON_THREAD_FAIL_INIT:
  2354. dev->thread_fail_init_count++;
  2355. break;
  2356. case REASON_THREAD_ZERO_HASH:
  2357. dev->thread_zero_hash_count++;
  2358. break;
  2359. case REASON_THREAD_FAIL_QUEUE:
  2360. dev->thread_fail_queue_count++;
  2361. break;
  2362. case REASON_DEV_SICK_IDLE_60:
  2363. dev->dev_sick_idle_60_count++;
  2364. break;
  2365. case REASON_DEV_DEAD_IDLE_600:
  2366. dev->dev_dead_idle_600_count++;
  2367. break;
  2368. case REASON_DEV_NOSTART:
  2369. dev->dev_nostart_count++;
  2370. break;
  2371. case REASON_DEV_OVER_HEAT:
  2372. dev->dev_over_heat_count++;
  2373. break;
  2374. case REASON_DEV_THERMAL_CUTOFF:
  2375. dev->dev_thermal_cutoff_count++;
  2376. break;
  2377. case REASON_DEV_COMMS_ERROR:
  2378. dev->dev_comms_error_count++;
  2379. break;
  2380. case REASON_DEV_THROTTLE:
  2381. dev->dev_throttle_count++;
  2382. break;
  2383. }
  2384. }
  2385. /* Realloc an existing string to fit an extra string s, appending s to it. */
  2386. void *realloc_strcat(char *ptr, char *s)
  2387. {
  2388. size_t old = 0, len = strlen(s);
  2389. char *ret;
  2390. if (!len)
  2391. return ptr;
  2392. if (ptr)
  2393. old = strlen(ptr);
  2394. len += old + 1;
  2395. align_len(&len);
  2396. ret = malloc(len);
  2397. if (unlikely(!ret))
  2398. quithere(1, "Failed to malloc");
  2399. if (ptr) {
  2400. sprintf(ret, "%s%s", ptr, s);
  2401. free(ptr);
  2402. } else
  2403. sprintf(ret, "%s", s);
  2404. return ret;
  2405. }
  2406. /* Make a text readable version of a string using 0xNN for < ' ' or > '~'
  2407. * Including 0x00 at the end
  2408. * You must free the result yourself */
  2409. void *str_text(char *ptr)
  2410. {
  2411. unsigned char *uptr;
  2412. char *ret, *txt;
  2413. if (ptr == NULL) {
  2414. ret = strdup("(null)");
  2415. if (unlikely(!ret))
  2416. quithere(1, "Failed to malloc null");
  2417. }
  2418. uptr = (unsigned char *)ptr;
  2419. ret = txt = malloc(strlen(ptr)*4+5); // Guaranteed >= needed
  2420. if (unlikely(!txt))
  2421. quithere(1, "Failed to malloc txt");
  2422. do {
  2423. if (*uptr < ' ' || *uptr > '~') {
  2424. sprintf(txt, "0x%02x", *uptr);
  2425. txt += 4;
  2426. } else
  2427. *(txt++) = *uptr;
  2428. } while (*(uptr++));
  2429. *txt = '\0';
  2430. return ret;
  2431. }
  2432. void RenameThread(const char* name)
  2433. {
  2434. char buf[16];
  2435. snprintf(buf, sizeof(buf), "cg@%s", name);
  2436. #if defined(PR_SET_NAME)
  2437. // Only the first 15 characters are used (16 - NUL terminator)
  2438. prctl(PR_SET_NAME, buf, 0, 0, 0);
  2439. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  2440. pthread_set_name_np(pthread_self(), buf);
  2441. #elif defined(MAC_OSX)
  2442. pthread_setname_np(buf);
  2443. #else
  2444. // Prevent warnings
  2445. (void)buf;
  2446. #endif
  2447. }
  2448. /* cgminer specific wrappers for true unnamed semaphore usage on platforms
  2449. * that support them and for apple which does not. We use a single byte across
  2450. * a pipe to emulate semaphore behaviour there. */
  2451. #ifdef __APPLE__
  2452. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2453. {
  2454. int flags, fd, i;
  2455. if (pipe(cgsem->pipefd) == -1)
  2456. quitfrom(1, file, func, line, "Failed pipe errno=%d", errno);
  2457. /* Make the pipes FD_CLOEXEC to allow them to close should we call
  2458. * execv on restart. */
  2459. for (i = 0; i < 2; i++) {
  2460. fd = cgsem->pipefd[i];
  2461. flags = fcntl(fd, F_GETFD, 0);
  2462. flags |= FD_CLOEXEC;
  2463. if (fcntl(fd, F_SETFD, flags) == -1)
  2464. quitfrom(1, file, func, line, "Failed to fcntl errno=%d", errno);
  2465. }
  2466. }
  2467. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2468. {
  2469. const char buf = 1;
  2470. int ret;
  2471. retry:
  2472. ret = write(cgsem->pipefd[1], &buf, 1);
  2473. if (unlikely(ret == 0))
  2474. applog(LOG_WARNING, "Failed to write errno=%d" IN_FMT_FFL, errno, file, func, line);
  2475. else if (unlikely(ret < 0 && interrupted))
  2476. goto retry;
  2477. }
  2478. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2479. {
  2480. char buf;
  2481. int ret;
  2482. retry:
  2483. ret = read(cgsem->pipefd[0], &buf, 1);
  2484. if (unlikely(ret == 0))
  2485. applog(LOG_WARNING, "Failed to read errno=%d" IN_FMT_FFL, errno, file, func, line);
  2486. else if (unlikely(ret < 0 && interrupted))
  2487. goto retry;
  2488. }
  2489. void cgsem_destroy(cgsem_t *cgsem)
  2490. {
  2491. close(cgsem->pipefd[1]);
  2492. close(cgsem->pipefd[0]);
  2493. }
  2494. /* This is similar to sem_timedwait but takes a millisecond value */
  2495. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  2496. {
  2497. struct timeval timeout;
  2498. int ret, fd;
  2499. fd_set rd;
  2500. char buf;
  2501. retry:
  2502. fd = cgsem->pipefd[0];
  2503. FD_ZERO(&rd);
  2504. FD_SET(fd, &rd);
  2505. ms_to_timeval(&timeout, ms);
  2506. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  2507. if (ret > 0) {
  2508. ret = read(fd, &buf, 1);
  2509. return 0;
  2510. }
  2511. if (likely(!ret))
  2512. return ETIMEDOUT;
  2513. if (interrupted())
  2514. goto retry;
  2515. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  2516. /* We don't reach here */
  2517. return 0;
  2518. }
  2519. /* Reset semaphore count back to zero */
  2520. void cgsem_reset(cgsem_t *cgsem)
  2521. {
  2522. int ret, fd;
  2523. fd_set rd;
  2524. char buf;
  2525. fd = cgsem->pipefd[0];
  2526. FD_ZERO(&rd);
  2527. FD_SET(fd, &rd);
  2528. do {
  2529. struct timeval timeout = {0, 0};
  2530. ret = select(fd + 1, &rd, NULL, NULL, &timeout);
  2531. if (ret > 0)
  2532. ret = read(fd, &buf, 1);
  2533. else if (unlikely(ret < 0 && interrupted()))
  2534. ret = 1;
  2535. } while (ret > 0);
  2536. }
  2537. #else
  2538. void _cgsem_init(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2539. {
  2540. int ret;
  2541. if ((ret = sem_init(cgsem, 0, 0)))
  2542. quitfrom(1, file, func, line, "Failed to sem_init ret=%d errno=%d", ret, errno);
  2543. }
  2544. void _cgsem_post(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2545. {
  2546. if (unlikely(sem_post(cgsem)))
  2547. quitfrom(1, file, func, line, "Failed to sem_post errno=%d cgsem=0x%p", errno, cgsem);
  2548. }
  2549. void _cgsem_wait(cgsem_t *cgsem, const char *file, const char *func, const int line)
  2550. {
  2551. retry:
  2552. if (unlikely(sem_wait(cgsem))) {
  2553. if (interrupted())
  2554. goto retry;
  2555. quitfrom(1, file, func, line, "Failed to sem_wait errno=%d cgsem=0x%p", errno, cgsem);
  2556. }
  2557. }
  2558. int _cgsem_mswait(cgsem_t *cgsem, int ms, const char *file, const char *func, const int line)
  2559. {
  2560. struct timespec abs_timeout, ts_now;
  2561. struct timeval tv_now;
  2562. int ret;
  2563. cgtime(&tv_now);
  2564. timeval_to_spec(&ts_now, &tv_now);
  2565. ms_to_timespec(&abs_timeout, ms);
  2566. retry:
  2567. timeraddspec(&abs_timeout, &ts_now);
  2568. ret = sem_timedwait(cgsem, &abs_timeout);
  2569. if (ret) {
  2570. if (likely(sock_timeout()))
  2571. return ETIMEDOUT;
  2572. if (interrupted())
  2573. goto retry;
  2574. quitfrom(1, file, func, line, "Failed to sem_timedwait errno=%d cgsem=0x%p", errno, cgsem);
  2575. }
  2576. return 0;
  2577. }
  2578. void cgsem_reset(cgsem_t *cgsem)
  2579. {
  2580. int ret;
  2581. do {
  2582. ret = sem_trywait(cgsem);
  2583. if (unlikely(ret < 0 && interrupted()))
  2584. ret = 0;
  2585. } while (!ret);
  2586. }
  2587. void cgsem_destroy(cgsem_t *cgsem)
  2588. {
  2589. sem_destroy(cgsem);
  2590. }
  2591. #endif
  2592. /* Provide a completion_timeout helper function for unreliable functions that
  2593. * may die due to driver issues etc that time out if the function fails and
  2594. * can then reliably return. */
  2595. struct cg_completion {
  2596. cgsem_t cgsem;
  2597. void (*fn)(void *fnarg);
  2598. void *fnarg;
  2599. };
  2600. void *completion_thread(void *arg)
  2601. {
  2602. struct cg_completion *cgc = (struct cg_completion *)arg;
  2603. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2604. cgc->fn(cgc->fnarg);
  2605. cgsem_post(&cgc->cgsem);
  2606. return NULL;
  2607. }
  2608. bool cg_completion_timeout(void *fn, void *fnarg, int timeout)
  2609. {
  2610. struct cg_completion *cgc;
  2611. pthread_t pthread;
  2612. bool ret = false;
  2613. cgc = malloc(sizeof(struct cg_completion));
  2614. if (unlikely(!cgc))
  2615. return ret;
  2616. cgsem_init(&cgc->cgsem);
  2617. cgc->fn = fn;
  2618. cgc->fnarg = fnarg;
  2619. pthread_create(&pthread, NULL, completion_thread, (void *)cgc);
  2620. ret = cgsem_mswait(&cgc->cgsem, timeout);
  2621. if (!ret) {
  2622. pthread_join(pthread, NULL);
  2623. free(cgc);
  2624. } else
  2625. pthread_cancel(pthread);
  2626. return !ret;
  2627. }
  2628. void _cg_memcpy(void *dest, const void *src, unsigned int n, const char *file, const char *func, const int line)
  2629. {
  2630. if (unlikely(n < 1 || n > (1ul << 31))) {
  2631. applog(LOG_ERR, "ERR: Asked to memcpy %u bytes from %s %s():%d",
  2632. n, file, func, line);
  2633. return;
  2634. }
  2635. memcpy(dest, src, n);
  2636. }