util.c 71 KB

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