api.c 62 KB

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