util.c 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058
  1. /*
  2. * Copyright 2011-2013 Con Kolivas
  3. * Copyright 2011-2013 Luke Dashjr
  4. * Copyright 2010 Jeff Garzik
  5. * Copyright 2012 Giel van Schijndel
  6. * Copyright 2012 Gavin Andresen
  7. *
  8. * This program is free software; you can redistribute it and/or modify it
  9. * under the terms of the GNU General Public License as published by the Free
  10. * Software Foundation; either version 3 of the License, or (at your option)
  11. * any later version. See COPYING for more details.
  12. */
  13. #include "config.h"
  14. #include <stdbool.h>
  15. #include <stdint.h>
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #include <ctype.h>
  19. #include <stdarg.h>
  20. #include <string.h>
  21. #include <pthread.h>
  22. #include <jansson.h>
  23. #include <curl/curl.h>
  24. #include <time.h>
  25. #include <errno.h>
  26. #include <unistd.h>
  27. #include <sys/types.h>
  28. #ifdef HAVE_SYS_PRCTL_H
  29. # include <sys/prctl.h>
  30. #endif
  31. #if defined(__FreeBSD__) || defined(__OpenBSD__)
  32. # include <pthread_np.h>
  33. #endif
  34. #ifndef WIN32
  35. #include <fcntl.h>
  36. # ifdef __linux
  37. # include <sys/prctl.h>
  38. # endif
  39. # include <sys/socket.h>
  40. # include <netinet/in.h>
  41. # include <netinet/tcp.h>
  42. # include <netdb.h>
  43. #else
  44. # include <windows.h>
  45. # include <winsock2.h>
  46. # include <mstcpip.h>
  47. # include <ws2tcpip.h>
  48. # include <mmsystem.h>
  49. #endif
  50. #include <utlist.h>
  51. #ifdef NEED_BFG_LOWL_VCOM
  52. #include "lowl-vcom.h"
  53. #endif
  54. #include "miner.h"
  55. #include "compat.h"
  56. #include "util.h"
  57. #define DEFAULT_SOCKWAIT 60
  58. bool successful_connect = false;
  59. struct timeval nettime;
  60. struct data_buffer {
  61. void *buf;
  62. size_t len;
  63. curl_socket_t *idlemarker;
  64. };
  65. struct upload_buffer {
  66. const void *buf;
  67. size_t len;
  68. };
  69. struct header_info {
  70. char *lp_path;
  71. int rolltime;
  72. char *reason;
  73. char *stratum_url;
  74. bool hadrolltime;
  75. bool canroll;
  76. bool hadexpire;
  77. };
  78. struct tq_ent {
  79. void *data;
  80. struct tq_ent *prev;
  81. struct tq_ent *next;
  82. };
  83. static void databuf_free(struct data_buffer *db)
  84. {
  85. if (!db)
  86. return;
  87. free(db->buf);
  88. #ifdef DEBUG_DATABUF
  89. applog(LOG_DEBUG, "databuf_free(%p)", db->buf);
  90. #endif
  91. memset(db, 0, sizeof(*db));
  92. }
  93. // aka data_buffer_write
  94. static size_t all_data_cb(const void *ptr, size_t size, size_t nmemb,
  95. void *user_data)
  96. {
  97. struct data_buffer *db = user_data;
  98. size_t oldlen, newlen;
  99. oldlen = db->len;
  100. if (unlikely(nmemb == 0 || size == 0 || oldlen >= SIZE_MAX - size))
  101. return 0;
  102. if (unlikely(nmemb > (SIZE_MAX - oldlen) / size))
  103. nmemb = (SIZE_MAX - oldlen) / size;
  104. size_t len = size * nmemb;
  105. void *newmem;
  106. static const unsigned char zero = 0;
  107. if (db->idlemarker) {
  108. const unsigned char *cptr = ptr;
  109. for (size_t i = 0; i < len; ++i)
  110. if (!(isCspace(cptr[i]) || cptr[i] == '{')) {
  111. *db->idlemarker = CURL_SOCKET_BAD;
  112. db->idlemarker = NULL;
  113. break;
  114. }
  115. }
  116. newlen = oldlen + len;
  117. newmem = realloc(db->buf, newlen + 1);
  118. #ifdef DEBUG_DATABUF
  119. applog(LOG_DEBUG, "data_buffer_write realloc(%p, %lu) => %p", db->buf, (long unsigned)(newlen + 1), newmem);
  120. #endif
  121. if (!newmem)
  122. return 0;
  123. db->buf = newmem;
  124. db->len = newlen;
  125. memcpy(db->buf + oldlen, ptr, len);
  126. memcpy(db->buf + newlen, &zero, 1); /* null terminate */
  127. return nmemb;
  128. }
  129. static size_t upload_data_cb(void *ptr, size_t size, size_t nmemb,
  130. void *user_data)
  131. {
  132. struct upload_buffer *ub = user_data;
  133. unsigned int len = size * nmemb;
  134. if (len > ub->len)
  135. len = ub->len;
  136. if (len) {
  137. memcpy(ptr, ub->buf, len);
  138. ub->buf += len;
  139. ub->len -= len;
  140. }
  141. return len;
  142. }
  143. static size_t resp_hdr_cb(void *ptr, size_t size, size_t nmemb, void *user_data)
  144. {
  145. struct header_info *hi = user_data;
  146. size_t remlen, slen, ptrlen = size * nmemb;
  147. char *rem, *val = NULL, *key = NULL;
  148. void *tmp;
  149. val = calloc(1, ptrlen);
  150. key = calloc(1, ptrlen);
  151. if (!key || !val)
  152. goto out;
  153. tmp = memchr(ptr, ':', ptrlen);
  154. if (!tmp || (tmp == ptr)) /* skip empty keys / blanks */
  155. goto out;
  156. slen = tmp - ptr;
  157. if ((slen + 1) == ptrlen) /* skip key w/ no value */
  158. goto out;
  159. memcpy(key, ptr, slen); /* store & nul term key */
  160. key[slen] = 0;
  161. rem = ptr + slen + 1; /* trim value's leading whitespace */
  162. remlen = ptrlen - slen - 1;
  163. while ((remlen > 0) && (isCspace(*rem))) {
  164. remlen--;
  165. rem++;
  166. }
  167. memcpy(val, rem, remlen); /* store value, trim trailing ws */
  168. val[remlen] = 0;
  169. while ((*val) && (isCspace(val[strlen(val) - 1])))
  170. val[strlen(val) - 1] = 0;
  171. if (!*val) /* skip blank value */
  172. goto out;
  173. if (opt_protocol)
  174. applog(LOG_DEBUG, "HTTP hdr(%s): %s", key, val);
  175. if (!strcasecmp("X-Roll-Ntime", key)) {
  176. hi->hadrolltime = true;
  177. if (!strncasecmp("N", val, 1))
  178. applog(LOG_DEBUG, "X-Roll-Ntime: N found");
  179. else {
  180. hi->canroll = true;
  181. /* Check to see if expire= is supported and if not, set
  182. * the rolltime to the default scantime */
  183. if (strlen(val) > 7 && !strncasecmp("expire=", val, 7)) {
  184. sscanf(val + 7, "%d", &hi->rolltime);
  185. hi->hadexpire = true;
  186. } else
  187. hi->rolltime = opt_scantime;
  188. applog(LOG_DEBUG, "X-Roll-Ntime expiry set to %d", hi->rolltime);
  189. }
  190. }
  191. if (!strcasecmp("X-Long-Polling", key)) {
  192. hi->lp_path = val; /* steal memory reference */
  193. val = NULL;
  194. }
  195. if (!strcasecmp("X-Reject-Reason", key)) {
  196. hi->reason = val; /* steal memory reference */
  197. val = NULL;
  198. }
  199. if (!strcasecmp("X-Stratum", key)) {
  200. hi->stratum_url = val;
  201. val = NULL;
  202. }
  203. out:
  204. free(key);
  205. free(val);
  206. return ptrlen;
  207. }
  208. static int keep_sockalive(SOCKETTYPE fd)
  209. {
  210. const int tcp_one = 1;
  211. const int tcp_keepidle = 45;
  212. const int tcp_keepintvl = 30;
  213. int ret = 0;
  214. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&tcp_one, sizeof(tcp_one))))
  215. ret = 1;
  216. #ifndef WIN32
  217. int flags = fcntl(fd, F_GETFL, 0);
  218. fcntl(fd, F_SETFL, O_NONBLOCK | flags);
  219. #else
  220. u_long flags = 1;
  221. ioctlsocket(fd, FIONBIO, &flags);
  222. #endif
  223. if (!opt_delaynet)
  224. #ifndef __linux
  225. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  226. #else /* __linux */
  227. if (unlikely(setsockopt(fd, SOL_TCP, TCP_NODELAY, (const void *)&tcp_one, sizeof(tcp_one))))
  228. #endif /* __linux */
  229. ret = 1;
  230. #ifdef __linux
  231. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPCNT, &tcp_one, sizeof(tcp_one))))
  232. ret = 1;
  233. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &tcp_keepidle, sizeof(tcp_keepidle))))
  234. ret = 1;
  235. if (unlikely(setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  236. ret = 1;
  237. #endif /* __linux */
  238. #ifdef __APPLE_CC__
  239. if (unlikely(setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tcp_keepintvl, sizeof(tcp_keepintvl))))
  240. ret = 1;
  241. #endif /* __APPLE_CC__ */
  242. #ifdef WIN32
  243. const int zero = 0;
  244. struct tcp_keepalive vals;
  245. vals.onoff = 1;
  246. vals.keepalivetime = tcp_keepidle * 1000;
  247. vals.keepaliveinterval = tcp_keepintvl * 1000;
  248. DWORD outputBytes;
  249. if (unlikely(WSAIoctl(fd, SIO_KEEPALIVE_VALS, &vals, sizeof(vals), NULL, 0, &outputBytes, NULL, NULL)))
  250. ret = 1;
  251. /* Windows happily submits indefinitely to the send buffer blissfully
  252. * unaware nothing is getting there without gracefully failing unless
  253. * we disable the send buffer */
  254. if (unlikely(setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char *)&zero, sizeof(zero))))
  255. ret = 1;
  256. #endif /* WIN32 */
  257. return ret;
  258. }
  259. int json_rpc_call_sockopt_cb(void __maybe_unused *userdata, curl_socket_t fd,
  260. curlsocktype __maybe_unused purpose)
  261. {
  262. return keep_sockalive(fd);
  263. }
  264. static void last_nettime(struct timeval *last)
  265. {
  266. rd_lock(&netacc_lock);
  267. last->tv_sec = nettime.tv_sec;
  268. last->tv_usec = nettime.tv_usec;
  269. rd_unlock(&netacc_lock);
  270. }
  271. static void set_nettime(void)
  272. {
  273. wr_lock(&netacc_lock);
  274. cgtime(&nettime);
  275. wr_unlock(&netacc_lock);
  276. }
  277. static int curl_debug_cb(__maybe_unused CURL *handle, curl_infotype type,
  278. char *data, size_t size,
  279. void *userdata)
  280. {
  281. struct pool *pool = (struct pool *)userdata;
  282. switch(type) {
  283. case CURLINFO_HEADER_IN:
  284. case CURLINFO_DATA_IN:
  285. case CURLINFO_SSL_DATA_IN:
  286. pool->cgminer_pool_stats.bytes_received += size;
  287. total_bytes_rcvd += size;
  288. pool->cgminer_pool_stats.net_bytes_received += size;
  289. break;
  290. case CURLINFO_HEADER_OUT:
  291. case CURLINFO_DATA_OUT:
  292. case CURLINFO_SSL_DATA_OUT:
  293. pool->cgminer_pool_stats.bytes_sent += size;
  294. total_bytes_sent += size;
  295. pool->cgminer_pool_stats.net_bytes_sent += size;
  296. break;
  297. case CURLINFO_TEXT:
  298. {
  299. if (!opt_protocol)
  300. break;
  301. // data is not null-terminated, so we need to copy and terminate it for applog
  302. char datacp[size + 1];
  303. memcpy(datacp, data, size);
  304. while (likely(size) && unlikely(isCspace(datacp[size-1])))
  305. --size;
  306. if (unlikely(!size))
  307. break;
  308. datacp[size] = '\0';
  309. applog(LOG_DEBUG, "Pool %u: %s", pool->pool_no, datacp);
  310. break;
  311. }
  312. default:
  313. break;
  314. }
  315. return 0;
  316. }
  317. struct json_rpc_call_state {
  318. struct data_buffer all_data;
  319. struct header_info hi;
  320. void *priv;
  321. char curl_err_str[CURL_ERROR_SIZE];
  322. struct curl_slist *headers;
  323. struct upload_buffer upload_data;
  324. struct pool *pool;
  325. };
  326. void json_rpc_call_async(CURL *curl, const char *url,
  327. const char *userpass, const char *rpc_req,
  328. bool longpoll,
  329. struct pool *pool, bool share,
  330. void *priv)
  331. {
  332. struct json_rpc_call_state *state = malloc(sizeof(struct json_rpc_call_state));
  333. *state = (struct json_rpc_call_state){
  334. .priv = priv,
  335. .pool = pool,
  336. };
  337. long timeout = longpoll ? (60 * 60) : 60;
  338. char len_hdr[64], user_agent_hdr[128];
  339. struct curl_slist *headers = NULL;
  340. if (longpoll)
  341. state->all_data.idlemarker = &pool->lp_socket;
  342. /* it is assumed that 'curl' is freshly [re]initialized at this pt */
  343. curl_easy_setopt(curl, CURLOPT_PRIVATE, state);
  344. curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
  345. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  346. * to enable it */
  347. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  348. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  349. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  350. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  351. curl_easy_setopt(curl, CURLOPT_URL, url);
  352. curl_easy_setopt(curl, CURLOPT_ENCODING, "");
  353. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  354. /* Shares are staggered already and delays in submission can be costly
  355. * so do not delay them */
  356. if (!opt_delaynet || share)
  357. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  358. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
  359. curl_easy_setopt(curl, CURLOPT_WRITEDATA, &state->all_data);
  360. curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
  361. curl_easy_setopt(curl, CURLOPT_READDATA, &state->upload_data);
  362. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &state->curl_err_str[0]);
  363. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  364. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
  365. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &state->hi);
  366. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  367. if (pool->rpc_proxy) {
  368. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  369. } else if (opt_socks_proxy) {
  370. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  371. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  372. }
  373. if (userpass) {
  374. curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
  375. curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  376. }
  377. if (longpoll)
  378. curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, json_rpc_call_sockopt_cb);
  379. curl_easy_setopt(curl, CURLOPT_POST, 1);
  380. if (opt_protocol)
  381. applog(LOG_DEBUG, "JSON protocol request:\n%s", rpc_req);
  382. state->upload_data.buf = rpc_req;
  383. state->upload_data.len = strlen(rpc_req);
  384. sprintf(len_hdr, "Content-Length: %lu",
  385. (unsigned long) state->upload_data.len);
  386. sprintf(user_agent_hdr, "User-Agent: %s", PACKAGE"/"VERSION);
  387. headers = curl_slist_append(headers,
  388. "Content-type: application/json");
  389. headers = curl_slist_append(headers,
  390. "X-Mining-Extensions: longpoll midstate rollntime submitold");
  391. if (longpoll)
  392. headers = curl_slist_append(headers,
  393. "X-Minimum-Wait: 0");
  394. if (likely(global_hashrate)) {
  395. char ghashrate[255];
  396. sprintf(ghashrate, "X-Mining-Hashrate: %"PRIu64, (uint64_t)global_hashrate);
  397. headers = curl_slist_append(headers, ghashrate);
  398. }
  399. headers = curl_slist_append(headers, len_hdr);
  400. headers = curl_slist_append(headers, user_agent_hdr);
  401. headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/
  402. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  403. state->headers = headers;
  404. if (opt_delaynet) {
  405. /* Don't delay share submission, but still track the nettime */
  406. if (!share) {
  407. long long now_msecs, last_msecs;
  408. struct timeval now, last;
  409. cgtime(&now);
  410. last_nettime(&last);
  411. now_msecs = (long long)now.tv_sec * 1000;
  412. now_msecs += now.tv_usec / 1000;
  413. last_msecs = (long long)last.tv_sec * 1000;
  414. last_msecs += last.tv_usec / 1000;
  415. if (now_msecs > last_msecs && now_msecs - last_msecs < 250) {
  416. struct timespec rgtp;
  417. rgtp.tv_sec = 0;
  418. rgtp.tv_nsec = (250 - (now_msecs - last_msecs)) * 1000000;
  419. nanosleep(&rgtp, NULL);
  420. }
  421. }
  422. set_nettime();
  423. }
  424. }
  425. json_t *json_rpc_call_completed(CURL *curl, int rc, bool probe, int *rolltime, void *out_priv)
  426. {
  427. struct json_rpc_call_state *state;
  428. if (curl_easy_getinfo(curl, CURLINFO_PRIVATE, (void*)&state) != CURLE_OK) {
  429. applog(LOG_ERR, "Failed to get private curl data");
  430. if (out_priv)
  431. *(void**)out_priv = NULL;
  432. goto err_out;
  433. }
  434. if (out_priv)
  435. *(void**)out_priv = state->priv;
  436. json_t *val, *err_val, *res_val;
  437. json_error_t err;
  438. struct pool *pool = state->pool;
  439. bool probing = probe && !pool->probed;
  440. if (rc) {
  441. applog(LOG_INFO, "HTTP request failed: %s", state->curl_err_str);
  442. goto err_out;
  443. }
  444. if (!state->all_data.buf) {
  445. applog(LOG_DEBUG, "Empty data received in json_rpc_call.");
  446. goto err_out;
  447. }
  448. pool->cgminer_pool_stats.times_sent++;
  449. pool->cgminer_pool_stats.times_received++;
  450. if (probing) {
  451. pool->probed = true;
  452. /* If X-Long-Polling was found, activate long polling */
  453. if (state->hi.lp_path) {
  454. if (pool->hdr_path != NULL)
  455. free(pool->hdr_path);
  456. pool->hdr_path = state->hi.lp_path;
  457. } else
  458. pool->hdr_path = NULL;
  459. if (state->hi.stratum_url) {
  460. pool->stratum_url = state->hi.stratum_url;
  461. state->hi.stratum_url = NULL;
  462. }
  463. } else {
  464. if (state->hi.lp_path) {
  465. free(state->hi.lp_path);
  466. state->hi.lp_path = NULL;
  467. }
  468. if (state->hi.stratum_url) {
  469. free(state->hi.stratum_url);
  470. state->hi.stratum_url = NULL;
  471. }
  472. }
  473. if (pool->force_rollntime)
  474. {
  475. state->hi.canroll = true;
  476. state->hi.hadexpire = true;
  477. state->hi.rolltime = pool->force_rollntime;
  478. }
  479. if (rolltime)
  480. *rolltime = state->hi.rolltime;
  481. pool->cgminer_pool_stats.rolltime = state->hi.rolltime;
  482. pool->cgminer_pool_stats.hadrolltime = state->hi.hadrolltime;
  483. pool->cgminer_pool_stats.canroll = state->hi.canroll;
  484. pool->cgminer_pool_stats.hadexpire = state->hi.hadexpire;
  485. val = JSON_LOADS(state->all_data.buf, &err);
  486. if (!val) {
  487. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  488. if (opt_protocol)
  489. applog(LOG_DEBUG, "JSON protocol response:\n%s", (char*)state->all_data.buf);
  490. goto err_out;
  491. }
  492. if (opt_protocol) {
  493. char *s = json_dumps(val, JSON_INDENT(3));
  494. applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
  495. free(s);
  496. }
  497. /* JSON-RPC valid response returns a non-null 'result',
  498. * and a null 'error'.
  499. */
  500. res_val = json_object_get(val, "result");
  501. err_val = json_object_get(val, "error");
  502. if (!res_val ||(err_val && !json_is_null(err_val))) {
  503. char *s;
  504. if (err_val)
  505. s = json_dumps(err_val, JSON_INDENT(3));
  506. else
  507. s = strdup("(unknown reason)");
  508. applog(LOG_INFO, "JSON-RPC call failed: %s", s);
  509. free(s);
  510. json_decref(val);
  511. goto err_out;
  512. }
  513. if (state->hi.reason) {
  514. json_object_set_new(val, "reject-reason", json_string(state->hi.reason));
  515. free(state->hi.reason);
  516. state->hi.reason = NULL;
  517. }
  518. successful_connect = true;
  519. databuf_free(&state->all_data);
  520. curl_slist_free_all(state->headers);
  521. curl_easy_reset(curl);
  522. free(state);
  523. return val;
  524. err_out:
  525. databuf_free(&state->all_data);
  526. curl_slist_free_all(state->headers);
  527. curl_easy_reset(curl);
  528. if (!successful_connect)
  529. applog(LOG_DEBUG, "Failed to connect in json_rpc_call");
  530. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  531. free(state);
  532. return NULL;
  533. }
  534. json_t *json_rpc_call(CURL *curl, const char *url,
  535. const char *userpass, const char *rpc_req,
  536. bool probe, bool longpoll, int *rolltime,
  537. struct pool *pool, bool share)
  538. {
  539. json_rpc_call_async(curl, url, userpass, rpc_req, longpoll, pool, share, NULL);
  540. int rc = curl_easy_perform(curl);
  541. return json_rpc_call_completed(curl, rc, probe, rolltime, NULL);
  542. }
  543. bool our_curl_supports_proxy_uris()
  544. {
  545. curl_version_info_data *data = curl_version_info(CURLVERSION_NOW);
  546. return data->age && data->version_num >= (( 7 <<16)|( 21 <<8)| 7); // 7.21.7
  547. }
  548. // NOTE: This assumes reference URI is a root
  549. char *absolute_uri(char *uri, const char *ref)
  550. {
  551. if (strstr(uri, "://"))
  552. return strdup(uri);
  553. char *copy_start, *abs;
  554. bool need_slash = false;
  555. copy_start = (uri[0] == '/') ? &uri[1] : uri;
  556. if (ref[strlen(ref) - 1] != '/')
  557. need_slash = true;
  558. abs = malloc(strlen(ref) + strlen(copy_start) + 2);
  559. if (!abs) {
  560. applog(LOG_ERR, "Malloc failure in absolute_uri");
  561. return NULL;
  562. }
  563. sprintf(abs, "%s%s%s", ref, need_slash ? "/" : "", copy_start);
  564. return abs;
  565. }
  566. static const char _hexchars[0x10] = "0123456789abcdef";
  567. void bin2hex(char *out, const void *in, size_t len)
  568. {
  569. const unsigned char *p = in;
  570. while (len--)
  571. {
  572. (out++)[0] = _hexchars[p[0] >> 4];
  573. (out++)[0] = _hexchars[p[0] & 0xf];
  574. ++p;
  575. }
  576. out[0] = '\0';
  577. }
  578. static inline
  579. int _hex2bin_char(const char c)
  580. {
  581. if (c >= '0' && c <= '9')
  582. return c - '0';
  583. if (c >= 'a' && c <= 'f')
  584. return (c - 'a') + 10;
  585. if (c >= 'A' && c <= 'F')
  586. return (c - 'A') + 10;
  587. return -1;
  588. }
  589. /* Does the reverse of bin2hex but does not allocate any ram */
  590. bool hex2bin(unsigned char *p, const char *hexstr, size_t len)
  591. {
  592. int n, o;
  593. while (len--)
  594. {
  595. n = _hex2bin_char((hexstr++)[0]);
  596. if (unlikely(n == -1))
  597. {
  598. badchar:
  599. if (!hexstr[-1])
  600. applog(LOG_ERR, "hex2bin: str truncated");
  601. else
  602. applog(LOG_ERR, "hex2bin: invalid character 0x%02x", (int)hexstr[-1]);
  603. return false;
  604. }
  605. o = _hex2bin_char((hexstr++)[0]);
  606. if (unlikely(o == -1))
  607. goto badchar;
  608. (p++)[0] = (n << 4) | o;
  609. }
  610. return likely(!hexstr[0]);
  611. }
  612. size_t ucs2_to_utf8(char * const out, const uint16_t * const in, const size_t sz)
  613. {
  614. uint8_t *p = (void*)out;
  615. for (int i = 0; i < sz; ++i)
  616. {
  617. const uint16_t c = in[i];
  618. if (c < 0x80)
  619. p++[0] = c;
  620. else
  621. {
  622. if (c < 0x800)
  623. p++[0] = 0xc0 | (c >> 6);
  624. else
  625. {
  626. p++[0] = 0xe0 | (c >> 12);
  627. p++[0] = 0x80 | ((c >> 6) & 0x3f);
  628. }
  629. p++[0] = 0x80 | (c & 0x3f);
  630. }
  631. }
  632. return p - (uint8_t*)(void*)out;
  633. }
  634. char *ucs2_to_utf8_dup(uint16_t * const in, size_t sz)
  635. {
  636. char * const out = malloc((sz * 4) + 1);
  637. sz = ucs2_to_utf8(out, in, sz);
  638. out[sz] = '\0';
  639. return out;
  640. }
  641. void hash_data(unsigned char *out_hash, const unsigned char *data)
  642. {
  643. unsigned char blkheader[80];
  644. // data is past the first SHA256 step (padding and interpreting as big endian on a little endian platform), so we need to flip each 32-bit chunk around to get the original input block header
  645. swap32yes(blkheader, data, 80 / 4);
  646. // double-SHA256 to get the block hash
  647. gen_hash(blkheader, out_hash, 80);
  648. }
  649. // Example output: 0000000000000000000000000000000000000000000000000000ffff00000000 (bdiff 1)
  650. void real_block_target(unsigned char *target, const unsigned char *data)
  651. {
  652. uint8_t targetshift;
  653. if (unlikely(data[72] < 3 || data[72] > 0x20))
  654. {
  655. // Invalid (out of bounds) target
  656. memset(target, 0xff, 32);
  657. return;
  658. }
  659. targetshift = data[72] - 3;
  660. memset(target, 0, targetshift);
  661. target[targetshift++] = data[75];
  662. target[targetshift++] = data[74];
  663. target[targetshift++] = data[73];
  664. memset(&target[targetshift], 0, 0x20 - targetshift);
  665. }
  666. bool hash_target_check(const unsigned char *hash, const unsigned char *target)
  667. {
  668. const uint32_t *h32 = (uint32_t*)&hash[0];
  669. const uint32_t *t32 = (uint32_t*)&target[0];
  670. for (int i = 7; i >= 0; --i) {
  671. uint32_t h32i = le32toh(h32[i]);
  672. uint32_t t32i = le32toh(t32[i]);
  673. if (h32i > t32i)
  674. return false;
  675. if (h32i < t32i)
  676. return true;
  677. }
  678. return true;
  679. }
  680. bool hash_target_check_v(const unsigned char *hash, const unsigned char *target)
  681. {
  682. bool rc;
  683. rc = hash_target_check(hash, target);
  684. if (opt_debug) {
  685. unsigned char hash_swap[32], target_swap[32];
  686. char hash_str[65];
  687. char target_str[65];
  688. for (int i = 0; i < 32; ++i) {
  689. hash_swap[i] = hash[31-i];
  690. target_swap[i] = target[31-i];
  691. }
  692. bin2hex(hash_str, hash_swap, 32);
  693. bin2hex(target_str, target_swap, 32);
  694. applog(LOG_DEBUG, " Proof: %s\nTarget: %s\nTrgVal? %s",
  695. hash_str,
  696. target_str,
  697. rc ? "YES (hash <= target)" :
  698. "no (false positive; hash > target)");
  699. }
  700. return rc;
  701. }
  702. // This operates on a native-endian SHA256 state
  703. // In other words, on little endian platforms, every 4 bytes are in reverse order
  704. bool fulltest(const unsigned char *hash, const unsigned char *target)
  705. {
  706. unsigned char hash2[32];
  707. swap32tobe(hash2, hash, 32 / 4);
  708. return hash_target_check_v(hash2, target);
  709. }
  710. struct thread_q *tq_new(void)
  711. {
  712. struct thread_q *tq;
  713. tq = calloc(1, sizeof(*tq));
  714. if (!tq)
  715. return NULL;
  716. pthread_mutex_init(&tq->mutex, NULL);
  717. pthread_cond_init(&tq->cond, bfg_condattr);
  718. return tq;
  719. }
  720. void tq_free(struct thread_q *tq)
  721. {
  722. struct tq_ent *ent, *iter;
  723. if (!tq)
  724. return;
  725. DL_FOREACH_SAFE(tq->q, ent, iter) {
  726. DL_DELETE(tq->q, ent);
  727. free(ent);
  728. }
  729. pthread_cond_destroy(&tq->cond);
  730. pthread_mutex_destroy(&tq->mutex);
  731. memset(tq, 0, sizeof(*tq)); /* poison */
  732. free(tq);
  733. }
  734. static void tq_freezethaw(struct thread_q *tq, bool frozen)
  735. {
  736. mutex_lock(&tq->mutex);
  737. tq->frozen = frozen;
  738. pthread_cond_signal(&tq->cond);
  739. mutex_unlock(&tq->mutex);
  740. }
  741. void tq_freeze(struct thread_q *tq)
  742. {
  743. tq_freezethaw(tq, true);
  744. }
  745. void tq_thaw(struct thread_q *tq)
  746. {
  747. tq_freezethaw(tq, false);
  748. }
  749. bool tq_push(struct thread_q *tq, void *data)
  750. {
  751. struct tq_ent *ent;
  752. bool rc = true;
  753. ent = calloc(1, sizeof(*ent));
  754. if (!ent)
  755. return false;
  756. ent->data = data;
  757. mutex_lock(&tq->mutex);
  758. if (!tq->frozen) {
  759. DL_APPEND(tq->q, ent);
  760. } else {
  761. free(ent);
  762. rc = false;
  763. }
  764. pthread_cond_signal(&tq->cond);
  765. mutex_unlock(&tq->mutex);
  766. return rc;
  767. }
  768. void *tq_pop(struct thread_q *tq, const struct timespec *abstime)
  769. {
  770. struct tq_ent *ent;
  771. void *rval = NULL;
  772. int rc;
  773. mutex_lock(&tq->mutex);
  774. if (tq->q)
  775. goto pop;
  776. if (abstime)
  777. rc = pthread_cond_timedwait(&tq->cond, &tq->mutex, abstime);
  778. else
  779. rc = pthread_cond_wait(&tq->cond, &tq->mutex);
  780. if (rc)
  781. goto out;
  782. if (!tq->q)
  783. goto out;
  784. pop:
  785. ent = tq->q;
  786. rval = ent->data;
  787. DL_DELETE(tq->q, ent);
  788. free(ent);
  789. out:
  790. mutex_unlock(&tq->mutex);
  791. return rval;
  792. }
  793. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg)
  794. {
  795. int rv = pthread_create(&thr->pth, attr, start, arg);
  796. if (likely(!rv))
  797. thr->has_pth = true;
  798. return rv;
  799. }
  800. void thr_info_freeze(struct thr_info *thr)
  801. {
  802. struct tq_ent *ent, *iter;
  803. struct thread_q *tq;
  804. if (!thr)
  805. return;
  806. tq = thr->q;
  807. if (!tq)
  808. return;
  809. mutex_lock(&tq->mutex);
  810. tq->frozen = true;
  811. DL_FOREACH_SAFE(tq->q, ent, iter) {
  812. DL_DELETE(tq->q, ent);
  813. free(ent);
  814. }
  815. mutex_unlock(&tq->mutex);
  816. }
  817. void thr_info_cancel(struct thr_info *thr)
  818. {
  819. if (!thr)
  820. return;
  821. if (thr->has_pth) {
  822. pthread_cancel(thr->pth);
  823. thr->has_pth = false;
  824. }
  825. }
  826. #ifndef HAVE_PTHREAD_CANCEL
  827. // Bionic (Android) is intentionally missing pthread_cancel, so it is implemented using pthread_kill
  828. enum pthread_cancel_workaround_mode {
  829. PCWM_DEFAULT = 0,
  830. PCWM_TERMINATE = 1,
  831. PCWM_ASYNC = 2,
  832. PCWM_DISABLED = 4,
  833. PCWM_CANCELLED = 8,
  834. };
  835. static pthread_key_t key_pcwm;
  836. struct sigaction pcwm_orig_term_handler;
  837. static
  838. void do_pthread_cancel_exit(int flags)
  839. {
  840. if (!(flags & PCWM_ASYNC))
  841. // NOTE: Logging disables cancel while mutex held, so this is safe
  842. applog(LOG_WARNING, "pthread_cancel workaround: Cannot defer cancellation, terminating thread NOW");
  843. pthread_exit(PTHREAD_CANCELED);
  844. }
  845. static
  846. void sighandler_pthread_cancel(int sig)
  847. {
  848. int flags = (int)pthread_getspecific(key_pcwm);
  849. if (flags & PCWM_TERMINATE) // Main thread
  850. {
  851. // Restore original handler and call it
  852. if (sigaction(sig, &pcwm_orig_term_handler, NULL))
  853. quit(1, "pthread_cancel workaround: Failed to restore original handler");
  854. raise(SIGTERM);
  855. quit(1, "pthread_cancel workaround: Original handler returned");
  856. }
  857. if (flags & PCWM_CANCELLED) // Already pending cancel
  858. return;
  859. if (flags & PCWM_DISABLED)
  860. {
  861. flags |= PCWM_CANCELLED;
  862. if (pthread_setspecific(key_pcwm, (void*)flags))
  863. quit(1, "pthread_cancel workaround: pthread_setspecific failed (setting PCWM_CANCELLED)");
  864. return;
  865. }
  866. do_pthread_cancel_exit(flags);
  867. }
  868. void pthread_testcancel(void)
  869. {
  870. int flags = (int)pthread_getspecific(key_pcwm);
  871. if (flags & PCWM_CANCELLED && !(flags & PCWM_DISABLED))
  872. do_pthread_cancel_exit(flags);
  873. }
  874. int pthread_setcancelstate(int state, int *oldstate)
  875. {
  876. int flags = (int)pthread_getspecific(key_pcwm);
  877. if (oldstate)
  878. *oldstate = (flags & PCWM_DISABLED) ? PTHREAD_CANCEL_DISABLE : PTHREAD_CANCEL_ENABLE;
  879. if (state == PTHREAD_CANCEL_DISABLE)
  880. flags |= PCWM_DISABLED;
  881. else
  882. {
  883. if (flags & PCWM_CANCELLED)
  884. do_pthread_cancel_exit(flags);
  885. flags &= ~PCWM_DISABLED;
  886. }
  887. if (pthread_setspecific(key_pcwm, (void*)flags))
  888. return -1;
  889. return 0;
  890. }
  891. int pthread_setcanceltype(int type, int *oldtype)
  892. {
  893. int flags = (int)pthread_getspecific(key_pcwm);
  894. if (oldtype)
  895. *oldtype = (flags & PCWM_ASYNC) ? PTHREAD_CANCEL_ASYNCHRONOUS : PTHREAD_CANCEL_DEFERRED;
  896. if (type == PTHREAD_CANCEL_ASYNCHRONOUS)
  897. flags |= PCWM_ASYNC;
  898. else
  899. flags &= ~PCWM_ASYNC;
  900. if (pthread_setspecific(key_pcwm, (void*)flags))
  901. return -1;
  902. return 0;
  903. }
  904. void setup_pthread_cancel_workaround()
  905. {
  906. if (pthread_key_create(&key_pcwm, NULL))
  907. quit(1, "pthread_cancel workaround: pthread_key_create failed");
  908. if (pthread_setspecific(key_pcwm, (void*)PCWM_TERMINATE))
  909. quit(1, "pthread_cancel workaround: pthread_setspecific failed");
  910. struct sigaction new_sigact = {
  911. .sa_handler = sighandler_pthread_cancel,
  912. };
  913. if (sigaction(SIGTERM, &new_sigact, &pcwm_orig_term_handler))
  914. quit(1, "pthread_cancel workaround: Failed to install SIGTERM handler");
  915. }
  916. #endif
  917. static void _now_gettimeofday(struct timeval *);
  918. static void _cgsleep_us_r_nanosleep(cgtimer_t *, int64_t);
  919. #ifdef HAVE_POOR_GETTIMEOFDAY
  920. static struct timeval tv_timeofday_offset;
  921. static struct timeval _tv_timeofday_lastchecked;
  922. static pthread_mutex_t _tv_timeofday_mutex = PTHREAD_MUTEX_INITIALIZER;
  923. static
  924. void bfg_calibrate_timeofday(struct timeval *expected, char *buf)
  925. {
  926. struct timeval actual, delta;
  927. timeradd(expected, &tv_timeofday_offset, expected);
  928. _now_gettimeofday(&actual);
  929. if (expected->tv_sec >= actual.tv_sec - 1 && expected->tv_sec <= actual.tv_sec + 1)
  930. // Within reason - no change necessary
  931. return;
  932. timersub(&actual, expected, &delta);
  933. timeradd(&tv_timeofday_offset, &delta, &tv_timeofday_offset);
  934. sprintf(buf, "Recalibrating timeofday offset (delta %ld.%06lds)", (long)delta.tv_sec, (long)delta.tv_usec);
  935. *expected = actual;
  936. }
  937. void bfg_gettimeofday(struct timeval *out)
  938. {
  939. char buf[64] = "";
  940. timer_set_now(out);
  941. mutex_lock(&_tv_timeofday_mutex);
  942. if (_tv_timeofday_lastchecked.tv_sec < out->tv_sec - 21)
  943. bfg_calibrate_timeofday(out, buf);
  944. else
  945. timeradd(out, &tv_timeofday_offset, out);
  946. mutex_unlock(&_tv_timeofday_mutex);
  947. if (unlikely(buf[0]))
  948. applog(LOG_WARNING, "%s", buf);
  949. }
  950. #endif
  951. #ifdef WIN32
  952. static LARGE_INTEGER _perffreq;
  953. static
  954. void _now_queryperformancecounter(struct timeval *tv)
  955. {
  956. LARGE_INTEGER now;
  957. if (unlikely(!QueryPerformanceCounter(&now)))
  958. quit(1, "QueryPerformanceCounter failed");
  959. *tv = (struct timeval){
  960. .tv_sec = now.QuadPart / _perffreq.QuadPart,
  961. .tv_usec = (now.QuadPart % _perffreq.QuadPart) * 1000000 / _perffreq.QuadPart,
  962. };
  963. }
  964. #endif
  965. static void bfg_init_time();
  966. static
  967. void _now_is_not_set(__maybe_unused struct timeval *tv)
  968. {
  969. bfg_init_time();
  970. timer_set_now(tv);
  971. }
  972. void (*timer_set_now)(struct timeval *tv) = _now_is_not_set;
  973. void (*cgsleep_us_r)(cgtimer_t *, int64_t) = _cgsleep_us_r_nanosleep;
  974. static clockid_t bfg_timedwait_clk;
  975. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  976. static clockid_t bfg_timer_clk;
  977. static
  978. void _now_clock_gettime(struct timeval *tv)
  979. {
  980. struct timespec ts;
  981. if (unlikely(clock_gettime(bfg_timer_clk, &ts)))
  982. quit(1, "clock_gettime failed");
  983. *tv = (struct timeval){
  984. .tv_sec = ts.tv_sec,
  985. .tv_usec = ts.tv_nsec / 1000,
  986. };
  987. }
  988. #ifdef HAVE_CLOCK_NANOSLEEP
  989. static
  990. void _cgsleep_us_r_monotonic(cgtimer_t *tv_start, int64_t us)
  991. {
  992. struct timeval tv_end[1];
  993. struct timespec ts_end[1];
  994. int ret;
  995. timer_set_delay(tv_end, tv_start, us);
  996. timeval_to_spec(ts_end, tv_end);
  997. do {
  998. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ts_end, NULL);
  999. } while (ret == EINTR);
  1000. }
  1001. #endif
  1002. static
  1003. bool _bfg_try_clock_gettime(clockid_t clk)
  1004. {
  1005. struct timespec ts;
  1006. if (clock_gettime(clk, &ts))
  1007. return false;
  1008. bfg_timer_clk = clk;
  1009. timer_set_now = _now_clock_gettime;
  1010. return true;
  1011. }
  1012. #endif
  1013. int bfg_cond_timedwait(pthread_cond_t * restrict cond, pthread_mutex_t * restrict mutex, const struct timeval *tvp)
  1014. {
  1015. struct timespec ts;
  1016. clock_gettime(bfg_timedwait_clk, &ts);
  1017. ts.tv_sec += tvp->tv_sec;
  1018. ts.tv_nsec += (long)tvp->tv_usec * 1000;
  1019. if (ts.tv_nsec > 1000000000L)
  1020. {
  1021. ++ts.tv_sec;
  1022. ts.tv_nsec -= 1000000000L;
  1023. }
  1024. return pthread_cond_timedwait(cond, mutex, &ts);
  1025. }
  1026. pthread_condattr_t *bfg_condattr_()
  1027. {
  1028. static pthread_condattr_t attr;
  1029. static bool initialized;
  1030. if (unlikely(!initialized))
  1031. {
  1032. pthread_condattr_init(&attr);
  1033. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  1034. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC_RAW
  1035. if (!pthread_condattr_setclock(&attr, CLOCK_MONOTONIC_RAW))
  1036. {
  1037. applog(LOG_DEBUG, "Timers: Using %s for cond timedwait", "CLOCK_MONOTONIC_RAW");
  1038. bfg_timedwait_clk = CLOCK_MONOTONIC_RAW;
  1039. }
  1040. else
  1041. #endif
  1042. if (!pthread_condattr_setclock(&attr, CLOCK_MONOTONIC))
  1043. {
  1044. applog(LOG_DEBUG, "Timers: Using %s for cond timedwait", "CLOCK_MONOTONIC");
  1045. bfg_timedwait_clk = CLOCK_MONOTONIC;
  1046. }
  1047. else
  1048. #endif
  1049. if (!pthread_condattr_setclock(&attr, CLOCK_REALTIME))
  1050. {
  1051. applog(LOG_DEBUG, "Timers: Using %s for cond timedwait", "CLOCK_REALTIME");
  1052. bfg_timedwait_clk = CLOCK_REALTIME;
  1053. }
  1054. else
  1055. {
  1056. applog(LOG_DEBUG, "Timers: Cannot find a clock for cond timedwait");
  1057. return NULL;
  1058. }
  1059. initialized = true;
  1060. }
  1061. return &attr;
  1062. }
  1063. static
  1064. void bfg_init_time()
  1065. {
  1066. if (timer_set_now != _now_is_not_set)
  1067. return;
  1068. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC
  1069. #ifdef HAVE_CLOCK_GETTIME_MONOTONIC_RAW
  1070. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC_RAW))
  1071. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC_RAW)");
  1072. else
  1073. #endif
  1074. if (_bfg_try_clock_gettime(CLOCK_MONOTONIC))
  1075. {
  1076. applog(LOG_DEBUG, "Timers: Using clock_gettime(CLOCK_MONOTONIC)");
  1077. #ifdef HAVE_CLOCK_NANOSLEEP
  1078. cgsleep_us_r = _cgsleep_us_r_monotonic;
  1079. #endif
  1080. }
  1081. else
  1082. #endif
  1083. #ifdef WIN32
  1084. if (QueryPerformanceFrequency(&_perffreq) && _perffreq.QuadPart)
  1085. {
  1086. timer_set_now = _now_queryperformancecounter;
  1087. applog(LOG_DEBUG, "Timers: Using QueryPerformanceCounter");
  1088. }
  1089. else
  1090. #endif
  1091. {
  1092. timer_set_now = _now_gettimeofday;
  1093. applog(LOG_DEBUG, "Timers: Using gettimeofday");
  1094. }
  1095. #ifdef HAVE_POOR_GETTIMEOFDAY
  1096. char buf[64] = "";
  1097. struct timeval tv;
  1098. timer_set_now(&tv);
  1099. bfg_calibrate_timeofday(&tv, buf);
  1100. applog(LOG_DEBUG, "%s", buf);
  1101. #endif
  1102. }
  1103. void subtime(struct timeval *a, struct timeval *b)
  1104. {
  1105. timersub(a, b, b);
  1106. }
  1107. void addtime(struct timeval *a, struct timeval *b)
  1108. {
  1109. timeradd(a, b, b);
  1110. }
  1111. bool time_more(struct timeval *a, struct timeval *b)
  1112. {
  1113. return timercmp(a, b, >);
  1114. }
  1115. bool time_less(struct timeval *a, struct timeval *b)
  1116. {
  1117. return timercmp(a, b, <);
  1118. }
  1119. void copy_time(struct timeval *dest, const struct timeval *src)
  1120. {
  1121. memcpy(dest, src, sizeof(struct timeval));
  1122. }
  1123. void timespec_to_val(struct timeval *val, const struct timespec *spec)
  1124. {
  1125. val->tv_sec = spec->tv_sec;
  1126. val->tv_usec = spec->tv_nsec / 1000;
  1127. }
  1128. void timeval_to_spec(struct timespec *spec, const struct timeval *val)
  1129. {
  1130. spec->tv_sec = val->tv_sec;
  1131. spec->tv_nsec = val->tv_usec * 1000;
  1132. }
  1133. void us_to_timeval(struct timeval *val, int64_t us)
  1134. {
  1135. lldiv_t tvdiv = lldiv(us, 1000000);
  1136. val->tv_sec = tvdiv.quot;
  1137. val->tv_usec = tvdiv.rem;
  1138. }
  1139. void us_to_timespec(struct timespec *spec, int64_t us)
  1140. {
  1141. lldiv_t tvdiv = lldiv(us, 1000000);
  1142. spec->tv_sec = tvdiv.quot;
  1143. spec->tv_nsec = tvdiv.rem * 1000;
  1144. }
  1145. void ms_to_timespec(struct timespec *spec, int64_t ms)
  1146. {
  1147. lldiv_t tvdiv = lldiv(ms, 1000);
  1148. spec->tv_sec = tvdiv.quot;
  1149. spec->tv_nsec = tvdiv.rem * 1000000;
  1150. }
  1151. void timeraddspec(struct timespec *a, const struct timespec *b)
  1152. {
  1153. a->tv_sec += b->tv_sec;
  1154. a->tv_nsec += b->tv_nsec;
  1155. if (a->tv_nsec >= 1000000000) {
  1156. a->tv_nsec -= 1000000000;
  1157. a->tv_sec++;
  1158. }
  1159. }
  1160. #ifndef WIN32
  1161. static
  1162. void _now_gettimeofday(struct timeval *tv)
  1163. {
  1164. gettimeofday(tv, NULL);
  1165. }
  1166. #else
  1167. /* Windows start time is since 1601 lol so convert it to unix epoch 1970. */
  1168. #define EPOCHFILETIME (116444736000000000LL)
  1169. /* Return the system time as an lldiv_t in decimicroseconds. */
  1170. static void decius_time(lldiv_t *lidiv)
  1171. {
  1172. FILETIME ft;
  1173. LARGE_INTEGER li;
  1174. GetSystemTimeAsFileTime(&ft);
  1175. li.LowPart = ft.dwLowDateTime;
  1176. li.HighPart = ft.dwHighDateTime;
  1177. li.QuadPart -= EPOCHFILETIME;
  1178. /* SystemTime is in decimicroseconds so divide by an unusual number */
  1179. *lidiv = lldiv(li.QuadPart, 10000000);
  1180. }
  1181. void _now_gettimeofday(struct timeval *tv)
  1182. {
  1183. lldiv_t lidiv;
  1184. decius_time(&lidiv);
  1185. tv->tv_sec = lidiv.quot;
  1186. tv->tv_usec = lidiv.rem / 10;
  1187. }
  1188. #endif
  1189. void cgsleep_ms_r(cgtimer_t *tv_start, int ms)
  1190. {
  1191. cgsleep_us_r(tv_start, ((int64_t)ms) * 1000);
  1192. }
  1193. static
  1194. void _cgsleep_us_r_nanosleep(cgtimer_t *tv_start, int64_t us)
  1195. {
  1196. struct timeval tv_timer[1], tv[1];
  1197. struct timespec ts[1];
  1198. timer_set_delay(tv_timer, tv_start, us);
  1199. while (true)
  1200. {
  1201. timer_set_now(tv);
  1202. if (!timercmp(tv_timer, tv, >))
  1203. return;
  1204. timersub(tv_timer, tv, tv);
  1205. timeval_to_spec(ts, tv);
  1206. nanosleep(ts, NULL);
  1207. }
  1208. }
  1209. void cgsleep_ms(int ms)
  1210. {
  1211. cgtimer_t ts_start;
  1212. cgsleep_prepare_r(&ts_start);
  1213. cgsleep_ms_r(&ts_start, ms);
  1214. }
  1215. void cgsleep_us(int64_t us)
  1216. {
  1217. cgtimer_t ts_start;
  1218. cgsleep_prepare_r(&ts_start);
  1219. cgsleep_us_r(&ts_start, us);
  1220. }
  1221. /* Returns the microseconds difference between end and start times as a double */
  1222. double us_tdiff(struct timeval *end, struct timeval *start)
  1223. {
  1224. return end->tv_sec * 1000000 + end->tv_usec - start->tv_sec * 1000000 - start->tv_usec;
  1225. }
  1226. /* Returns the seconds difference between end and start times as a double */
  1227. double tdiff(struct timeval *end, struct timeval *start)
  1228. {
  1229. return end->tv_sec - start->tv_sec + (end->tv_usec - start->tv_usec) / 1000000.0;
  1230. }
  1231. int32_t utf8_decode(const void *b, int *out_len)
  1232. {
  1233. int32_t w;
  1234. const unsigned char *s = b;
  1235. if (!(s[0] & 0x80))
  1236. {
  1237. // ASCII
  1238. *out_len = 1;
  1239. return s[0];
  1240. }
  1241. #ifdef STRICT_UTF8
  1242. if (unlikely(!(s[0] & 0x40)))
  1243. goto invalid;
  1244. #endif
  1245. if (!(s[0] & 0x20))
  1246. *out_len = 2;
  1247. else
  1248. if (!(s[0] & 0x10))
  1249. *out_len = 3;
  1250. else
  1251. if (likely(!(s[0] & 8)))
  1252. *out_len = 4;
  1253. else
  1254. goto invalid;
  1255. w = s[0] & ((2 << (6 - *out_len)) - 1);
  1256. for (int i = 1; i < *out_len; ++i)
  1257. {
  1258. #ifdef STRICT_UTF8
  1259. if (unlikely((s[i] & 0xc0) != 0x80))
  1260. goto invalid;
  1261. #endif
  1262. w = (w << 6) | (s[i] & 0x3f);
  1263. }
  1264. #if defined(STRICT_UTF8)
  1265. if (unlikely(w > 0x10FFFF))
  1266. goto invalid;
  1267. // FIXME: UTF-8 requires smallest possible encoding; check it
  1268. #endif
  1269. return w;
  1270. invalid:
  1271. *out_len = 1;
  1272. return REPLACEMENT_CHAR;
  1273. }
  1274. static
  1275. void _utf8_test(const char *s, const wchar_t expected, int expectedlen)
  1276. {
  1277. int len;
  1278. wchar_t r;
  1279. r = utf8_decode(s, &len);
  1280. if (unlikely(r != expected || expectedlen != len))
  1281. applog(LOG_ERR, "UTF-8 test U+%06lX (len %d) failed: got U+%06lX (len %d)", (unsigned long)expected, expectedlen, (unsigned long)r, len);
  1282. }
  1283. #define _test_intrange(s, ...) _test_intrange(s, (int[]){ __VA_ARGS__ })
  1284. void utf8_test()
  1285. {
  1286. _utf8_test("", 0, 1);
  1287. _utf8_test("\1", 1, 1);
  1288. _utf8_test("\x7f", 0x7f, 1);
  1289. #if WCHAR_MAX >= 0x80
  1290. _utf8_test("\xc2\x80", 0x80, 2);
  1291. #if WCHAR_MAX >= 0xff
  1292. _utf8_test("\xc3\xbf", 0xff, 2);
  1293. #if WCHAR_MAX >= 0x7ff
  1294. _utf8_test("\xdf\xbf", 0x7ff, 2);
  1295. #if WCHAR_MAX >= 0x800
  1296. _utf8_test("\xe0\xa0\x80", 0x800, 3);
  1297. #if WCHAR_MAX >= 0xffff
  1298. _utf8_test("\xef\xbf\xbf", 0xffff, 3);
  1299. #if WCHAR_MAX >= 0x10000
  1300. _utf8_test("\xf0\x90\x80\x80", 0x10000, 4);
  1301. #if WCHAR_MAX >= 0x10ffff
  1302. _utf8_test("\xf4\x8f\xbf\xbf", 0x10ffff, 4);
  1303. #endif
  1304. #endif
  1305. #endif
  1306. #endif
  1307. #endif
  1308. #endif
  1309. #endif
  1310. #ifdef STRICT_UTF8
  1311. _utf8_test("\x80", REPLACEMENT_CHAR, 1);
  1312. _utf8_test("\xbf", REPLACEMENT_CHAR, 1);
  1313. _utf8_test("\xfe", REPLACEMENT_CHAR, 1);
  1314. _utf8_test("\xff", REPLACEMENT_CHAR, 1);
  1315. #endif
  1316. }
  1317. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port)
  1318. {
  1319. char *url_begin, *url_end, *ipv6_begin, *ipv6_end, *port_start = NULL;
  1320. char url_address[256], port[6];
  1321. int url_len, port_len = 0;
  1322. url_begin = strstr(url, "//");
  1323. if (!url_begin)
  1324. url_begin = url;
  1325. else
  1326. url_begin += 2;
  1327. /* Look for numeric ipv6 entries */
  1328. ipv6_begin = strstr(url_begin, "[");
  1329. ipv6_end = strstr(url_begin, "]");
  1330. if (ipv6_begin && ipv6_end && ipv6_end > ipv6_begin)
  1331. url_end = strstr(ipv6_end, ":");
  1332. else
  1333. url_end = strstr(url_begin, ":");
  1334. if (url_end) {
  1335. url_len = url_end - url_begin;
  1336. port_len = strlen(url_begin) - url_len - 1;
  1337. if (port_len < 1)
  1338. return false;
  1339. port_start = url_end + 1;
  1340. } else
  1341. url_len = strlen(url_begin);
  1342. if (url_len < 1)
  1343. return false;
  1344. sprintf(url_address, "%.*s", url_len, url_begin);
  1345. if (port_len) {
  1346. char *slash;
  1347. snprintf(port, 6, "%.*s", port_len, port_start);
  1348. slash = strchr(port, '/');
  1349. if (slash)
  1350. *slash = '\0';
  1351. } else
  1352. strcpy(port, "80");
  1353. free(*sockaddr_port);
  1354. *sockaddr_port = strdup(port);
  1355. free(*sockaddr_url);
  1356. *sockaddr_url = strdup(url_address);
  1357. return true;
  1358. }
  1359. enum send_ret {
  1360. SEND_OK,
  1361. SEND_SELECTFAIL,
  1362. SEND_SENDFAIL,
  1363. SEND_INACTIVE
  1364. };
  1365. /* Send a single command across a socket, appending \n to it. This should all
  1366. * be done under stratum lock except when first establishing the socket */
  1367. static enum send_ret __stratum_send(struct pool *pool, char *s, ssize_t len)
  1368. {
  1369. SOCKETTYPE sock = pool->sock;
  1370. ssize_t ssent = 0;
  1371. strcat(s, "\n");
  1372. len++;
  1373. while (len > 0 ) {
  1374. struct timeval timeout = {1, 0};
  1375. ssize_t sent;
  1376. fd_set wd;
  1377. FD_ZERO(&wd);
  1378. FD_SET(sock, &wd);
  1379. if (select(sock + 1, NULL, &wd, NULL, &timeout) < 1)
  1380. return SEND_SELECTFAIL;
  1381. #ifdef __APPLE__
  1382. sent = send(pool->sock, s + ssent, len, SO_NOSIGPIPE);
  1383. #elif WIN32
  1384. sent = send(pool->sock, s + ssent, len, 0);
  1385. #else
  1386. sent = send(pool->sock, s + ssent, len, MSG_NOSIGNAL);
  1387. #endif
  1388. if (sent < 0) {
  1389. if (!sock_blocks())
  1390. return SEND_SENDFAIL;
  1391. sent = 0;
  1392. }
  1393. ssent += sent;
  1394. len -= sent;
  1395. }
  1396. pool->cgminer_pool_stats.times_sent++;
  1397. pool->cgminer_pool_stats.bytes_sent += ssent;
  1398. total_bytes_sent += ssent;
  1399. pool->cgminer_pool_stats.net_bytes_sent += ssent;
  1400. return SEND_OK;
  1401. }
  1402. bool _stratum_send(struct pool *pool, char *s, ssize_t len, bool force)
  1403. {
  1404. enum send_ret ret = SEND_INACTIVE;
  1405. if (opt_protocol)
  1406. applog(LOG_DEBUG, "Pool %u: SEND: %s", pool->pool_no, s);
  1407. mutex_lock(&pool->stratum_lock);
  1408. if (pool->stratum_active || force)
  1409. ret = __stratum_send(pool, s, len);
  1410. mutex_unlock(&pool->stratum_lock);
  1411. /* This is to avoid doing applog under stratum_lock */
  1412. switch (ret) {
  1413. default:
  1414. case SEND_OK:
  1415. break;
  1416. case SEND_SELECTFAIL:
  1417. applog(LOG_DEBUG, "Write select failed on pool %d sock", pool->pool_no);
  1418. suspend_stratum(pool);
  1419. break;
  1420. case SEND_SENDFAIL:
  1421. applog(LOG_DEBUG, "Failed to send in stratum_send");
  1422. suspend_stratum(pool);
  1423. break;
  1424. case SEND_INACTIVE:
  1425. applog(LOG_DEBUG, "Stratum send failed due to no pool stratum_active");
  1426. break;
  1427. }
  1428. return (ret == SEND_OK);
  1429. }
  1430. static bool socket_full(struct pool *pool, int wait)
  1431. {
  1432. SOCKETTYPE sock = pool->sock;
  1433. struct timeval timeout;
  1434. fd_set rd;
  1435. if (sock == INVSOCK)
  1436. return true;
  1437. if (unlikely(wait < 0))
  1438. wait = 0;
  1439. FD_ZERO(&rd);
  1440. FD_SET(sock, &rd);
  1441. timeout.tv_usec = 0;
  1442. timeout.tv_sec = wait;
  1443. if (select(sock + 1, &rd, NULL, NULL, &timeout) > 0)
  1444. return true;
  1445. return false;
  1446. }
  1447. /* Check to see if Santa's been good to you */
  1448. bool sock_full(struct pool *pool)
  1449. {
  1450. if (strlen(pool->sockbuf))
  1451. return true;
  1452. return (socket_full(pool, 0));
  1453. }
  1454. static void clear_sockbuf(struct pool *pool)
  1455. {
  1456. strcpy(pool->sockbuf, "");
  1457. }
  1458. static void clear_sock(struct pool *pool)
  1459. {
  1460. ssize_t n;
  1461. mutex_lock(&pool->stratum_lock);
  1462. do {
  1463. if (pool->sock)
  1464. n = recv(pool->sock, pool->sockbuf, RECVSIZE, 0);
  1465. else
  1466. n = 0;
  1467. } while (n > 0);
  1468. mutex_unlock(&pool->stratum_lock);
  1469. clear_sockbuf(pool);
  1470. }
  1471. /* Make sure the pool sockbuf is large enough to cope with any coinbase size
  1472. * by reallocing it to a large enough size rounded up to a multiple of RBUFSIZE
  1473. * and zeroing the new memory */
  1474. static void recalloc_sock(struct pool *pool, size_t len)
  1475. {
  1476. size_t old, new;
  1477. old = strlen(pool->sockbuf);
  1478. new = old + len + 1;
  1479. if (new < pool->sockbuf_size)
  1480. return;
  1481. new = new + (RBUFSIZE - (new % RBUFSIZE));
  1482. // Avoid potentially recursive locking
  1483. // applog(LOG_DEBUG, "Recallocing pool sockbuf to %lu", (unsigned long)new);
  1484. pool->sockbuf = realloc(pool->sockbuf, new);
  1485. if (!pool->sockbuf)
  1486. quithere(1, "Failed to realloc pool sockbuf");
  1487. memset(pool->sockbuf + old, 0, new - old);
  1488. pool->sockbuf_size = new;
  1489. }
  1490. /* Peeks at a socket to find the first end of line and then reads just that
  1491. * from the socket and returns that as a malloced char */
  1492. char *recv_line(struct pool *pool)
  1493. {
  1494. char *tok, *sret = NULL;
  1495. ssize_t len, buflen;
  1496. int waited = 0;
  1497. if (!strstr(pool->sockbuf, "\n")) {
  1498. struct timeval rstart, now;
  1499. cgtime(&rstart);
  1500. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  1501. applog(LOG_DEBUG, "Timed out waiting for data on socket_full");
  1502. goto out;
  1503. }
  1504. do {
  1505. char s[RBUFSIZE];
  1506. size_t slen;
  1507. ssize_t n;
  1508. memset(s, 0, RBUFSIZE);
  1509. n = recv(pool->sock, s, RECVSIZE, 0);
  1510. if (!n) {
  1511. applog(LOG_DEBUG, "Socket closed waiting in recv_line");
  1512. suspend_stratum(pool);
  1513. break;
  1514. }
  1515. cgtime(&now);
  1516. waited = tdiff(&now, &rstart);
  1517. if (n < 0) {
  1518. //Save errno from being overweitten bei socket_ commands
  1519. int socket_recv_errno;
  1520. socket_recv_errno = SOCKERR;
  1521. if (!sock_blocks() || !socket_full(pool, DEFAULT_SOCKWAIT - waited)) {
  1522. applog(LOG_DEBUG, "Failed to recv sock in recv_line: %s", bfg_strerror(socket_recv_errno, BST_SOCKET));
  1523. suspend_stratum(pool);
  1524. break;
  1525. }
  1526. } else {
  1527. slen = strlen(s);
  1528. recalloc_sock(pool, slen);
  1529. strcat(pool->sockbuf, s);
  1530. }
  1531. } while (waited < DEFAULT_SOCKWAIT && !strstr(pool->sockbuf, "\n"));
  1532. }
  1533. buflen = strlen(pool->sockbuf);
  1534. tok = strtok(pool->sockbuf, "\n");
  1535. if (!tok) {
  1536. applog(LOG_DEBUG, "Failed to parse a \\n terminated string in recv_line");
  1537. goto out;
  1538. }
  1539. sret = strdup(tok);
  1540. len = strlen(sret);
  1541. /* Copy what's left in the buffer after the \n, including the
  1542. * terminating \0 */
  1543. if (buflen > len + 1)
  1544. memmove(pool->sockbuf, pool->sockbuf + len + 1, buflen - len + 1);
  1545. else
  1546. strcpy(pool->sockbuf, "");
  1547. pool->cgminer_pool_stats.times_received++;
  1548. pool->cgminer_pool_stats.bytes_received += len;
  1549. total_bytes_rcvd += len;
  1550. pool->cgminer_pool_stats.net_bytes_received += len;
  1551. out:
  1552. if (!sret)
  1553. clear_sock(pool);
  1554. else if (opt_protocol)
  1555. applog(LOG_DEBUG, "Pool %u: RECV: %s", pool->pool_no, sret);
  1556. return sret;
  1557. }
  1558. /* Dumps any JSON value as a string. Just like jansson 2.1's JSON_ENCODE_ANY
  1559. * flag, but this is compatible with 2.0. */
  1560. char *json_dumps_ANY(json_t *json, size_t flags)
  1561. {
  1562. switch (json_typeof(json))
  1563. {
  1564. case JSON_ARRAY:
  1565. case JSON_OBJECT:
  1566. return json_dumps(json, flags);
  1567. default:
  1568. break;
  1569. }
  1570. char *rv;
  1571. #ifdef JSON_ENCODE_ANY
  1572. rv = json_dumps(json, JSON_ENCODE_ANY | flags);
  1573. if (rv)
  1574. return rv;
  1575. #endif
  1576. json_t *tmp = json_array();
  1577. char *s;
  1578. int i;
  1579. size_t len;
  1580. if (!tmp)
  1581. quithere(1, "Failed to allocate json array");
  1582. if (json_array_append(tmp, json))
  1583. quithere(1, "Failed to append temporary array");
  1584. s = json_dumps(tmp, flags);
  1585. if (!s)
  1586. return NULL;
  1587. for (i = 0; s[i] != '['; ++i)
  1588. if (unlikely(!(s[i] && isCspace(s[i]))))
  1589. quithere(1, "Failed to find opening bracket in array dump");
  1590. len = strlen(&s[++i]) - 1;
  1591. if (unlikely(s[i+len] != ']'))
  1592. quithere(1, "Failed to find closing bracket in array dump");
  1593. rv = malloc(len + 1);
  1594. memcpy(rv, &s[i], len);
  1595. rv[len] = '\0';
  1596. free(s);
  1597. json_decref(tmp);
  1598. return rv;
  1599. }
  1600. /* Extracts a string value from a json array with error checking. To be used
  1601. * when the value of the string returned is only examined and not to be stored.
  1602. * See json_array_string below */
  1603. const char *__json_array_string(json_t *val, unsigned int entry)
  1604. {
  1605. json_t *arr_entry;
  1606. if (json_is_null(val))
  1607. return NULL;
  1608. if (!json_is_array(val))
  1609. return NULL;
  1610. if (entry > json_array_size(val))
  1611. return NULL;
  1612. arr_entry = json_array_get(val, entry);
  1613. if (!json_is_string(arr_entry))
  1614. return NULL;
  1615. return json_string_value(arr_entry);
  1616. }
  1617. /* Creates a freshly malloced dup of __json_array_string */
  1618. static char *json_array_string(json_t *val, unsigned int entry)
  1619. {
  1620. const char *buf = __json_array_string(val, entry);
  1621. if (buf)
  1622. return strdup(buf);
  1623. return NULL;
  1624. }
  1625. void stratum_probe_transparency(struct pool *pool)
  1626. {
  1627. // Request transaction data to discourage pools from doing anything shady
  1628. char s[1024];
  1629. int sLen;
  1630. sLen = sprintf(s, "{\"params\": [\"%s\"], \"id\": \"txlist%s\", \"method\": \"mining.get_transactions\"}",
  1631. pool->swork.job_id,
  1632. pool->swork.job_id);
  1633. stratum_send(pool, s, sLen);
  1634. if ((!pool->swork.opaque) && !timer_isset(&pool->swork.tv_transparency))
  1635. cgtime(&pool->swork.tv_transparency);
  1636. pool->swork.transparency_probed = true;
  1637. }
  1638. static bool parse_notify(struct pool *pool, json_t *val)
  1639. {
  1640. const char *prev_hash, *coinbase1, *coinbase2, *bbversion, *nbit, *ntime;
  1641. char *job_id;
  1642. bool clean, ret = false;
  1643. int merkles, i;
  1644. size_t cb1_len, cb2_len;
  1645. json_t *arr;
  1646. arr = json_array_get(val, 4);
  1647. if (!arr || !json_is_array(arr))
  1648. goto out;
  1649. merkles = json_array_size(arr);
  1650. for (i = 0; i < merkles; i++)
  1651. if (!json_is_string(json_array_get(arr, i)))
  1652. goto out;
  1653. prev_hash = __json_array_string(val, 1);
  1654. coinbase1 = __json_array_string(val, 2);
  1655. coinbase2 = __json_array_string(val, 3);
  1656. bbversion = __json_array_string(val, 5);
  1657. nbit = __json_array_string(val, 6);
  1658. ntime = __json_array_string(val, 7);
  1659. clean = json_is_true(json_array_get(val, 8));
  1660. if (!prev_hash || !coinbase1 || !coinbase2 || !bbversion || !nbit || !ntime)
  1661. goto out;
  1662. job_id = json_array_string(val, 0);
  1663. if (!job_id)
  1664. goto out;
  1665. cg_wlock(&pool->data_lock);
  1666. cgtime(&pool->swork.tv_received);
  1667. free(pool->swork.job_id);
  1668. pool->swork.job_id = job_id;
  1669. pool->submit_old = !clean;
  1670. pool->swork.clean = true;
  1671. hex2bin(&pool->swork.header1[0], bbversion, 4);
  1672. hex2bin(&pool->swork.header1[4], prev_hash, 32);
  1673. hex2bin((void*)&pool->swork.ntime, ntime, 4);
  1674. pool->swork.ntime = be32toh(pool->swork.ntime);
  1675. hex2bin(&pool->swork.diffbits[0], nbit, 4);
  1676. cb1_len = strlen(coinbase1) / 2;
  1677. pool->swork.nonce2_offset = cb1_len + pool->n1_len;
  1678. cb2_len = strlen(coinbase2) / 2;
  1679. bytes_resize(&pool->swork.coinbase, pool->swork.nonce2_offset + pool->n2size + cb2_len);
  1680. uint8_t *coinbase = bytes_buf(&pool->swork.coinbase);
  1681. hex2bin(coinbase, coinbase1, cb1_len);
  1682. hex2bin(&coinbase[cb1_len], pool->nonce1, pool->n1_len);
  1683. // NOTE: gap for nonce2, filled at work generation time
  1684. hex2bin(&coinbase[pool->swork.nonce2_offset + pool->n2size], coinbase2, cb2_len);
  1685. bytes_resize(&pool->swork.merkle_bin, 32 * merkles);
  1686. for (i = 0; i < merkles; i++)
  1687. hex2bin(&bytes_buf(&pool->swork.merkle_bin)[i * 32], json_string_value(json_array_get(arr, i)), 32);
  1688. pool->swork.merkles = merkles;
  1689. pool->nonce2 = 0;
  1690. cg_wunlock(&pool->data_lock);
  1691. applog(LOG_DEBUG, "Received stratum notify from pool %u with job_id=%s",
  1692. pool->pool_no, job_id);
  1693. if (opt_debug && opt_protocol)
  1694. {
  1695. applog(LOG_DEBUG, "job_id: %s", job_id);
  1696. applog(LOG_DEBUG, "prev_hash: %s", prev_hash);
  1697. applog(LOG_DEBUG, "coinbase1: %s", coinbase1);
  1698. applog(LOG_DEBUG, "coinbase2: %s", coinbase2);
  1699. for (i = 0; i < merkles; i++)
  1700. applog(LOG_DEBUG, "merkle%d: %s", i, json_string_value(json_array_get(arr, i)));
  1701. applog(LOG_DEBUG, "bbversion: %s", bbversion);
  1702. applog(LOG_DEBUG, "nbit: %s", nbit);
  1703. applog(LOG_DEBUG, "ntime: %s", ntime);
  1704. applog(LOG_DEBUG, "clean: %s", clean ? "yes" : "no");
  1705. }
  1706. /* A notify message is the closest stratum gets to a getwork */
  1707. pool->getwork_requested++;
  1708. total_getworks++;
  1709. if ((merkles && (!pool->swork.transparency_probed || rand() <= RAND_MAX / (opt_skip_checks + 1))) || timer_isset(&pool->swork.tv_transparency))
  1710. if (pool->probed)
  1711. stratum_probe_transparency(pool);
  1712. ret = true;
  1713. out:
  1714. return ret;
  1715. }
  1716. static bool parse_diff(struct pool *pool, json_t *val)
  1717. {
  1718. double diff;
  1719. diff = json_number_value(json_array_get(val, 0));
  1720. if (diff == 0)
  1721. return false;
  1722. cg_wlock(&pool->data_lock);
  1723. pool->swork.diff = diff;
  1724. cg_wunlock(&pool->data_lock);
  1725. applog(LOG_DEBUG, "Pool %d stratum bdifficulty set to %f", pool->pool_no, diff);
  1726. return true;
  1727. }
  1728. static bool parse_reconnect(struct pool *pool, json_t *val)
  1729. {
  1730. const char *url;
  1731. char address[256];
  1732. json_t *port_json;
  1733. url = __json_array_string(val, 0);
  1734. if (!url)
  1735. url = pool->sockaddr_url;
  1736. port_json = json_array_get(val, 1);
  1737. if (json_is_number(port_json))
  1738. {
  1739. const unsigned port = json_number_value(port_json);
  1740. snprintf(address, sizeof(address), "%s:%u", url, port);
  1741. }
  1742. else
  1743. {
  1744. const char *port;
  1745. if (json_is_string(port_json))
  1746. port = json_string_value(port_json);
  1747. else
  1748. port = pool->stratum_port;
  1749. snprintf(address, sizeof(address), "%s:%s", url, port);
  1750. }
  1751. if (!extract_sockaddr(address, &pool->sockaddr_url, &pool->stratum_port))
  1752. return false;
  1753. pool->stratum_url = pool->sockaddr_url;
  1754. applog(LOG_NOTICE, "Reconnect requested from pool %d to %s", pool->pool_no, address);
  1755. if (!restart_stratum(pool))
  1756. return false;
  1757. return true;
  1758. }
  1759. static bool send_version(struct pool *pool, json_t *val)
  1760. {
  1761. char s[RBUFSIZE], *idstr;
  1762. json_t *id = json_object_get(val, "id");
  1763. if (!(id && !json_is_null(id)))
  1764. return false;
  1765. idstr = json_dumps_ANY(id, 0);
  1766. sprintf(s, "{\"id\": %s, \"result\": \""PACKAGE"/"VERSION"\", \"error\": null}", idstr);
  1767. free(idstr);
  1768. if (!stratum_send(pool, s, strlen(s)))
  1769. return false;
  1770. return true;
  1771. }
  1772. static bool stratum_show_message(struct pool *pool, json_t *val, json_t *params)
  1773. {
  1774. char *msg;
  1775. char s[RBUFSIZE], *idstr;
  1776. json_t *id = json_object_get(val, "id");
  1777. msg = json_array_string(params, 0);
  1778. if (likely(msg))
  1779. {
  1780. free(pool->admin_msg);
  1781. pool->admin_msg = msg;
  1782. applog(LOG_NOTICE, "Message from pool %u: %s", pool->pool_no, msg);
  1783. }
  1784. if (!(id && !json_is_null(id)))
  1785. return true;
  1786. idstr = json_dumps_ANY(id, 0);
  1787. if (likely(msg))
  1788. sprintf(s, "{\"id\": %s, \"result\": true, \"error\": null}", idstr);
  1789. else
  1790. sprintf(s, "{\"id\": %s, \"result\": null, \"error\": [-1, \"Failed to parse message\", null]}", idstr);
  1791. free(idstr);
  1792. if (!stratum_send(pool, s, strlen(s)))
  1793. return false;
  1794. return true;
  1795. }
  1796. bool parse_method(struct pool *pool, char *s)
  1797. {
  1798. json_t *val = NULL, *method, *err_val, *params;
  1799. json_error_t err;
  1800. bool ret = false;
  1801. const char *buf;
  1802. if (!s)
  1803. goto out;
  1804. val = JSON_LOADS(s, &err);
  1805. if (!val) {
  1806. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  1807. goto out;
  1808. }
  1809. method = json_object_get(val, "method");
  1810. if (!method)
  1811. goto out;
  1812. err_val = json_object_get(val, "error");
  1813. params = json_object_get(val, "params");
  1814. if (err_val && !json_is_null(err_val)) {
  1815. char *ss;
  1816. if (err_val)
  1817. ss = json_dumps(err_val, JSON_INDENT(3));
  1818. else
  1819. ss = strdup("(unknown reason)");
  1820. applog(LOG_INFO, "JSON-RPC method decode failed: %s", ss);
  1821. free(ss);
  1822. goto out;
  1823. }
  1824. buf = json_string_value(method);
  1825. if (!buf)
  1826. goto out;
  1827. if (!strncasecmp(buf, "mining.notify", 13)) {
  1828. if (parse_notify(pool, params))
  1829. pool->stratum_notify = ret = true;
  1830. else
  1831. pool->stratum_notify = ret = false;
  1832. goto out;
  1833. }
  1834. if (!strncasecmp(buf, "mining.set_difficulty", 21) && parse_diff(pool, params)) {
  1835. ret = true;
  1836. goto out;
  1837. }
  1838. if (!strncasecmp(buf, "client.reconnect", 16) && parse_reconnect(pool, params)) {
  1839. ret = true;
  1840. goto out;
  1841. }
  1842. if (!strncasecmp(buf, "client.get_version", 18) && send_version(pool, val)) {
  1843. ret = true;
  1844. goto out;
  1845. }
  1846. if (!strncasecmp(buf, "client.show_message", 19) && stratum_show_message(pool, val, params)) {
  1847. ret = true;
  1848. goto out;
  1849. }
  1850. out:
  1851. if (val)
  1852. json_decref(val);
  1853. return ret;
  1854. }
  1855. extern bool parse_stratum_response(struct pool *, char *s);
  1856. bool auth_stratum(struct pool *pool)
  1857. {
  1858. json_t *val = NULL, *res_val, *err_val;
  1859. char s[RBUFSIZE], *sret = NULL;
  1860. json_error_t err;
  1861. bool ret = false;
  1862. sprintf(s, "{\"id\": \"auth\", \"method\": \"mining.authorize\", \"params\": [\"%s\", \"%s\"]}",
  1863. pool->rpc_user, pool->rpc_pass);
  1864. if (!stratum_send(pool, s, strlen(s)))
  1865. goto out;
  1866. /* Parse all data in the queue and anything left should be auth */
  1867. while (42) {
  1868. sret = recv_line(pool);
  1869. if (!sret)
  1870. goto out;
  1871. if (parse_method(pool, sret))
  1872. free(sret);
  1873. else
  1874. break;
  1875. }
  1876. val = JSON_LOADS(sret, &err);
  1877. free(sret);
  1878. res_val = json_object_get(val, "result");
  1879. err_val = json_object_get(val, "error");
  1880. if (!res_val || json_is_false(res_val) || (err_val && !json_is_null(err_val))) {
  1881. char *ss;
  1882. if (err_val)
  1883. ss = json_dumps(err_val, JSON_INDENT(3));
  1884. else
  1885. ss = strdup("(unknown reason)");
  1886. applog(LOG_WARNING, "pool %d JSON stratum auth failed: %s", pool->pool_no, ss);
  1887. free(ss);
  1888. goto out;
  1889. }
  1890. ret = true;
  1891. applog(LOG_INFO, "Stratum authorisation success for pool %d", pool->pool_no);
  1892. pool->probed = true;
  1893. successful_connect = true;
  1894. out:
  1895. if (val)
  1896. json_decref(val);
  1897. if (pool->stratum_notify)
  1898. stratum_probe_transparency(pool);
  1899. return ret;
  1900. }
  1901. curl_socket_t grab_socket_opensocket_cb(void *clientp, __maybe_unused curlsocktype purpose, struct curl_sockaddr *addr)
  1902. {
  1903. struct pool *pool = clientp;
  1904. curl_socket_t sck = socket(addr->family, addr->socktype, addr->protocol);
  1905. pool->sock = sck;
  1906. return sck;
  1907. }
  1908. static bool setup_stratum_curl(struct pool *pool)
  1909. {
  1910. char curl_err_str[CURL_ERROR_SIZE];
  1911. CURL *curl = NULL;
  1912. char s[RBUFSIZE];
  1913. bool ret = false;
  1914. applog(LOG_DEBUG, "initiate_stratum with sockbuf=%p", pool->sockbuf);
  1915. mutex_lock(&pool->stratum_lock);
  1916. timer_unset(&pool->swork.tv_transparency);
  1917. pool->stratum_active = false;
  1918. pool->stratum_notify = false;
  1919. pool->swork.transparency_probed = false;
  1920. if (pool->stratum_curl)
  1921. curl_easy_cleanup(pool->stratum_curl);
  1922. pool->stratum_curl = curl_easy_init();
  1923. if (unlikely(!pool->stratum_curl))
  1924. quithere(1, "Failed to curl_easy_init");
  1925. if (pool->sockbuf)
  1926. pool->sockbuf[0] = '\0';
  1927. curl = pool->stratum_curl;
  1928. if (!pool->sockbuf) {
  1929. pool->sockbuf = calloc(RBUFSIZE, 1);
  1930. if (!pool->sockbuf)
  1931. quithere(1, "Failed to calloc pool sockbuf");
  1932. pool->sockbuf_size = RBUFSIZE;
  1933. }
  1934. /* Create a http url for use with curl */
  1935. sprintf(s, "http://%s:%s", pool->sockaddr_url, pool->stratum_port);
  1936. curl_easy_setopt(curl, CURLOPT_FRESH_CONNECT, 1);
  1937. curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 30);
  1938. curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
  1939. curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
  1940. curl_easy_setopt(curl, CURLOPT_URL, s);
  1941. if (!opt_delaynet)
  1942. curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
  1943. /* We use DEBUGFUNCTION to count bytes sent/received, and verbose is needed
  1944. * to enable it */
  1945. curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, curl_debug_cb);
  1946. curl_easy_setopt(curl, CURLOPT_DEBUGDATA, (void *)pool);
  1947. curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  1948. // CURLINFO_LASTSOCKET is broken on Win64 (which has a wider SOCKET type than curl_easy_getinfo returns), so we use this hack for now
  1949. curl_easy_setopt(curl, CURLOPT_OPENSOCKETFUNCTION, grab_socket_opensocket_cb);
  1950. curl_easy_setopt(curl, CURLOPT_OPENSOCKETDATA, pool);
  1951. curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_TRY);
  1952. if (pool->rpc_proxy) {
  1953. curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  1954. curl_easy_setopt(curl, CURLOPT_PROXY, pool->rpc_proxy);
  1955. } else if (opt_socks_proxy) {
  1956. curl_easy_setopt(curl, CURLOPT_HTTPPROXYTUNNEL, 1);
  1957. curl_easy_setopt(curl, CURLOPT_PROXY, opt_socks_proxy);
  1958. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  1959. }
  1960. curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1);
  1961. pool->sock = INVSOCK;
  1962. if (curl_easy_perform(curl)) {
  1963. applog(LOG_INFO, "Stratum connect failed to pool %d: %s", pool->pool_no, curl_err_str);
  1964. errout:
  1965. curl_easy_cleanup(curl);
  1966. pool->stratum_curl = NULL;
  1967. goto out;
  1968. }
  1969. if (pool->sock == INVSOCK)
  1970. {
  1971. applog(LOG_ERR, "Stratum connect succeeded, but technical problem extracting socket (pool %u)", pool->pool_no);
  1972. goto errout;
  1973. }
  1974. keep_sockalive(pool->sock);
  1975. pool->cgminer_pool_stats.times_sent++;
  1976. pool->cgminer_pool_stats.times_received++;
  1977. ret = true;
  1978. out:
  1979. mutex_unlock(&pool->stratum_lock);
  1980. return ret;
  1981. }
  1982. static char *get_sessionid(json_t *val)
  1983. {
  1984. char *ret = NULL;
  1985. json_t *arr_val;
  1986. int arrsize, i;
  1987. arr_val = json_array_get(val, 0);
  1988. if (!arr_val || !json_is_array(arr_val))
  1989. goto out;
  1990. arrsize = json_array_size(arr_val);
  1991. for (i = 0; i < arrsize; i++) {
  1992. json_t *arr = json_array_get(arr_val, i);
  1993. const char *notify;
  1994. if (!arr | !json_is_array(arr))
  1995. break;
  1996. notify = __json_array_string(arr, 0);
  1997. if (!notify)
  1998. continue;
  1999. if (!strncasecmp(notify, "mining.notify", 13)) {
  2000. ret = json_array_string(arr, 1);
  2001. break;
  2002. }
  2003. }
  2004. out:
  2005. return ret;
  2006. }
  2007. void suspend_stratum(struct pool *pool)
  2008. {
  2009. clear_sockbuf(pool);
  2010. applog(LOG_INFO, "Closing socket for stratum pool %d", pool->pool_no);
  2011. mutex_lock(&pool->stratum_lock);
  2012. pool->stratum_active = pool->stratum_notify = false;
  2013. if (pool->stratum_curl) {
  2014. curl_easy_cleanup(pool->stratum_curl);
  2015. }
  2016. pool->stratum_curl = NULL;
  2017. pool->sock = INVSOCK;
  2018. mutex_unlock(&pool->stratum_lock);
  2019. }
  2020. bool initiate_stratum(struct pool *pool)
  2021. {
  2022. bool ret = false, recvd = false, noresume = false, sockd = false;
  2023. bool trysuggest = request_target_str;
  2024. char s[RBUFSIZE], *sret = NULL, *nonce1, *sessionid;
  2025. json_t *val = NULL, *res_val, *err_val;
  2026. json_error_t err;
  2027. int n2size;
  2028. resend:
  2029. if (!setup_stratum_curl(pool)) {
  2030. sockd = false;
  2031. goto out;
  2032. }
  2033. sockd = true;
  2034. clear_sock(pool);
  2035. if (trysuggest)
  2036. {
  2037. int sz = sprintf(s, "{\"id\": null, \"method\": \"mining.suggest_target\", \"params\": [\"%s\"]}", request_target_str);
  2038. if (!_stratum_send(pool, s, sz, true))
  2039. {
  2040. applog(LOG_DEBUG, "Pool %u: Failed to send suggest_target in initiate_stratum", pool->pool_no);
  2041. goto out;
  2042. }
  2043. recvd = true;
  2044. }
  2045. if (noresume) {
  2046. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": []}", swork_id++);
  2047. } else {
  2048. if (pool->sessionid)
  2049. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\", \"%s\"]}", swork_id++, pool->sessionid);
  2050. else
  2051. sprintf(s, "{\"id\": %d, \"method\": \"mining.subscribe\", \"params\": [\""PACKAGE"/"VERSION"\"]}", swork_id++);
  2052. }
  2053. if (!_stratum_send(pool, s, strlen(s), true)) {
  2054. applog(LOG_DEBUG, "Failed to send s in initiate_stratum");
  2055. goto out;
  2056. }
  2057. recvd = true;
  2058. if (!socket_full(pool, DEFAULT_SOCKWAIT)) {
  2059. applog(LOG_DEBUG, "Timed out waiting for response in initiate_stratum");
  2060. goto out;
  2061. }
  2062. sret = recv_line(pool);
  2063. if (!sret)
  2064. goto out;
  2065. val = JSON_LOADS(sret, &err);
  2066. free(sret);
  2067. if (!val) {
  2068. applog(LOG_INFO, "JSON decode failed(%d): %s", err.line, err.text);
  2069. goto out;
  2070. }
  2071. res_val = json_object_get(val, "result");
  2072. err_val = json_object_get(val, "error");
  2073. if (!res_val || json_is_null(res_val) ||
  2074. (err_val && !json_is_null(err_val))) {
  2075. char *ss;
  2076. if (err_val)
  2077. ss = json_dumps(err_val, JSON_INDENT(3));
  2078. else
  2079. ss = strdup("(unknown reason)");
  2080. applog(LOG_INFO, "JSON-RPC decode failed: %s", ss);
  2081. free(ss);
  2082. goto out;
  2083. }
  2084. sessionid = get_sessionid(res_val);
  2085. if (!sessionid)
  2086. applog(LOG_DEBUG, "Failed to get sessionid in initiate_stratum");
  2087. nonce1 = json_array_string(res_val, 1);
  2088. if (!nonce1) {
  2089. applog(LOG_INFO, "Failed to get nonce1 in initiate_stratum");
  2090. free(sessionid);
  2091. goto out;
  2092. }
  2093. n2size = json_integer_value(json_array_get(res_val, 2));
  2094. if (!n2size) {
  2095. applog(LOG_INFO, "Failed to get n2size in initiate_stratum");
  2096. free(sessionid);
  2097. free(nonce1);
  2098. goto out;
  2099. }
  2100. cg_wlock(&pool->data_lock);
  2101. free(pool->sessionid);
  2102. pool->sessionid = sessionid;
  2103. free(pool->nonce1);
  2104. pool->nonce1 = nonce1;
  2105. pool->n1_len = strlen(nonce1) / 2;
  2106. pool->n2size = n2size;
  2107. pool->nonce2sz = (n2size > sizeof(pool->nonce2)) ? sizeof(pool->nonce2) : n2size;
  2108. #ifdef WORDS_BIGENDIAN
  2109. pool->nonce2off = (n2size < sizeof(pool->nonce2)) ? (sizeof(pool->nonce2) - n2size) : 0;
  2110. #endif
  2111. cg_wunlock(&pool->data_lock);
  2112. if (sessionid)
  2113. applog(LOG_DEBUG, "Pool %d stratum session id: %s", pool->pool_no, pool->sessionid);
  2114. ret = true;
  2115. out:
  2116. if (val)
  2117. {
  2118. json_decref(val);
  2119. val = NULL;
  2120. }
  2121. if (ret) {
  2122. if (!pool->stratum_url)
  2123. pool->stratum_url = pool->sockaddr_url;
  2124. pool->stratum_active = true;
  2125. pool->swork.diff = 1;
  2126. if (opt_protocol) {
  2127. applog(LOG_DEBUG, "Pool %d confirmed mining.subscribe with extranonce1 %s extran2size %d",
  2128. pool->pool_no, pool->nonce1, pool->n2size);
  2129. }
  2130. } else {
  2131. if (recvd)
  2132. {
  2133. if (trysuggest)
  2134. {
  2135. applog(LOG_DEBUG, "Pool %u: Failed to connect stratum with mining.suggest_target, retrying without", pool->pool_no);
  2136. trysuggest = false;
  2137. goto resend;
  2138. }
  2139. if (!noresume)
  2140. {
  2141. applog(LOG_DEBUG, "Failed to resume stratum, trying afresh");
  2142. noresume = true;
  2143. goto resend;
  2144. }
  2145. }
  2146. applog(LOG_DEBUG, "Initiate stratum failed");
  2147. if (sockd)
  2148. suspend_stratum(pool);
  2149. }
  2150. return ret;
  2151. }
  2152. bool restart_stratum(struct pool *pool)
  2153. {
  2154. if (pool->stratum_active)
  2155. suspend_stratum(pool);
  2156. if (!initiate_stratum(pool))
  2157. return false;
  2158. if (!auth_stratum(pool))
  2159. return false;
  2160. return true;
  2161. }
  2162. void dev_error_update(struct cgpu_info *dev, enum dev_reason reason)
  2163. {
  2164. dev->device_last_not_well = time(NULL);
  2165. cgtime(&dev->tv_device_last_not_well);
  2166. dev->device_not_well_reason = reason;
  2167. }
  2168. void dev_error(struct cgpu_info *dev, enum dev_reason reason)
  2169. {
  2170. dev_error_update(dev, reason);
  2171. switch (reason) {
  2172. case REASON_THREAD_FAIL_INIT:
  2173. dev->thread_fail_init_count++;
  2174. break;
  2175. case REASON_THREAD_ZERO_HASH:
  2176. dev->thread_zero_hash_count++;
  2177. break;
  2178. case REASON_THREAD_FAIL_QUEUE:
  2179. dev->thread_fail_queue_count++;
  2180. break;
  2181. case REASON_DEV_SICK_IDLE_60:
  2182. dev->dev_sick_idle_60_count++;
  2183. break;
  2184. case REASON_DEV_DEAD_IDLE_600:
  2185. dev->dev_dead_idle_600_count++;
  2186. break;
  2187. case REASON_DEV_NOSTART:
  2188. dev->dev_nostart_count++;
  2189. break;
  2190. case REASON_DEV_OVER_HEAT:
  2191. dev->dev_over_heat_count++;
  2192. break;
  2193. case REASON_DEV_THERMAL_CUTOFF:
  2194. dev->dev_thermal_cutoff_count++;
  2195. break;
  2196. case REASON_DEV_COMMS_ERROR:
  2197. dev->dev_comms_error_count++;
  2198. break;
  2199. case REASON_DEV_THROTTLE:
  2200. dev->dev_throttle_count++;
  2201. break;
  2202. }
  2203. }
  2204. /* Realloc an existing string to fit an extra string s, appending s to it. */
  2205. void *realloc_strcat(char *ptr, char *s)
  2206. {
  2207. size_t old = strlen(ptr), len = strlen(s);
  2208. char *ret;
  2209. if (!len)
  2210. return ptr;
  2211. len += old + 1;
  2212. align_len(&len);
  2213. ret = malloc(len);
  2214. if (unlikely(!ret))
  2215. quithere(1, "Failed to malloc");
  2216. sprintf(ret, "%s%s", ptr, s);
  2217. free(ptr);
  2218. return ret;
  2219. }
  2220. static
  2221. bool sanechars[] = {
  2222. false, false, false, false, false, false, false, false,
  2223. false, false, false, false, false, false, false, false,
  2224. false, false, false, false, false, false, false, false,
  2225. false, false, false, false, false, false, false, false,
  2226. false, false, false, false, false, false, false, false,
  2227. false, false, false, false, false, false, false, false,
  2228. true , true , true , true , true , true , true , true ,
  2229. true , true , false, false, false, false, false, false,
  2230. false, true , true , true , true , true , true , true ,
  2231. true , true , true , true , true , true , true , true ,
  2232. true , true , true , true , true , true , true , true ,
  2233. true , true , true , false, false, false, false, false,
  2234. false, true , true , true , true , true , true , true ,
  2235. true , true , true , true , true , true , true , true ,
  2236. true , true , true , true , true , true , true , true ,
  2237. true , true , true , false, false, false, false, false,
  2238. };
  2239. char *sanestr(char *o, char *s)
  2240. {
  2241. char *rv = o;
  2242. bool br = false;
  2243. for ( ; s[0]; ++s)
  2244. {
  2245. if (sanechars[s[0] & 0x7f])
  2246. {
  2247. if (br)
  2248. {
  2249. br = false;
  2250. if (s[0] >= '0' && s[0] <= '9')
  2251. (o++)[0] = '_';
  2252. }
  2253. (o++)[0] = s[0];
  2254. }
  2255. else
  2256. if (o != s && o[-1] >= '0' && o[-1] <= '9')
  2257. br = true;
  2258. }
  2259. o[0] = '\0';
  2260. return rv;
  2261. }
  2262. void RenameThread(const char* name)
  2263. {
  2264. #if defined(PR_SET_NAME)
  2265. // Only the first 15 characters are used (16 - NUL terminator)
  2266. prctl(PR_SET_NAME, name, 0, 0, 0);
  2267. #elif defined(__APPLE__)
  2268. pthread_setname_np(name);
  2269. #elif (defined(__FreeBSD__) || defined(__OpenBSD__))
  2270. pthread_set_name_np(pthread_self(), name);
  2271. #else
  2272. // Prevent warnings for unused parameters...
  2273. (void)name;
  2274. #endif
  2275. }
  2276. static pthread_key_t key_bfgtls;
  2277. struct bfgtls_data {
  2278. char *bfg_strerror_result;
  2279. size_t bfg_strerror_resultsz;
  2280. #ifdef WIN32
  2281. LPSTR bfg_strerror_socketresult;
  2282. #endif
  2283. #ifdef NEED_BFG_LOWL_VCOM
  2284. struct detectone_meta_info_t __detectone_meta_info;
  2285. #endif
  2286. };
  2287. static
  2288. struct bfgtls_data *get_bfgtls()
  2289. {
  2290. struct bfgtls_data *bfgtls = pthread_getspecific(key_bfgtls);
  2291. if (bfgtls)
  2292. return bfgtls;
  2293. void *p;
  2294. bfgtls = malloc(sizeof(*bfgtls));
  2295. if (!bfgtls)
  2296. quithere(1, "malloc bfgtls failed");
  2297. p = malloc(64);
  2298. if (!p)
  2299. quithere(1, "malloc bfg_strerror_result failed");
  2300. *bfgtls = (struct bfgtls_data){
  2301. .bfg_strerror_resultsz = 64,
  2302. .bfg_strerror_result = p,
  2303. };
  2304. if (pthread_setspecific(key_bfgtls, bfgtls))
  2305. quithere(1, "pthread_setspecific failed");
  2306. return bfgtls;
  2307. }
  2308. static
  2309. void bfgtls_free(void * const p)
  2310. {
  2311. struct bfgtls_data * const bfgtls = p;
  2312. free(bfgtls->bfg_strerror_result);
  2313. #ifdef WIN32
  2314. if (bfgtls->bfg_strerror_socketresult)
  2315. LocalFree(bfgtls->bfg_strerror_socketresult);
  2316. #endif
  2317. free(bfgtls);
  2318. }
  2319. #ifdef NEED_BFG_LOWL_VCOM
  2320. struct detectone_meta_info_t *_detectone_meta_info()
  2321. {
  2322. return &get_bfgtls()->__detectone_meta_info;
  2323. }
  2324. #endif
  2325. void bfg_init_threadlocal()
  2326. {
  2327. if (pthread_key_create(&key_bfgtls, bfgtls_free))
  2328. quithere(1, "pthread_key_create failed");
  2329. }
  2330. static
  2331. bool bfg_grow_buffer(char ** const bufp, size_t * const bufszp, size_t minimum)
  2332. {
  2333. if (minimum <= *bufszp)
  2334. return false;
  2335. while (minimum > *bufszp)
  2336. *bufszp = 2;
  2337. *bufp = realloc(*bufp, *bufszp);
  2338. if (unlikely(!*bufp))
  2339. quithere(1, "realloc failed");
  2340. return true;
  2341. }
  2342. static
  2343. const char *bfg_strcpy_growing_buffer(char ** const bufp, size_t * const bufszp, const char *src)
  2344. {
  2345. if (!src)
  2346. return NULL;
  2347. const size_t srcsz = strlen(src) + 1;
  2348. bfg_grow_buffer(bufp, bufszp, srcsz);
  2349. memcpy(*bufp, src, srcsz);
  2350. return *bufp;
  2351. }
  2352. // Guaranteed to always return some string (or quit)
  2353. const char *bfg_strerror(int e, enum bfg_strerror_type type)
  2354. {
  2355. static __maybe_unused pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  2356. struct bfgtls_data *bfgtls = get_bfgtls();
  2357. size_t * const bufszp = &bfgtls->bfg_strerror_resultsz;
  2358. char ** const bufp = &bfgtls->bfg_strerror_result;
  2359. const char *have = NULL;
  2360. switch (type) {
  2361. case BST_LIBUSB:
  2362. // NOTE: Nested preprocessor checks since the latter isn't defined at all without the former
  2363. #ifdef HAVE_LIBUSB
  2364. # if HAVE_DECL_LIBUSB_ERROR_NAME
  2365. // libusb makes no guarantees for thread-safety or persistence
  2366. mutex_lock(&mutex);
  2367. have = bfg_strcpy_growing_buffer(bufp, bufszp, libusb_error_name(e));
  2368. mutex_unlock(&mutex);
  2369. # endif
  2370. #endif
  2371. break;
  2372. case BST_SOCKET:
  2373. case BST_SYSTEM:
  2374. {
  2375. #ifdef WIN32
  2376. // Windows has a different namespace for system and socket errors
  2377. LPSTR *msg = &bfgtls->bfg_strerror_socketresult;
  2378. if (*msg)
  2379. LocalFree(*msg);
  2380. if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, e, 0, (LPSTR)msg, 0, 0))
  2381. {
  2382. LPSTR msgp = *msg;
  2383. size_t n = strlen(msgp);
  2384. while (isCspace(msgp[--n]))
  2385. msgp[n] = '\0';
  2386. return *msg;
  2387. }
  2388. *msg = NULL;
  2389. break;
  2390. #endif
  2391. }
  2392. // Fallthru on non-WIN32
  2393. case BST_ERRNO:
  2394. {
  2395. #ifdef __STRERROR_S_WORKS
  2396. // FIXME: Not sure how to get this on MingW64
  2397. retry:
  2398. if (likely(!strerror_s(*bufp, *bufszp, e)))
  2399. {
  2400. if (bfg_grow_buffer(bufp, bufszp, strlen(*bufp) + 2))
  2401. goto retry;
  2402. return *bufp;
  2403. }
  2404. // TODO: XSI strerror_r
  2405. // TODO: GNU strerror_r
  2406. #else
  2407. mutex_lock(&mutex);
  2408. have = bfg_strcpy_growing_buffer(bufp, bufszp, strerror(e));
  2409. mutex_unlock(&mutex);
  2410. #endif
  2411. }
  2412. }
  2413. if (have)
  2414. return *bufp;
  2415. // Failback: Stringify the number
  2416. static const char fmt[] = "%s error #%d", *typestr;
  2417. switch (type) {
  2418. case BST_ERRNO:
  2419. typestr = "System";
  2420. break;
  2421. case BST_SOCKET:
  2422. typestr = "Socket";
  2423. break;
  2424. case BST_LIBUSB:
  2425. typestr = "libusb";
  2426. break;
  2427. default:
  2428. typestr = "Unexpected";
  2429. }
  2430. int sz = snprintf((char*)bfgtls, 0, fmt, typestr, e) + 1;
  2431. bfg_grow_buffer(bufp, bufszp, sz);
  2432. sprintf(*bufp, fmt, typestr, e);
  2433. return *bufp;
  2434. }
  2435. void notifier_init(notifier_t pipefd)
  2436. {
  2437. #ifdef WIN32
  2438. #define WindowsErrorStr(e) bfg_strerror(e, BST_SOCKET)
  2439. SOCKET listener, connecter, acceptor;
  2440. listener = socket(AF_INET, SOCK_STREAM, 0);
  2441. if (listener == INVALID_SOCKET)
  2442. quit(1, "Failed to create listener socket"IN_FMT_FFL": %s",
  2443. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2444. connecter = socket(AF_INET, SOCK_STREAM, 0);
  2445. if (connecter == INVALID_SOCKET)
  2446. quit(1, "Failed to create connect socket"IN_FMT_FFL": %s",
  2447. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2448. struct sockaddr_in inaddr = {
  2449. .sin_family = AF_INET,
  2450. .sin_addr = {
  2451. .s_addr = htonl(INADDR_LOOPBACK),
  2452. },
  2453. .sin_port = 0,
  2454. };
  2455. {
  2456. static const int reuse = 1;
  2457. setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));
  2458. }
  2459. if (bind(listener, (struct sockaddr*)&inaddr, sizeof(inaddr)) == SOCKET_ERROR)
  2460. quit(1, "Failed to bind listener socket"IN_FMT_FFL": %s",
  2461. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2462. socklen_t inaddr_sz = sizeof(inaddr);
  2463. if (getsockname(listener, (struct sockaddr*)&inaddr, &inaddr_sz) == SOCKET_ERROR)
  2464. quit(1, "Failed to getsockname"IN_FMT_FFL": %s",
  2465. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2466. if (listen(listener, 1) == SOCKET_ERROR)
  2467. quit(1, "Failed to listen"IN_FMT_FFL": %s",
  2468. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2469. inaddr.sin_family = AF_INET;
  2470. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  2471. if (connect(connecter, (struct sockaddr*)&inaddr, inaddr_sz) == SOCKET_ERROR)
  2472. quit(1, "Failed to connect"IN_FMT_FFL": %s",
  2473. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2474. acceptor = accept(listener, NULL, NULL);
  2475. if (acceptor == INVALID_SOCKET)
  2476. quit(1, "Failed to accept"IN_FMT_FFL": %s",
  2477. __FILE__, __func__, __LINE__, WindowsErrorStr(WSAGetLastError()));
  2478. closesocket(listener);
  2479. pipefd[0] = connecter;
  2480. pipefd[1] = acceptor;
  2481. #else
  2482. if (pipe(pipefd))
  2483. quithere(1, "Failed to create pipe");
  2484. #endif
  2485. }
  2486. void notifier_wake(notifier_t fd)
  2487. {
  2488. if (fd[1] == INVSOCK)
  2489. return;
  2490. if (1 !=
  2491. #ifdef WIN32
  2492. send(fd[1], "\0", 1, 0)
  2493. #else
  2494. write(fd[1], "\0", 1)
  2495. #endif
  2496. )
  2497. applog(LOG_WARNING, "Error trying to wake notifier");
  2498. }
  2499. void notifier_read(notifier_t fd)
  2500. {
  2501. char buf[0x10];
  2502. #ifdef WIN32
  2503. IGNORE_RETURN_VALUE(recv(fd[0], buf, sizeof(buf), 0));
  2504. #else
  2505. IGNORE_RETURN_VALUE(read(fd[0], buf, sizeof(buf)));
  2506. #endif
  2507. }
  2508. void notifier_init_invalid(notifier_t fd)
  2509. {
  2510. fd[0] = fd[1] = INVSOCK;
  2511. }
  2512. void notifier_destroy(notifier_t fd)
  2513. {
  2514. #ifdef WIN32
  2515. closesocket(fd[0]);
  2516. closesocket(fd[1]);
  2517. #else
  2518. close(fd[0]);
  2519. close(fd[1]);
  2520. #endif
  2521. fd[0] = fd[1] = INVSOCK;
  2522. }
  2523. void _bytes_alloc_failure(size_t sz)
  2524. {
  2525. quit(1, "bytes_resize failed to allocate %lu bytes", (unsigned long)sz);
  2526. }
  2527. void *cmd_thread(void *cmdp)
  2528. {
  2529. const char *cmd = cmdp;
  2530. applog(LOG_DEBUG, "Executing command: %s", cmd);
  2531. int rc = system(cmd);
  2532. if (rc)
  2533. applog(LOG_WARNING, "Command returned %d exit code: %s", rc, cmd);
  2534. return NULL;
  2535. }
  2536. void run_cmd(const char *cmd)
  2537. {
  2538. if (!cmd)
  2539. return;
  2540. pthread_t pth;
  2541. pthread_create(&pth, NULL, cmd_thread, (void*)cmd);
  2542. }
  2543. uint8_t crc5usb(unsigned char *ptr, uint8_t len)
  2544. {
  2545. uint8_t i, j, k;
  2546. uint8_t crc = 0x1f;
  2547. uint8_t crcin[5] = {1, 1, 1, 1, 1};
  2548. uint8_t crcout[5] = {1, 1, 1, 1, 1};
  2549. uint8_t din = 0;
  2550. j = 0x80;
  2551. k = 0;
  2552. for (i = 0; i < len; i++)
  2553. {
  2554. if (*ptr & j)
  2555. din = 1;
  2556. else
  2557. din = 0;
  2558. crcout[0] = crcin[4] ^ din;
  2559. crcout[1] = crcin[0];
  2560. crcout[2] = crcin[1] ^ crcin[4] ^ din;
  2561. crcout[3] = crcin[2];
  2562. crcout[4] = crcin[3];
  2563. j = j >> 1;
  2564. k++;
  2565. if (k == 8)
  2566. {
  2567. j = 0x80;
  2568. k = 0;
  2569. ptr++;
  2570. }
  2571. memcpy(crcin, crcout, 5);
  2572. }
  2573. crc = 0;
  2574. if(crcin[4])
  2575. crc |= 0x10;
  2576. if(crcin[3])
  2577. crc |= 0x08;
  2578. if(crcin[2])
  2579. crc |= 0x04;
  2580. if(crcin[1])
  2581. crc |= 0x02;
  2582. if(crcin[0])
  2583. crc |= 0x01;
  2584. return crc;
  2585. }
  2586. static uint8_t _crc8ccitt_table[0x100];
  2587. void bfg_init_checksums(void)
  2588. {
  2589. for (int i = 0; i < 0x100; ++i)
  2590. {
  2591. uint8_t crc = i;
  2592. for (int j = 0; j < 8; ++j)
  2593. crc = (crc << 1) ^ ((crc & 0x80) ? 7 : 0);
  2594. _crc8ccitt_table[i] = crc & 0xff;
  2595. }
  2596. }
  2597. uint8_t crc8ccitt(const void * const buf, const size_t buflen)
  2598. {
  2599. const uint8_t *p = buf;
  2600. uint8_t crc = 0xff;
  2601. for (int i = 0; i < buflen; ++i)
  2602. crc = _crc8ccitt_table[crc ^ *p++];
  2603. return crc;
  2604. }