api.c 64 KB

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