api.c 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  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 "device-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 32768 // 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. static const char GPUSEP = ',';
  137. static const char *APIVERSION = "1.5";
  138. static const char *DEAD = "Dead";
  139. static const char *SICK = "Sick";
  140. static const char *NOSTART = "NoStart";
  141. static const char *DISABLED = "Disabled";
  142. static const char *ALIVE = "Alive";
  143. #define _DYNAMIC "D"
  144. static const char *DYNAMIC = _DYNAMIC;
  145. static const char *YES = "Y";
  146. static const char *NO = "N";
  147. #define _DEVS "DEVS"
  148. #define _POOLS "POOLS"
  149. #define _SUMMARY "SUMMARY"
  150. #define _STATUS "STATUS"
  151. #define _VERSION "VERSION"
  152. #define _MINECON "CONFIG"
  153. #define _GPU "GPU"
  154. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  155. #define _PGA "PGA"
  156. #endif
  157. #ifdef WANT_CPUMINE
  158. #define _CPU "CPU"
  159. #endif
  160. #define _GPUS "GPUS"
  161. #define _PGAS "PGAS"
  162. #define _CPUS "CPUS"
  163. #define _BYE "BYE"
  164. static const char ISJSON = '{';
  165. #define JSON0 "{"
  166. #define JSON1 "\""
  167. #define JSON2 "\":["
  168. #define JSON3 "]"
  169. #define JSON4 ",\"id\":1}"
  170. #define JSON_START JSON0
  171. #define JSON_DEVS JSON1 _DEVS JSON2
  172. #define JSON_POOLS JSON1 _POOLS JSON2
  173. #define JSON_SUMMARY JSON1 _SUMMARY JSON2
  174. #define JSON_STATUS JSON1 _STATUS JSON2
  175. #define JSON_VERSION JSON1 _VERSION JSON2
  176. #define JSON_MINECON JSON1 _MINECON JSON2
  177. #define JSON_GPU JSON1 _GPU JSON2
  178. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  179. #define JSON_PGA JSON1 _PGA JSON2
  180. #endif
  181. #ifdef WANT_CPUMINE
  182. #define JSON_CPU JSON1 _CPU JSON2
  183. #endif
  184. #define JSON_GPUS JSON1 _GPUS JSON2
  185. #define JSON_PGAS JSON1 _PGAS JSON2
  186. #define JSON_CPUS JSON1 _CPUS JSON2
  187. #define JSON_BYE JSON1 _BYE JSON1
  188. #define JSON_CLOSE JSON3
  189. #define JSON_END JSON4
  190. static const char *JSON_COMMAND = "command";
  191. static const char *JSON_PARAMETER = "parameter";
  192. #define MSG_INVGPU 1
  193. #define MSG_ALRENA 2
  194. #define MSG_ALRDIS 3
  195. #define MSG_GPUMRE 4
  196. #define MSG_GPUREN 5
  197. #define MSG_GPUNON 6
  198. #define MSG_POOL 7
  199. #define MSG_NOPOOL 8
  200. #define MSG_DEVS 9
  201. #define MSG_NODEVS 10
  202. #define MSG_SUMM 11
  203. #define MSG_GPUDIS 12
  204. #define MSG_GPUREI 13
  205. #define MSG_INVCMD 14
  206. #define MSG_MISID 15
  207. #define MSG_GPUDEV 17
  208. #ifdef WANT_CPUMINE
  209. #define MSG_CPUNON 16
  210. #define MSG_CPUDEV 18
  211. #define MSG_INVCPU 19
  212. #endif
  213. #define MSG_NUMGPU 20
  214. #define MSG_NUMCPU 21
  215. #define MSG_VERSION 22
  216. #define MSG_INVJSON 23
  217. #define MSG_MISCMD 24
  218. #define MSG_MISPID 25
  219. #define MSG_INVPID 26
  220. #define MSG_SWITCHP 27
  221. #define MSG_MISVAL 28
  222. #define MSG_NOADL 29
  223. #define MSG_NOGPUADL 30
  224. #define MSG_INVINT 31
  225. #define MSG_GPUINT 32
  226. #define MSG_MINECON 33
  227. #define MSG_GPUMERR 34
  228. #define MSG_GPUMEM 35
  229. #define MSG_GPUEERR 36
  230. #define MSG_GPUENG 37
  231. #define MSG_GPUVERR 38
  232. #define MSG_GPUVDDC 39
  233. #define MSG_GPUFERR 40
  234. #define MSG_GPUFAN 41
  235. #define MSG_MISFN 42
  236. #define MSG_BADFN 43
  237. #define MSG_SAVED 44
  238. #define MSG_ACCDENY 45
  239. #define MSG_ACCOK 46
  240. #define MSG_ENAPOOL 47
  241. #define MSG_DISPOOL 48
  242. #define MSG_ALRENAP 49
  243. #define MSG_ALRDISP 50
  244. #define MSG_DISLASTP 51
  245. #define MSG_MISPDP 52
  246. #define MSG_INVPDP 53
  247. #define MSG_TOOMANYP 54
  248. #define MSG_ADDPOOL 55
  249. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  250. #define MSG_PGANON 56
  251. #define MSG_PGADEV 57
  252. #define MSG_INVPGA 58
  253. #endif
  254. #define MSG_NUMPGA 59
  255. enum code_severity {
  256. SEVERITY_ERR,
  257. SEVERITY_WARN,
  258. SEVERITY_INFO,
  259. SEVERITY_SUCC,
  260. SEVERITY_FAIL
  261. };
  262. enum code_parameters {
  263. PARAM_GPU,
  264. PARAM_PGA,
  265. PARAM_CPU,
  266. PARAM_GPUMAX,
  267. PARAM_PGAMAX,
  268. PARAM_CPUMAX,
  269. PARAM_PMAX,
  270. PARAM_POOLMAX,
  271. // Single generic case: have the code resolve it - see below
  272. PARAM_DMAX,
  273. PARAM_CMD,
  274. PARAM_POOL,
  275. PARAM_STR,
  276. PARAM_BOTH,
  277. PARAM_NONE
  278. };
  279. struct CODES {
  280. const enum code_severity severity;
  281. const int code;
  282. const enum code_parameters params;
  283. const char *description;
  284. } codes[] = {
  285. { SEVERITY_ERR, MSG_INVGPU, PARAM_GPUMAX, "Invalid GPU id %d - range is 0 - %d" },
  286. { SEVERITY_INFO, MSG_ALRENA, PARAM_GPU, "GPU %d already enabled" },
  287. { SEVERITY_INFO, MSG_ALRDIS, PARAM_GPU, "GPU %d already disabled" },
  288. { SEVERITY_WARN, MSG_GPUMRE, PARAM_GPU, "GPU %d must be restarted first" },
  289. { SEVERITY_INFO, MSG_GPUREN, PARAM_GPU, "GPU %d sent enable message" },
  290. { SEVERITY_ERR, MSG_GPUNON, PARAM_NONE, "No GPUs" },
  291. { SEVERITY_SUCC, MSG_POOL, PARAM_PMAX, "%d Pool(s)" },
  292. { SEVERITY_ERR, MSG_NOPOOL, PARAM_NONE, "No pools" },
  293. { SEVERITY_SUCC, MSG_DEVS, PARAM_DMAX, "%d GPU(s)"
  294. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  295. " - %d PGA(s)"
  296. #endif
  297. #ifdef WANT_CPUMINE
  298. " - %d CPU(s)"
  299. #endif
  300. },
  301. { SEVERITY_ERR, MSG_NODEVS, PARAM_NONE, "No GPUs"
  302. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  303. "/PGAs"
  304. #endif
  305. #ifdef WANT_CPUMINE
  306. "/CPUs"
  307. #endif
  308. },
  309. { SEVERITY_SUCC, MSG_SUMM, PARAM_NONE, "Summary" },
  310. { SEVERITY_INFO, MSG_GPUDIS, PARAM_GPU, "GPU %d set disable flag" },
  311. { SEVERITY_INFO, MSG_GPUREI, PARAM_GPU, "GPU %d restart attempted" },
  312. { SEVERITY_ERR, MSG_INVCMD, PARAM_NONE, "Invalid command" },
  313. { SEVERITY_ERR, MSG_MISID, PARAM_NONE, "Missing device id parameter" },
  314. { SEVERITY_SUCC, MSG_GPUDEV, PARAM_GPU, "GPU%d" },
  315. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  316. { SEVERITY_ERR, MSG_PGANON, PARAM_NONE, "No PGAs" },
  317. { SEVERITY_SUCC, MSG_PGADEV, PARAM_PGA, "PGA%d" },
  318. { SEVERITY_ERR, MSG_INVPGA, PARAM_PGAMAX, "Invalid PGA id %d - range is 0 - %d" },
  319. #endif
  320. #ifdef WANT_CPUMINE
  321. { SEVERITY_ERR, MSG_CPUNON, PARAM_NONE, "No CPUs" },
  322. { SEVERITY_SUCC, MSG_CPUDEV, PARAM_CPU, "CPU%d" },
  323. { SEVERITY_ERR, MSG_INVCPU, PARAM_CPUMAX, "Invalid CPU id %d - range is 0 - %d" },
  324. #endif
  325. { SEVERITY_SUCC, MSG_NUMGPU, PARAM_NONE, "GPU count" },
  326. { SEVERITY_SUCC, MSG_NUMPGA, PARAM_NONE, "PGA count" },
  327. { SEVERITY_SUCC, MSG_NUMCPU, PARAM_NONE, "CPU count" },
  328. { SEVERITY_SUCC, MSG_VERSION, PARAM_NONE, "CGMiner versions" },
  329. { SEVERITY_ERR, MSG_INVJSON, PARAM_NONE, "Invalid JSON" },
  330. { SEVERITY_ERR, MSG_MISCMD, PARAM_CMD, "Missing JSON '%s'" },
  331. { SEVERITY_ERR, MSG_MISPID, PARAM_NONE, "Missing pool id parameter" },
  332. { SEVERITY_ERR, MSG_INVPID, PARAM_POOLMAX, "Invalid pool id %d - range is 0 - %d" },
  333. { SEVERITY_SUCC, MSG_SWITCHP, PARAM_POOL, "Switching to pool %d:'%s'" },
  334. { SEVERITY_ERR, MSG_MISVAL, PARAM_NONE, "Missing comma after GPU number" },
  335. { SEVERITY_ERR, MSG_NOADL, PARAM_NONE, "ADL is not available" },
  336. { SEVERITY_ERR, MSG_NOGPUADL,PARAM_GPU, "GPU %d does not have ADL" },
  337. { SEVERITY_ERR, MSG_INVINT, PARAM_STR, "Invalid intensity (%s) - must be '" _DYNAMIC "' or range " _MIN_INTENSITY_STR " - " _MAX_INTENSITY_STR },
  338. { SEVERITY_INFO, MSG_GPUINT, PARAM_BOTH, "GPU %d set new intensity to %s" },
  339. { SEVERITY_SUCC, MSG_MINECON, PARAM_NONE, "CGMiner config" },
  340. { SEVERITY_ERR, MSG_GPUMERR, PARAM_BOTH, "Setting GPU %d memoryclock to (%s) reported failure" },
  341. { SEVERITY_SUCC, MSG_GPUMEM, PARAM_BOTH, "Setting GPU %d memoryclock to (%s) reported succeess" },
  342. { SEVERITY_ERR, MSG_GPUEERR, PARAM_BOTH, "Setting GPU %d clock to (%s) reported failure" },
  343. { SEVERITY_SUCC, MSG_GPUENG, PARAM_BOTH, "Setting GPU %d clock to (%s) reported succeess" },
  344. { SEVERITY_ERR, MSG_GPUVERR, PARAM_BOTH, "Setting GPU %d vddc to (%s) reported failure" },
  345. { SEVERITY_SUCC, MSG_GPUVDDC, PARAM_BOTH, "Setting GPU %d vddc to (%s) reported succeess" },
  346. { SEVERITY_ERR, MSG_GPUFERR, PARAM_BOTH, "Setting GPU %d fan to (%s) reported failure" },
  347. { SEVERITY_SUCC, MSG_GPUFAN, PARAM_BOTH, "Setting GPU %d fan to (%s) reported succeess" },
  348. { SEVERITY_ERR, MSG_MISFN, PARAM_NONE, "Missing save filename parameter" },
  349. { SEVERITY_ERR, MSG_BADFN, PARAM_STR, "Can't open or create save file '%s'" },
  350. { SEVERITY_ERR, MSG_SAVED, PARAM_STR, "Configuration saved to file '%s'" },
  351. { SEVERITY_ERR, MSG_ACCDENY, PARAM_STR, "Access denied to '%s' command" },
  352. { SEVERITY_SUCC, MSG_ACCOK, PARAM_NONE, "Privileged access OK" },
  353. { SEVERITY_SUCC, MSG_ENAPOOL, PARAM_POOL, "Enabling pool %d:'%s'" },
  354. { SEVERITY_SUCC, MSG_DISPOOL, PARAM_POOL, "Disabling pool %d:'%s'" },
  355. { SEVERITY_INFO, MSG_ALRENAP, PARAM_POOL, "Pool %d:'%s' already enabled" },
  356. { SEVERITY_INFO, MSG_ALRDISP, PARAM_POOL, "Pool %d:'%s' already disabled" },
  357. { SEVERITY_ERR, MSG_DISLASTP,PARAM_POOL, "Cannot disable last active pool %d:'%s'" },
  358. { SEVERITY_ERR, MSG_MISPDP, PARAM_NONE, "Missing addpool details" },
  359. { SEVERITY_ERR, MSG_INVPDP, PARAM_STR, "Invalid addpool details '%s'" },
  360. { SEVERITY_ERR, MSG_TOOMANYP,PARAM_NONE, "Reached maximum number of pools (%d)" },
  361. { SEVERITY_SUCC, MSG_ADDPOOL, PARAM_STR, "Added pool '%s'" },
  362. { SEVERITY_FAIL, 0, 0, NULL }
  363. };
  364. static int my_thr_id = 0;
  365. static int bye = 0;
  366. static bool ping = true;
  367. static time_t when = 0; // when the request occurred
  368. struct IP4ACCESS {
  369. in_addr_t ip;
  370. in_addr_t mask;
  371. bool writemode;
  372. };
  373. static struct IP4ACCESS *ipaccess = NULL;
  374. static int ips = 0;
  375. #ifdef USE_BITFORCE
  376. extern struct device_api bitforce_api;
  377. #endif
  378. #ifdef USE_ICARUS
  379. extern struct device_api icarus_api;
  380. #endif
  381. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  382. static int numpgas()
  383. {
  384. int count = 0;
  385. int i;
  386. for (i = 0; i < total_devices; i++) {
  387. #ifdef USE_BITFORCE
  388. if (devices[i]->api == &bitforce_api)
  389. count++;
  390. #endif
  391. #ifdef USE_ICARUS
  392. if (devices[i]->api == &icarus_api)
  393. count++;
  394. #endif
  395. }
  396. return count;
  397. }
  398. static int pgadevice(int pgaid)
  399. {
  400. int count = 0;
  401. int i;
  402. for (i = 0; i < total_devices; i++) {
  403. #ifdef USE_BITFORCE
  404. if (devices[i]->api == &bitforce_api)
  405. count++;
  406. #endif
  407. #ifdef USE_ICARUS
  408. if (devices[i]->api == &icarus_api)
  409. count++;
  410. #endif
  411. if (count == (pgaid + 1))
  412. return i;
  413. }
  414. return -1;
  415. }
  416. #endif
  417. // All replies (except BYE) start with a message
  418. // thus for JSON, message() inserts JSON_START at the front
  419. // and send_result() adds JSON_END at the end
  420. static char *message(int messageid, int paramid, char *param2, bool isjson)
  421. {
  422. char severity;
  423. char *ptr;
  424. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  425. int pga;
  426. #endif
  427. #ifdef WANT_CPUMINE
  428. int cpu;
  429. #endif
  430. int i;
  431. for (i = 0; codes[i].severity != SEVERITY_FAIL; i++) {
  432. if (codes[i].code == messageid) {
  433. switch (codes[i].severity) {
  434. case SEVERITY_WARN:
  435. severity = 'W';
  436. break;
  437. case SEVERITY_INFO:
  438. severity = 'I';
  439. break;
  440. case SEVERITY_SUCC:
  441. severity = 'S';
  442. break;
  443. case SEVERITY_ERR:
  444. default:
  445. severity = 'E';
  446. break;
  447. }
  448. if (isjson)
  449. sprintf(msg_buffer, JSON_START JSON_STATUS "{\"" _STATUS "\":\"%c\",\"When\":%lu,\"Code\":%d,\"Msg\":\"", severity, (unsigned long)when, messageid);
  450. else
  451. sprintf(msg_buffer, _STATUS "=%c,When=%lu,Code=%d,Msg=", severity, (unsigned long)when, messageid);
  452. ptr = msg_buffer + strlen(msg_buffer);
  453. switch(codes[i].params) {
  454. case PARAM_GPU:
  455. case PARAM_PGA:
  456. case PARAM_CPU:
  457. sprintf(ptr, codes[i].description, paramid);
  458. break;
  459. case PARAM_POOL:
  460. sprintf(ptr, codes[i].description, paramid, pools[paramid]->rpc_url);
  461. break;
  462. case PARAM_GPUMAX:
  463. sprintf(ptr, codes[i].description, paramid, nDevs - 1);
  464. break;
  465. case PARAM_PMAX:
  466. sprintf(ptr, codes[i].description, total_pools);
  467. break;
  468. case PARAM_POOLMAX:
  469. sprintf(ptr, codes[i].description, paramid, total_pools - 1);
  470. break;
  471. case PARAM_DMAX:
  472. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  473. pga = numpgas();
  474. #endif
  475. #ifdef WANT_CPUMINE
  476. if (opt_n_threads > 0)
  477. cpu = num_processors;
  478. else
  479. cpu = 0;
  480. #endif
  481. sprintf(ptr, codes[i].description, nDevs
  482. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  483. , pga
  484. #endif
  485. #ifdef WANT_CPUMINE
  486. , cpu
  487. #endif
  488. );
  489. break;
  490. case PARAM_CMD:
  491. sprintf(ptr, codes[i].description, JSON_COMMAND);
  492. break;
  493. case PARAM_STR:
  494. sprintf(ptr, codes[i].description, param2);
  495. break;
  496. case PARAM_BOTH:
  497. sprintf(ptr, codes[i].description, paramid, param2);
  498. break;
  499. case PARAM_NONE:
  500. default:
  501. strcpy(ptr, codes[i].description);
  502. }
  503. ptr = msg_buffer + strlen(msg_buffer);
  504. if (isjson)
  505. sprintf(ptr, "\",\"Description\":\"%s\"}" JSON_CLOSE, opt_api_description);
  506. else
  507. sprintf(ptr, ",Description=%s%c", opt_api_description, SEPARATOR);
  508. return msg_buffer;
  509. }
  510. }
  511. if (isjson)
  512. sprintf(msg_buffer, JSON_START JSON_STATUS "{\"" _STATUS "\":\"F\",\"When\":%lu,\"Code\":-1,\"Msg\":\"%d\",\"Description\":\"%s\"}" JSON_CLOSE,
  513. (unsigned long)when, messageid, opt_api_description);
  514. else
  515. sprintf(msg_buffer, _STATUS "=F,When=%lu,Code=-1,Msg=%d,Description=%s%c",
  516. (unsigned long)when, messageid, opt_api_description, SEPARATOR);
  517. return msg_buffer;
  518. }
  519. static void apiversion(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  520. {
  521. if (isjson)
  522. sprintf(io_buffer, "%s," JSON_VERSION "{\"CGMiner\":\"%s\",\"API\":\"%s\"}" JSON_CLOSE,
  523. message(MSG_VERSION, 0, NULL, isjson),
  524. VERSION, APIVERSION);
  525. else
  526. sprintf(io_buffer, "%s" _VERSION ",CGMiner=%s,API=%s%c",
  527. message(MSG_VERSION, 0, NULL, isjson),
  528. VERSION, APIVERSION, SEPARATOR);
  529. }
  530. static void minerconfig(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  531. {
  532. char buf[BUFSIZ];
  533. int pgacount = 0;
  534. int cpucount = 0;
  535. char *adlinuse = (char *)NO;
  536. #ifdef HAVE_ADL
  537. const char *adl = YES;
  538. int i;
  539. for (i = 0; i < nDevs; i++) {
  540. if (gpus[i].has_adl) {
  541. adlinuse = (char *)YES;
  542. break;
  543. }
  544. }
  545. #else
  546. const char *adl = NO;
  547. #endif
  548. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  549. pgacount = numpgas();
  550. #endif
  551. #ifdef WANT_CPUMINE
  552. cpucount = opt_n_threads > 0 ? num_processors : 0;
  553. #endif
  554. strcpy(io_buffer, message(MSG_MINECON, 0, NULL, isjson));
  555. if (isjson)
  556. sprintf(buf, "," 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\"}" JSON_CLOSE, nDevs, pgacount, cpucount, total_pools, adl, adlinuse, strategies[pool_strategy].s, opt_log_interval);
  557. else
  558. sprintf(buf, _MINECON ",GPU Count=%d,PGA Count=%d,CPU Count=%d,Pool Count=%d,ADL=%s,ADL in use=%s,Strategy=%s,Log Interval=%d%c", nDevs, pgacount, cpucount, total_pools, adl, adlinuse, strategies[pool_strategy].s, opt_log_interval, SEPARATOR);
  559. strcat(io_buffer, buf);
  560. }
  561. static void gpustatus(int gpu, bool isjson)
  562. {
  563. char intensity[20];
  564. char buf[BUFSIZ];
  565. char *enabled;
  566. char *status;
  567. float gt, gv;
  568. int ga, gf, gp, gc, gm, pt;
  569. if (gpu >= 0 && gpu < nDevs) {
  570. struct cgpu_info *cgpu = &gpus[gpu];
  571. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  572. #ifdef HAVE_ADL
  573. if (!gpu_stats(gpu, &gt, &gc, &gm, &gv, &ga, &gf, &gp, &pt))
  574. #endif
  575. gt = gv = gm = gc = ga = gf = gp = pt = 0;
  576. if (cgpu->deven != DEV_DISABLED)
  577. enabled = (char *)YES;
  578. else
  579. enabled = (char *)NO;
  580. if (cgpu->status == LIFE_DEAD)
  581. status = (char *)DEAD;
  582. else if (cgpu->status == LIFE_SICK)
  583. status = (char *)SICK;
  584. else if (cgpu->status == LIFE_NOSTART)
  585. status = (char *)NOSTART;
  586. else
  587. status = (char *)ALIVE;
  588. if (cgpu->dynamic)
  589. strcpy(intensity, DYNAMIC);
  590. else
  591. sprintf(intensity, "%d", cgpu->intensity);
  592. if (isjson)
  593. sprintf(buf, "{\"GPU\":%d,\"Enabled\":\"%s\",\"Status\":\"%s\",\"Temperature\":%.2f,\"Fan Speed\":%d,\"Fan Percent\":%d,\"GPU Clock\":%d,\"Memory Clock\":%d,\"GPU Voltage\":%.3f,\"GPU Activity\":%d,\"Powertune\":%d,\"MHS av\":%.2f,\"MHS %ds\":%.2f,\"Accepted\":%d,\"Rejected\":%d,\"Hardware Errors\":%d,\"Utility\":%.2f,\"Intensity\":\"%s\",\"Last Share Pool\":%d,\"Last Share Time\":%lu,\"Total MH\":%.4f}",
  594. gpu, enabled, status, gt, gf, gp, gc, gm, gv, ga, pt,
  595. cgpu->total_mhashes / total_secs, opt_log_interval, cgpu->rolling,
  596. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  597. cgpu->utility, intensity,
  598. ((unsigned long)(cgpu->last_share_pool_time) > 0) ? cgpu->last_share_pool : -1,
  599. (unsigned long)(cgpu->last_share_pool_time), cgpu->total_mhashes);
  600. else
  601. sprintf(buf, "GPU=%d,Enabled=%s,Status=%s,Temperature=%.2f,Fan Speed=%d,Fan Percent=%d,GPU Clock=%d,Memory Clock=%d,GPU Voltage=%.3f,GPU Activity=%d,Powertune=%d,MHS av=%.2f,MHS %ds=%.2f,Accepted=%d,Rejected=%d,Hardware Errors=%d,Utility=%.2f,Intensity=%s,Last Share Pool=%d,Last Share Time=%lu,Total MH=%.4f%c",
  602. gpu, enabled, status, gt, gf, gp, gc, gm, gv, ga, pt,
  603. cgpu->total_mhashes / total_secs, opt_log_interval, cgpu->rolling,
  604. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  605. cgpu->utility, intensity,
  606. ((unsigned long)(cgpu->last_share_pool_time) > 0) ? cgpu->last_share_pool : -1,
  607. (unsigned long)(cgpu->last_share_pool_time), cgpu->total_mhashes, SEPARATOR);
  608. strcat(io_buffer, buf);
  609. }
  610. }
  611. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  612. static void pgastatus(int pga, bool isjson)
  613. {
  614. char buf[BUFSIZ];
  615. char *enabled;
  616. char *status;
  617. int numpga = numpgas();
  618. if (numpga > 0 && pga >= 0 && pga < numpga) {
  619. int dev = pgadevice(pga);
  620. if (dev < 0) // Should never happen
  621. return;
  622. struct cgpu_info *cgpu = devices[dev];
  623. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  624. if (cgpu->deven != DEV_DISABLED)
  625. enabled = (char *)YES;
  626. else
  627. enabled = (char *)NO;
  628. if (cgpu->status == LIFE_DEAD)
  629. status = (char *)DEAD;
  630. else if (cgpu->status == LIFE_SICK)
  631. status = (char *)SICK;
  632. else if (cgpu->status == LIFE_NOSTART)
  633. status = (char *)NOSTART;
  634. else
  635. status = (char *)ALIVE;
  636. if (isjson)
  637. sprintf(buf, "{\"PGA\":%d,\"Name\":\"%s\",\"ID\":%d,\"Enabled\":\"%s\",\"Status\":\"%s\",\"Temperature\":%.2f,\"MHS av\":%.2f,\"MHS %ds\":%.2f,\"Accepted\":%d,\"Rejected\":%d,\"Hardware Errors\":%d,\"Utility\":%.2f,\"Last Share Pool\":%d,\"Last Share Time\":%lu,\"Total MH\":%.4f}",
  638. pga, cgpu->api->name, cgpu->device_id,
  639. enabled, status, cgpu->temp,
  640. cgpu->total_mhashes / total_secs, opt_log_interval, cgpu->rolling,
  641. cgpu->accepted, cgpu->rejected, cgpu->hw_errors, cgpu->utility,
  642. ((unsigned long)(cgpu->last_share_pool_time) > 0) ? cgpu->last_share_pool : -1,
  643. (unsigned long)(cgpu->last_share_pool_time), cgpu->total_mhashes);
  644. else
  645. sprintf(buf, "PGA=%d,Name=%s,ID=%d,Enabled=%s,Status=%s,Temperature=%.2f,MHS av=%.2f,MHS %ds=%.2f,Accepted=%d,Rejected=%d,Hardware Errors=%d,Utility=%.2f,Last Share Pool=%d,Last Share Time=%lu,Total MH=%.4f%c",
  646. pga, cgpu->api->name, cgpu->device_id,
  647. enabled, status, cgpu->temp,
  648. cgpu->total_mhashes / total_secs, opt_log_interval, cgpu->rolling,
  649. cgpu->accepted, cgpu->rejected, cgpu->hw_errors, cgpu->utility,
  650. ((unsigned long)(cgpu->last_share_pool_time) > 0) ? cgpu->last_share_pool : -1,
  651. (unsigned long)(cgpu->last_share_pool_time), cgpu->total_mhashes, SEPARATOR);
  652. strcat(io_buffer, buf);
  653. }
  654. }
  655. #endif
  656. #ifdef WANT_CPUMINE
  657. static void cpustatus(int cpu, bool isjson)
  658. {
  659. char buf[BUFSIZ];
  660. if (opt_n_threads > 0 && cpu >= 0 && cpu < num_processors) {
  661. struct cgpu_info *cgpu = &cpus[cpu];
  662. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  663. if (isjson)
  664. sprintf(buf, "{\"CPU\":%d,\"MHS av\":%.2f,\"MHS %ds\":%.2f,\"Accepted\":%d,\"Rejected\":%d,\"Utility\":%.2f,\"Last Share Pool\":%d,\"Last Share Time\":%lu,\"Total MH\":%.4f}",
  665. cpu, cgpu->total_mhashes / total_secs,
  666. opt_log_interval, cgpu->rolling,
  667. cgpu->accepted, cgpu->rejected,
  668. cgpu->utility,
  669. ((unsigned long)(cgpu->last_share_pool_time) > 0) ? cgpu->last_share_pool : -1,
  670. (unsigned long)(cgpu->last_share_pool_time), cgpu->total_mhashes);
  671. else
  672. sprintf(buf, "CPU=%d,MHS av=%.2f,MHS %ds=%.2f,Accepted=%d,Rejected=%d,Utility=%.2f,Last Share Pool=%d,Last Share Time=%lu,Total MH=%.4f%c",
  673. cpu, cgpu->total_mhashes / total_secs,
  674. opt_log_interval, cgpu->rolling,
  675. cgpu->accepted, cgpu->rejected,
  676. cgpu->utility,
  677. ((unsigned long)(cgpu->last_share_pool_time) > 0) ? cgpu->last_share_pool : -1,
  678. (unsigned long)(cgpu->last_share_pool_time), cgpu->total_mhashes, SEPARATOR);
  679. strcat(io_buffer, buf);
  680. }
  681. }
  682. #endif
  683. static void devstatus(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  684. {
  685. int devcount = 0;
  686. int i;
  687. if (nDevs == 0 && opt_n_threads == 0) {
  688. strcpy(io_buffer, message(MSG_NODEVS, 0, NULL, isjson));
  689. return;
  690. }
  691. strcpy(io_buffer, message(MSG_DEVS, 0, NULL, isjson));
  692. if (isjson) {
  693. strcat(io_buffer, COMMA);
  694. strcat(io_buffer, JSON_DEVS);
  695. }
  696. for (i = 0; i < nDevs; i++) {
  697. if (isjson && devcount > 0)
  698. strcat(io_buffer, COMMA);
  699. gpustatus(i, isjson);
  700. devcount++;
  701. }
  702. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  703. int numpga = numpgas();
  704. if (numpga > 0)
  705. for (i = 0; i < numpga; i++) {
  706. if (isjson && devcount > 0)
  707. strcat(io_buffer, COMMA);
  708. pgastatus(i, isjson);
  709. devcount++;
  710. }
  711. #endif
  712. #ifdef WANT_CPUMINE
  713. if (opt_n_threads > 0)
  714. for (i = 0; i < num_processors; i++) {
  715. if (isjson && devcount > 0)
  716. strcat(io_buffer, COMMA);
  717. cpustatus(i, isjson);
  718. devcount++;
  719. }
  720. #endif
  721. if (isjson)
  722. strcat(io_buffer, JSON_CLOSE);
  723. }
  724. static void gpudev(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  725. {
  726. int id;
  727. if (nDevs == 0) {
  728. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  729. return;
  730. }
  731. if (param == NULL || *param == '\0') {
  732. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  733. return;
  734. }
  735. id = atoi(param);
  736. if (id < 0 || id >= nDevs) {
  737. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  738. return;
  739. }
  740. strcpy(io_buffer, message(MSG_GPUDEV, id, NULL, isjson));
  741. if (isjson) {
  742. strcat(io_buffer, COMMA);
  743. strcat(io_buffer, JSON_GPU);
  744. }
  745. gpustatus(id, isjson);
  746. if (isjson)
  747. strcat(io_buffer, JSON_CLOSE);
  748. }
  749. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  750. static void pgadev(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  751. {
  752. int numpga = numpgas();
  753. int id;
  754. if (numpga == 0) {
  755. strcpy(io_buffer, message(MSG_PGANON, 0, NULL, isjson));
  756. return;
  757. }
  758. if (param == NULL || *param == '\0') {
  759. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  760. return;
  761. }
  762. id = atoi(param);
  763. if (id < 0 || id >= numpga) {
  764. strcpy(io_buffer, message(MSG_INVPGA, id, NULL, isjson));
  765. return;
  766. }
  767. strcpy(io_buffer, message(MSG_PGADEV, id, NULL, isjson));
  768. if (isjson) {
  769. strcat(io_buffer, COMMA);
  770. strcat(io_buffer, JSON_PGA);
  771. }
  772. pgastatus(id, isjson);
  773. if (isjson)
  774. strcat(io_buffer, JSON_CLOSE);
  775. }
  776. #endif
  777. #ifdef WANT_CPUMINE
  778. static void cpudev(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  779. {
  780. int id;
  781. if (opt_n_threads == 0) {
  782. strcpy(io_buffer, message(MSG_CPUNON, 0, NULL, isjson));
  783. return;
  784. }
  785. if (param == NULL || *param == '\0') {
  786. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  787. return;
  788. }
  789. id = atoi(param);
  790. if (id < 0 || id >= num_processors) {
  791. strcpy(io_buffer, message(MSG_INVCPU, id, NULL, isjson));
  792. return;
  793. }
  794. strcpy(io_buffer, message(MSG_CPUDEV, id, NULL, isjson));
  795. if (isjson) {
  796. strcat(io_buffer, COMMA);
  797. strcat(io_buffer, JSON_CPU);
  798. }
  799. cpustatus(id, isjson);
  800. if (isjson)
  801. strcat(io_buffer, JSON_CLOSE);
  802. }
  803. #endif
  804. static void poolstatus(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  805. {
  806. char buf[BUFSIZ];
  807. char *status, *lp;
  808. int i;
  809. if (total_pools == 0) {
  810. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  811. return;
  812. }
  813. strcpy(io_buffer, message(MSG_POOL, 0, NULL, isjson));
  814. if (isjson) {
  815. strcat(io_buffer, COMMA);
  816. strcat(io_buffer, JSON_POOLS);
  817. }
  818. for (i = 0; i < total_pools; i++) {
  819. struct pool *pool = pools[i];
  820. if (!pool->enabled)
  821. status = (char *)DISABLED;
  822. else {
  823. if (pool->idle)
  824. status = (char *)DEAD;
  825. else
  826. status = (char *)ALIVE;
  827. }
  828. if (pool->hdr_path)
  829. lp = (char *)YES;
  830. else
  831. lp = (char *)NO;
  832. if (isjson)
  833. sprintf(buf, "%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}",
  834. (i > 0) ? COMMA : "",
  835. i, pool->rpc_url, status, pool->prio, lp,
  836. pool->getwork_requested,
  837. pool->accepted, pool->rejected,
  838. pool->discarded_work,
  839. pool->stale_shares,
  840. pool->getfail_occasions,
  841. pool->remotefail_occasions);
  842. else
  843. sprintf(buf, "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%c",
  844. i, pool->rpc_url, status, pool->prio, lp,
  845. pool->getwork_requested,
  846. pool->accepted, pool->rejected,
  847. pool->discarded_work,
  848. pool->stale_shares,
  849. pool->getfail_occasions,
  850. pool->remotefail_occasions, SEPARATOR);
  851. strcat(io_buffer, buf);
  852. }
  853. if (isjson)
  854. strcat(io_buffer, JSON_CLOSE);
  855. }
  856. static void summary(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  857. {
  858. double utility, mhs;
  859. #ifdef WANT_CPUMINE
  860. char *algo = (char *)(algo_names[opt_algo]);
  861. if (algo == NULL)
  862. algo = "(null)";
  863. #endif
  864. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  865. mhs = total_mhashes_done / total_secs;
  866. #ifdef WANT_CPUMINE
  867. if (isjson)
  868. sprintf(io_buffer, "%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,
  869. message(MSG_SUMM, 0, NULL, isjson),
  870. total_secs, algo, mhs, found_blocks,
  871. total_getworks, total_accepted, total_rejected,
  872. hw_errors, utility, total_discarded, total_stale,
  873. total_go, local_work, total_ro, new_blocks, total_mhashes_done);
  874. else
  875. sprintf(io_buffer, "%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%c",
  876. message(MSG_SUMM, 0, NULL, isjson),
  877. total_secs, algo, mhs, found_blocks,
  878. total_getworks, total_accepted, total_rejected,
  879. hw_errors, utility, total_discarded, total_stale,
  880. total_go, local_work, total_ro, new_blocks, total_mhashes_done, SEPARATOR);
  881. #else
  882. if (isjson)
  883. sprintf(io_buffer, "%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,
  884. message(MSG_SUMM, 0, NULL, isjson),
  885. total_secs, mhs, found_blocks,
  886. total_getworks, total_accepted, total_rejected,
  887. hw_errors, utility, total_discarded, total_stale,
  888. total_go, local_work, total_ro, new_blocks, total_mhashes_done);
  889. else
  890. sprintf(io_buffer, "%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%c",
  891. message(MSG_SUMM, 0, NULL, isjson),
  892. total_secs, mhs, found_blocks,
  893. total_getworks, total_accepted, total_rejected,
  894. hw_errors, utility, total_discarded, total_stale,
  895. total_go, local_work, total_ro, new_blocks, total_mhashes_done, SEPARATOR);
  896. #endif
  897. }
  898. static void gpuenable(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  899. {
  900. struct thr_info *thr;
  901. int gpu;
  902. int id;
  903. int i;
  904. if (gpu_threads == 0) {
  905. strcpy(io_buffer, message(MSG_GPUNON, 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 >= nDevs) {
  914. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  915. return;
  916. }
  917. if (gpus[id].deven != DEV_DISABLED) {
  918. strcpy(io_buffer, message(MSG_ALRENA, id, NULL, isjson));
  919. return;
  920. }
  921. for (i = 0; i < gpu_threads; i++) {
  922. gpu = thr_info[i].cgpu->device_id;
  923. if (gpu == id) {
  924. thr = &thr_info[i];
  925. if (thr->cgpu->status != LIFE_WELL) {
  926. strcpy(io_buffer, message(MSG_GPUMRE, id, NULL, isjson));
  927. return;
  928. }
  929. gpus[id].deven = DEV_ENABLED;
  930. tq_push(thr->q, &ping);
  931. }
  932. }
  933. strcpy(io_buffer, message(MSG_GPUREN, id, NULL, isjson));
  934. }
  935. static void gpudisable(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  936. {
  937. int id;
  938. if (nDevs == 0) {
  939. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  940. return;
  941. }
  942. if (param == NULL || *param == '\0') {
  943. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  944. return;
  945. }
  946. id = atoi(param);
  947. if (id < 0 || id >= nDevs) {
  948. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  949. return;
  950. }
  951. if (gpus[id].deven == DEV_DISABLED) {
  952. strcpy(io_buffer, message(MSG_ALRDIS, id, NULL, isjson));
  953. return;
  954. }
  955. gpus[id].deven = DEV_DISABLED;
  956. strcpy(io_buffer, message(MSG_GPUDIS, id, NULL, isjson));
  957. }
  958. static void gpurestart(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  959. {
  960. int id;
  961. if (nDevs == 0) {
  962. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  963. return;
  964. }
  965. if (param == NULL || *param == '\0') {
  966. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  967. return;
  968. }
  969. id = atoi(param);
  970. if (id < 0 || id >= nDevs) {
  971. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  972. return;
  973. }
  974. reinit_device(&gpus[id]);
  975. strcpy(io_buffer, message(MSG_GPUREI, id, NULL, isjson));
  976. }
  977. static void gpucount(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  978. {
  979. char buf[BUFSIZ];
  980. strcpy(io_buffer, message(MSG_NUMGPU, 0, NULL, isjson));
  981. if (isjson)
  982. sprintf(buf, "," JSON_GPUS "{\"Count\":%d}" JSON_CLOSE, nDevs);
  983. else
  984. sprintf(buf, _GPUS ",Count=%d%c", nDevs, SEPARATOR);
  985. strcat(io_buffer, buf);
  986. }
  987. static void pgacount(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  988. {
  989. char buf[BUFSIZ];
  990. int count = 0;
  991. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  992. count = numpgas();
  993. #endif
  994. strcpy(io_buffer, message(MSG_NUMPGA, 0, NULL, isjson));
  995. if (isjson)
  996. sprintf(buf, "," JSON_PGAS "{\"Count\":%d}" JSON_CLOSE, count);
  997. else
  998. sprintf(buf, _PGAS ",Count=%d%c", count, SEPARATOR);
  999. strcat(io_buffer, buf);
  1000. }
  1001. static void cpucount(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1002. {
  1003. char buf[BUFSIZ];
  1004. int count = 0;
  1005. #ifdef WANT_CPUMINE
  1006. count = opt_n_threads > 0 ? num_processors : 0;
  1007. #endif
  1008. strcpy(io_buffer, message(MSG_NUMCPU, 0, NULL, isjson));
  1009. if (isjson)
  1010. sprintf(buf, "," JSON_CPUS "{\"Count\":%d}" JSON_CLOSE, count);
  1011. else
  1012. sprintf(buf, _CPUS ",Count=%d%c", count, SEPARATOR);
  1013. strcat(io_buffer, buf);
  1014. }
  1015. static void switchpool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1016. {
  1017. struct pool *pool;
  1018. int id;
  1019. if (total_pools == 0) {
  1020. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1021. return;
  1022. }
  1023. if (param == NULL || *param == '\0') {
  1024. strcpy(io_buffer, message(MSG_MISPID, 0, NULL, isjson));
  1025. return;
  1026. }
  1027. id = atoi(param);
  1028. if (id < 0 || id >= total_pools) {
  1029. strcpy(io_buffer, message(MSG_INVPID, id, NULL, isjson));
  1030. return;
  1031. }
  1032. pool = pools[id];
  1033. pool->enabled = true;
  1034. switch_pools(pool);
  1035. strcpy(io_buffer, message(MSG_SWITCHP, id, NULL, isjson));
  1036. }
  1037. static void copyadvanceafter(char ch, char **param, char **buf)
  1038. {
  1039. #define src_p (*param)
  1040. #define dst_b (*buf)
  1041. while (*src_p && *src_p != ch) {
  1042. if (*src_p == '\\' && *(src_p+1) != '\0')
  1043. src_p++;
  1044. *(dst_b++) = *(src_p++);
  1045. }
  1046. if (*src_p)
  1047. src_p++;
  1048. *(dst_b++) = '\0';
  1049. }
  1050. static bool pooldetails(char *param, char **url, char **user, char **pass)
  1051. {
  1052. char *ptr, *buf;
  1053. ptr = buf = malloc(strlen(param)+1);
  1054. if (unlikely(!buf))
  1055. quit(1, "Failed to malloc pooldetails buf");
  1056. *url = buf;
  1057. // copy url
  1058. copyadvanceafter(',', &param, &buf);
  1059. if (!(*param)) // missing user
  1060. goto exitsama;
  1061. *user = buf;
  1062. // copy user
  1063. copyadvanceafter(',', &param, &buf);
  1064. if (!*param) // missing pass
  1065. goto exitsama;
  1066. *pass = buf;
  1067. // copy pass
  1068. copyadvanceafter(',', &param, &buf);
  1069. return true;
  1070. exitsama:
  1071. free(ptr);
  1072. return false;
  1073. }
  1074. static void addpool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1075. {
  1076. char *url, *user, *pass;
  1077. if (param == NULL || *param == '\0') {
  1078. strcpy(io_buffer, message(MSG_MISPDP, 0, NULL, isjson));
  1079. return;
  1080. }
  1081. if (!pooldetails(param, &url, &user, &pass)) {
  1082. strcpy(io_buffer, message(MSG_INVPDP, 0, param, isjson));
  1083. return;
  1084. }
  1085. if (add_pool_details(true, url, user, pass) == ADD_POOL_MAXIMUM) {
  1086. strcpy(io_buffer, message(MSG_TOOMANYP, MAX_POOLS, NULL, isjson));
  1087. return;
  1088. }
  1089. strcpy(io_buffer, message(MSG_ADDPOOL, 0, url, isjson));
  1090. }
  1091. static void enablepool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1092. {
  1093. struct pool *pool;
  1094. int id;
  1095. if (total_pools == 0) {
  1096. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1097. return;
  1098. }
  1099. if (param == NULL || *param == '\0') {
  1100. strcpy(io_buffer, message(MSG_MISPID, 0, NULL, isjson));
  1101. return;
  1102. }
  1103. id = atoi(param);
  1104. if (id < 0 || id >= total_pools) {
  1105. strcpy(io_buffer, message(MSG_INVPID, id, NULL, isjson));
  1106. return;
  1107. }
  1108. pool = pools[id];
  1109. if (pool->enabled == true) {
  1110. strcpy(io_buffer, message(MSG_ALRENAP, id, NULL, isjson));
  1111. return;
  1112. }
  1113. pool->enabled = true;
  1114. if (pool->prio < current_pool()->prio)
  1115. switch_pools(pool);
  1116. strcpy(io_buffer, message(MSG_ENAPOOL, id, NULL, isjson));
  1117. }
  1118. static void disablepool(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1119. {
  1120. struct pool *pool;
  1121. int id;
  1122. if (total_pools == 0) {
  1123. strcpy(io_buffer, message(MSG_NOPOOL, 0, NULL, isjson));
  1124. return;
  1125. }
  1126. if (param == NULL || *param == '\0') {
  1127. strcpy(io_buffer, message(MSG_MISPID, 0, NULL, isjson));
  1128. return;
  1129. }
  1130. id = atoi(param);
  1131. if (id < 0 || id >= total_pools) {
  1132. strcpy(io_buffer, message(MSG_INVPID, id, NULL, isjson));
  1133. return;
  1134. }
  1135. pool = pools[id];
  1136. if (pool->enabled == false) {
  1137. strcpy(io_buffer, message(MSG_ALRDISP, id, NULL, isjson));
  1138. return;
  1139. }
  1140. if (active_pools() <= 1) {
  1141. strcpy(io_buffer, message(MSG_DISLASTP, id, NULL, isjson));
  1142. return;
  1143. }
  1144. pool->enabled = false;
  1145. if (pool == current_pool())
  1146. switch_pools(NULL);
  1147. strcpy(io_buffer, message(MSG_DISPOOL, id, NULL, isjson));
  1148. }
  1149. static bool splitgpuvalue(char *param, int *gpu, char **value, bool isjson)
  1150. {
  1151. int id;
  1152. char *gpusep;
  1153. if (nDevs == 0) {
  1154. strcpy(io_buffer, message(MSG_GPUNON, 0, NULL, isjson));
  1155. return false;
  1156. }
  1157. if (param == NULL || *param == '\0') {
  1158. strcpy(io_buffer, message(MSG_MISID, 0, NULL, isjson));
  1159. return false;
  1160. }
  1161. gpusep = strchr(param, GPUSEP);
  1162. if (gpusep == NULL) {
  1163. strcpy(io_buffer, message(MSG_MISVAL, 0, NULL, isjson));
  1164. return false;
  1165. }
  1166. *(gpusep++) = '\0';
  1167. id = atoi(param);
  1168. if (id < 0 || id >= nDevs) {
  1169. strcpy(io_buffer, message(MSG_INVGPU, id, NULL, isjson));
  1170. return false;
  1171. }
  1172. *gpu = id;
  1173. *value = gpusep;
  1174. return true;
  1175. }
  1176. static void gpuintensity(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1177. {
  1178. int id;
  1179. char *value;
  1180. int intensity;
  1181. char intensitystr[7];
  1182. if (!splitgpuvalue(param, &id, &value, isjson))
  1183. return;
  1184. if (!strncasecmp(value, DYNAMIC, 1)) {
  1185. gpus[id].dynamic = true;
  1186. strcpy(intensitystr, DYNAMIC);
  1187. }
  1188. else {
  1189. intensity = atoi(value);
  1190. if (intensity < MIN_INTENSITY || intensity > MAX_INTENSITY) {
  1191. strcpy(io_buffer, message(MSG_INVINT, 0, value, isjson));
  1192. return;
  1193. }
  1194. gpus[id].dynamic = false;
  1195. gpus[id].intensity = intensity;
  1196. sprintf(intensitystr, "%d", intensity);
  1197. }
  1198. strcpy(io_buffer, message(MSG_GPUINT, id, intensitystr, isjson));
  1199. }
  1200. static void gpumem(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1201. {
  1202. #ifdef HAVE_ADL
  1203. int id;
  1204. char *value;
  1205. int clock;
  1206. if (!splitgpuvalue(param, &id, &value, isjson))
  1207. return;
  1208. clock = atoi(value);
  1209. if (set_memoryclock(id, clock))
  1210. strcpy(io_buffer, message(MSG_GPUMERR, id, value, isjson));
  1211. else
  1212. strcpy(io_buffer, message(MSG_GPUMEM, id, value, isjson));
  1213. #else
  1214. strcpy(io_buffer, message(MSG_NOADL, 0, NULL, isjson));
  1215. #endif
  1216. }
  1217. static void gpuengine(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1218. {
  1219. #ifdef HAVE_ADL
  1220. int id;
  1221. char *value;
  1222. int clock;
  1223. if (!splitgpuvalue(param, &id, &value, isjson))
  1224. return;
  1225. clock = atoi(value);
  1226. if (set_engineclock(id, clock))
  1227. strcpy(io_buffer, message(MSG_GPUEERR, id, value, isjson));
  1228. else
  1229. strcpy(io_buffer, message(MSG_GPUENG, id, value, isjson));
  1230. #else
  1231. strcpy(io_buffer, message(MSG_NOADL, 0, NULL, isjson));
  1232. #endif
  1233. }
  1234. static void gpufan(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1235. {
  1236. #ifdef HAVE_ADL
  1237. int id;
  1238. char *value;
  1239. int fan;
  1240. if (!splitgpuvalue(param, &id, &value, isjson))
  1241. return;
  1242. fan = atoi(value);
  1243. if (set_fanspeed(id, fan))
  1244. strcpy(io_buffer, message(MSG_GPUFERR, id, value, isjson));
  1245. else
  1246. strcpy(io_buffer, message(MSG_GPUFAN, id, value, isjson));
  1247. #else
  1248. strcpy(io_buffer, message(MSG_NOADL, 0, NULL, isjson));
  1249. #endif
  1250. }
  1251. static void gpuvddc(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1252. {
  1253. #ifdef HAVE_ADL
  1254. int id;
  1255. char *value;
  1256. float vddc;
  1257. if (!splitgpuvalue(param, &id, &value, isjson))
  1258. return;
  1259. vddc = atof(value);
  1260. if (set_vddc(id, vddc))
  1261. strcpy(io_buffer, message(MSG_GPUVERR, id, value, isjson));
  1262. else
  1263. strcpy(io_buffer, message(MSG_GPUVDDC, id, value, isjson));
  1264. #else
  1265. strcpy(io_buffer, message(MSG_NOADL, 0, NULL, isjson));
  1266. #endif
  1267. }
  1268. static void send_result(SOCKETTYPE c, bool isjson);
  1269. void doquit(SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1270. {
  1271. if (isjson)
  1272. strcpy(io_buffer, JSON_START JSON_BYE);
  1273. else
  1274. strcpy(io_buffer, _BYE);
  1275. send_result(c, isjson);
  1276. *io_buffer = '\0';
  1277. bye = 1;
  1278. PTH(&thr_info[my_thr_id]) = 0L;
  1279. kill_work();
  1280. }
  1281. void privileged(__maybe_unused SOCKETTYPE c, __maybe_unused char *param, bool isjson)
  1282. {
  1283. strcpy(io_buffer, message(MSG_ACCOK, 0, NULL, isjson));
  1284. }
  1285. void dosave(__maybe_unused SOCKETTYPE c, char *param, bool isjson)
  1286. {
  1287. FILE *fcfg;
  1288. if (param == NULL || *param == '\0') {
  1289. strcpy(io_buffer, message(MSG_MISFN, 0, NULL, isjson));
  1290. return;
  1291. }
  1292. fcfg = fopen(param, "w");
  1293. if (!fcfg) {
  1294. strcpy(io_buffer, message(MSG_BADFN, 0, param, isjson));
  1295. return;
  1296. }
  1297. write_config(fcfg);
  1298. fclose(fcfg);
  1299. strcpy(io_buffer, message(MSG_SAVED, 0, param, isjson));
  1300. }
  1301. struct CMDS {
  1302. char *name;
  1303. void (*func)(SOCKETTYPE, char *, bool);
  1304. bool requires_writemode;
  1305. } cmds[] = {
  1306. { "version", apiversion, false },
  1307. { "config", minerconfig, false },
  1308. { "devs", devstatus, false },
  1309. { "pools", poolstatus, false },
  1310. { "summary", summary, false },
  1311. { "gpuenable", gpuenable, true },
  1312. { "gpudisable", gpudisable, true },
  1313. { "gpurestart", gpurestart, true },
  1314. { "gpu", gpudev, false },
  1315. #if defined(USE_BITFORCE) || defined(USE_ICARUS)
  1316. { "pga", pgadev, false },
  1317. #endif
  1318. #ifdef WANT_CPUMINE
  1319. { "cpu", cpudev, false },
  1320. #endif
  1321. { "gpucount", gpucount, false },
  1322. { "pgacount", pgacount, false },
  1323. { "cpucount", cpucount, false },
  1324. { "switchpool", switchpool, true },
  1325. { "addpool", addpool, true },
  1326. { "enablepool", enablepool, true },
  1327. { "disablepool", disablepool, true },
  1328. { "gpuintensity", gpuintensity, true },
  1329. { "gpumem", gpumem, true },
  1330. { "gpuengine", gpuengine, true },
  1331. { "gpufan", gpufan, true },
  1332. { "gpuvddc", gpuvddc, true },
  1333. { "save", dosave, true },
  1334. { "quit", doquit, true },
  1335. { "privileged", privileged, true },
  1336. { NULL, NULL, false }
  1337. };
  1338. static void send_result(SOCKETTYPE c, bool isjson)
  1339. {
  1340. int n;
  1341. int len;
  1342. if (isjson)
  1343. strcat(io_buffer, JSON_END);
  1344. len = strlen(io_buffer);
  1345. applog(LOG_DEBUG, "API: send reply: (%d) '%.10s%s'", len+1, io_buffer, len > 10 ? "..." : "");
  1346. // ignore failure - it's closed immediately anyway
  1347. n = send(c, io_buffer, len+1, 0);
  1348. if (opt_debug) {
  1349. if (SOCKETFAIL(n))
  1350. applog(LOG_DEBUG, "API: send failed: %s", SOCKERRMSG);
  1351. else
  1352. applog(LOG_DEBUG, "API: sent %d", n);
  1353. }
  1354. }
  1355. static void tidyup()
  1356. {
  1357. bye = 1;
  1358. if (sock != INVSOCK) {
  1359. shutdown(sock, SHUT_RDWR);
  1360. CLOSESOCKET(sock);
  1361. sock = INVSOCK;
  1362. }
  1363. if (ipaccess != NULL) {
  1364. free(ipaccess);
  1365. ipaccess = NULL;
  1366. }
  1367. if (msg_buffer != NULL) {
  1368. free(msg_buffer);
  1369. msg_buffer = NULL;
  1370. }
  1371. if (io_buffer != NULL) {
  1372. free(io_buffer);
  1373. io_buffer = NULL;
  1374. }
  1375. }
  1376. /*
  1377. * Interpret [R|W:]IP[/Prefix][,[R|W:]IP2[/Prefix2][,...]] --api-allow option
  1378. * special case of 0/0 allows /0 (means all IP addresses)
  1379. */
  1380. #define ALLIP4 "0/0"
  1381. /*
  1382. * N.B. IP4 addresses are by Definition 32bit big endian on all platforms
  1383. */
  1384. static void setup_ipaccess()
  1385. {
  1386. char *buf, *ptr, *comma, *slash, *dot;
  1387. int ipcount, mask, octet, i;
  1388. bool writemode;
  1389. buf = malloc(strlen(opt_api_allow) + 1);
  1390. if (unlikely(!buf))
  1391. quit(1, "Failed to malloc ipaccess buf");
  1392. strcpy(buf, opt_api_allow);
  1393. ipcount = 1;
  1394. ptr = buf;
  1395. while (*ptr)
  1396. if (*(ptr++) == ',')
  1397. ipcount++;
  1398. // possibly more than needed, but never less
  1399. ipaccess = calloc(ipcount, sizeof(struct IP4ACCESS));
  1400. if (unlikely(!ipaccess))
  1401. quit(1, "Failed to calloc ipaccess");
  1402. ips = 0;
  1403. ptr = buf;
  1404. while (ptr && *ptr) {
  1405. while (*ptr == ' ' || *ptr == '\t')
  1406. ptr++;
  1407. if (*ptr == ',') {
  1408. ptr++;
  1409. continue;
  1410. }
  1411. comma = strchr(ptr, ',');
  1412. if (comma)
  1413. *(comma++) = '\0';
  1414. writemode = false;
  1415. if (isalpha(*ptr) && *(ptr+1) == ':') {
  1416. if (tolower(*ptr) == 'w')
  1417. writemode = true;
  1418. ptr += 2;
  1419. }
  1420. ipaccess[ips].writemode = writemode;
  1421. if (strcmp(ptr, ALLIP4) == 0)
  1422. ipaccess[ips].ip = ipaccess[ips].mask = 0;
  1423. else {
  1424. slash = strchr(ptr, '/');
  1425. if (!slash)
  1426. ipaccess[ips].mask = 0xffffffff;
  1427. else {
  1428. *(slash++) = '\0';
  1429. mask = atoi(slash);
  1430. if (mask < 1 || mask > 32)
  1431. goto popipo; // skip invalid/zero
  1432. ipaccess[ips].mask = 0;
  1433. while (mask-- >= 0) {
  1434. octet = 1 << (mask % 8);
  1435. ipaccess[ips].mask |= (octet << (8 * (mask >> 3)));
  1436. }
  1437. }
  1438. ipaccess[ips].ip = 0; // missing default to '.0'
  1439. for (i = 0; ptr && (i < 4); i++) {
  1440. dot = strchr(ptr, '.');
  1441. if (dot)
  1442. *(dot++) = '\0';
  1443. octet = atoi(ptr);
  1444. if (octet < 0 || octet > 0xff)
  1445. goto popipo; // skip invalid
  1446. ipaccess[ips].ip |= (octet << (i * 8));
  1447. ptr = dot;
  1448. }
  1449. ipaccess[ips].ip &= ipaccess[ips].mask;
  1450. }
  1451. ips++;
  1452. popipo:
  1453. ptr = comma;
  1454. }
  1455. free(buf);
  1456. }
  1457. void api(int api_thr_id)
  1458. {
  1459. char buf[BUFSIZ];
  1460. char param_buf[BUFSIZ];
  1461. const char *localaddr = "127.0.0.1";
  1462. SOCKETTYPE c;
  1463. int n, bound;
  1464. char *connectaddr;
  1465. char *binderror;
  1466. time_t bindstart;
  1467. short int port = opt_api_port;
  1468. struct sockaddr_in serv;
  1469. struct sockaddr_in cli;
  1470. socklen_t clisiz;
  1471. char *cmd;
  1472. char *param;
  1473. bool addrok;
  1474. bool writemode;
  1475. json_error_t json_err;
  1476. json_t *json_config;
  1477. json_t *json_val;
  1478. bool isjson;
  1479. bool did;
  1480. int i;
  1481. my_thr_id = api_thr_id;
  1482. /* This should be done first to ensure curl has already called WSAStartup() in windows */
  1483. sleep(opt_log_interval);
  1484. if (!opt_api_listen) {
  1485. applog(LOG_DEBUG, "API not running%s", UNAVAILABLE);
  1486. return;
  1487. }
  1488. if (opt_api_allow) {
  1489. setup_ipaccess();
  1490. if (ips == 0) {
  1491. applog(LOG_WARNING, "API not running (no valid IPs specified)%s", UNAVAILABLE);
  1492. return;
  1493. }
  1494. }
  1495. sock = socket(AF_INET, SOCK_STREAM, 0);
  1496. if (sock == INVSOCK) {
  1497. applog(LOG_ERR, "API1 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  1498. return;
  1499. }
  1500. memset(&serv, 0, sizeof(serv));
  1501. serv.sin_family = AF_INET;
  1502. if (!opt_api_allow && !opt_api_network) {
  1503. serv.sin_addr.s_addr = inet_addr(localaddr);
  1504. if (serv.sin_addr.s_addr == (in_addr_t)INVINETADDR) {
  1505. applog(LOG_ERR, "API2 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  1506. return;
  1507. }
  1508. }
  1509. serv.sin_port = htons(port);
  1510. // try for more than 1 minute ... in case the old one hasn't completely gone yet
  1511. bound = 0;
  1512. bindstart = time(NULL);
  1513. while (bound == 0) {
  1514. if (SOCKETFAIL(bind(sock, (struct sockaddr *)(&serv), sizeof(serv)))) {
  1515. binderror = SOCKERRMSG;
  1516. if ((time(NULL) - bindstart) > 61)
  1517. break;
  1518. else {
  1519. applog(LOG_WARNING, "API bind to port %d failed - trying again in 15sec", port);
  1520. sleep(15);
  1521. }
  1522. }
  1523. else
  1524. bound = 1;
  1525. }
  1526. if (bound == 0) {
  1527. applog(LOG_ERR, "API bind to port %d failed (%s)%s", port, binderror, UNAVAILABLE);
  1528. return;
  1529. }
  1530. if (SOCKETFAIL(listen(sock, QUEUE))) {
  1531. applog(LOG_ERR, "API3 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  1532. CLOSESOCKET(sock);
  1533. return;
  1534. }
  1535. if (opt_api_allow)
  1536. applog(LOG_WARNING, "API running in IP access mode");
  1537. else {
  1538. if (opt_api_network)
  1539. applog(LOG_WARNING, "API running in UNRESTRICTED access mode");
  1540. else
  1541. applog(LOG_WARNING, "API running in local access mode");
  1542. }
  1543. io_buffer = malloc(MYBUFSIZ+1);
  1544. msg_buffer = malloc(MYBUFSIZ+1);
  1545. while (bye == 0) {
  1546. clisiz = sizeof(cli);
  1547. if (SOCKETFAIL(c = accept(sock, (struct sockaddr *)(&cli), &clisiz))) {
  1548. applog(LOG_ERR, "API failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  1549. goto die;
  1550. }
  1551. connectaddr = inet_ntoa(cli.sin_addr);
  1552. addrok = false;
  1553. writemode = false;
  1554. if (opt_api_allow) {
  1555. for (i = 0; i < ips; i++) {
  1556. if ((cli.sin_addr.s_addr & ipaccess[i].mask) == ipaccess[i].ip) {
  1557. addrok = true;
  1558. writemode = ipaccess[i].writemode;
  1559. break;
  1560. }
  1561. }
  1562. } else {
  1563. if (opt_api_network)
  1564. addrok = true;
  1565. else
  1566. addrok = (strcmp(connectaddr, localaddr) == 0);
  1567. }
  1568. if (opt_debug)
  1569. applog(LOG_DEBUG, "API: connection from %s - %s", connectaddr, addrok ? "Accepted" : "Ignored");
  1570. if (addrok) {
  1571. n = recv(c, &buf[0], BUFSIZ-1, 0);
  1572. if (SOCKETFAIL(n))
  1573. buf[0] = '\0';
  1574. else
  1575. buf[n] = '\0';
  1576. if (opt_debug) {
  1577. if (SOCKETFAIL(n))
  1578. applog(LOG_DEBUG, "API: recv failed: %s", SOCKERRMSG);
  1579. else
  1580. applog(LOG_DEBUG, "API: recv command: (%d) '%s'", n, buf);
  1581. }
  1582. if (!SOCKETFAIL(n)) {
  1583. // the time of the request in now
  1584. when = time(NULL);
  1585. did = false;
  1586. if (*buf != ISJSON) {
  1587. isjson = false;
  1588. param = strchr(buf, SEPARATOR);
  1589. if (param != NULL)
  1590. *(param++) = '\0';
  1591. cmd = buf;
  1592. }
  1593. else {
  1594. isjson = true;
  1595. param = NULL;
  1596. #if JANSSON_MAJOR_VERSION > 2 || (JANSSON_MAJOR_VERSION == 2 && JANSSON_MINOR_VERSION > 0)
  1597. json_config = json_loadb(buf, n, 0, &json_err);
  1598. #elif JANSSON_MAJOR_VERSION > 1
  1599. json_config = json_loads(buf, 0, &json_err);
  1600. #else
  1601. json_config = json_loads(buf, &json_err);
  1602. #endif
  1603. if (!json_is_object(json_config)) {
  1604. strcpy(io_buffer, message(MSG_INVJSON, 0, NULL, isjson));
  1605. send_result(c, isjson);
  1606. did = true;
  1607. }
  1608. else {
  1609. json_val = json_object_get(json_config, JSON_COMMAND);
  1610. if (json_val == NULL) {
  1611. strcpy(io_buffer, message(MSG_MISCMD, 0, NULL, isjson));
  1612. send_result(c, isjson);
  1613. did = true;
  1614. }
  1615. else {
  1616. if (!json_is_string(json_val)) {
  1617. strcpy(io_buffer, message(MSG_INVCMD, 0, NULL, isjson));
  1618. send_result(c, isjson);
  1619. did = true;
  1620. }
  1621. else {
  1622. cmd = (char *)json_string_value(json_val);
  1623. json_val = json_object_get(json_config, JSON_PARAMETER);
  1624. if (json_is_string(json_val))
  1625. param = (char *)json_string_value(json_val);
  1626. else if (json_is_integer(json_val)) {
  1627. sprintf(param_buf, "%d", (int)json_integer_value(json_val));
  1628. param = param_buf;
  1629. } else if (json_is_real(json_val)) {
  1630. sprintf(param_buf, "%f", (double)json_real_value(json_val));
  1631. param = param_buf;
  1632. }
  1633. }
  1634. }
  1635. }
  1636. }
  1637. if (!did)
  1638. for (i = 0; cmds[i].name != NULL; i++) {
  1639. if (strcmp(cmd, cmds[i].name) == 0) {
  1640. if (cmds[i].requires_writemode && !writemode) {
  1641. strcpy(io_buffer, message(MSG_ACCDENY, 0, cmds[i].name, isjson));
  1642. applog(LOG_DEBUG, "API: access denied to '%s' for '%s' command", connectaddr, cmds[i].name);
  1643. }
  1644. else
  1645. (cmds[i].func)(c, param, isjson);
  1646. send_result(c, isjson);
  1647. did = true;
  1648. break;
  1649. }
  1650. }
  1651. if (!did) {
  1652. strcpy(io_buffer, message(MSG_INVCMD, 0, NULL, isjson));
  1653. send_result(c, isjson);
  1654. }
  1655. }
  1656. }
  1657. CLOSESOCKET(c);
  1658. }
  1659. die:
  1660. tidyup();
  1661. }