api.c 65 KB

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