api.c 63 KB

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