util.c 72 KB

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