api.c 61 KB

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