api.c 60 KB

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