api.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539
  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, "BFGMiner 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, "BFGMiner 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 const char*
  713. bool2str(bool b)
  714. {
  715. return b ? YES : NO;
  716. }
  717. static const char*
  718. status2str(enum alive status)
  719. {
  720. switch (status) {
  721. case LIFE_WELL:
  722. return ALIVE;
  723. case LIFE_SICK:
  724. return SICK;
  725. case LIFE_DEAD:
  726. return DEAD;
  727. case LIFE_NOSTART:
  728. return NOSTART;
  729. default:
  730. return UNKNOWN;
  731. }
  732. }
  733. static void
  734. append_kv(char *buf, json_t*info, bool isjson)
  735. {
  736. json_t *value;
  737. const char *key, *tmpl = isjson ? ",\"%s\":%s" : ",%s=%s";
  738. char *vdump;
  739. void *it;
  740. for (it = json_object_iter(info); it; it = json_object_iter_next(info, it)) {
  741. key = json_object_iter_key(it);
  742. value = json_object_iter_value(it);
  743. if (isjson || !json_is_string(value))
  744. vdump = json_dumps(value, JSON_COMPACT | JSON_ENCODE_ANY);
  745. else
  746. vdump = strdup(json_string_value(value));
  747. tailsprintf(buf, tmpl, key, vdump);
  748. free(vdump);
  749. }
  750. }
  751. static void
  752. devdetail_an(char *buf, struct cgpu_info *cgpu, bool isjson)
  753. {
  754. tailsprintf(buf, isjson
  755. ? "{\"%s\":%d,Driver=%s"
  756. : "%s=%d,Driver=%s",
  757. cgpu->api->name, cgpu->device_id,
  758. cgpu->api->dname
  759. );
  760. if (cgpu->kname)
  761. tailsprintf(buf, isjson ? ",\"Kernel\":\"%s\"" : ",Kernel=%s", cgpu->kname);
  762. if (cgpu->name)
  763. tailsprintf(buf, isjson ? ",\"Model\":\"%s\"" : ",Model=%s", cgpu->name);
  764. if (cgpu->device_path)
  765. tailsprintf(buf, isjson ? ",\"Device Path\":\"%s\"" : ",Device Path=%s", cgpu->device_path);
  766. if (cgpu->api->get_extra_device_detail) {
  767. json_t *info = cgpu->api->get_extra_device_detail(cgpu);
  768. append_kv(buf, info, isjson);
  769. json_decref(info);
  770. }
  771. tailsprintf(buf, "%c", isjson ? '}' : SEPARATOR);
  772. }
  773. static void devstatus_an(char *buf, struct cgpu_info *cgpu, bool isjson)
  774. {
  775. tailsprintf(buf, isjson
  776. ? "{\"%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"
  777. : "%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",
  778. cgpu->api->name, cgpu->device_id,
  779. bool2str(cgpu->deven != DEV_DISABLED),
  780. status2str(cgpu->status),
  781. cgpu->temp,
  782. cgpu->total_mhashes / total_secs, opt_log_interval, cgpu->rolling,
  783. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  784. cgpu->utility,
  785. ((unsigned long)(cgpu->last_share_pool_time) > 0) ? cgpu->last_share_pool : -1,
  786. (unsigned long)(cgpu->last_share_pool_time), cgpu->total_mhashes
  787. );
  788. if (cgpu->api->get_extra_device_status) {
  789. json_t *info = cgpu->api->get_extra_device_status(cgpu);
  790. append_kv(buf, info, isjson);
  791. json_decref(info);
  792. }
  793. tailsprintf(buf, "%c", isjson ? '}' : SEPARATOR);
  794. }
  795. static void gpustatus(int gpu, bool isjson)
  796. {
  797. if (gpu < 0 || gpu >= nDevs)
  798. return;
  799. devstatus_an(io_buffer, &gpus[gpu], isjson);
  800. }
  801. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_ZTEX)
  802. static void pgastatus(int pga, bool isjson)
  803. {
  804. int dev = pgadevice(pga);
  805. if (dev < 0) // Should never happen
  806. return;
  807. devstatus_an(io_buffer, devices[dev], isjson);
  808. }
  809. #endif
  810. __maybe_unused
  811. static void cpustatus(int cpu, bool isjson)
  812. {
  813. if (opt_n_threads <= 0 || cpu < 0 || cpu >= num_processors)
  814. return;
  815. devstatus_an(io_buffer, &cpus[cpu], isjson);
  816. }
  817. static void
  818. devinfo_internal(void (*func)(char*, struct cgpu_info*, bool),
  819. __maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  820. {
  821. int i;
  822. if (total_devices == 0) {
  823. strcpy(io_buffer, message(MSG_NODEVS, 0, NULL, isjson));
  824. return;
  825. }
  826. strcpy(io_buffer, message(MSG_DEVS, 0, NULL, isjson));
  827. if (isjson) {
  828. strcat(io_buffer, COMMA);
  829. strcat(io_buffer, JSON_DEVS);
  830. }
  831. for (i = 0; i < total_devices; ++i) {
  832. if (isjson && i)
  833. strcat(io_buffer, COMMA);
  834. func(io_buffer, devices[i], isjson);
  835. }
  836. if (isjson)
  837. strcat(io_buffer, JSON_CLOSE);
  838. }
  839. static void
  840. devdetail(SOCKETTYPE c, char *param, bool isjson)
  841. {
  842. return devinfo_internal(devdetail_an, c, param, isjson);
  843. }
  844. static void
  845. devstatus(SOCKETTYPE c, char *param, bool isjson)
  846. {
  847. return devinfo_internal(devstatus_an, c, param, isjson);
  848. }
  849. static void gpudev(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  850. {
  851. int id;
  852. if (nDevs == 0) {
  853. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  854. return;
  855. }
  856. if (param == NULL || *param == '\0') {
  857. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  858. return;
  859. }
  860. id = atoi(param);
  861. if (id < 0 || id >= nDevs) {
  862. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  863. return;
  864. }
  865. strcpy(io_buffer, message(MSG_GPUDEV, id, NULL, isjson));
  866. if (isjson) {
  867. strcat(io_buffer, COMMA);
  868. strcat(io_buffer, JSON_GPU);
  869. }
  870. gpustatus(id, isjson);
  871. if (isjson)
  872. strcat(io_buffer, JSON_CLOSE);
  873. }
  874. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_ZTEX)
  875. static void pgadev(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  876. {
  877. int numpga = numpgas();
  878. int id;
  879. if (numpga == 0) {
  880. strcpy(io_buffer, message(MSG_PGANON, 0, NULL, isjson));
  881. return;
  882. }
  883. if (param == NULL || *param == '\0') {
  884. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  885. return;
  886. }
  887. id = atoi(param);
  888. if (id < 0 || id >= numpga) {
  889. strcpy(io_buffer, message(MSG_INVPGA, id, NULL, isjson));
  890. return;
  891. }
  892. strcpy(io_buffer, message(MSG_PGADEV, id, NULL, isjson));
  893. if (isjson) {
  894. strcat(io_buffer, COMMA);
  895. strcat(io_buffer, JSON_PGA);
  896. }
  897. pgastatus(id, isjson);
  898. if (isjson)
  899. strcat(io_buffer, JSON_CLOSE);
  900. }
  901. static void pgaenable(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  902. {
  903. int numpga = numpgas();
  904. struct thr_info *thr;
  905. int pga;
  906. int id;
  907. int i;
  908. if (numpga == 0) {
  909. strcpy(io_buffer, message(MSG_PGANON, 0, NULL, isjson));
  910. return;
  911. }
  912. if (param == NULL || *param == '\0') {
  913. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  914. return;
  915. }
  916. id = atoi(param);
  917. if (id < 0 || id >= numpga) {
  918. strcpy(io_buffer, message(MSG_INVPGA, id, NULL, isjson));
  919. return;
  920. }
  921. int dev = pgadevice(id);
  922. if (dev < 0) { // Should never happen
  923. strcpy(io_buffer, message(MSG_INVPGA, id, NULL, isjson));
  924. return;
  925. }
  926. struct cgpu_info *cgpu = devices[dev];
  927. if (cgpu->deven != DEV_DISABLED) {
  928. strcpy(io_buffer, message(MSG_PGALRENA, id, NULL, isjson));
  929. return;
  930. }
  931. if (cgpu->status != LIFE_WELL) {
  932. strcpy(io_buffer, message(MSG_PGAUNW, id, NULL, isjson));
  933. return;
  934. }
  935. for (i = 0; i < mining_threads; i++) {
  936. pga = thr_info[i].cgpu->device_id;
  937. if (pga == dev) {
  938. thr = &thr_info[i];
  939. cgpu->deven = DEV_ENABLED;
  940. tq_push(thr->q, &ping);
  941. }
  942. }
  943. strcpy(io_buffer, message(MSG_PGAENA, id, NULL, isjson));
  944. }
  945. static void pgadisable(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  946. {
  947. int numpga = numpgas();
  948. int id;
  949. if (numpga == 0) {
  950. strcpy(io_buffer, message(MSG_PGANON, 0, NULL, isjson));
  951. return;
  952. }
  953. if (param == NULL || *param == '\0') {
  954. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  955. return;
  956. }
  957. id = atoi(param);
  958. if (id < 0 || id >= numpga) {
  959. strcpy(io_buffer, message(MSG_INVPGA, id, NULL, isjson));
  960. return;
  961. }
  962. int dev = pgadevice(id);
  963. if (dev < 0) { // Should never happen
  964. strcpy(io_buffer, message(MSG_INVPGA, id, NULL, isjson));
  965. return;
  966. }
  967. struct cgpu_info *cgpu = devices[dev];
  968. if (cgpu->deven == DEV_DISABLED) {
  969. strcpy(io_buffer, message(MSG_PGALRDIS, id, NULL, isjson));
  970. return;
  971. }
  972. cgpu->deven = DEV_DISABLED;
  973. strcpy(io_buffer, message(MSG_PGADIS, id, NULL, isjson));
  974. }
  975. #endif
  976. #ifdef WANT_CPUMINE
  977. static void cpudev(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  978. {
  979. int id;
  980. if (opt_n_threads == 0) {
  981. strcpy(io_buffer, message(MSG_CPUNON, 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 >= num_processors) {
  990. strcpy(io_buffer, message(MSG_INVCPU, id, NULL, isjson));
  991. return;
  992. }
  993. strcpy(io_buffer, message(MSG_CPUDEV, id, NULL, isjson));
  994. if (isjson) {
  995. strcat(io_buffer, COMMA);
  996. strcat(io_buffer, JSON_CPU);
  997. }
  998. cpustatus(id, isjson);
  999. if (isjson)
  1000. strcat(io_buffer, JSON_CLOSE);
  1001. }
  1002. #endif
  1003. static void poolstatus(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1004. {
  1005. char buf[BUFSIZ];
  1006. char *status, *lp;
  1007. char *rpc_url;
  1008. char *rpc_user;
  1009. int i;
  1010. if (total_pools == 0) {
  1011. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1012. return;
  1013. }
  1014. strcpy(io_buffer, message(MSG_POOL, 0, NULL, isjson));
  1015. if (isjson) {
  1016. strcat(io_buffer, COMMA);
  1017. strcat(io_buffer, JSON_POOLS);
  1018. }
  1019. for (i = 0; i < total_pools; i++) {
  1020. struct pool *pool = pools[i];
  1021. switch (pool->enabled) {
  1022. case POOL_DISABLED:
  1023. status = (char *)DISABLED;
  1024. break;
  1025. case POOL_REJECTING:
  1026. status = (char *)REJECTING;
  1027. break;
  1028. case POOL_ENABLED:
  1029. if (pool->idle)
  1030. status = (char *)DEAD;
  1031. else
  1032. status = (char *)ALIVE;
  1033. break;
  1034. default:
  1035. status = (char *)UNKNOWN;
  1036. break;
  1037. }
  1038. if (pool->hdr_path)
  1039. lp = (char *)YES;
  1040. else
  1041. lp = (char *)NO;
  1042. rpc_url = escape_string(pool->rpc_url, isjson);
  1043. rpc_user = escape_string(pool->rpc_user, isjson);
  1044. sprintf(buf, isjson
  1045. ? "%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}"
  1046. : "%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,
  1047. (isjson && (i > 0)) ? COMMA : BLANK,
  1048. i, rpc_url, status, pool->prio, lp,
  1049. pool->getwork_requested,
  1050. pool->accepted, pool->rejected,
  1051. pool->discarded_work,
  1052. pool->stale_shares,
  1053. pool->getfail_occasions,
  1054. pool->remotefail_occasions,
  1055. rpc_user, pool->last_share_time);
  1056. strcat(io_buffer, buf);
  1057. if (rpc_url != pool->rpc_url)
  1058. free(rpc_url);
  1059. rpc_url = NULL;
  1060. if (rpc_user != pool->rpc_user)
  1061. free(rpc_user);
  1062. rpc_user = NULL;
  1063. }
  1064. if (isjson)
  1065. strcat(io_buffer, JSON_CLOSE);
  1066. }
  1067. static void summary(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1068. {
  1069. double utility, mhs;
  1070. #ifdef WANT_CPUMINE
  1071. char *algo = (char *)(algo_names[opt_algo]);
  1072. if (algo == NULL)
  1073. algo = "(null)";
  1074. #endif
  1075. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  1076. mhs = total_mhashes_done / total_secs;
  1077. #ifdef WANT_CPUMINE
  1078. sprintf(io_buffer, isjson
  1079. ? "%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
  1080. : "%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,
  1081. message(MSG_SUMM, 0, NULL, isjson),
  1082. total_secs, algo, mhs, found_blocks,
  1083. total_getworks, total_accepted, total_rejected,
  1084. hw_errors, utility, total_discarded, total_stale,
  1085. total_go, local_work, total_ro, new_blocks, total_mhashes_done);
  1086. #else
  1087. sprintf(io_buffer, isjson
  1088. ? "%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
  1089. : "%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,
  1090. message(MSG_SUMM, 0, NULL, isjson),
  1091. total_secs, mhs, found_blocks,
  1092. total_getworks, total_accepted, total_rejected,
  1093. hw_errors, utility, total_discarded, total_stale,
  1094. total_go, local_work, total_ro, new_blocks, total_mhashes_done);
  1095. #endif
  1096. }
  1097. static void gpuenable(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1098. {
  1099. struct thr_info *thr;
  1100. int gpu;
  1101. int id;
  1102. int i;
  1103. if (gpu_threads == 0) {
  1104. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  1105. return;
  1106. }
  1107. if (param == NULL || *param == '\0') {
  1108. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  1109. return;
  1110. }
  1111. id = atoi(param);
  1112. if (id < 0 || id >= nDevs) {
  1113. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  1114. return;
  1115. }
  1116. if (gpus[id].deven != DEV_DISABLED) {
  1117. strcpy(io_buffer, message(MSG_ALRENA, id, NULL, isjson));
  1118. return;
  1119. }
  1120. for (i = 0; i < gpu_threads; i++) {
  1121. gpu = thr_info[i].cgpu->device_id;
  1122. if (gpu == id) {
  1123. thr = &thr_info[i];
  1124. if (thr->cgpu->status != LIFE_WELL) {
  1125. strcpy(io_buffer, message(MSG_GPUMRE, id, NULL, isjson));
  1126. return;
  1127. }
  1128. gpus[id].deven = DEV_ENABLED;
  1129. tq_push(thr->q, &ping);
  1130. }
  1131. }
  1132. strcpy(io_buffer, message(MSG_GPUREN, id, NULL, isjson));
  1133. }
  1134. static void gpudisable(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1135. {
  1136. int id;
  1137. if (nDevs == 0) {
  1138. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  1139. return;
  1140. }
  1141. if (param == NULL || *param == '\0') {
  1142. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  1143. return;
  1144. }
  1145. id = atoi(param);
  1146. if (id < 0 || id >= nDevs) {
  1147. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  1148. return;
  1149. }
  1150. if (gpus[id].deven == DEV_DISABLED) {
  1151. strcpy(io_buffer, message(MSG_ALRDIS, id, NULL, isjson));
  1152. return;
  1153. }
  1154. gpus[id].deven = DEV_DISABLED;
  1155. strcpy(io_buffer, message(MSG_GPUDIS, id, NULL, isjson));
  1156. }
  1157. static void gpurestart(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1158. {
  1159. int id;
  1160. if (nDevs == 0) {
  1161. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  1162. return;
  1163. }
  1164. if (param == NULL || *param == '\0') {
  1165. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  1166. return;
  1167. }
  1168. id = atoi(param);
  1169. if (id < 0 || id >= nDevs) {
  1170. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  1171. return;
  1172. }
  1173. reinit_device(&gpus[id]);
  1174. strcpy(io_buffer, message(MSG_GPUREI, id, NULL, isjson));
  1175. }
  1176. static void gpucount(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1177. {
  1178. char buf[BUFSIZ];
  1179. strcpy(io_buffer, message(MSG_NUMGPU, 0, NULL, isjson));
  1180. sprintf(buf, isjson
  1181. ? "," JSON_GPUS "{\"Count\":%d}" JSON_CLOSE
  1182. : _GPUS ",Count=%d" SEPSTR,
  1183. nDevs);
  1184. strcat(io_buffer, buf);
  1185. }
  1186. static void pgacount(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1187. {
  1188. char buf[BUFSIZ];
  1189. int count = 0;
  1190. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_ZTEX)
  1191. count = numpgas();
  1192. #endif
  1193. strcpy(io_buffer, message(MSG_NUMPGA, 0, NULL, isjson));
  1194. sprintf(buf, isjson
  1195. ? "," JSON_PGAS "{\"Count\":%d}" JSON_CLOSE
  1196. : _PGAS ",Count=%d" SEPSTR,
  1197. count);
  1198. strcat(io_buffer, buf);
  1199. }
  1200. static void cpucount(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1201. {
  1202. char buf[BUFSIZ];
  1203. int count = 0;
  1204. #ifdef WANT_CPUMINE
  1205. count = opt_n_threads > 0 ? num_processors : 0;
  1206. #endif
  1207. strcpy(io_buffer, message(MSG_NUMCPU, 0, NULL, isjson));
  1208. sprintf(buf, isjson
  1209. ? "," JSON_CPUS "{\"Count\":%d}" JSON_CLOSE
  1210. : _CPUS ",Count=%d" SEPSTR,
  1211. count);
  1212. strcat(io_buffer, buf);
  1213. }
  1214. static void switchpool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1215. {
  1216. struct pool *pool;
  1217. int id;
  1218. if (total_pools == 0) {
  1219. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1220. return;
  1221. }
  1222. if (param == NULL || *param == '\0') {
  1223. strcpy(io_buffer, message(MSG_MISPID, 0, NULL, isjson));
  1224. return;
  1225. }
  1226. id = atoi(param);
  1227. if (id < 0 || id >= total_pools) {
  1228. strcpy(io_buffer, message(MSG_INVPID, id, NULL, isjson));
  1229. return;
  1230. }
  1231. pool = pools[id];
  1232. pool->enabled = true;
  1233. switch_pools(pool);
  1234. strcpy(io_buffer, message(MSG_SWITCHP, id, NULL, isjson));
  1235. }
  1236. static void copyadvanceafter(char ch, char **param, char **buf)
  1237. {
  1238. #define src_p (*param)
  1239. #define dst_b (*buf)
  1240. while (*src_p && *src_p != ch) {
  1241. if (*src_p == '\\' && *(src_p+1) != '\0')
  1242. src_p++;
  1243. *(dst_b++) = *(src_p++);
  1244. }
  1245. if (*src_p)
  1246. src_p++;
  1247. *(dst_b++) = '\0';
  1248. }
  1249. static bool pooldetails(char *param, char **url, char **user, char **pass)
  1250. {
  1251. char *ptr, *buf;
  1252. ptr = buf = malloc(strlen(param)+1);
  1253. if (unlikely(!buf))
  1254. quit(1, "Failed to malloc pooldetails buf");
  1255. *url = buf;
  1256. // copy url
  1257. copyadvanceafter(',', &param, &buf);
  1258. if (!(*param)) // missing user
  1259. goto exitsama;
  1260. *user = buf;
  1261. // copy user
  1262. copyadvanceafter(',', &param, &buf);
  1263. if (!*param) // missing pass
  1264. goto exitsama;
  1265. *pass = buf;
  1266. // copy pass
  1267. copyadvanceafter(',', &param, &buf);
  1268. return true;
  1269. exitsama:
  1270. free(ptr);
  1271. return false;
  1272. }
  1273. static void addpool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1274. {
  1275. char *url, *user, *pass;
  1276. char *ptr;
  1277. if (param == NULL || *param == '\0') {
  1278. strcpy(io_buffer, message(MSG_MISPDP, 0, NULL, isjson));
  1279. return;
  1280. }
  1281. if (!pooldetails(param, &url, &user, &pass)) {
  1282. ptr = escape_string(param, isjson);
  1283. strcpy(io_buffer, message(MSG_INVPDP, 0, ptr, isjson));
  1284. if (ptr != param)
  1285. free(ptr);
  1286. ptr = NULL;
  1287. return;
  1288. }
  1289. if (add_pool_details(true, url, user, pass) == ADD_POOL_MAXIMUM) {
  1290. strcpy(io_buffer, message(MSG_TOOMANYP, MAX_POOLS, NULL, isjson));
  1291. return;
  1292. }
  1293. ptr = escape_string(url, isjson);
  1294. strcpy(io_buffer, message(MSG_ADDPOOL, 0, ptr, isjson));
  1295. if (ptr != url)
  1296. free(ptr);
  1297. ptr = NULL;
  1298. }
  1299. static void enablepool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1300. {
  1301. struct pool *pool;
  1302. int id;
  1303. if (total_pools == 0) {
  1304. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1305. return;
  1306. }
  1307. if (param == NULL || *param == '\0') {
  1308. strcpy(io_buffer, message(MSG_MISPID, 0, NULL, isjson));
  1309. return;
  1310. }
  1311. id = atoi(param);
  1312. if (id < 0 || id >= total_pools) {
  1313. strcpy(io_buffer, message(MSG_INVPID, id, NULL, isjson));
  1314. return;
  1315. }
  1316. pool = pools[id];
  1317. if (pool->enabled == true) {
  1318. strcpy(io_buffer, message(MSG_ALRENAP, id, NULL, isjson));
  1319. return;
  1320. }
  1321. pool->enabled = true;
  1322. if (pool->prio < current_pool()->prio)
  1323. switch_pools(pool);
  1324. strcpy(io_buffer, message(MSG_ENAPOOL, id, NULL, isjson));
  1325. }
  1326. static void disablepool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1327. {
  1328. struct pool *pool;
  1329. int id;
  1330. if (total_pools == 0) {
  1331. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1332. return;
  1333. }
  1334. if (param == NULL || *param == '\0') {
  1335. strcpy(io_buffer, message(MSG_MISPID, 0, NULL, isjson));
  1336. return;
  1337. }
  1338. id = atoi(param);
  1339. if (id < 0 || id >= total_pools) {
  1340. strcpy(io_buffer, message(MSG_INVPID, id, NULL, isjson));
  1341. return;
  1342. }
  1343. pool = pools[id];
  1344. if (pool->enabled == false) {
  1345. strcpy(io_buffer, message(MSG_ALRDISP, id, NULL, isjson));
  1346. return;
  1347. }
  1348. if (active_pools() <= 1) {
  1349. strcpy(io_buffer, message(MSG_DISLASTP, id, NULL, isjson));
  1350. return;
  1351. }
  1352. pool->enabled = false;
  1353. if (pool == current_pool())
  1354. switch_pools(NULL);
  1355. strcpy(io_buffer, message(MSG_DISPOOL, id, NULL, isjson));
  1356. }
  1357. static void removepool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1358. {
  1359. struct pool *pool;
  1360. char *rpc_url;
  1361. bool dofree = false;
  1362. int id;
  1363. if (total_pools == 0) {
  1364. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1365. return;
  1366. }
  1367. if (param == NULL || *param == '\0') {
  1368. strcpy(io_buffer, message(MSG_MISPID, 0, NULL, isjson));
  1369. return;
  1370. }
  1371. id = atoi(param);
  1372. if (id < 0 || id >= total_pools) {
  1373. strcpy(io_buffer, message(MSG_INVPID, id, NULL, isjson));
  1374. return;
  1375. }
  1376. if (total_pools <= 1) {
  1377. strcpy(io_buffer, message(MSG_REMLASTP, id, NULL, isjson));
  1378. return;
  1379. }
  1380. pool = pools[id];
  1381. if (pool == current_pool())
  1382. switch_pools(NULL);
  1383. if (pool == current_pool()) {
  1384. strcpy(io_buffer, message(MSG_ACTPOOL, id, NULL, isjson));
  1385. return;
  1386. }
  1387. pool->enabled = false;
  1388. rpc_url = escape_string(pool->rpc_url, isjson);
  1389. if (rpc_url != pool->rpc_url)
  1390. dofree = true;
  1391. remove_pool(pool);
  1392. strcpy(io_buffer, message(MSG_REMPOOL, id, rpc_url, isjson));
  1393. if (dofree)
  1394. free(rpc_url);
  1395. rpc_url = NULL;
  1396. }
  1397. static bool splitgpuvalue(char *param, int *gpu, char **value, bool isjson)
  1398. {
  1399. int id;
  1400. char *gpusep;
  1401. if (nDevs == 0) {
  1402. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  1403. return false;
  1404. }
  1405. if (param == NULL || *param == '\0') {
  1406. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  1407. return false;
  1408. }
  1409. gpusep = strchr(param, GPUSEP);
  1410. if (gpusep == NULL) {
  1411. strcpy(io_buffer, message(MSG_MISVAL, 0, NULL, isjson));
  1412. return false;
  1413. }
  1414. *(gpusep++) = '\0';
  1415. id = atoi(param);
  1416. if (id < 0 || id >= nDevs) {
  1417. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  1418. return false;
  1419. }
  1420. *gpu = id;
  1421. *value = gpusep;
  1422. return true;
  1423. }
  1424. static void gpuintensity(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1425. {
  1426. int id;
  1427. char *value;
  1428. int intensity;
  1429. char intensitystr[7];
  1430. if (!splitgpuvalue(param, &id, &value, isjson))
  1431. return;
  1432. if (!strncasecmp(value, DYNAMIC, 1)) {
  1433. gpus[id].dynamic = true;
  1434. strcpy(intensitystr, DYNAMIC);
  1435. }
  1436. else {
  1437. intensity = atoi(value);
  1438. if (intensity < MIN_INTENSITY || intensity > MAX_INTENSITY) {
  1439. strcpy(io_buffer, message(MSG_INVINT, 0, value, isjson));
  1440. return;
  1441. }
  1442. gpus[id].dynamic = false;
  1443. gpus[id].intensity = intensity;
  1444. sprintf(intensitystr, "%d", intensity);
  1445. }
  1446. strcpy(io_buffer, message(MSG_GPUINT, id, intensitystr, isjson));
  1447. }
  1448. static void gpumem(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1449. {
  1450. #ifdef HAVE_ADL
  1451. int id;
  1452. char *value;
  1453. int clock;
  1454. if (!splitgpuvalue(param, &id, &value, isjson))
  1455. return;
  1456. clock = atoi(value);
  1457. if (set_memoryclock(id, clock))
  1458. strcpy(io_buffer, message(MSG_GPUMERR, id, value, isjson));
  1459. else
  1460. strcpy(io_buffer, message(MSG_GPUMEM, id, value, isjson));
  1461. #else
  1462. strcpy(io_buffer, message(MSG_NOADL, 0, NULL, isjson));
  1463. #endif
  1464. }
  1465. static void gpuengine(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1466. {
  1467. #ifdef HAVE_ADL
  1468. int id;
  1469. char *value;
  1470. int clock;
  1471. if (!splitgpuvalue(param, &id, &value, isjson))
  1472. return;
  1473. clock = atoi(value);
  1474. if (set_engineclock(id, clock))
  1475. strcpy(io_buffer, message(MSG_GPUEERR, id, value, isjson));
  1476. else
  1477. strcpy(io_buffer, message(MSG_GPUENG, id, value, isjson));
  1478. #else
  1479. strcpy(io_buffer, message(MSG_NOADL, 0, NULL, isjson));
  1480. #endif
  1481. }
  1482. static void gpufan(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1483. {
  1484. #ifdef HAVE_ADL
  1485. int id;
  1486. char *value;
  1487. int fan;
  1488. if (!splitgpuvalue(param, &id, &value, isjson))
  1489. return;
  1490. fan = atoi(value);
  1491. if (set_fanspeed(id, fan))
  1492. strcpy(io_buffer, message(MSG_GPUFERR, id, value, isjson));
  1493. else
  1494. strcpy(io_buffer, message(MSG_GPUFAN, id, value, isjson));
  1495. #else
  1496. strcpy(io_buffer, message(MSG_NOADL, 0, NULL, isjson));
  1497. #endif
  1498. }
  1499. static void gpuvddc(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1500. {
  1501. #ifdef HAVE_ADL
  1502. int id;
  1503. char *value;
  1504. float vddc;
  1505. if (!splitgpuvalue(param, &id, &value, isjson))
  1506. return;
  1507. vddc = atof(value);
  1508. if (set_vddc(id, vddc))
  1509. strcpy(io_buffer, message(MSG_GPUVERR, id, value, isjson));
  1510. else
  1511. strcpy(io_buffer, message(MSG_GPUVDDC, id, value, isjson));
  1512. #else
  1513. strcpy(io_buffer, message(MSG_NOADL, 0, NULL, isjson));
  1514. #endif
  1515. }
  1516. void doquit(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1517. {
  1518. if (isjson)
  1519. strcpy(io_buffer, JSON_START JSON_BYE);
  1520. else
  1521. strcpy(io_buffer, _BYE);
  1522. bye = true;
  1523. do_a_quit = true;
  1524. }
  1525. void dorestart(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1526. {
  1527. if (isjson)
  1528. strcpy(io_buffer, JSON_START JSON_RESTART);
  1529. else
  1530. strcpy(io_buffer, _RESTART);
  1531. bye = true;
  1532. do_a_restart = true;
  1533. }
  1534. void privileged(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1535. {
  1536. strcpy(io_buffer, message(MSG_ACCOK, 0, NULL, isjson));
  1537. }
  1538. void notifystatus(int device, struct cgpu_info *cgpu, bool isjson)
  1539. {
  1540. char buf[BUFSIZ];
  1541. char *reason;
  1542. if (cgpu->device_last_not_well == 0)
  1543. reason = REASON_NONE;
  1544. else
  1545. switch(cgpu->device_not_well_reason) {
  1546. case REASON_THREAD_FAIL_INIT:
  1547. reason = REASON_THREAD_FAIL_INIT_STR;
  1548. break;
  1549. case REASON_THREAD_ZERO_HASH:
  1550. reason = REASON_THREAD_ZERO_HASH_STR;
  1551. break;
  1552. case REASON_THREAD_FAIL_QUEUE:
  1553. reason = REASON_THREAD_FAIL_QUEUE_STR;
  1554. break;
  1555. case REASON_DEV_SICK_IDLE_60:
  1556. reason = REASON_DEV_SICK_IDLE_60_STR;
  1557. break;
  1558. case REASON_DEV_DEAD_IDLE_600:
  1559. reason = REASON_DEV_DEAD_IDLE_600_STR;
  1560. break;
  1561. case REASON_DEV_NOSTART:
  1562. reason = REASON_DEV_NOSTART_STR;
  1563. break;
  1564. case REASON_DEV_OVER_HEAT:
  1565. reason = REASON_DEV_OVER_HEAT_STR;
  1566. break;
  1567. case REASON_DEV_THERMAL_CUTOFF:
  1568. reason = REASON_DEV_THERMAL_CUTOFF_STR;
  1569. break;
  1570. default:
  1571. reason = REASON_UNKNOWN_STR;
  1572. break;
  1573. }
  1574. // ALL counters (and only counters) must start the name with a '*'
  1575. // Simplifies future external support for adding new counters
  1576. sprintf(buf, isjson
  1577. ? "%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}"
  1578. : "%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,
  1579. (isjson && (device > 0)) ? COMMA : BLANK,
  1580. device, cgpu->api->name, cgpu->device_id,
  1581. cgpu->device_last_well, cgpu->device_last_not_well, reason,
  1582. cgpu->thread_fail_init_count, cgpu->thread_zero_hash_count,
  1583. cgpu->thread_fail_queue_count, cgpu->dev_sick_idle_60_count,
  1584. cgpu->dev_dead_idle_600_count, cgpu->dev_nostart_count,
  1585. cgpu->dev_over_heat_count, cgpu->dev_thermal_cutoff_count);
  1586. strcat(io_buffer, buf);
  1587. }
  1588. static void notify(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1589. {
  1590. int i;
  1591. if (total_devices == 0) {
  1592. strcpy(io_buffer, message(MSG_NODEVS, 0, NULL, isjson));
  1593. return;
  1594. }
  1595. strcpy(io_buffer, message(MSG_NOTIFY, 0, NULL, isjson));
  1596. if (isjson) {
  1597. strcat(io_buffer, COMMA);
  1598. strcat(io_buffer, JSON_NOTIFY);
  1599. }
  1600. for (i = 0; i < total_devices; i++)
  1601. notifystatus(i, devices[i], isjson);
  1602. if (isjson)
  1603. strcat(io_buffer, JSON_CLOSE);
  1604. }
  1605. static void devdetails(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1606. {
  1607. char buf[BUFSIZ];
  1608. struct cgpu_info *cgpu;
  1609. int i;
  1610. if (total_devices == 0) {
  1611. strcpy(io_buffer, message(MSG_NODEVS, 0, NULL, isjson));
  1612. return;
  1613. }
  1614. strcpy(io_buffer, message(MSG_DEVDETAILS, 0, NULL, isjson));
  1615. if (isjson) {
  1616. strcat(io_buffer, COMMA);
  1617. strcat(io_buffer, JSON_DEVDETAILS);
  1618. }
  1619. for (i = 0; i < total_devices; i++) {
  1620. cgpu = devices[i];
  1621. sprintf(buf, isjson
  1622. ? "%s{\"DEVDETAILS\":%d,\"Name\":\"%s\",\"ID\":%d,\"Driver\":\"%s\",\"Kernel\":\"%s\",\"Model\":\"%s\",\"Device Path\":\"%s\"}"
  1623. : "%sDEVDETAILS=%d,Name=%s,ID=%d,Driver=%s,Kernel=%s,Model=%s,Device Path=%s" SEPSTR,
  1624. (isjson && (i > 0)) ? COMMA : BLANK,
  1625. i, cgpu->api->name, cgpu->device_id,
  1626. cgpu->api->dname, cgpu->kname ? : BLANK,
  1627. cgpu->name ? : BLANK, cgpu->device_path ? : BLANK);
  1628. strcat(io_buffer, buf);
  1629. }
  1630. if (isjson)
  1631. strcat(io_buffer, JSON_CLOSE);
  1632. }
  1633. void dosave(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1634. {
  1635. FILE *fcfg;
  1636. char *ptr;
  1637. if (param == NULL || *param == '\0') {
  1638. strcpy(io_buffer, message(MSG_MISFN, 0, NULL, isjson));
  1639. return;
  1640. }
  1641. fcfg = fopen(param, "w");
  1642. if (!fcfg) {
  1643. ptr = escape_string(param, isjson);
  1644. strcpy(io_buffer, message(MSG_BADFN, 0, ptr, isjson));
  1645. if (ptr != param)
  1646. free(ptr);
  1647. ptr = NULL;
  1648. return;
  1649. }
  1650. write_config(fcfg);
  1651. fclose(fcfg);
  1652. ptr = escape_string(param, isjson);
  1653. strcpy(io_buffer, message(MSG_SAVED, 0, ptr, isjson));
  1654. if (ptr != param)
  1655. free(ptr);
  1656. ptr = NULL;
  1657. }
  1658. static int itemstats(int i, char *id, struct cgminer_stats *stats, char *extra, bool isjson)
  1659. {
  1660. char buf[BUFSIZ];
  1661. if (stats->getwork_calls || (extra != NULL && *extra))
  1662. {
  1663. if (extra == NULL)
  1664. extra = (char *)BLANK;
  1665. sprintf(buf, isjson
  1666. ? "%s{\"STATS\":%d,\"ID\":\"%s\",\"Elapsed\":%.0f,\"Calls\":%d,\"Wait\":%ld.%06ld,\"Max\":%ld.%06ld,\"Min\":%ld.%06ld%s%s}"
  1667. : "%sSTATS=%d,ID=%s,Elapsed=%.0f,Calls=%d,Wait=%ld.%06ld,Max=%ld.%06ld,Min=%ld.%06ld%s%s" SEPSTR,
  1668. (isjson && (i > 0)) ? COMMA : BLANK,
  1669. i, id, total_secs, stats->getwork_calls,
  1670. stats->getwork_wait.tv_sec, stats->getwork_wait.tv_usec,
  1671. stats->getwork_wait_max.tv_sec, stats->getwork_wait_max.tv_usec,
  1672. stats->getwork_wait_min.tv_sec, stats->getwork_wait_min.tv_usec,
  1673. *extra ? COMMA : BLANK, extra);
  1674. strcat(io_buffer, buf);
  1675. i++;
  1676. }
  1677. return i;
  1678. }
  1679. static void minerstats(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1680. {
  1681. char extra[BUFSIZ];
  1682. char id[20];
  1683. int i, j;
  1684. strcpy(io_buffer, message(MSG_MINESTATS, 0, NULL, isjson));
  1685. if (isjson) {
  1686. strcat(io_buffer, COMMA);
  1687. strcat(io_buffer, JSON_MINESTATS);
  1688. }
  1689. i = 0;
  1690. for (j = 0; j < total_devices; j++) {
  1691. struct cgpu_info *cgpu = devices[j];
  1692. if (cgpu && cgpu->api) {
  1693. if (cgpu->api->get_api_stats)
  1694. cgpu->api->get_api_stats(extra, cgpu, isjson);
  1695. else
  1696. extra[0] = '\0';
  1697. sprintf(id, "%s%d", cgpu->api->name, cgpu->device_id);
  1698. i = itemstats(i, id, &(cgpu->cgminer_stats), extra, isjson);
  1699. }
  1700. }
  1701. for (j = 0; j < total_pools; j++) {
  1702. struct pool *pool = pools[j];
  1703. sprintf(id, "POOL%d", j);
  1704. i = itemstats(i, id, &(pool->cgminer_stats), NULL, isjson);
  1705. }
  1706. if (isjson)
  1707. strcat(io_buffer, JSON_CLOSE);
  1708. }
  1709. struct CMDS {
  1710. char *name;
  1711. void (*func)(SOCKETTYPE, char *, bool);
  1712. bool requires_writemode;
  1713. } cmds[] = {
  1714. { "version", apiversion, false },
  1715. { "config", minerconfig, false },
  1716. { "devs", devstatus, false },
  1717. { "devdetail", devdetail, false },
  1718. { "pools", poolstatus, false },
  1719. { "summary", summary, false },
  1720. { "gpuenable", gpuenable, true },
  1721. { "gpudisable", gpudisable, true },
  1722. { "gpurestart", gpurestart, true },
  1723. { "gpu", gpudev, false },
  1724. #if defined(USE_BITFORCE) || defined(USE_ICARUS) || defined(USE_ZTEX)
  1725. { "pga", pgadev, false },
  1726. { "pgaenable", pgaenable, true },
  1727. { "pgadisable", pgadisable, true },
  1728. #endif
  1729. #ifdef WANT_CPUMINE
  1730. { "cpu", cpudev, false },
  1731. #endif
  1732. { "gpucount", gpucount, false },
  1733. { "pgacount", pgacount, false },
  1734. { "cpucount", cpucount, false },
  1735. { "switchpool", switchpool, true },
  1736. { "addpool", addpool, true },
  1737. { "enablepool", enablepool, true },
  1738. { "disablepool", disablepool, true },
  1739. { "removepool", removepool, true },
  1740. { "gpuintensity", gpuintensity, true },
  1741. { "gpumem", gpumem, true },
  1742. { "gpuengine", gpuengine, true },
  1743. { "gpufan", gpufan, true },
  1744. { "gpuvddc", gpuvddc, true },
  1745. { "save", dosave, true },
  1746. { "quit", doquit, true },
  1747. { "privileged", privileged, true },
  1748. { "notify", notify, false },
  1749. { "devdetails", devdetails, false },
  1750. { "restart", dorestart, true },
  1751. { "stats", minerstats, false },
  1752. { NULL, NULL, false }
  1753. };
  1754. static void send_result(SOCKETTYPE c, bool isjson)
  1755. {
  1756. int n;
  1757. int len;
  1758. if (isjson)
  1759. strcat(io_buffer, JSON_END);
  1760. len = strlen(io_buffer);
  1761. applog(LOG_DEBUG, "API: send reply: (%d) '%.10s%s'", len+1, io_buffer, len > 10 ? "..." : BLANK);
  1762. // ignore failure - it's closed immediately anyway
  1763. n = send(c, io_buffer, len+1, 0);
  1764. if (opt_debug) {
  1765. if (SOCKETFAIL(n))
  1766. applog(LOG_DEBUG, "API: send failed: %s", SOCKERRMSG);
  1767. else
  1768. applog(LOG_DEBUG, "API: sent %d", n);
  1769. }
  1770. }
  1771. static void tidyup(__maybe_unused void *arg)
  1772. {
  1773. mutex_lock(&quit_restart_lock);
  1774. bye = true;
  1775. if (sock != INVSOCK) {
  1776. shutdown(sock, SHUT_RDWR);
  1777. CLOSESOCKET(sock);
  1778. sock = INVSOCK;
  1779. }
  1780. if (ipaccess != NULL) {
  1781. free(ipaccess);
  1782. ipaccess = NULL;
  1783. }
  1784. if (msg_buffer != NULL) {
  1785. free(msg_buffer);
  1786. msg_buffer = NULL;
  1787. }
  1788. if (io_buffer != NULL) {
  1789. free(io_buffer);
  1790. io_buffer = NULL;
  1791. }
  1792. mutex_unlock(&quit_restart_lock);
  1793. }
  1794. /*
  1795. * Interpret [R|W:]IP[/Prefix][,[R|W:]IP2[/Prefix2][,...]] --api-allow option
  1796. * special case of 0/0 allows /0 (means all IP addresses)
  1797. */
  1798. #define ALLIP4 "0/0"
  1799. /*
  1800. * N.B. IP4 addresses are by Definition 32bit big endian on all platforms
  1801. */
  1802. static void setup_ipaccess()
  1803. {
  1804. char *buf, *ptr, *comma, *slash, *dot;
  1805. int ipcount, mask, octet, i;
  1806. bool writemode;
  1807. buf = malloc(strlen(opt_api_allow) + 1);
  1808. if (unlikely(!buf))
  1809. quit(1, "Failed to malloc ipaccess buf");
  1810. strcpy(buf, opt_api_allow);
  1811. ipcount = 1;
  1812. ptr = buf;
  1813. while (*ptr)
  1814. if (*(ptr++) == ',')
  1815. ipcount++;
  1816. // possibly more than needed, but never less
  1817. ipaccess = calloc(ipcount, sizeof(struct IP4ACCESS));
  1818. if (unlikely(!ipaccess))
  1819. quit(1, "Failed to calloc ipaccess");
  1820. ips = 0;
  1821. ptr = buf;
  1822. while (ptr && *ptr) {
  1823. while (*ptr == ' ' || *ptr == '\t')
  1824. ptr++;
  1825. if (*ptr == ',') {
  1826. ptr++;
  1827. continue;
  1828. }
  1829. comma = strchr(ptr, ',');
  1830. if (comma)
  1831. *(comma++) = '\0';
  1832. writemode = false;
  1833. if (isalpha(*ptr) && *(ptr+1) == ':') {
  1834. if (tolower(*ptr) == 'w')
  1835. writemode = true;
  1836. ptr += 2;
  1837. }
  1838. ipaccess[ips].writemode = writemode;
  1839. if (strcmp(ptr, ALLIP4) == 0)
  1840. ipaccess[ips].ip = ipaccess[ips].mask = 0;
  1841. else {
  1842. slash = strchr(ptr, '/');
  1843. if (!slash)
  1844. ipaccess[ips].mask = 0xffffffff;
  1845. else {
  1846. *(slash++) = '\0';
  1847. mask = atoi(slash);
  1848. if (mask < 1 || mask > 32)
  1849. goto popipo; // skip invalid/zero
  1850. ipaccess[ips].mask = 0;
  1851. while (mask-- >= 0) {
  1852. octet = 1 << (mask % 8);
  1853. ipaccess[ips].mask |= (octet << (8 * (mask >> 3)));
  1854. }
  1855. }
  1856. ipaccess[ips].ip = 0; // missing default to '.0'
  1857. for (i = 0; ptr && (i < 4); i++) {
  1858. dot = strchr(ptr, '.');
  1859. if (dot)
  1860. *(dot++) = '\0';
  1861. octet = atoi(ptr);
  1862. if (octet < 0 || octet > 0xff)
  1863. goto popipo; // skip invalid
  1864. ipaccess[ips].ip |= (octet << (i * 8));
  1865. ptr = dot;
  1866. }
  1867. ipaccess[ips].ip &= ipaccess[ips].mask;
  1868. }
  1869. ips++;
  1870. popipo:
  1871. ptr = comma;
  1872. }
  1873. free(buf);
  1874. }
  1875. static void *quit_thread(__maybe_unused void *userdata)
  1876. {
  1877. // allow thread creator to finish whatever it's doing
  1878. mutex_lock(&quit_restart_lock);
  1879. mutex_unlock(&quit_restart_lock);
  1880. if (opt_debug)
  1881. applog(LOG_DEBUG, "API: killing cgminer");
  1882. kill_work();
  1883. return NULL;
  1884. }
  1885. static void *restart_thread(__maybe_unused void *userdata)
  1886. {
  1887. // allow thread creator to finish whatever it's doing
  1888. mutex_lock(&quit_restart_lock);
  1889. mutex_unlock(&quit_restart_lock);
  1890. if (opt_debug)
  1891. applog(LOG_DEBUG, "API: restarting cgminer");
  1892. app_restart();
  1893. return NULL;
  1894. }
  1895. void api(int api_thr_id)
  1896. {
  1897. struct thr_info bye_thr;
  1898. char buf[BUFSIZ];
  1899. char param_buf[BUFSIZ];
  1900. const char *localaddr = "127.0.0.1";
  1901. SOCKETTYPE c;
  1902. int n, bound;
  1903. char *connectaddr;
  1904. char *binderror;
  1905. time_t bindstart;
  1906. short int port = opt_api_port;
  1907. struct sockaddr_in serv;
  1908. struct sockaddr_in cli;
  1909. socklen_t clisiz;
  1910. char *cmd;
  1911. char *param;
  1912. bool addrok;
  1913. bool writemode;
  1914. json_error_t json_err;
  1915. json_t *json_config;
  1916. json_t *json_val;
  1917. bool isjson;
  1918. bool did;
  1919. int i;
  1920. mutex_init(&quit_restart_lock);
  1921. pthread_cleanup_push(tidyup, NULL);
  1922. my_thr_id = api_thr_id;
  1923. /* This should be done first to ensure curl has already called WSAStartup() in windows */
  1924. sleep(opt_log_interval);
  1925. if (!opt_api_listen) {
  1926. applog(LOG_DEBUG, "API not running%s", UNAVAILABLE);
  1927. return;
  1928. }
  1929. if (opt_api_allow) {
  1930. setup_ipaccess();
  1931. if (ips == 0) {
  1932. applog(LOG_WARNING, "API not running (no valid IPs specified)%s", UNAVAILABLE);
  1933. return;
  1934. }
  1935. }
  1936. sock = socket(AF_INET, SOCK_STREAM, 0);
  1937. if (sock == INVSOCK) {
  1938. applog(LOG_ERR, "API1 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  1939. return;
  1940. }
  1941. memset(&serv, 0, sizeof(serv));
  1942. serv.sin_family = AF_INET;
  1943. if (!opt_api_allow && !opt_api_network) {
  1944. serv.sin_addr.s_addr = inet_addr(localaddr);
  1945. if (serv.sin_addr.s_addr == (in_addr_t)INVINETADDR) {
  1946. applog(LOG_ERR, "API2 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  1947. return;
  1948. }
  1949. }
  1950. serv.sin_port = htons(port);
  1951. // try for more than 1 minute ... in case the old one hasn't completely gone yet
  1952. bound = 0;
  1953. bindstart = time(NULL);
  1954. while (bound == 0) {
  1955. if (SOCKETFAIL(bind(sock, (struct sockaddr *)(&serv), sizeof(serv)))) {
  1956. binderror = SOCKERRMSG;
  1957. if ((time(NULL) - bindstart) > 61)
  1958. break;
  1959. else {
  1960. applog(LOG_WARNING, "API bind to port %d failed - trying again in 30sec", port);
  1961. sleep(30);
  1962. }
  1963. } else
  1964. bound = 1;
  1965. }
  1966. if (bound == 0) {
  1967. applog(LOG_ERR, "API bind to port %d failed (%s)%s", port, binderror, UNAVAILABLE);
  1968. return;
  1969. }
  1970. if (SOCKETFAIL(listen(sock, QUEUE))) {
  1971. applog(LOG_ERR, "API3 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  1972. CLOSESOCKET(sock);
  1973. return;
  1974. }
  1975. if (opt_api_allow)
  1976. applog(LOG_WARNING, "API running in IP access mode");
  1977. else {
  1978. if (opt_api_network)
  1979. applog(LOG_WARNING, "API running in UNRESTRICTED access mode");
  1980. else
  1981. applog(LOG_WARNING, "API running in local access mode");
  1982. }
  1983. io_buffer = malloc(MYBUFSIZ+1);
  1984. msg_buffer = malloc(MYBUFSIZ+1);
  1985. while (!bye) {
  1986. clisiz = sizeof(cli);
  1987. if (SOCKETFAIL(c = accept(sock, (struct sockaddr *)(&cli), &clisiz))) {
  1988. applog(LOG_ERR, "API failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  1989. goto die;
  1990. }
  1991. connectaddr = inet_ntoa(cli.sin_addr);
  1992. addrok = false;
  1993. writemode = false;
  1994. if (opt_api_allow) {
  1995. for (i = 0; i < ips; i++) {
  1996. if ((cli.sin_addr.s_addr & ipaccess[i].mask) == ipaccess[i].ip) {
  1997. addrok = true;
  1998. writemode = ipaccess[i].writemode;
  1999. break;
  2000. }
  2001. }
  2002. } else {
  2003. if (opt_api_network)
  2004. addrok = true;
  2005. else
  2006. addrok = (strcmp(connectaddr, localaddr) == 0);
  2007. }
  2008. if (opt_debug)
  2009. applog(LOG_DEBUG, "API: connection from %s - %s", connectaddr, addrok ? "Accepted" : "Ignored");
  2010. if (addrok) {
  2011. n = recv(c, &buf[0], BUFSIZ-1, 0);
  2012. if (SOCKETFAIL(n))
  2013. buf[0] = '\0';
  2014. else
  2015. buf[n] = '\0';
  2016. if (opt_debug) {
  2017. if (SOCKETFAIL(n))
  2018. applog(LOG_DEBUG, "API: recv failed: %s", SOCKERRMSG);
  2019. else
  2020. applog(LOG_DEBUG, "API: recv command: (%d) '%s'", n, buf);
  2021. }
  2022. if (!SOCKETFAIL(n)) {
  2023. // the time of the request in now
  2024. when = time(NULL);
  2025. did = false;
  2026. if (*buf != ISJSON) {
  2027. isjson = false;
  2028. param = strchr(buf, SEPARATOR);
  2029. if (param != NULL)
  2030. *(param++) = '\0';
  2031. cmd = buf;
  2032. }
  2033. else {
  2034. isjson = true;
  2035. param = NULL;
  2036. #if JANSSON_MAJOR_VERSION > 2 || (JANSSON_MAJOR_VERSION == 2 && JANSSON_MINOR_VERSION > 0)
  2037. json_config = json_loadb(buf, n, 0, &json_err);
  2038. #elif JANSSON_MAJOR_VERSION > 1
  2039. json_config = json_loads(buf, 0, &json_err);
  2040. #else
  2041. json_config = json_loads(buf, &json_err);
  2042. #endif
  2043. if (!json_is_object(json_config)) {
  2044. strcpy(io_buffer, message(MSG_INVJSON, 0, NULL, isjson));
  2045. send_result(c, isjson);
  2046. did = true;
  2047. }
  2048. else {
  2049. json_val = json_object_get(json_config, JSON_COMMAND);
  2050. if (json_val == NULL) {
  2051. strcpy(io_buffer, message(MSG_MISCMD, 0, NULL, isjson));
  2052. send_result(c, isjson);
  2053. did = true;
  2054. }
  2055. else {
  2056. if (!json_is_string(json_val)) {
  2057. strcpy(io_buffer, message(MSG_INVCMD, 0, NULL, isjson));
  2058. send_result(c, isjson);
  2059. did = true;
  2060. }
  2061. else {
  2062. cmd = (char *)json_string_value(json_val);
  2063. json_val = json_object_get(json_config, JSON_PARAMETER);
  2064. if (json_is_string(json_val))
  2065. param = (char *)json_string_value(json_val);
  2066. else if (json_is_integer(json_val)) {
  2067. sprintf(param_buf, "%d", (int)json_integer_value(json_val));
  2068. param = param_buf;
  2069. } else if (json_is_real(json_val)) {
  2070. sprintf(param_buf, "%f", (double)json_real_value(json_val));
  2071. param = param_buf;
  2072. }
  2073. }
  2074. }
  2075. }
  2076. }
  2077. if (!did)
  2078. for (i = 0; cmds[i].name != NULL; i++) {
  2079. if (strcmp(cmd, cmds[i].name) == 0) {
  2080. if (cmds[i].requires_writemode && !writemode) {
  2081. strcpy(io_buffer, message(MSG_ACCDENY, 0, cmds[i].name, isjson));
  2082. applog(LOG_DEBUG, "API: access denied to '%s' for '%s' command", connectaddr, cmds[i].name);
  2083. }
  2084. else
  2085. (cmds[i].func)(c, param, isjson);
  2086. send_result(c, isjson);
  2087. did = true;
  2088. break;
  2089. }
  2090. }
  2091. if (!did) {
  2092. strcpy(io_buffer, message(MSG_INVCMD, 0, NULL, isjson));
  2093. send_result(c, isjson);
  2094. }
  2095. }
  2096. }
  2097. CLOSESOCKET(c);
  2098. }
  2099. die:
  2100. /* Blank line fix for older compilers since pthread_cleanup_pop is a
  2101. * macro that gets confused by a label existing immediately before it
  2102. */
  2103. ;
  2104. pthread_cleanup_pop(true);
  2105. if (opt_debug)
  2106. applog(LOG_DEBUG, "API: terminating due to: %s",
  2107. do_a_quit ? "QUIT" : (do_a_restart ? "RESTART" : (bye ? "BYE" : "UNKNOWN!")));
  2108. mutex_lock(&quit_restart_lock);
  2109. if (do_a_restart) {
  2110. if (thr_info_create(&bye_thr, NULL, restart_thread, &bye_thr)) {
  2111. mutex_unlock(&quit_restart_lock);
  2112. quit(1, "API failed to initiate a restart - aborting");
  2113. }
  2114. pthread_detach(bye_thr.pth);
  2115. } else if (do_a_quit) {
  2116. if (thr_info_create(&bye_thr, NULL, quit_thread, &bye_thr)) {
  2117. mutex_unlock(&quit_restart_lock);
  2118. quit(1, "API failed to initiate a clean quit - aborting");
  2119. }
  2120. pthread_detach(bye_thr.pth);
  2121. }
  2122. mutex_unlock(&quit_restart_lock);
  2123. }