api.c 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650
  1. /*
  2. * Copyright 2011-2012 Andrew Smith
  3. * Copyright 2011-2012 Con Kolivas
  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. * Note: the code always includes GPU support even if there are no GPUs
  11. * this simplifies handling multiple other device code being included
  12. * depending on compile options
  13. */
  14. #include "config.h"
  15. #include <assert.h>
  16. #include <stdio.h>
  17. #include <ctype.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <stdbool.h>
  21. #include <stdint.h>
  22. #include <unistd.h>
  23. #include <sys/types.h>
  24. #include "compat.h"
  25. #include "miner.h"
  26. #include "driver-cpu.h" /* for algo_names[], TODO: re-factor dependency */
  27. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_ZTEX) || defined(USE_MODMINER)
  28. #define HAVE_AN_FPGA 1
  29. #endif
  30. #if defined(unix) || defined(__APPLE__)
  31. #include <errno.h>
  32. #include <sys/socket.h>
  33. #include <netinet/in.h>
  34. #include <arpa/inet.h>
  35. #define SOCKETTYPE int
  36. #define SOCKETFAIL(a) ((a) < 0)
  37. #define INVSOCK -1
  38. #define INVINETADDR -1
  39. #define CLOSESOCKET close
  40. #define SOCKERRMSG strerror(errno)
  41. #endif
  42. #ifdef WIN32
  43. #include <ws2tcpip.h>
  44. #include <winsock2.h>
  45. #define SOCKETTYPE SOCKET
  46. #define SOCKETFAIL(a) ((a) == SOCKET_ERROR)
  47. #define INVSOCK INVALID_SOCKET
  48. #define INVINETADDR INADDR_NONE
  49. #define CLOSESOCKET closesocket
  50. static char WSAbuf[1024];
  51. struct WSAERRORS {
  52. int id;
  53. char *code;
  54. } WSAErrors[] = {
  55. { 0, "No error" },
  56. { WSAEINTR, "Interrupted system call" },
  57. { WSAEBADF, "Bad file number" },
  58. { WSAEACCES, "Permission denied" },
  59. { WSAEFAULT, "Bad address" },
  60. { WSAEINVAL, "Invalid argument" },
  61. { WSAEMFILE, "Too many open sockets" },
  62. { WSAEWOULDBLOCK, "Operation would block" },
  63. { WSAEINPROGRESS, "Operation now in progress" },
  64. { WSAEALREADY, "Operation already in progress" },
  65. { WSAENOTSOCK, "Socket operation on non-socket" },
  66. { WSAEDESTADDRREQ, "Destination address required" },
  67. { WSAEMSGSIZE, "Message too long" },
  68. { WSAEPROTOTYPE, "Protocol wrong type for socket" },
  69. { WSAENOPROTOOPT, "Bad protocol option" },
  70. { WSAEPROTONOSUPPORT, "Protocol not supported" },
  71. { WSAESOCKTNOSUPPORT, "Socket type not supported" },
  72. { WSAEOPNOTSUPP, "Operation not supported on socket" },
  73. { WSAEPFNOSUPPORT, "Protocol family not supported" },
  74. { WSAEAFNOSUPPORT, "Address family not supported" },
  75. { WSAEADDRINUSE, "Address already in use" },
  76. { WSAEADDRNOTAVAIL, "Can't assign requested address" },
  77. { WSAENETDOWN, "Network is down" },
  78. { WSAENETUNREACH, "Network is unreachable" },
  79. { WSAENETRESET, "Net connection reset" },
  80. { WSAECONNABORTED, "Software caused connection abort" },
  81. { WSAECONNRESET, "Connection reset by peer" },
  82. { WSAENOBUFS, "No buffer space available" },
  83. { WSAEISCONN, "Socket is already connected" },
  84. { WSAENOTCONN, "Socket is not connected" },
  85. { WSAESHUTDOWN, "Can't send after socket shutdown" },
  86. { WSAETOOMANYREFS, "Too many references, can't splice" },
  87. { WSAETIMEDOUT, "Connection timed out" },
  88. { WSAECONNREFUSED, "Connection refused" },
  89. { WSAELOOP, "Too many levels of symbolic links" },
  90. { WSAENAMETOOLONG, "File name too long" },
  91. { WSAEHOSTDOWN, "Host is down" },
  92. { WSAEHOSTUNREACH, "No route to host" },
  93. { WSAENOTEMPTY, "Directory not empty" },
  94. { WSAEPROCLIM, "Too many processes" },
  95. { WSAEUSERS, "Too many users" },
  96. { WSAEDQUOT, "Disc quota exceeded" },
  97. { WSAESTALE, "Stale NFS file handle" },
  98. { WSAEREMOTE, "Too many levels of remote in path" },
  99. { WSASYSNOTREADY, "Network system is unavailable" },
  100. { WSAVERNOTSUPPORTED, "Winsock version out of range" },
  101. { WSANOTINITIALISED, "WSAStartup not yet called" },
  102. { WSAEDISCON, "Graceful shutdown in progress" },
  103. { WSAHOST_NOT_FOUND, "Host not found" },
  104. { WSANO_DATA, "No host data of that type was found" },
  105. { -1, "Unknown error code" }
  106. };
  107. static char *WSAErrorMsg()
  108. {
  109. int i;
  110. int id = WSAGetLastError();
  111. /* Assume none of them are actually -1 */
  112. for (i = 0; WSAErrors[i].id != -1; i++)
  113. if (WSAErrors[i].id == id)
  114. break;
  115. sprintf(WSAbuf, "Socket Error: (%d) %s", id, WSAErrors[i].code);
  116. return &(WSAbuf[0]);
  117. }
  118. #define SOCKERRMSG WSAErrorMsg()
  119. #ifndef SHUT_RDWR
  120. #define SHUT_RDWR SD_BOTH
  121. #endif
  122. #ifndef in_addr_t
  123. #define in_addr_t uint32_t
  124. #endif
  125. #endif
  126. // Big enough for largest API request
  127. // though a PC with 100s of PGAs/CPUs may exceed the size ...
  128. // Current code assumes it can socket send this size also
  129. #define MYBUFSIZ 65432 // TODO: intercept before it's exceeded
  130. // BUFSIZ varies on Windows and Linux
  131. #define TMPBUFSIZ 8192
  132. // Number of requests to queue - normally would be small
  133. // However lots of PGA's may mean more
  134. #define QUEUE 100
  135. static char *io_buffer = NULL;
  136. static char *msg_buffer = NULL;
  137. static SOCKETTYPE sock = INVSOCK;
  138. static const char *UNAVAILABLE = " - API will not be available";
  139. static const char *BLANK = "";
  140. static const char *COMMA = ",";
  141. static const char SEPARATOR = '|';
  142. #define SEPSTR "|"
  143. static const char GPUSEP = ',';
  144. static const char *APIVERSION = "1.12";
  145. static const char *DEAD = "Dead";
  146. static const char *SICK = "Sick";
  147. static const char *NOSTART = "NoStart";
  148. static const char *DISABLED = "Disabled";
  149. static const char *ALIVE = "Alive";
  150. static const char *REJECTING = "Rejecting";
  151. static const char *UNKNOWN = "Unknown";
  152. #define _DYNAMIC "D"
  153. static const char *DYNAMIC = _DYNAMIC;
  154. static const char *YES = "Y";
  155. static const char *NO = "N";
  156. static const char *DEVICECODE = ""
  157. #ifdef HAVE_OPENCL
  158. "GPU "
  159. #endif
  160. #ifdef USE_BITFORCE
  161. "BFL "
  162. #endif
  163. #ifdef USE_ICARUS
  164. "ICA "
  165. #endif
  166. #ifdef USE_ZTEX
  167. "ZTX "
  168. #endif
  169. #ifdef USE_MODMINER
  170. "MMQ "
  171. #endif
  172. #ifdef WANT_CPUMINE
  173. "CPU "
  174. #endif
  175. "";
  176. static const char *OSINFO =
  177. #if defined(__linux)
  178. "Linux";
  179. #else
  180. #if defined(__APPLE__)
  181. "Apple";
  182. #else
  183. #if defined (WIN32)
  184. "Windows";
  185. #else
  186. #if defined(unix)
  187. "Unix";
  188. #else
  189. "Unknown";
  190. #endif
  191. #endif
  192. #endif
  193. #endif
  194. #define _DEVS "DEVS"
  195. #define _POOLS "POOLS"
  196. #define _SUMMARY "SUMMARY"
  197. #define _STATUS "STATUS"
  198. #define _VERSION "VERSION"
  199. #define _MINECON "CONFIG"
  200. #define _GPU "GPU"
  201. #ifdef HAVE_AN_FPGA
  202. #define _PGA "PGA"
  203. #endif
  204. #ifdef WANT_CPUMINE
  205. #define _CPU "CPU"
  206. #endif
  207. #define _GPUS "GPUS"
  208. #define _PGAS "PGAS"
  209. #define _CPUS "CPUS"
  210. #define _NOTIFY "NOTIFY"
  211. #define _DEVDETAILS "DEVDETAILS"
  212. #define _BYE "BYE"
  213. #define _RESTART "RESTART"
  214. #define _MINESTATS "STATS"
  215. static const char ISJSON = '{';
  216. #define JSON0 "{"
  217. #define JSON1 "\""
  218. #define JSON2 "\":["
  219. #define JSON3 "]"
  220. #define JSON4 ",\"id\":1}"
  221. #define JSON_START JSON0
  222. #define JSON_DEVS JSON1 _DEVS JSON2
  223. #define JSON_POOLS JSON1 _POOLS JSON2
  224. #define JSON_SUMMARY JSON1 _SUMMARY JSON2
  225. #define JSON_STATUS JSON1 _STATUS JSON2
  226. #define JSON_VERSION JSON1 _VERSION JSON2
  227. #define JSON_MINECON JSON1 _MINECON JSON2
  228. #define JSON_GPU JSON1 _GPU JSON2
  229. #ifdef HAVE_AN_FPGA
  230. #define JSON_PGA JSON1 _PGA JSON2
  231. #endif
  232. #ifdef WANT_CPUMINE
  233. #define JSON_CPU JSON1 _CPU JSON2
  234. #endif
  235. #define JSON_GPUS JSON1 _GPUS JSON2
  236. #define JSON_PGAS JSON1 _PGAS JSON2
  237. #define JSON_CPUS JSON1 _CPUS JSON2
  238. #define JSON_NOTIFY JSON1 _NOTIFY JSON2
  239. #define JSON_DEVDETAILS JSON1 _DEVDETAILS JSON2
  240. #define JSON_BYE JSON1 _BYE JSON1
  241. #define JSON_RESTART JSON1 _RESTART JSON1
  242. #define JSON_CLOSE JSON3
  243. #define JSON_MINESTATS JSON1 _MINESTATS JSON2
  244. #define JSON_END JSON4
  245. static const char *JSON_COMMAND = "command";
  246. static const char *JSON_PARAMETER = "parameter";
  247. #define MSG_INVGPU 1
  248. #define MSG_ALRENA 2
  249. #define MSG_ALRDIS 3
  250. #define MSG_GPUMRE 4
  251. #define MSG_GPUREN 5
  252. #define MSG_GPUNON 6
  253. #define MSG_POOL 7
  254. #define MSG_NOPOOL 8
  255. #define MSG_DEVS 9
  256. #define MSG_NODEVS 10
  257. #define MSG_SUMM 11
  258. #define MSG_GPUDIS 12
  259. #define MSG_GPUREI 13
  260. #define MSG_INVCMD 14
  261. #define MSG_MISID 15
  262. #define MSG_GPUDEV 17
  263. #ifdef WANT_CPUMINE
  264. #define MSG_CPUNON 16
  265. #define MSG_CPUDEV 18
  266. #define MSG_INVCPU 19
  267. #endif
  268. #define MSG_NUMGPU 20
  269. #define MSG_NUMCPU 21
  270. #define MSG_VERSION 22
  271. #define MSG_INVJSON 23
  272. #define MSG_MISCMD 24
  273. #define MSG_MISPID 25
  274. #define MSG_INVPID 26
  275. #define MSG_SWITCHP 27
  276. #define MSG_MISVAL 28
  277. #define MSG_NOADL 29
  278. #define MSG_NOGPUADL 30
  279. #define MSG_INVINT 31
  280. #define MSG_GPUINT 32
  281. #define MSG_MINECON 33
  282. #define MSG_GPUMERR 34
  283. #define MSG_GPUMEM 35
  284. #define MSG_GPUEERR 36
  285. #define MSG_GPUENG 37
  286. #define MSG_GPUVERR 38
  287. #define MSG_GPUVDDC 39
  288. #define MSG_GPUFERR 40
  289. #define MSG_GPUFAN 41
  290. #define MSG_MISFN 42
  291. #define MSG_BADFN 43
  292. #define MSG_SAVED 44
  293. #define MSG_ACCDENY 45
  294. #define MSG_ACCOK 46
  295. #define MSG_ENAPOOL 47
  296. #define MSG_DISPOOL 48
  297. #define MSG_ALRENAP 49
  298. #define MSG_ALRDISP 50
  299. #define MSG_DISLASTP 51
  300. #define MSG_MISPDP 52
  301. #define MSG_INVPDP 53
  302. #define MSG_TOOMANYP 54
  303. #define MSG_ADDPOOL 55
  304. #ifdef HAVE_AN_FPGA
  305. #define MSG_PGANON 56
  306. #define MSG_PGADEV 57
  307. #define MSG_INVPGA 58
  308. #endif
  309. #define MSG_NUMPGA 59
  310. #define MSG_NOTIFY 60
  311. #ifdef HAVE_AN_FPGA
  312. #define MSG_PGALRENA 61
  313. #define MSG_PGALRDIS 62
  314. #define MSG_PGAENA 63
  315. #define MSG_PGADIS 64
  316. #define MSG_PGAUNW 65
  317. #endif
  318. #define MSG_REMLASTP 66
  319. #define MSG_ACTPOOL 67
  320. #define MSG_REMPOOL 68
  321. #define MSG_DEVDETAILS 69
  322. #define MSG_MINESTATS 70
  323. enum code_severity {
  324. SEVERITY_ERR,
  325. SEVERITY_WARN,
  326. SEVERITY_INFO,
  327. SEVERITY_SUCC,
  328. SEVERITY_FAIL
  329. };
  330. enum code_parameters {
  331. PARAM_GPU,
  332. PARAM_PGA,
  333. PARAM_CPU,
  334. PARAM_GPUMAX,
  335. PARAM_PGAMAX,
  336. PARAM_CPUMAX,
  337. PARAM_PMAX,
  338. PARAM_POOLMAX,
  339. // Single generic case: have the code resolve it - see below
  340. PARAM_DMAX,
  341. PARAM_CMD,
  342. PARAM_POOL,
  343. PARAM_STR,
  344. PARAM_BOTH,
  345. PARAM_NONE
  346. };
  347. struct CODES {
  348. const enum code_severity severity;
  349. const int code;
  350. const enum code_parameters params;
  351. const char *description;
  352. } codes[] = {
  353. #ifdef HAVE_OPENCL
  354. { SEVERITY_ERR, MSG_INVGPU, PARAM_GPUMAX, "Invalid GPU id %d - range is 0 - %d" },
  355. { SEVERITY_INFO, MSG_ALRENA, PARAM_GPU, "GPU %d already enabled" },
  356. { SEVERITY_INFO, MSG_ALRDIS, PARAM_GPU, "GPU %d already disabled" },
  357. { SEVERITY_WARN, MSG_GPUMRE, PARAM_GPU, "GPU %d must be restarted first" },
  358. { SEVERITY_INFO, MSG_GPUREN, PARAM_GPU, "GPU %d sent enable message" },
  359. #endif
  360. { SEVERITY_ERR, MSG_GPUNON, PARAM_NONE, "No GPUs" },
  361. { SEVERITY_SUCC, MSG_POOL, PARAM_PMAX, "%d Pool(s)" },
  362. { SEVERITY_ERR, MSG_NOPOOL, PARAM_NONE, "No pools" },
  363. { SEVERITY_SUCC, MSG_DEVS, PARAM_DMAX,
  364. #ifdef HAVE_OPENCL
  365. "%d GPU(s)"
  366. #endif
  367. #if defined(HAVE_AN_FPGA) && defined(HAVE_OPENCL)
  368. " - "
  369. #endif
  370. #ifdef HAVE_AN_FPGA
  371. "%d PGA(s)"
  372. #endif
  373. #if defined(WANT_CPUMINE) && (defined(HAVE_OPENCL) || defined(HAVE_AN_FPGA))
  374. " - "
  375. #endif
  376. #ifdef WANT_CPUMINE
  377. "%d CPU(s)"
  378. #endif
  379. },
  380. { SEVERITY_ERR, MSG_NODEVS, PARAM_NONE, "No GPUs"
  381. #ifdef HAVE_AN_FPGA
  382. "/PGAs"
  383. #endif
  384. #ifdef WANT_CPUMINE
  385. "/CPUs"
  386. #endif
  387. },
  388. { SEVERITY_SUCC, MSG_SUMM, PARAM_NONE, "Summary" },
  389. #ifdef HAVE_OPENCL
  390. { SEVERITY_INFO, MSG_GPUDIS, PARAM_GPU, "GPU %d set disable flag" },
  391. { SEVERITY_INFO, MSG_GPUREI, PARAM_GPU, "GPU %d restart attempted" },
  392. #endif
  393. { SEVERITY_ERR, MSG_INVCMD, PARAM_NONE, "Invalid command" },
  394. { SEVERITY_ERR, MSG_MISID, PARAM_NONE, "Missing device id parameter" },
  395. #ifdef HAVE_OPENCL
  396. { SEVERITY_SUCC, MSG_GPUDEV, PARAM_GPU, "GPU%d" },
  397. #endif
  398. #ifdef HAVE_AN_FPGA
  399. { SEVERITY_ERR, MSG_PGANON, PARAM_NONE, "No PGAs" },
  400. { SEVERITY_SUCC, MSG_PGADEV, PARAM_PGA, "PGA%d" },
  401. { SEVERITY_ERR, MSG_INVPGA, PARAM_PGAMAX, "Invalid PGA id %d - range is 0 - %d" },
  402. { SEVERITY_INFO, MSG_PGALRENA,PARAM_PGA, "PGA %d already enabled" },
  403. { SEVERITY_INFO, MSG_PGALRDIS,PARAM_PGA, "PGA %d already disabled" },
  404. { SEVERITY_INFO, MSG_PGAENA, PARAM_PGA, "PGA %d sent enable message" },
  405. { SEVERITY_INFO, MSG_PGADIS, PARAM_PGA, "PGA %d set disable flag" },
  406. { SEVERITY_ERR, MSG_PGAUNW, PARAM_PGA, "PGA %d is not flagged WELL, cannot enable" },
  407. #endif
  408. #ifdef WANT_CPUMINE
  409. { SEVERITY_ERR, MSG_CPUNON, PARAM_NONE, "No CPUs" },
  410. { SEVERITY_SUCC, MSG_CPUDEV, PARAM_CPU, "CPU%d" },
  411. { SEVERITY_ERR, MSG_INVCPU, PARAM_CPUMAX, "Invalid CPU id %d - range is 0 - %d" },
  412. #endif
  413. { SEVERITY_SUCC, MSG_NUMGPU, PARAM_NONE, "GPU count" },
  414. { SEVERITY_SUCC, MSG_NUMPGA, PARAM_NONE, "PGA count" },
  415. { SEVERITY_SUCC, MSG_NUMCPU, PARAM_NONE, "CPU count" },
  416. { SEVERITY_SUCC, MSG_VERSION, PARAM_NONE, "BFGMiner versions" },
  417. { SEVERITY_ERR, MSG_INVJSON, PARAM_NONE, "Invalid JSON" },
  418. { SEVERITY_ERR, MSG_MISCMD, PARAM_CMD, "Missing JSON '%s'" },
  419. { SEVERITY_ERR, MSG_MISPID, PARAM_NONE, "Missing pool id parameter" },
  420. { SEVERITY_ERR, MSG_INVPID, PARAM_POOLMAX, "Invalid pool id %d - range is 0 - %d" },
  421. { SEVERITY_SUCC, MSG_SWITCHP, PARAM_POOL, "Switching to pool %d:'%s'" },
  422. { SEVERITY_ERR, MSG_MISVAL, PARAM_NONE, "Missing comma after GPU number" },
  423. { SEVERITY_ERR, MSG_NOADL, PARAM_NONE, "ADL is not available" },
  424. { SEVERITY_ERR, MSG_NOGPUADL,PARAM_GPU, "GPU %d does not have ADL" },
  425. { SEVERITY_ERR, MSG_INVINT, PARAM_STR, "Invalid intensity (%s) - must be '" _DYNAMIC "' or range " _MIN_INTENSITY_STR " - " _MAX_INTENSITY_STR },
  426. { SEVERITY_INFO, MSG_GPUINT, PARAM_BOTH, "GPU %d set new intensity to %s" },
  427. { SEVERITY_SUCC, MSG_MINECON, PARAM_NONE, "BFGMiner config" },
  428. #ifdef HAVE_OPENCL
  429. { SEVERITY_ERR, MSG_GPUMERR, PARAM_BOTH, "Setting GPU %d memoryclock to (%s) reported failure" },
  430. { SEVERITY_SUCC, MSG_GPUMEM, PARAM_BOTH, "Setting GPU %d memoryclock to (%s) reported success" },
  431. { SEVERITY_ERR, MSG_GPUEERR, PARAM_BOTH, "Setting GPU %d clock to (%s) reported failure" },
  432. { SEVERITY_SUCC, MSG_GPUENG, PARAM_BOTH, "Setting GPU %d clock to (%s) reported success" },
  433. { SEVERITY_ERR, MSG_GPUVERR, PARAM_BOTH, "Setting GPU %d vddc to (%s) reported failure" },
  434. { SEVERITY_SUCC, MSG_GPUVDDC, PARAM_BOTH, "Setting GPU %d vddc to (%s) reported success" },
  435. { SEVERITY_ERR, MSG_GPUFERR, PARAM_BOTH, "Setting GPU %d fan to (%s) reported failure" },
  436. { SEVERITY_SUCC, MSG_GPUFAN, PARAM_BOTH, "Setting GPU %d fan to (%s) reported success" },
  437. #endif
  438. { SEVERITY_ERR, MSG_MISFN, PARAM_NONE, "Missing save filename parameter" },
  439. { SEVERITY_ERR, MSG_BADFN, PARAM_STR, "Can't open or create save file '%s'" },
  440. { SEVERITY_SUCC, MSG_SAVED, PARAM_STR, "Configuration saved to file '%s'" },
  441. { SEVERITY_ERR, MSG_ACCDENY, PARAM_STR, "Access denied to '%s' command" },
  442. { SEVERITY_SUCC, MSG_ACCOK, PARAM_NONE, "Privileged access OK" },
  443. { SEVERITY_SUCC, MSG_ENAPOOL, PARAM_POOL, "Enabling pool %d:'%s'" },
  444. { SEVERITY_SUCC, MSG_DISPOOL, PARAM_POOL, "Disabling pool %d:'%s'" },
  445. { SEVERITY_INFO, MSG_ALRENAP, PARAM_POOL, "Pool %d:'%s' already enabled" },
  446. { SEVERITY_INFO, MSG_ALRDISP, PARAM_POOL, "Pool %d:'%s' already disabled" },
  447. { SEVERITY_ERR, MSG_DISLASTP,PARAM_POOL, "Cannot disable last active pool %d:'%s'" },
  448. { SEVERITY_ERR, MSG_MISPDP, PARAM_NONE, "Missing addpool details" },
  449. { SEVERITY_ERR, MSG_INVPDP, PARAM_STR, "Invalid addpool details '%s'" },
  450. { SEVERITY_ERR, MSG_TOOMANYP,PARAM_NONE, "Reached maximum number of pools (%d)" },
  451. { SEVERITY_SUCC, MSG_ADDPOOL, PARAM_STR, "Added pool '%s'" },
  452. { SEVERITY_ERR, MSG_REMLASTP,PARAM_POOL, "Cannot remove last pool %d:'%s'" },
  453. { SEVERITY_ERR, MSG_ACTPOOL, PARAM_POOL, "Cannot remove active pool %d:'%s'" },
  454. { SEVERITY_SUCC, MSG_REMPOOL, PARAM_BOTH, "Removed pool %d:'%s'" },
  455. { SEVERITY_SUCC, MSG_NOTIFY, PARAM_NONE, "Notify" },
  456. { SEVERITY_SUCC, MSG_DEVDETAILS,PARAM_NONE, "Device Details" },
  457. { SEVERITY_SUCC, MSG_MINESTATS,PARAM_NONE, "CGMiner stats" },
  458. { SEVERITY_FAIL, 0, 0, NULL }
  459. };
  460. static int my_thr_id = 0;
  461. static bool bye;
  462. static bool ping = true;
  463. // Used to control quit restart access to shutdown variables
  464. static pthread_mutex_t quit_restart_lock;
  465. static bool do_a_quit;
  466. static bool do_a_restart;
  467. static time_t when = 0; // when the request occurred
  468. struct IP4ACCESS {
  469. in_addr_t ip;
  470. in_addr_t mask;
  471. bool writemode;
  472. };
  473. static struct IP4ACCESS *ipaccess = NULL;
  474. static int ips = 0;
  475. #ifdef USE_BITFORCE
  476. extern struct device_api bitforce_api;
  477. #endif
  478. #ifdef USE_ICARUS
  479. extern struct device_api icarus_api;
  480. #endif
  481. #ifdef USE_ZTEX
  482. extern struct device_api ztex_api;
  483. #endif
  484. #ifdef USE_MODMINER
  485. extern struct device_api modminer_api;
  486. #endif
  487. // This is only called when expected to be needed (rarely)
  488. // i.e. strings outside of the codes control (input from the user)
  489. static char *escape_string(char *str, bool isjson)
  490. {
  491. char *buf, *ptr;
  492. int count;
  493. count = 0;
  494. for (ptr = str; *ptr; ptr++) {
  495. switch (*ptr) {
  496. case ',':
  497. case '|':
  498. case '=':
  499. if (!isjson)
  500. count++;
  501. break;
  502. case '"':
  503. if (isjson)
  504. count++;
  505. break;
  506. case '\\':
  507. count++;
  508. break;
  509. }
  510. }
  511. if (count == 0)
  512. return str;
  513. buf = malloc(strlen(str) + count + 1);
  514. if (unlikely(!buf))
  515. quit(1, "Failed to malloc escape buf");
  516. ptr = buf;
  517. while (*str)
  518. switch (*str) {
  519. case ',':
  520. case '|':
  521. case '=':
  522. if (!isjson)
  523. *(ptr++) = '\\';
  524. *(ptr++) = *(str++);
  525. break;
  526. case '"':
  527. if (isjson)
  528. *(ptr++) = '\\';
  529. *(ptr++) = *(str++);
  530. break;
  531. case '\\':
  532. *(ptr++) = '\\';
  533. *(ptr++) = *(str++);
  534. break;
  535. default:
  536. *(ptr++) = *(str++);
  537. break;
  538. }
  539. *ptr = '\0';
  540. return buf;
  541. }
  542. #ifdef HAVE_AN_FPGA
  543. static int numpgas()
  544. {
  545. int count = 0;
  546. int i;
  547. for (i = 0; i < total_devices; i++) {
  548. #ifdef USE_BITFORCE
  549. if (devices[i]->api == &bitforce_api)
  550. count++;
  551. #endif
  552. #ifdef USE_ICARUS
  553. if (devices[i]->api == &icarus_api)
  554. count++;
  555. #endif
  556. #ifdef USE_ZTEX
  557. if (devices[i]->api == &ztex_api)
  558. count++;
  559. #endif
  560. #ifdef USE_MODMINER
  561. if (devices[i]->api == &modminer_api)
  562. count++;
  563. #endif
  564. }
  565. return count;
  566. }
  567. static int pgadevice(int pgaid)
  568. {
  569. int count = 0;
  570. int i;
  571. for (i = 0; i < total_devices; i++) {
  572. #ifdef USE_BITFORCE
  573. if (devices[i]->api == &bitforce_api)
  574. count++;
  575. #endif
  576. #ifdef USE_ICARUS
  577. if (devices[i]->api == &icarus_api)
  578. count++;
  579. #endif
  580. #ifdef USE_ZTEX
  581. if (devices[i]->api == &ztex_api)
  582. count++;
  583. #endif
  584. #ifdef USE_MODMINER
  585. if (devices[i]->api == &modminer_api)
  586. count++;
  587. #endif
  588. if (count == (pgaid + 1))
  589. return i;
  590. }
  591. return -1;
  592. }
  593. #endif
  594. // All replies (except BYE and RESTART) start with a message
  595. // thus for JSON, message() inserts JSON_START at the front
  596. // and send_result() adds JSON_END at the end
  597. static char *message(int messageid, int paramid, char *param2, bool isjson)
  598. {
  599. char severity;
  600. char *ptr;
  601. #ifdef HAVE_AN_FPGA
  602. int pga;
  603. #endif
  604. #ifdef WANT_CPUMINE
  605. int cpu;
  606. #endif
  607. int i;
  608. for (i = 0; codes[i].severity != SEVERITY_FAIL; i++) {
  609. if (codes[i].code == messageid) {
  610. switch (codes[i].severity) {
  611. case SEVERITY_WARN:
  612. severity = 'W';
  613. break;
  614. case SEVERITY_INFO:
  615. severity = 'I';
  616. break;
  617. case SEVERITY_SUCC:
  618. severity = 'S';
  619. break;
  620. case SEVERITY_ERR:
  621. default:
  622. severity = 'E';
  623. break;
  624. }
  625. sprintf(msg_buffer, isjson
  626. ? JSON_START JSON_STATUS "{\"" _STATUS "\":\"%c\",\"When\":%lu,\"Code\":%d,\"Msg\":\""
  627. : _STATUS "=%c,When=%lu,Code=%d,Msg=",
  628. severity, (unsigned long)when, messageid);
  629. ptr = msg_buffer + strlen(msg_buffer);
  630. switch(codes[i].params) {
  631. case PARAM_GPU:
  632. case PARAM_PGA:
  633. case PARAM_CPU:
  634. sprintf(ptr, codes[i].description, paramid);
  635. break;
  636. case PARAM_POOL:
  637. sprintf(ptr, codes[i].description, paramid, pools[paramid]->rpc_url);
  638. break;
  639. #ifdef HAVE_OPENCL
  640. case PARAM_GPUMAX:
  641. sprintf(ptr, codes[i].description, paramid, nDevs - 1);
  642. break;
  643. #endif
  644. #ifdef HAVE_AN_FPGA
  645. case PARAM_PGAMAX:
  646. pga = numpgas();
  647. sprintf(ptr, codes[i].description, paramid, pga - 1);
  648. break;
  649. #endif
  650. #ifdef WANT_CPUMINE
  651. case PARAM_CPUMAX:
  652. if (opt_n_threads > 0)
  653. cpu = num_processors;
  654. else
  655. cpu = 0;
  656. sprintf(ptr, codes[i].description, paramid, cpu - 1);
  657. break;
  658. #endif
  659. case PARAM_PMAX:
  660. sprintf(ptr, codes[i].description, total_pools);
  661. break;
  662. case PARAM_POOLMAX:
  663. sprintf(ptr, codes[i].description, paramid, total_pools - 1);
  664. break;
  665. case PARAM_DMAX:
  666. #ifdef HAVE_AN_FPGA
  667. pga = numpgas();
  668. #endif
  669. #ifdef WANT_CPUMINE
  670. if (opt_n_threads > 0)
  671. cpu = num_processors;
  672. else
  673. cpu = 0;
  674. #endif
  675. sprintf(ptr, codes[i].description
  676. #ifdef HAVE_OPENCL
  677. , nDevs
  678. #endif
  679. #ifdef HAVE_AN_FPGA
  680. , pga
  681. #endif
  682. #ifdef WANT_CPUMINE
  683. , cpu
  684. #endif
  685. );
  686. break;
  687. case PARAM_CMD:
  688. sprintf(ptr, codes[i].description, JSON_COMMAND);
  689. break;
  690. case PARAM_STR:
  691. sprintf(ptr, codes[i].description, param2);
  692. break;
  693. case PARAM_BOTH:
  694. sprintf(ptr, codes[i].description, paramid, param2);
  695. break;
  696. case PARAM_NONE:
  697. default:
  698. strcpy(ptr, codes[i].description);
  699. }
  700. ptr = msg_buffer + strlen(msg_buffer);
  701. sprintf(ptr, isjson
  702. ? "\",\"Description\":\"%s\"}" JSON_CLOSE
  703. : ",Description=%s" SEPSTR,
  704. opt_api_description);
  705. return msg_buffer;
  706. }
  707. }
  708. sprintf(msg_buffer, isjson
  709. ? JSON_START JSON_STATUS "{\"" _STATUS "\":\"F\",\"When\":%lu,\"Code\":-1,\"Msg\":\"%d\",\"Description\":\"%s\"}" JSON_CLOSE
  710. : _STATUS "=F,When=%lu,Code=-1,Msg=%d,Description=%s" SEPSTR,
  711. (unsigned long)when, messageid, opt_api_description);
  712. return msg_buffer;
  713. }
  714. static void apiversion(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  715. {
  716. sprintf(io_buffer, isjson
  717. ? "%s," JSON_VERSION "{\"CGMiner\":\"%s\",\"API\":\"%s\"}" JSON_CLOSE
  718. : "%s" _VERSION ",CGMiner=%s,API=%s" SEPSTR,
  719. message(MSG_VERSION, 0, NULL, isjson),
  720. VERSION, APIVERSION);
  721. }
  722. static void minerconfig(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  723. {
  724. char buf[TMPBUFSIZ];
  725. int gpucount = 0;
  726. int pgacount = 0;
  727. int cpucount = 0;
  728. char *adlinuse = (char *)NO;
  729. #ifdef HAVE_ADL
  730. const char *adl = YES;
  731. int i;
  732. for (i = 0; i < nDevs; i++) {
  733. if (gpus[i].has_adl) {
  734. adlinuse = (char *)YES;
  735. break;
  736. }
  737. }
  738. #else
  739. const char *adl = NO;
  740. #endif
  741. #ifdef HAVE_OPENCL
  742. gpucount = nDevs;
  743. #endif
  744. #ifdef HAVE_AN_FPGA
  745. pgacount = numpgas();
  746. #endif
  747. #ifdef WANT_CPUMINE
  748. cpucount = opt_n_threads > 0 ? num_processors : 0;
  749. #endif
  750. strcpy(io_buffer, message(MSG_MINECON, 0, NULL, isjson));
  751. sprintf(buf, isjson
  752. ? "," JSON_MINECON "{\"GPU Count\":%d,\"PGA Count\":%d,\"CPU Count\":%d,\"Pool Count\":%d,\"ADL\":\"%s\",\"ADL in use\":\"%s\",\"Strategy\":\"%s\",\"Log Interval\":%d,\"Device Code\":\"%s\",\"OS\":\"%s\"}" JSON_CLOSE
  753. : _MINECON ",GPU Count=%d,PGA Count=%d,CPU Count=%d,Pool Count=%d,ADL=%s,ADL in use=%s,Strategy=%s,Log Interval=%d,Device Code=%s,OS=%s" SEPSTR,
  754. gpucount, pgacount, cpucount, total_pools, adl, adlinuse,
  755. strategies[pool_strategy].s, opt_log_interval, DEVICECODE, OSINFO);
  756. strcat(io_buffer, buf);
  757. }
  758. static const char*
  759. bool2str(bool b)
  760. {
  761. return b ? YES : NO;
  762. }
  763. static const char*
  764. status2str(enum alive status)
  765. {
  766. switch (status) {
  767. case LIFE_WELL:
  768. return ALIVE;
  769. case LIFE_SICK:
  770. return SICK;
  771. case LIFE_DEAD:
  772. return DEAD;
  773. case LIFE_NOSTART:
  774. return NOSTART;
  775. default:
  776. return UNKNOWN;
  777. }
  778. }
  779. #ifdef JSON_ENCODE_ANY
  780. # define json_dumps_val(value, flags) json_dumps(value, (flags) | JSON_ENCODE_ANY)
  781. #else
  782. static char*
  783. json_dumps_val(json_t*root, unsigned long flags)
  784. {
  785. json_t *json;
  786. char *s, *d;
  787. size_t l;
  788. json = json_array();
  789. json_array_append(json, root);
  790. s = json_dumps(json, flags);
  791. json_decref(json);
  792. if (!s)
  793. return s;
  794. assert(s[0] == '[');
  795. d = strdup(&s[1]);
  796. free(s);
  797. l = strlen(d);
  798. assert(l);
  799. --l;
  800. assert(d[l] == ']');
  801. d[l] = '\0';
  802. return d;
  803. }
  804. #endif
  805. static void
  806. append_kv(char *buf, json_t*info, bool isjson)
  807. {
  808. json_t *value;
  809. const char *key, *tmpl = isjson ? ",\"%s\":%s" : ",%s=%s";
  810. char *vdump;
  811. void *it;
  812. for (it = json_object_iter(info); it; it = json_object_iter_next(info, it)) {
  813. key = json_object_iter_key(it);
  814. value = json_object_iter_value(it);
  815. if (isjson || !json_is_string(value))
  816. vdump = json_dumps_val(value, JSON_COMPACT);
  817. else
  818. vdump = strdup(json_string_value(value));
  819. tailsprintf(buf, tmpl, key, vdump);
  820. free(vdump);
  821. }
  822. }
  823. static void
  824. devdetail_an(char *buf, struct cgpu_info *cgpu, bool isjson)
  825. {
  826. tailsprintf(buf, isjson
  827. ? "{\"%s\":%d,Driver=%s"
  828. : "%s=%d,Driver=%s",
  829. cgpu->api->name, cgpu->device_id,
  830. cgpu->api->dname
  831. );
  832. if (cgpu->kname)
  833. tailsprintf(buf, isjson ? ",\"Kernel\":\"%s\"" : ",Kernel=%s", cgpu->kname);
  834. if (cgpu->name)
  835. tailsprintf(buf, isjson ? ",\"Model\":\"%s\"" : ",Model=%s", cgpu->name);
  836. if (cgpu->device_path)
  837. tailsprintf(buf, isjson ? ",\"Device Path\":\"%s\"" : ",Device Path=%s", cgpu->device_path);
  838. if (cgpu->api->get_extra_device_detail) {
  839. json_t *info = cgpu->api->get_extra_device_detail(cgpu);
  840. append_kv(buf, info, isjson);
  841. json_decref(info);
  842. }
  843. tailsprintf(buf, "%c", isjson ? '}' : SEPARATOR);
  844. }
  845. static void devstatus_an(char *buf, struct cgpu_info *cgpu, bool isjson)
  846. {
  847. tailsprintf(buf, isjson
  848. ? "{\"%s\":%d,\"Enabled\":\"%s\",\"Status\":\"%s\",\"Temperature\":%.2f,\"MHS av\":%.2f,\"MHS %ds\":%.2f,\"Accepted\":%d,\"Rejected\":%d,\"Hardware Errors\":%d,\"Utility\":%.2f,\"Last Share Pool\":%d,\"Last Share Time\":%lu,\"Total MH\":%.4f"
  849. : "%s=%d,Enabled=%s,Status=%s,Temperature=%.2f,MHS av=%.2f,MHS %ds=%.2f,Accepted=%d,Rejected=%d,Hardware Errors=%d,Utility=%.2f,Last Share Pool=%d,Last Share Time=%lu,Total MH=%.4f",
  850. cgpu->api->name, cgpu->device_id,
  851. bool2str(cgpu->deven != DEV_DISABLED),
  852. status2str(cgpu->status),
  853. cgpu->temp,
  854. cgpu->total_mhashes / total_secs, opt_log_interval, cgpu->rolling,
  855. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  856. cgpu->utility,
  857. ((unsigned long)(cgpu->last_share_pool_time) > 0) ? cgpu->last_share_pool : -1,
  858. (unsigned long)(cgpu->last_share_pool_time), cgpu->total_mhashes
  859. );
  860. if (cgpu->api->get_extra_device_status) {
  861. json_t *info = cgpu->api->get_extra_device_status(cgpu);
  862. append_kv(buf, info, isjson);
  863. json_decref(info);
  864. }
  865. tailsprintf(buf, "%c", isjson ? '}' : SEPARATOR);
  866. }
  867. #ifdef HAVE_OPENCL
  868. static void gpustatus(int gpu, bool isjson)
  869. {
  870. if (gpu < 0 || gpu >= nDevs)
  871. return;
  872. devstatus_an(io_buffer, &gpus[gpu], isjson);
  873. }
  874. #endif
  875. #ifdef HAVE_AN_FPGA
  876. static void pgastatus(int pga, bool isjson)
  877. {
  878. int dev = pgadevice(pga);
  879. if (dev < 0) // Should never happen
  880. return;
  881. devstatus_an(io_buffer, devices[dev], isjson);
  882. }
  883. #endif
  884. __maybe_unused
  885. static void cpustatus(int cpu, bool isjson)
  886. {
  887. if (opt_n_threads <= 0 || cpu < 0 || cpu >= num_processors)
  888. return;
  889. devstatus_an(io_buffer, &cpus[cpu], isjson);
  890. }
  891. static void
  892. devinfo_internal(void (*func)(char*, struct cgpu_info*, bool),
  893. __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  894. {
  895. int i;
  896. if (total_devices == 0) {
  897. strcpy(io_buffer, message(MSG_NODEVS, 0, NULL, isjson));
  898. return;
  899. }
  900. strcpy(io_buffer, message(MSG_DEVS, 0, NULL, isjson));
  901. if (isjson) {
  902. strcat(io_buffer, COMMA);
  903. strcat(io_buffer, JSON_DEVS);
  904. }
  905. for (i = 0; i < total_devices; ++i) {
  906. if (isjson && i)
  907. strcat(io_buffer, COMMA);
  908. func(io_buffer, devices[i], isjson);
  909. }
  910. if (isjson)
  911. strcat(io_buffer, JSON_CLOSE);
  912. }
  913. static void
  914. devdetail(SOCKETTYPE c, char *param, bool isjson)
  915. {
  916. return devinfo_internal(devdetail_an, c, param, isjson);
  917. }
  918. static void
  919. devstatus(SOCKETTYPE c, char *param, bool isjson)
  920. {
  921. return devinfo_internal(devstatus_an, c, param, isjson);
  922. }
  923. #ifdef HAVE_OPENCL
  924. static void gpudev(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  925. {
  926. int id;
  927. if (nDevs == 0) {
  928. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  929. return;
  930. }
  931. if (param == NULL || *param == '\0') {
  932. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  933. return;
  934. }
  935. id = atoi(param);
  936. if (id < 0 || id >= nDevs) {
  937. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  938. return;
  939. }
  940. strcpy(io_buffer, message(MSG_GPUDEV, id, NULL, isjson));
  941. if (isjson) {
  942. strcat(io_buffer, COMMA);
  943. strcat(io_buffer, JSON_GPU);
  944. }
  945. gpustatus(id, isjson);
  946. if (isjson)
  947. strcat(io_buffer, JSON_CLOSE);
  948. }
  949. #endif
  950. #ifdef HAVE_AN_FPGA
  951. static void pgadev(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  952. {
  953. int numpga = numpgas();
  954. int id;
  955. if (numpga == 0) {
  956. strcpy(io_buffer, message(MSG_PGANON, 0, NULL, isjson));
  957. return;
  958. }
  959. if (param == NULL || *param == '\0') {
  960. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  961. return;
  962. }
  963. id = atoi(param);
  964. if (id < 0 || id >= numpga) {
  965. strcpy(io_buffer, message(MSG_INVPGA, id, NULL, isjson));
  966. return;
  967. }
  968. strcpy(io_buffer, message(MSG_PGADEV, id, NULL, isjson));
  969. if (isjson) {
  970. strcat(io_buffer, COMMA);
  971. strcat(io_buffer, JSON_PGA);
  972. }
  973. pgastatus(id, isjson);
  974. if (isjson)
  975. strcat(io_buffer, JSON_CLOSE);
  976. }
  977. static void pgaenable(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  978. {
  979. int numpga = numpgas();
  980. struct thr_info *thr;
  981. int pga;
  982. int id;
  983. int i;
  984. if (numpga == 0) {
  985. strcpy(io_buffer, message(MSG_PGANON, 0, NULL, isjson));
  986. return;
  987. }
  988. if (param == NULL || *param == '\0') {
  989. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  990. return;
  991. }
  992. id = atoi(param);
  993. if (id < 0 || id >= numpga) {
  994. strcpy(io_buffer, message(MSG_INVPGA, id, NULL, isjson));
  995. return;
  996. }
  997. int dev = pgadevice(id);
  998. if (dev < 0) { // Should never happen
  999. strcpy(io_buffer, message(MSG_INVPGA, id, NULL, isjson));
  1000. return;
  1001. }
  1002. struct cgpu_info *cgpu = devices[dev];
  1003. if (cgpu->deven != DEV_DISABLED) {
  1004. strcpy(io_buffer, message(MSG_PGALRENA, id, NULL, isjson));
  1005. return;
  1006. }
  1007. #if 0 /* A DISABLED device wont change status FIXME: should disabling make it WELL? */
  1008. if (cgpu->status != LIFE_WELL) {
  1009. strcpy(io_buffer, message(MSG_PGAUNW, id, NULL, isjson));
  1010. return;
  1011. }
  1012. #endif
  1013. for (i = 0; i < mining_threads; i++) {
  1014. pga = thr_info[i].cgpu->device_id;
  1015. if (pga == dev) {
  1016. thr = &thr_info[i];
  1017. cgpu->deven = DEV_ENABLED;
  1018. tq_push(thr->q, &ping);
  1019. }
  1020. }
  1021. strcpy(io_buffer, message(MSG_PGAENA, id, NULL, isjson));
  1022. }
  1023. static void pgadisable(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1024. {
  1025. int numpga = numpgas();
  1026. int id;
  1027. if (numpga == 0) {
  1028. strcpy(io_buffer, message(MSG_PGANON, 0, NULL, isjson));
  1029. return;
  1030. }
  1031. if (param == NULL || *param == '\0') {
  1032. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  1033. return;
  1034. }
  1035. id = atoi(param);
  1036. if (id < 0 || id >= numpga) {
  1037. strcpy(io_buffer, message(MSG_INVPGA, id, NULL, isjson));
  1038. return;
  1039. }
  1040. int dev = pgadevice(id);
  1041. if (dev < 0) { // Should never happen
  1042. strcpy(io_buffer, message(MSG_INVPGA, id, NULL, isjson));
  1043. return;
  1044. }
  1045. struct cgpu_info *cgpu = devices[dev];
  1046. if (cgpu->deven == DEV_DISABLED) {
  1047. strcpy(io_buffer, message(MSG_PGALRDIS, id, NULL, isjson));
  1048. return;
  1049. }
  1050. cgpu->deven = DEV_DISABLED;
  1051. strcpy(io_buffer, message(MSG_PGADIS, id, NULL, isjson));
  1052. }
  1053. #endif
  1054. #ifdef WANT_CPUMINE
  1055. static void cpudev(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1056. {
  1057. int id;
  1058. if (opt_n_threads == 0) {
  1059. strcpy(io_buffer, message(MSG_CPUNON, 0, NULL, isjson));
  1060. return;
  1061. }
  1062. if (param == NULL || *param == '\0') {
  1063. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  1064. return;
  1065. }
  1066. id = atoi(param);
  1067. if (id < 0 || id >= num_processors) {
  1068. strcpy(io_buffer, message(MSG_INVCPU, id, NULL, isjson));
  1069. return;
  1070. }
  1071. strcpy(io_buffer, message(MSG_CPUDEV, id, NULL, isjson));
  1072. if (isjson) {
  1073. strcat(io_buffer, COMMA);
  1074. strcat(io_buffer, JSON_CPU);
  1075. }
  1076. cpustatus(id, isjson);
  1077. if (isjson)
  1078. strcat(io_buffer, JSON_CLOSE);
  1079. }
  1080. #endif
  1081. static void poolstatus(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1082. {
  1083. char buf[TMPBUFSIZ];
  1084. char *status, *lp;
  1085. char *rpc_url;
  1086. char *rpc_user;
  1087. int i;
  1088. if (total_pools == 0) {
  1089. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1090. return;
  1091. }
  1092. strcpy(io_buffer, message(MSG_POOL, 0, NULL, isjson));
  1093. if (isjson) {
  1094. strcat(io_buffer, COMMA);
  1095. strcat(io_buffer, JSON_POOLS);
  1096. }
  1097. for (i = 0; i < total_pools; i++) {
  1098. struct pool *pool = pools[i];
  1099. switch (pool->enabled) {
  1100. case POOL_DISABLED:
  1101. status = (char *)DISABLED;
  1102. break;
  1103. case POOL_REJECTING:
  1104. status = (char *)REJECTING;
  1105. break;
  1106. case POOL_ENABLED:
  1107. if (pool->idle)
  1108. status = (char *)DEAD;
  1109. else
  1110. status = (char *)ALIVE;
  1111. break;
  1112. default:
  1113. status = (char *)UNKNOWN;
  1114. break;
  1115. }
  1116. if (pool->hdr_path)
  1117. lp = (char *)YES;
  1118. else
  1119. lp = (char *)NO;
  1120. rpc_url = escape_string(pool->rpc_url, isjson);
  1121. rpc_user = escape_string(pool->rpc_user, isjson);
  1122. sprintf(buf, isjson
  1123. ? "%s{\"POOL\":%d,\"URL\":\"%s\",\"Status\":\"%s\",\"Priority\":%d,\"Long Poll\":\"%s\",\"Getworks\":%d,\"Accepted\":%d,\"Rejected\":%d,\"Discarded\":%d,\"Stale\":%d,\"Get Failures\":%d,\"Remote Failures\":%d,\"User\":\"%s\",\"Last Share Time\":%lu}"
  1124. : "%sPOOL=%d,URL=%s,Status=%s,Priority=%d,Long Poll=%s,Getworks=%d,Accepted=%d,Rejected=%d,Discarded=%d,Stale=%d,Get Failures=%d,Remote Failures=%d,User=%s,Last Share Time=%lu" SEPSTR,
  1125. (isjson && (i > 0)) ? COMMA : BLANK,
  1126. i, rpc_url, status, pool->prio, lp,
  1127. pool->getwork_requested,
  1128. pool->accepted, pool->rejected,
  1129. pool->discarded_work,
  1130. pool->stale_shares,
  1131. pool->getfail_occasions,
  1132. pool->remotefail_occasions,
  1133. rpc_user, pool->last_share_time);
  1134. strcat(io_buffer, buf);
  1135. if (rpc_url != pool->rpc_url)
  1136. free(rpc_url);
  1137. rpc_url = NULL;
  1138. if (rpc_user != pool->rpc_user)
  1139. free(rpc_user);
  1140. rpc_user = NULL;
  1141. }
  1142. if (isjson)
  1143. strcat(io_buffer, JSON_CLOSE);
  1144. }
  1145. static void summary(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1146. {
  1147. double utility, mhs;
  1148. #ifdef WANT_CPUMINE
  1149. char *algo = (char *)(algo_names[opt_algo]);
  1150. if (algo == NULL)
  1151. algo = "(null)";
  1152. #endif
  1153. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  1154. mhs = total_mhashes_done / total_secs;
  1155. #ifdef WANT_CPUMINE
  1156. sprintf(io_buffer, isjson
  1157. ? "%s," JSON_SUMMARY "{\"Elapsed\":%.0f,\"Algorithm\":\"%s\",\"MHS av\":%.2f,\"Found Blocks\":%d,\"Getworks\":%d,\"Accepted\":%d,\"Rejected\":%d,\"Hardware Errors\":%d,\"Utility\":%.2f,\"Discarded\":%d,\"Stale\":%d,\"Get Failures\":%d,\"Local Work\":%u,\"Remote Failures\":%u,\"Network Blocks\":%u,\"Total MH\":%.4f}" JSON_CLOSE
  1158. : "%s" _SUMMARY ",Elapsed=%.0f,Algorithm=%s,MHS av=%.2f,Found Blocks=%d,Getworks=%d,Accepted=%d,Rejected=%d,Hardware Errors=%d,Utility=%.2f,Discarded=%d,Stale=%d,Get Failures=%d,Local Work=%u,Remote Failures=%u,Network Blocks=%u,Total MH=%.4f" SEPSTR,
  1159. message(MSG_SUMM, 0, NULL, isjson),
  1160. total_secs, algo, mhs, found_blocks,
  1161. total_getworks, total_accepted, total_rejected,
  1162. hw_errors, utility, total_discarded, total_stale,
  1163. total_go, local_work, total_ro, new_blocks, total_mhashes_done);
  1164. #else
  1165. sprintf(io_buffer, isjson
  1166. ? "%s," JSON_SUMMARY "{\"Elapsed\":%.0f,\"MHS av\":%.2f,\"Found Blocks\":%d,\"Getworks\":%d,\"Accepted\":%d,\"Rejected\":%d,\"Hardware Errors\":%d,\"Utility\":%.2f,\"Discarded\":%d,\"Stale\":%d,\"Get Failures\":%d,\"Local Work\":%u,\"Remote Failures\":%u,\"Network Blocks\":%u,\"Total MH\":%.4f}" JSON_CLOSE
  1167. : "%s" _SUMMARY ",Elapsed=%.0f,MHS av=%.2f,Found Blocks=%d,Getworks=%d,Accepted=%d,Rejected=%d,Hardware Errors=%d,Utility=%.2f,Discarded=%d,Stale=%d,Get Failures=%d,Local Work=%u,Remote Failures=%u,Network Blocks=%u,Total MH=%.4f" SEPSTR,
  1168. message(MSG_SUMM, 0, NULL, isjson),
  1169. total_secs, mhs, found_blocks,
  1170. total_getworks, total_accepted, total_rejected,
  1171. hw_errors, utility, total_discarded, total_stale,
  1172. total_go, local_work, total_ro, new_blocks, total_mhashes_done);
  1173. #endif
  1174. }
  1175. #ifdef HAVE_OPENCL
  1176. static void gpuenable(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1177. {
  1178. struct thr_info *thr;
  1179. int gpu;
  1180. int id;
  1181. int i;
  1182. if (gpu_threads == 0) {
  1183. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  1184. return;
  1185. }
  1186. if (param == NULL || *param == '\0') {
  1187. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  1188. return;
  1189. }
  1190. id = atoi(param);
  1191. if (id < 0 || id >= nDevs) {
  1192. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  1193. return;
  1194. }
  1195. if (gpus[id].deven != DEV_DISABLED) {
  1196. strcpy(io_buffer, message(MSG_ALRENA, id, NULL, isjson));
  1197. return;
  1198. }
  1199. for (i = 0; i < gpu_threads; i++) {
  1200. gpu = thr_info[i].cgpu->device_id;
  1201. if (gpu == id) {
  1202. thr = &thr_info[i];
  1203. if (thr->cgpu->status != LIFE_WELL) {
  1204. strcpy(io_buffer, message(MSG_GPUMRE, id, NULL, isjson));
  1205. return;
  1206. }
  1207. gpus[id].deven = DEV_ENABLED;
  1208. tq_push(thr->q, &ping);
  1209. }
  1210. }
  1211. strcpy(io_buffer, message(MSG_GPUREN, id, NULL, isjson));
  1212. }
  1213. static void gpudisable(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1214. {
  1215. int id;
  1216. if (nDevs == 0) {
  1217. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  1218. return;
  1219. }
  1220. if (param == NULL || *param == '\0') {
  1221. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  1222. return;
  1223. }
  1224. id = atoi(param);
  1225. if (id < 0 || id >= nDevs) {
  1226. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  1227. return;
  1228. }
  1229. if (gpus[id].deven == DEV_DISABLED) {
  1230. strcpy(io_buffer, message(MSG_ALRDIS, id, NULL, isjson));
  1231. return;
  1232. }
  1233. gpus[id].deven = DEV_DISABLED;
  1234. strcpy(io_buffer, message(MSG_GPUDIS, id, NULL, isjson));
  1235. }
  1236. static void gpurestart(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1237. {
  1238. int id;
  1239. if (nDevs == 0) {
  1240. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  1241. return;
  1242. }
  1243. if (param == NULL || *param == '\0') {
  1244. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  1245. return;
  1246. }
  1247. id = atoi(param);
  1248. if (id < 0 || id >= nDevs) {
  1249. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  1250. return;
  1251. }
  1252. reinit_device(&gpus[id]);
  1253. strcpy(io_buffer, message(MSG_GPUREI, id, NULL, isjson));
  1254. }
  1255. #endif
  1256. static void gpucount(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1257. {
  1258. char buf[TMPBUFSIZ];
  1259. int numgpu = 0;
  1260. #ifdef HAVE_OPENCL
  1261. numgpu = nDevs;
  1262. #endif
  1263. strcpy(io_buffer, message(MSG_NUMGPU, 0, NULL, isjson));
  1264. sprintf(buf, isjson
  1265. ? "," JSON_GPUS "{\"Count\":%d}" JSON_CLOSE
  1266. : _GPUS ",Count=%d" SEPSTR,
  1267. numgpu);
  1268. strcat(io_buffer, buf);
  1269. }
  1270. static void pgacount(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1271. {
  1272. char buf[TMPBUFSIZ];
  1273. int count = 0;
  1274. #ifdef HAVE_AN_FPGA
  1275. count = numpgas();
  1276. #endif
  1277. strcpy(io_buffer, message(MSG_NUMPGA, 0, NULL, isjson));
  1278. sprintf(buf, isjson
  1279. ? "," JSON_PGAS "{\"Count\":%d}" JSON_CLOSE
  1280. : _PGAS ",Count=%d" SEPSTR,
  1281. count);
  1282. strcat(io_buffer, buf);
  1283. }
  1284. static void cpucount(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1285. {
  1286. char buf[TMPBUFSIZ];
  1287. int count = 0;
  1288. #ifdef WANT_CPUMINE
  1289. count = opt_n_threads > 0 ? num_processors : 0;
  1290. #endif
  1291. strcpy(io_buffer, message(MSG_NUMCPU, 0, NULL, isjson));
  1292. sprintf(buf, isjson
  1293. ? "," JSON_CPUS "{\"Count\":%d}" JSON_CLOSE
  1294. : _CPUS ",Count=%d" SEPSTR,
  1295. count);
  1296. strcat(io_buffer, buf);
  1297. }
  1298. static void switchpool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1299. {
  1300. struct pool *pool;
  1301. int id;
  1302. if (total_pools == 0) {
  1303. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1304. return;
  1305. }
  1306. if (param == NULL || *param == '\0') {
  1307. strcpy(io_buffer, message(MSG_MISPID, 0, NULL, isjson));
  1308. return;
  1309. }
  1310. id = atoi(param);
  1311. if (id < 0 || id >= total_pools) {
  1312. strcpy(io_buffer, message(MSG_INVPID, id, NULL, isjson));
  1313. return;
  1314. }
  1315. pool = pools[id];
  1316. pool->enabled = POOL_ENABLED;
  1317. switch_pools(pool);
  1318. strcpy(io_buffer, message(MSG_SWITCHP, id, NULL, isjson));
  1319. }
  1320. static void copyadvanceafter(char ch, char **param, char **buf)
  1321. {
  1322. #define src_p (*param)
  1323. #define dst_b (*buf)
  1324. while (*src_p && *src_p != ch) {
  1325. if (*src_p == '\\' && *(src_p+1) != '\0')
  1326. src_p++;
  1327. *(dst_b++) = *(src_p++);
  1328. }
  1329. if (*src_p)
  1330. src_p++;
  1331. *(dst_b++) = '\0';
  1332. }
  1333. static bool pooldetails(char *param, char **url, char **user, char **pass)
  1334. {
  1335. char *ptr, *buf;
  1336. ptr = buf = malloc(strlen(param)+1);
  1337. if (unlikely(!buf))
  1338. quit(1, "Failed to malloc pooldetails buf");
  1339. *url = buf;
  1340. // copy url
  1341. copyadvanceafter(',', &param, &buf);
  1342. if (!(*param)) // missing user
  1343. goto exitsama;
  1344. *user = buf;
  1345. // copy user
  1346. copyadvanceafter(',', &param, &buf);
  1347. if (!*param) // missing pass
  1348. goto exitsama;
  1349. *pass = buf;
  1350. // copy pass
  1351. copyadvanceafter(',', &param, &buf);
  1352. return true;
  1353. exitsama:
  1354. free(ptr);
  1355. return false;
  1356. }
  1357. static void addpool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1358. {
  1359. char *url, *user, *pass;
  1360. char *ptr;
  1361. if (param == NULL || *param == '\0') {
  1362. strcpy(io_buffer, message(MSG_MISPDP, 0, NULL, isjson));
  1363. return;
  1364. }
  1365. if (!pooldetails(param, &url, &user, &pass)) {
  1366. ptr = escape_string(param, isjson);
  1367. strcpy(io_buffer, message(MSG_INVPDP, 0, ptr, isjson));
  1368. if (ptr != param)
  1369. free(ptr);
  1370. ptr = NULL;
  1371. return;
  1372. }
  1373. add_pool_details(true, url, user, pass);
  1374. ptr = escape_string(url, isjson);
  1375. strcpy(io_buffer, message(MSG_ADDPOOL, 0, ptr, isjson));
  1376. if (ptr != url)
  1377. free(ptr);
  1378. ptr = NULL;
  1379. }
  1380. static void enablepool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1381. {
  1382. struct pool *pool;
  1383. int id;
  1384. if (total_pools == 0) {
  1385. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1386. return;
  1387. }
  1388. if (param == NULL || *param == '\0') {
  1389. strcpy(io_buffer, message(MSG_MISPID, 0, NULL, isjson));
  1390. return;
  1391. }
  1392. id = atoi(param);
  1393. if (id < 0 || id >= total_pools) {
  1394. strcpy(io_buffer, message(MSG_INVPID, id, NULL, isjson));
  1395. return;
  1396. }
  1397. pool = pools[id];
  1398. if (pool->enabled == POOL_ENABLED) {
  1399. strcpy(io_buffer, message(MSG_ALRENAP, id, NULL, isjson));
  1400. return;
  1401. }
  1402. pool->enabled = POOL_ENABLED;
  1403. if (pool->prio < current_pool()->prio)
  1404. switch_pools(pool);
  1405. strcpy(io_buffer, message(MSG_ENAPOOL, id, NULL, isjson));
  1406. }
  1407. static void disablepool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1408. {
  1409. struct pool *pool;
  1410. int id;
  1411. if (total_pools == 0) {
  1412. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1413. return;
  1414. }
  1415. if (param == NULL || *param == '\0') {
  1416. strcpy(io_buffer, message(MSG_MISPID, 0, NULL, isjson));
  1417. return;
  1418. }
  1419. id = atoi(param);
  1420. if (id < 0 || id >= total_pools) {
  1421. strcpy(io_buffer, message(MSG_INVPID, id, NULL, isjson));
  1422. return;
  1423. }
  1424. pool = pools[id];
  1425. if (pool->enabled == POOL_DISABLED) {
  1426. strcpy(io_buffer, message(MSG_ALRDISP, id, NULL, isjson));
  1427. return;
  1428. }
  1429. if (active_pools() <= 1) {
  1430. strcpy(io_buffer, message(MSG_DISLASTP, id, NULL, isjson));
  1431. return;
  1432. }
  1433. pool->enabled = POOL_DISABLED;
  1434. if (pool == current_pool())
  1435. switch_pools(NULL);
  1436. strcpy(io_buffer, message(MSG_DISPOOL, id, NULL, isjson));
  1437. }
  1438. static void removepool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1439. {
  1440. struct pool *pool;
  1441. char *rpc_url;
  1442. bool dofree = false;
  1443. int id;
  1444. if (total_pools == 0) {
  1445. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1446. return;
  1447. }
  1448. if (param == NULL || *param == '\0') {
  1449. strcpy(io_buffer, message(MSG_MISPID, 0, NULL, isjson));
  1450. return;
  1451. }
  1452. id = atoi(param);
  1453. if (id < 0 || id >= total_pools) {
  1454. strcpy(io_buffer, message(MSG_INVPID, id, NULL, isjson));
  1455. return;
  1456. }
  1457. if (total_pools <= 1) {
  1458. strcpy(io_buffer, message(MSG_REMLASTP, id, NULL, isjson));
  1459. return;
  1460. }
  1461. pool = pools[id];
  1462. if (pool == current_pool())
  1463. switch_pools(NULL);
  1464. if (pool == current_pool()) {
  1465. strcpy(io_buffer, message(MSG_ACTPOOL, id, NULL, isjson));
  1466. return;
  1467. }
  1468. pool->enabled = POOL_DISABLED;
  1469. rpc_url = escape_string(pool->rpc_url, isjson);
  1470. if (rpc_url != pool->rpc_url)
  1471. dofree = true;
  1472. remove_pool(pool);
  1473. strcpy(io_buffer, message(MSG_REMPOOL, id, rpc_url, isjson));
  1474. if (dofree)
  1475. free(rpc_url);
  1476. rpc_url = NULL;
  1477. }
  1478. #ifdef HAVE_OPENCL
  1479. static bool splitgpuvalue(char *param, int *gpu, char **value, bool isjson)
  1480. {
  1481. int id;
  1482. char *gpusep;
  1483. if (nDevs == 0) {
  1484. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  1485. return false;
  1486. }
  1487. if (param == NULL || *param == '\0') {
  1488. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  1489. return false;
  1490. }
  1491. gpusep = strchr(param, GPUSEP);
  1492. if (gpusep == NULL) {
  1493. strcpy(io_buffer, message(MSG_MISVAL, 0, NULL, isjson));
  1494. return false;
  1495. }
  1496. *(gpusep++) = '\0';
  1497. id = atoi(param);
  1498. if (id < 0 || id >= nDevs) {
  1499. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  1500. return false;
  1501. }
  1502. *gpu = id;
  1503. *value = gpusep;
  1504. return true;
  1505. }
  1506. static void gpuintensity(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1507. {
  1508. int id;
  1509. char *value;
  1510. int intensity;
  1511. char intensitystr[7];
  1512. if (!splitgpuvalue(param, &id, &value, isjson))
  1513. return;
  1514. if (!strncasecmp(value, DYNAMIC, 1)) {
  1515. gpus[id].dynamic = true;
  1516. strcpy(intensitystr, DYNAMIC);
  1517. }
  1518. else {
  1519. intensity = atoi(value);
  1520. if (intensity < MIN_INTENSITY || intensity > MAX_INTENSITY) {
  1521. strcpy(io_buffer, message(MSG_INVINT, 0, value, isjson));
  1522. return;
  1523. }
  1524. gpus[id].dynamic = false;
  1525. gpus[id].intensity = intensity;
  1526. sprintf(intensitystr, "%d", intensity);
  1527. }
  1528. strcpy(io_buffer, message(MSG_GPUINT, id, intensitystr, isjson));
  1529. }
  1530. static void gpumem(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1531. {
  1532. #ifdef HAVE_ADL
  1533. int id;
  1534. char *value;
  1535. int clock;
  1536. if (!splitgpuvalue(param, &id, &value, isjson))
  1537. return;
  1538. clock = atoi(value);
  1539. if (set_memoryclock(id, clock))
  1540. strcpy(io_buffer, message(MSG_GPUMERR, id, value, isjson));
  1541. else
  1542. strcpy(io_buffer, message(MSG_GPUMEM, id, value, isjson));
  1543. #else
  1544. strcpy(io_buffer, message(MSG_NOADL, 0, NULL, isjson));
  1545. #endif
  1546. }
  1547. static void gpuengine(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1548. {
  1549. #ifdef HAVE_ADL
  1550. int id;
  1551. char *value;
  1552. int clock;
  1553. if (!splitgpuvalue(param, &id, &value, isjson))
  1554. return;
  1555. clock = atoi(value);
  1556. if (set_engineclock(id, clock))
  1557. strcpy(io_buffer, message(MSG_GPUEERR, id, value, isjson));
  1558. else
  1559. strcpy(io_buffer, message(MSG_GPUENG, id, value, isjson));
  1560. #else
  1561. strcpy(io_buffer, message(MSG_NOADL, 0, NULL, isjson));
  1562. #endif
  1563. }
  1564. static void gpufan(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1565. {
  1566. #ifdef HAVE_ADL
  1567. int id;
  1568. char *value;
  1569. int fan;
  1570. if (!splitgpuvalue(param, &id, &value, isjson))
  1571. return;
  1572. fan = atoi(value);
  1573. if (set_fanspeed(id, fan))
  1574. strcpy(io_buffer, message(MSG_GPUFERR, id, value, isjson));
  1575. else
  1576. strcpy(io_buffer, message(MSG_GPUFAN, id, value, isjson));
  1577. #else
  1578. strcpy(io_buffer, message(MSG_NOADL, 0, NULL, isjson));
  1579. #endif
  1580. }
  1581. static void gpuvddc(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1582. {
  1583. #ifdef HAVE_ADL
  1584. int id;
  1585. char *value;
  1586. float vddc;
  1587. if (!splitgpuvalue(param, &id, &value, isjson))
  1588. return;
  1589. vddc = atof(value);
  1590. if (set_vddc(id, vddc))
  1591. strcpy(io_buffer, message(MSG_GPUVERR, id, value, isjson));
  1592. else
  1593. strcpy(io_buffer, message(MSG_GPUVDDC, id, value, isjson));
  1594. #else
  1595. strcpy(io_buffer, message(MSG_NOADL, 0, NULL, isjson));
  1596. #endif
  1597. }
  1598. #endif
  1599. void doquit(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1600. {
  1601. if (isjson)
  1602. strcpy(io_buffer, JSON_START JSON_BYE);
  1603. else
  1604. strcpy(io_buffer, _BYE);
  1605. bye = true;
  1606. do_a_quit = true;
  1607. }
  1608. void dorestart(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1609. {
  1610. if (isjson)
  1611. strcpy(io_buffer, JSON_START JSON_RESTART);
  1612. else
  1613. strcpy(io_buffer, _RESTART);
  1614. bye = true;
  1615. do_a_restart = true;
  1616. }
  1617. void privileged(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1618. {
  1619. strcpy(io_buffer, message(MSG_ACCOK, 0, NULL, isjson));
  1620. }
  1621. void notifystatus(int device, struct cgpu_info *cgpu, bool isjson)
  1622. {
  1623. char buf[TMPBUFSIZ];
  1624. char *reason;
  1625. if (cgpu->device_last_not_well == 0)
  1626. reason = REASON_NONE;
  1627. else
  1628. switch(cgpu->device_not_well_reason) {
  1629. case REASON_THREAD_FAIL_INIT:
  1630. reason = REASON_THREAD_FAIL_INIT_STR;
  1631. break;
  1632. case REASON_THREAD_ZERO_HASH:
  1633. reason = REASON_THREAD_ZERO_HASH_STR;
  1634. break;
  1635. case REASON_THREAD_FAIL_QUEUE:
  1636. reason = REASON_THREAD_FAIL_QUEUE_STR;
  1637. break;
  1638. case REASON_DEV_SICK_IDLE_60:
  1639. reason = REASON_DEV_SICK_IDLE_60_STR;
  1640. break;
  1641. case REASON_DEV_DEAD_IDLE_600:
  1642. reason = REASON_DEV_DEAD_IDLE_600_STR;
  1643. break;
  1644. case REASON_DEV_NOSTART:
  1645. reason = REASON_DEV_NOSTART_STR;
  1646. break;
  1647. case REASON_DEV_OVER_HEAT:
  1648. reason = REASON_DEV_OVER_HEAT_STR;
  1649. break;
  1650. case REASON_DEV_THERMAL_CUTOFF:
  1651. reason = REASON_DEV_THERMAL_CUTOFF_STR;
  1652. break;
  1653. default:
  1654. reason = REASON_UNKNOWN_STR;
  1655. break;
  1656. }
  1657. // ALL counters (and only counters) must start the name with a '*'
  1658. // Simplifies future external support for adding new counters
  1659. sprintf(buf, isjson
  1660. ? "%s{\"NOTIFY\":%d,\"Name\":\"%s\",\"ID\":%d,\"Last Well\":%lu,\"Last Not Well\":%lu,\"Reason Not Well\":\"%s\",\"*Thread Fail Init\":%d,\"*Thread Zero Hash\":%d,\"*Thread Fail Queue\":%d,\"*Dev Sick Idle 60s\":%d,\"*Dev Dead Idle 600s\":%d,\"*Dev Nostart\":%d,\"*Dev Over Heat\":%d,\"*Dev Thermal Cutoff\":%d}"
  1661. : "%sNOTIFY=%d,Name=%s,ID=%d,Last Well=%lu,Last Not Well=%lu,Reason Not Well=%s,*Thread Fail Init=%d,*Thread Zero Hash=%d,*Thread Fail Queue=%d,*Dev Sick Idle 60s=%d,*Dev Dead Idle 600s=%d,*Dev Nostart=%d,*Dev Over Heat=%d,*Dev Thermal Cutoff=%d" SEPSTR,
  1662. (isjson && (device > 0)) ? COMMA : BLANK,
  1663. device, cgpu->api->name, cgpu->device_id,
  1664. cgpu->device_last_well, cgpu->device_last_not_well, reason,
  1665. cgpu->thread_fail_init_count, cgpu->thread_zero_hash_count,
  1666. cgpu->thread_fail_queue_count, cgpu->dev_sick_idle_60_count,
  1667. cgpu->dev_dead_idle_600_count, cgpu->dev_nostart_count,
  1668. cgpu->dev_over_heat_count, cgpu->dev_thermal_cutoff_count);
  1669. strcat(io_buffer, buf);
  1670. }
  1671. static void notify(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1672. {
  1673. int i;
  1674. if (total_devices == 0) {
  1675. strcpy(io_buffer, message(MSG_NODEVS, 0, NULL, isjson));
  1676. return;
  1677. }
  1678. strcpy(io_buffer, message(MSG_NOTIFY, 0, NULL, isjson));
  1679. if (isjson) {
  1680. strcat(io_buffer, COMMA);
  1681. strcat(io_buffer, JSON_NOTIFY);
  1682. }
  1683. for (i = 0; i < total_devices; i++)
  1684. notifystatus(i, devices[i], isjson);
  1685. if (isjson)
  1686. strcat(io_buffer, JSON_CLOSE);
  1687. }
  1688. static void devdetails(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1689. {
  1690. char buf[TMPBUFSIZ];
  1691. struct cgpu_info *cgpu;
  1692. int i;
  1693. if (total_devices == 0) {
  1694. strcpy(io_buffer, message(MSG_NODEVS, 0, NULL, isjson));
  1695. return;
  1696. }
  1697. strcpy(io_buffer, message(MSG_DEVDETAILS, 0, NULL, isjson));
  1698. if (isjson) {
  1699. strcat(io_buffer, COMMA);
  1700. strcat(io_buffer, JSON_DEVDETAILS);
  1701. }
  1702. for (i = 0; i < total_devices; i++) {
  1703. cgpu = devices[i];
  1704. sprintf(buf, isjson
  1705. ? "%s{\"DEVDETAILS\":%d,\"Name\":\"%s\",\"ID\":%d,\"Driver\":\"%s\",\"Kernel\":\"%s\",\"Model\":\"%s\",\"Device Path\":\"%s\"}"
  1706. : "%sDEVDETAILS=%d,Name=%s,ID=%d,Driver=%s,Kernel=%s,Model=%s,Device Path=%s" SEPSTR,
  1707. (isjson && (i > 0)) ? COMMA : BLANK,
  1708. i, cgpu->api->name, cgpu->device_id,
  1709. cgpu->api->dname, cgpu->kname ? : BLANK,
  1710. cgpu->name ? : BLANK, cgpu->device_path ? : BLANK);
  1711. strcat(io_buffer, buf);
  1712. }
  1713. if (isjson)
  1714. strcat(io_buffer, JSON_CLOSE);
  1715. }
  1716. void dosave(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1717. {
  1718. char filename[PATH_MAX];
  1719. FILE *fcfg;
  1720. char *ptr;
  1721. if (param == NULL || *param == '\0') {
  1722. default_save_file(filename);
  1723. param = filename;
  1724. }
  1725. fcfg = fopen(param, "w");
  1726. if (!fcfg) {
  1727. ptr = escape_string(param, isjson);
  1728. strcpy(io_buffer, message(MSG_BADFN, 0, ptr, isjson));
  1729. if (ptr != param)
  1730. free(ptr);
  1731. ptr = NULL;
  1732. return;
  1733. }
  1734. write_config(fcfg);
  1735. fclose(fcfg);
  1736. ptr = escape_string(param, isjson);
  1737. strcpy(io_buffer, message(MSG_SAVED, 0, ptr, isjson));
  1738. if (ptr != param)
  1739. free(ptr);
  1740. ptr = NULL;
  1741. }
  1742. static int itemstats(int i, char *id, struct cgminer_stats *stats, struct cgminer_pool_stats *pool_stats, char *extra, bool isjson)
  1743. {
  1744. char buf[TMPBUFSIZ];
  1745. if (stats->getwork_calls || (extra != NULL && *extra))
  1746. {
  1747. if (extra == NULL)
  1748. extra = (char *)BLANK;
  1749. sprintf(buf, isjson
  1750. ? "%s{\"STATS\":%d,\"ID\":\"%s\",\"Elapsed\":%.0f,\"Calls\":%d,\"Wait\":%ld.%06ld,\"Max\":%ld.%06ld,\"Min\":%ld.%06ld"
  1751. : "%sSTATS=%d,ID=%s,Elapsed=%.0f,Calls=%d,Wait=%ld.%06ld,Max=%ld.%06ld,Min=%ld.%06ld",
  1752. (isjson && (i > 0)) ? COMMA : BLANK,
  1753. i, id, total_secs, stats->getwork_calls,
  1754. stats->getwork_wait.tv_sec, stats->getwork_wait.tv_usec,
  1755. stats->getwork_wait_max.tv_sec, stats->getwork_wait_max.tv_usec,
  1756. stats->getwork_wait_min.tv_sec, stats->getwork_wait_min.tv_usec);
  1757. strcat(io_buffer, buf);
  1758. if (pool_stats) {
  1759. sprintf(buf, isjson
  1760. ? ",\"Pool Calls\":%d,\"Pool Attempts\":%d,\"Pool Wait\":%ld.%06ld,\"Pool Max\":%ld.%06ld,\"Pool Min\":%ld.%06ld,\"Pool Av\":%f"
  1761. : ",Pool Calls=%d,Pool Attempts=%d,Pool Wait=%ld.%06ld,Pool Max=%ld.%06ld,Pool Min=%ld.%06ld,Pool Av=%f",
  1762. pool_stats->getwork_calls, pool_stats->getwork_attempts,
  1763. pool_stats->getwork_wait.tv_sec, pool_stats->getwork_wait.tv_usec,
  1764. pool_stats->getwork_wait_max.tv_sec, pool_stats->getwork_wait_max.tv_usec,
  1765. pool_stats->getwork_wait_min.tv_sec, pool_stats->getwork_wait_min.tv_usec,
  1766. pool_stats->getwork_wait_rolling);
  1767. strcat(io_buffer, buf);
  1768. }
  1769. sprintf(buf, isjson
  1770. ? "%s}"
  1771. : "%s" SEPSTR,
  1772. extra);
  1773. strcat(io_buffer, buf);
  1774. i++;
  1775. }
  1776. return i;
  1777. }
  1778. static void minerstats(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1779. {
  1780. char extra[TMPBUFSIZ];
  1781. char id[20];
  1782. int i, j;
  1783. strcpy(io_buffer, message(MSG_MINESTATS, 0, NULL, isjson));
  1784. if (isjson) {
  1785. strcat(io_buffer, COMMA);
  1786. strcat(io_buffer, JSON_MINESTATS);
  1787. }
  1788. i = 0;
  1789. for (j = 0; j < total_devices; j++) {
  1790. struct cgpu_info *cgpu = devices[j];
  1791. extra[0] = '\0';
  1792. if (cgpu->api->get_extra_device_perf_stats) {
  1793. json_t *info = cgpu->api->get_extra_device_perf_stats(cgpu);
  1794. append_kv(extra, info, isjson);
  1795. json_decref(info);
  1796. }
  1797. sprintf(id, "%s%d", cgpu->api->name, cgpu->device_id);
  1798. i = itemstats(i, id, &(cgpu->cgminer_stats), NULL, extra, isjson);
  1799. }
  1800. for (j = 0; j < total_pools; j++) {
  1801. struct pool *pool = pools[j];
  1802. sprintf(id, "POOL%d", j);
  1803. i = itemstats(i, id, &(pool->cgminer_stats), &(pool->cgminer_pool_stats), NULL, isjson);
  1804. }
  1805. if (isjson)
  1806. strcat(io_buffer, JSON_CLOSE);
  1807. }
  1808. struct CMDS {
  1809. char *name;
  1810. void (*func)(SOCKETTYPE, char *, bool);
  1811. bool requires_writemode;
  1812. } cmds[] = {
  1813. { "version", apiversion, false },
  1814. { "config", minerconfig, false },
  1815. { "devs", devstatus, false },
  1816. { "devdetail", devdetail, false },
  1817. { "pools", poolstatus, false },
  1818. { "summary", summary, false },
  1819. #ifdef HAVE_OPENCL
  1820. { "gpuenable", gpuenable, true },
  1821. { "gpudisable", gpudisable, true },
  1822. { "gpurestart", gpurestart, true },
  1823. { "gpu", gpudev, false },
  1824. #endif
  1825. #ifdef HAVE_AN_FPGA
  1826. { "pga", pgadev, false },
  1827. { "pgaenable", pgaenable, true },
  1828. { "pgadisable", pgadisable, true },
  1829. #endif
  1830. #ifdef WANT_CPUMINE
  1831. { "cpu", cpudev, false },
  1832. #endif
  1833. { "gpucount", gpucount, false },
  1834. { "pgacount", pgacount, false },
  1835. { "cpucount", cpucount, false },
  1836. { "switchpool", switchpool, true },
  1837. { "addpool", addpool, true },
  1838. { "enablepool", enablepool, true },
  1839. { "disablepool", disablepool, true },
  1840. { "removepool", removepool, true },
  1841. #ifdef HAVE_OPENCL
  1842. { "gpuintensity", gpuintensity, true },
  1843. { "gpumem", gpumem, true },
  1844. { "gpuengine", gpuengine, true },
  1845. { "gpufan", gpufan, true },
  1846. { "gpuvddc", gpuvddc, true },
  1847. #endif
  1848. { "save", dosave, true },
  1849. { "quit", doquit, true },
  1850. { "privileged", privileged, true },
  1851. { "notify", notify, false },
  1852. { "devdetails", devdetails, false },
  1853. { "restart", dorestart, true },
  1854. { "stats", minerstats, false },
  1855. { NULL, NULL, false }
  1856. };
  1857. static void send_result(SOCKETTYPE c, bool isjson)
  1858. {
  1859. int n;
  1860. int len;
  1861. if (isjson)
  1862. strcat(io_buffer, JSON_END);
  1863. len = strlen(io_buffer);
  1864. applog(LOG_DEBUG, "API: send reply: (%d) '%.10s%s'", len+1, io_buffer, len > 10 ? "..." : BLANK);
  1865. // ignore failure - it's closed immediately anyway
  1866. n = send(c, io_buffer, len+1, 0);
  1867. if (opt_debug) {
  1868. if (SOCKETFAIL(n))
  1869. applog(LOG_DEBUG, "API: send failed: %s", SOCKERRMSG);
  1870. else
  1871. applog(LOG_DEBUG, "API: sent %d", n);
  1872. }
  1873. }
  1874. static void tidyup(__maybe_unused void *arg)
  1875. {
  1876. mutex_lock(&quit_restart_lock);
  1877. bye = true;
  1878. if (sock != INVSOCK) {
  1879. shutdown(sock, SHUT_RDWR);
  1880. CLOSESOCKET(sock);
  1881. sock = INVSOCK;
  1882. }
  1883. if (ipaccess != NULL) {
  1884. free(ipaccess);
  1885. ipaccess = NULL;
  1886. }
  1887. if (msg_buffer != NULL) {
  1888. free(msg_buffer);
  1889. msg_buffer = NULL;
  1890. }
  1891. if (io_buffer != NULL) {
  1892. free(io_buffer);
  1893. io_buffer = NULL;
  1894. }
  1895. mutex_unlock(&quit_restart_lock);
  1896. }
  1897. /*
  1898. * Interpret [R|W:]IP[/Prefix][,[R|W:]IP2[/Prefix2][,...]] --api-allow option
  1899. * special case of 0/0 allows /0 (means all IP addresses)
  1900. */
  1901. #define ALLIP4 "0/0"
  1902. /*
  1903. * N.B. IP4 addresses are by Definition 32bit big endian on all platforms
  1904. */
  1905. static void setup_ipaccess()
  1906. {
  1907. char *buf, *ptr, *comma, *slash, *dot;
  1908. int ipcount, mask, octet, i;
  1909. bool writemode;
  1910. buf = malloc(strlen(opt_api_allow) + 1);
  1911. if (unlikely(!buf))
  1912. quit(1, "Failed to malloc ipaccess buf");
  1913. strcpy(buf, opt_api_allow);
  1914. ipcount = 1;
  1915. ptr = buf;
  1916. while (*ptr)
  1917. if (*(ptr++) == ',')
  1918. ipcount++;
  1919. // possibly more than needed, but never less
  1920. ipaccess = calloc(ipcount, sizeof(struct IP4ACCESS));
  1921. if (unlikely(!ipaccess))
  1922. quit(1, "Failed to calloc ipaccess");
  1923. ips = 0;
  1924. ptr = buf;
  1925. while (ptr && *ptr) {
  1926. while (*ptr == ' ' || *ptr == '\t')
  1927. ptr++;
  1928. if (*ptr == ',') {
  1929. ptr++;
  1930. continue;
  1931. }
  1932. comma = strchr(ptr, ',');
  1933. if (comma)
  1934. *(comma++) = '\0';
  1935. writemode = false;
  1936. if (isalpha(*ptr) && *(ptr+1) == ':') {
  1937. if (tolower(*ptr) == 'w')
  1938. writemode = true;
  1939. ptr += 2;
  1940. }
  1941. ipaccess[ips].writemode = writemode;
  1942. if (strcmp(ptr, ALLIP4) == 0)
  1943. ipaccess[ips].ip = ipaccess[ips].mask = 0;
  1944. else {
  1945. slash = strchr(ptr, '/');
  1946. if (!slash)
  1947. ipaccess[ips].mask = 0xffffffff;
  1948. else {
  1949. *(slash++) = '\0';
  1950. mask = atoi(slash);
  1951. if (mask < 1 || mask > 32)
  1952. goto popipo; // skip invalid/zero
  1953. ipaccess[ips].mask = 0;
  1954. while (mask-- >= 0) {
  1955. octet = 1 << (mask % 8);
  1956. ipaccess[ips].mask |= (octet << (8 * (mask >> 3)));
  1957. }
  1958. }
  1959. ipaccess[ips].ip = 0; // missing default to '.0'
  1960. for (i = 0; ptr && (i < 4); i++) {
  1961. dot = strchr(ptr, '.');
  1962. if (dot)
  1963. *(dot++) = '\0';
  1964. octet = atoi(ptr);
  1965. if (octet < 0 || octet > 0xff)
  1966. goto popipo; // skip invalid
  1967. ipaccess[ips].ip |= (octet << (i * 8));
  1968. ptr = dot;
  1969. }
  1970. ipaccess[ips].ip &= ipaccess[ips].mask;
  1971. }
  1972. ips++;
  1973. popipo:
  1974. ptr = comma;
  1975. }
  1976. free(buf);
  1977. }
  1978. static void *quit_thread(__maybe_unused void *userdata)
  1979. {
  1980. // allow thread creator to finish whatever it's doing
  1981. mutex_lock(&quit_restart_lock);
  1982. mutex_unlock(&quit_restart_lock);
  1983. if (opt_debug)
  1984. applog(LOG_DEBUG, "API: killing cgminer");
  1985. kill_work();
  1986. return NULL;
  1987. }
  1988. static void *restart_thread(__maybe_unused void *userdata)
  1989. {
  1990. // allow thread creator to finish whatever it's doing
  1991. mutex_lock(&quit_restart_lock);
  1992. mutex_unlock(&quit_restart_lock);
  1993. if (opt_debug)
  1994. applog(LOG_DEBUG, "API: restarting cgminer");
  1995. app_restart();
  1996. return NULL;
  1997. }
  1998. void api(int api_thr_id)
  1999. {
  2000. struct thr_info bye_thr;
  2001. char buf[TMPBUFSIZ];
  2002. char param_buf[TMPBUFSIZ];
  2003. const char *localaddr = "127.0.0.1";
  2004. SOCKETTYPE c;
  2005. int n, bound;
  2006. char *connectaddr;
  2007. char *binderror;
  2008. time_t bindstart;
  2009. short int port = opt_api_port;
  2010. struct sockaddr_in serv;
  2011. struct sockaddr_in cli;
  2012. socklen_t clisiz;
  2013. char *cmd;
  2014. char *param;
  2015. bool addrok;
  2016. bool writemode;
  2017. json_error_t json_err;
  2018. json_t *json_config;
  2019. json_t *json_val;
  2020. bool isjson;
  2021. bool did;
  2022. int i;
  2023. mutex_init(&quit_restart_lock);
  2024. pthread_cleanup_push(tidyup, NULL);
  2025. my_thr_id = api_thr_id;
  2026. /* This should be done first to ensure curl has already called WSAStartup() in windows */
  2027. sleep(opt_log_interval);
  2028. if (!opt_api_listen) {
  2029. applog(LOG_DEBUG, "API not running%s", UNAVAILABLE);
  2030. return;
  2031. }
  2032. if (opt_api_allow) {
  2033. setup_ipaccess();
  2034. if (ips == 0) {
  2035. applog(LOG_WARNING, "API not running (no valid IPs specified)%s", UNAVAILABLE);
  2036. return;
  2037. }
  2038. }
  2039. sock = socket(AF_INET, SOCK_STREAM, 0);
  2040. if (sock == INVSOCK) {
  2041. applog(LOG_ERR, "API1 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  2042. return;
  2043. }
  2044. memset(&serv, 0, sizeof(serv));
  2045. serv.sin_family = AF_INET;
  2046. if (!opt_api_allow && !opt_api_network) {
  2047. serv.sin_addr.s_addr = inet_addr(localaddr);
  2048. if (serv.sin_addr.s_addr == (in_addr_t)INVINETADDR) {
  2049. applog(LOG_ERR, "API2 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  2050. return;
  2051. }
  2052. }
  2053. serv.sin_port = htons(port);
  2054. // try for more than 1 minute ... in case the old one hasn't completely gone yet
  2055. bound = 0;
  2056. bindstart = time(NULL);
  2057. while (bound == 0) {
  2058. if (SOCKETFAIL(bind(sock, (struct sockaddr *)(&serv), sizeof(serv)))) {
  2059. binderror = SOCKERRMSG;
  2060. if ((time(NULL) - bindstart) > 61)
  2061. break;
  2062. else {
  2063. applog(LOG_WARNING, "API bind to port %d failed - trying again in 30sec", port);
  2064. sleep(30);
  2065. }
  2066. } else
  2067. bound = 1;
  2068. }
  2069. if (bound == 0) {
  2070. applog(LOG_ERR, "API bind to port %d failed (%s)%s", port, binderror, UNAVAILABLE);
  2071. return;
  2072. }
  2073. if (SOCKETFAIL(listen(sock, QUEUE))) {
  2074. applog(LOG_ERR, "API3 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  2075. CLOSESOCKET(sock);
  2076. return;
  2077. }
  2078. if (opt_api_allow)
  2079. applog(LOG_WARNING, "API running in IP access mode");
  2080. else {
  2081. if (opt_api_network)
  2082. applog(LOG_WARNING, "API running in UNRESTRICTED access mode");
  2083. else
  2084. applog(LOG_WARNING, "API running in local access mode");
  2085. }
  2086. io_buffer = malloc(MYBUFSIZ+1);
  2087. msg_buffer = malloc(MYBUFSIZ+1);
  2088. while (!bye) {
  2089. clisiz = sizeof(cli);
  2090. if (SOCKETFAIL(c = accept(sock, (struct sockaddr *)(&cli), &clisiz))) {
  2091. applog(LOG_ERR, "API failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  2092. goto die;
  2093. }
  2094. connectaddr = inet_ntoa(cli.sin_addr);
  2095. addrok = false;
  2096. writemode = false;
  2097. if (opt_api_allow) {
  2098. for (i = 0; i < ips; i++) {
  2099. if ((cli.sin_addr.s_addr & ipaccess[i].mask) == ipaccess[i].ip) {
  2100. addrok = true;
  2101. writemode = ipaccess[i].writemode;
  2102. break;
  2103. }
  2104. }
  2105. } else {
  2106. if (opt_api_network)
  2107. addrok = true;
  2108. else
  2109. addrok = (strcmp(connectaddr, localaddr) == 0);
  2110. }
  2111. if (opt_debug)
  2112. applog(LOG_DEBUG, "API: connection from %s - %s", connectaddr, addrok ? "Accepted" : "Ignored");
  2113. if (addrok) {
  2114. n = recv(c, &buf[0], TMPBUFSIZ-1, 0);
  2115. if (SOCKETFAIL(n))
  2116. buf[0] = '\0';
  2117. else
  2118. buf[n] = '\0';
  2119. if (opt_debug) {
  2120. if (SOCKETFAIL(n))
  2121. applog(LOG_DEBUG, "API: recv failed: %s", SOCKERRMSG);
  2122. else
  2123. applog(LOG_DEBUG, "API: recv command: (%d) '%s'", n, buf);
  2124. }
  2125. if (!SOCKETFAIL(n)) {
  2126. // the time of the request in now
  2127. when = time(NULL);
  2128. did = false;
  2129. if (*buf != ISJSON) {
  2130. isjson = false;
  2131. param = strchr(buf, SEPARATOR);
  2132. if (param != NULL)
  2133. *(param++) = '\0';
  2134. cmd = buf;
  2135. }
  2136. else {
  2137. isjson = true;
  2138. param = NULL;
  2139. #if JANSSON_MAJOR_VERSION > 2 || (JANSSON_MAJOR_VERSION == 2 && JANSSON_MINOR_VERSION > 0)
  2140. json_config = json_loadb(buf, n, 0, &json_err);
  2141. #elif JANSSON_MAJOR_VERSION > 1
  2142. json_config = json_loads(buf, 0, &json_err);
  2143. #else
  2144. json_config = json_loads(buf, &json_err);
  2145. #endif
  2146. if (!json_is_object(json_config)) {
  2147. strcpy(io_buffer, message(MSG_INVJSON, 0, NULL, isjson));
  2148. send_result(c, isjson);
  2149. did = true;
  2150. }
  2151. else {
  2152. json_val = json_object_get(json_config, JSON_COMMAND);
  2153. if (json_val == NULL) {
  2154. strcpy(io_buffer, message(MSG_MISCMD, 0, NULL, isjson));
  2155. send_result(c, isjson);
  2156. did = true;
  2157. }
  2158. else {
  2159. if (!json_is_string(json_val)) {
  2160. strcpy(io_buffer, message(MSG_INVCMD, 0, NULL, isjson));
  2161. send_result(c, isjson);
  2162. did = true;
  2163. }
  2164. else {
  2165. cmd = (char *)json_string_value(json_val);
  2166. json_val = json_object_get(json_config, JSON_PARAMETER);
  2167. if (json_is_string(json_val))
  2168. param = (char *)json_string_value(json_val);
  2169. else if (json_is_integer(json_val)) {
  2170. sprintf(param_buf, "%d", (int)json_integer_value(json_val));
  2171. param = param_buf;
  2172. } else if (json_is_real(json_val)) {
  2173. sprintf(param_buf, "%f", (double)json_real_value(json_val));
  2174. param = param_buf;
  2175. }
  2176. }
  2177. }
  2178. }
  2179. }
  2180. if (!did)
  2181. for (i = 0; cmds[i].name != NULL; i++) {
  2182. if (strcmp(cmd, cmds[i].name) == 0) {
  2183. if (cmds[i].requires_writemode && !writemode) {
  2184. strcpy(io_buffer, message(MSG_ACCDENY, 0, cmds[i].name, isjson));
  2185. applog(LOG_DEBUG, "API: access denied to '%s' for '%s' command", connectaddr, cmds[i].name);
  2186. }
  2187. else
  2188. (cmds[i].func)(c, param, isjson);
  2189. send_result(c, isjson);
  2190. did = true;
  2191. break;
  2192. }
  2193. }
  2194. if (!did) {
  2195. strcpy(io_buffer, message(MSG_INVCMD, 0, NULL, isjson));
  2196. send_result(c, isjson);
  2197. }
  2198. }
  2199. }
  2200. CLOSESOCKET(c);
  2201. }
  2202. die:
  2203. /* Blank line fix for older compilers since pthread_cleanup_pop is a
  2204. * macro that gets confused by a label existing immediately before it
  2205. */
  2206. ;
  2207. pthread_cleanup_pop(true);
  2208. if (opt_debug)
  2209. applog(LOG_DEBUG, "API: terminating due to: %s",
  2210. do_a_quit ? "QUIT" : (do_a_restart ? "RESTART" : (bye ? "BYE" : "UNKNOWN!")));
  2211. mutex_lock(&quit_restart_lock);
  2212. if (do_a_restart) {
  2213. if (thr_info_create(&bye_thr, NULL, restart_thread, &bye_thr)) {
  2214. mutex_unlock(&quit_restart_lock);
  2215. quit(1, "API failed to initiate a restart - aborting");
  2216. }
  2217. pthread_detach(bye_thr.pth);
  2218. } else if (do_a_quit) {
  2219. if (thr_info_create(&bye_thr, NULL, quit_thread, &bye_thr)) {
  2220. mutex_unlock(&quit_restart_lock);
  2221. quit(1, "API failed to initiate a clean quit - aborting");
  2222. }
  2223. pthread_detach(bye_thr.pth);
  2224. }
  2225. mutex_unlock(&quit_restart_lock);
  2226. }