api.c 62 KB

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