util.c 78 KB

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