api.c 62 KB

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