util.c.bak 73 KB

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