api.c 64 KB

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