api.c 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046
  1. /*
  2. * Copyright 2011 Andrew Smith
  3. * Copyright 2011 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 2 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. #include <string.h>
  14. #include <stdbool.h>
  15. #include <stdint.h>
  16. #include <unistd.h>
  17. #include <sys/types.h>
  18. #include "compat.h"
  19. #include "miner.h"
  20. #if defined(unix)
  21. #include <errno.h>
  22. #include <sys/socket.h>
  23. #include <netinet/in.h>
  24. #include <arpa/inet.h>
  25. #define SOCKETTYPE int
  26. #define SOCKETFAIL(a) ((a) < 0)
  27. #define INVSOCK -1
  28. #define INVINETADDR -1
  29. #define CLOSESOCKET close
  30. #define SOCKERRMSG strerror(errno)
  31. #endif
  32. #ifdef WIN32
  33. #include <winsock2.h>
  34. #define SOCKETTYPE SOCKET
  35. #define SOCKETFAIL(a) ((a) == SOCKET_ERROR)
  36. #define INVSOCK INVALID_SOCKET
  37. #define INVINETADDR INADDR_NONE
  38. #define CLOSESOCKET closesocket
  39. static char WSAbuf[1024];
  40. struct WSAERRORS {
  41. int id;
  42. char *code;
  43. } WSAErrors[] = {
  44. { 0, "No error" },
  45. { WSAEINTR, "Interrupted system call" },
  46. { WSAEBADF, "Bad file number" },
  47. { WSAEACCES, "Permission denied" },
  48. { WSAEFAULT, "Bad address" },
  49. { WSAEINVAL, "Invalid argument" },
  50. { WSAEMFILE, "Too many open sockets" },
  51. { WSAEWOULDBLOCK, "Operation would block" },
  52. { WSAEINPROGRESS, "Operation now in progress" },
  53. { WSAEALREADY, "Operation already in progress" },
  54. { WSAENOTSOCK, "Socket operation on non-socket" },
  55. { WSAEDESTADDRREQ, "Destination address required" },
  56. { WSAEMSGSIZE, "Message too long" },
  57. { WSAEPROTOTYPE, "Protocol wrong type for socket" },
  58. { WSAENOPROTOOPT, "Bad protocol option" },
  59. { WSAEPROTONOSUPPORT, "Protocol not supported" },
  60. { WSAESOCKTNOSUPPORT, "Socket type not supported" },
  61. { WSAEOPNOTSUPP, "Operation not supported on socket" },
  62. { WSAEPFNOSUPPORT, "Protocol family not supported" },
  63. { WSAEAFNOSUPPORT, "Address family not supported" },
  64. { WSAEADDRINUSE, "Address already in use" },
  65. { WSAEADDRNOTAVAIL, "Can't assign requested address" },
  66. { WSAENETDOWN, "Network is down" },
  67. { WSAENETUNREACH, "Network is unreachable" },
  68. { WSAENETRESET, "Net connection reset" },
  69. { WSAECONNABORTED, "Software caused connection abort" },
  70. { WSAECONNRESET, "Connection reset by peer" },
  71. { WSAENOBUFS, "No buffer space available" },
  72. { WSAEISCONN, "Socket is already connected" },
  73. { WSAENOTCONN, "Socket is not connected" },
  74. { WSAESHUTDOWN, "Can't send after socket shutdown" },
  75. { WSAETOOMANYREFS, "Too many references, can't splice" },
  76. { WSAETIMEDOUT, "Connection timed out" },
  77. { WSAECONNREFUSED, "Connection refused" },
  78. { WSAELOOP, "Too many levels of symbolic links" },
  79. { WSAENAMETOOLONG, "File name too long" },
  80. { WSAEHOSTDOWN, "Host is down" },
  81. { WSAEHOSTUNREACH, "No route to host" },
  82. { WSAENOTEMPTY, "Directory not empty" },
  83. { WSAEPROCLIM, "Too many processes" },
  84. { WSAEUSERS, "Too many users" },
  85. { WSAEDQUOT, "Disc quota exceeded" },
  86. { WSAESTALE, "Stale NFS file handle" },
  87. { WSAEREMOTE, "Too many levels of remote in path" },
  88. { WSASYSNOTREADY, "Network system is unavailable" },
  89. { WSAVERNOTSUPPORTED, "Winsock version out of range" },
  90. { WSANOTINITIALISED, "WSAStartup not yet called" },
  91. { WSAEDISCON, "Graceful shutdown in progress" },
  92. { WSAHOST_NOT_FOUND, "Host not found" },
  93. { WSANO_DATA, "No host data of that type was found" },
  94. { -1, "Unknown error code" }
  95. };
  96. static char *WSAErrorMsg()
  97. {
  98. char *msg;
  99. int i;
  100. int id = WSAGetLastError();
  101. /* Assume none of them are actually -1 */
  102. for (i = 0; WSAErrors[i].id != -1; i++)
  103. if (WSAErrors[i].id == id)
  104. break;
  105. sprintf(WSAbuf, "Socket Error: (%d) %s", id, WSAErrors[i].code);
  106. return &(WSAbuf[0]);
  107. }
  108. #define SOCKERRMSG WSAErrorMsg()
  109. #ifndef SHUT_RDWR
  110. #define SHUT_RDWR SD_BOTH
  111. #endif
  112. #endif
  113. // Big enough for largest API request
  114. // though a PC with 100s of CPUs may exceed the size ...
  115. // Current code assumes it can socket send this size also
  116. #define MYBUFSIZ 32768
  117. // Number of requests to queue - normally would be small
  118. #define QUEUE 10
  119. static char *io_buffer = NULL;
  120. static char *msg_buffer = NULL;
  121. static SOCKETTYPE sock = INVSOCK;
  122. static const char *UNAVAILABLE = " - API will not be available";
  123. //static const char *BLANK = "";
  124. static const char *COMMA = ",";
  125. static const char SEPARATOR = '|';
  126. #define _DEVS "DEVS"
  127. #define _POOLS "POOLS"
  128. #define _SUMMARY "SUMMARY"
  129. #define _STATUS "STATUS"
  130. #define _VERSION "VERSION"
  131. #define _CPU "CPU"
  132. #define _GPU "GPU"
  133. #define _CPUS "CPUS"
  134. #define _GPUS "GPUS"
  135. #define _BYE "BYE"
  136. static const char ISJSON = '{';
  137. #define JSON0 "{"
  138. #define JSON1 "\""
  139. #define JSON2 "\":["
  140. #define JSON3 "]"
  141. #define JSON4 ",\"id\":1}"
  142. #define JSON_START JSON0
  143. #define JSON_DEVS JSON1 _DEVS JSON2
  144. #define JSON_POOLS JSON1 _POOLS JSON2
  145. #define JSON_SUMMARY JSON1 _SUMMARY JSON2
  146. #define JSON_STATUS JSON1 _STATUS JSON2
  147. #define JSON_VERSION JSON1 _VERSION JSON2
  148. #define JSON_GPU JSON1 _GPU JSON2
  149. #define JSON_CPU JSON1 _CPU JSON2
  150. #define JSON_GPUS JSON1 _GPUS JSON2
  151. #define JSON_CPUS JSON1 _CPUS JSON2
  152. #define JSON_BYE JSON1 _BYE JSON1
  153. #define JSON_CLOSE JSON3
  154. #define JSON_END JSON4
  155. static const char *JSON_COMMAND = "command";
  156. static const char *JSON_PARAMETER = "parameter";
  157. #define MSG_INVGPU 1
  158. #define MSG_ALRENA 2
  159. #define MSG_ALRDIS 3
  160. #define MSG_GPUMRE 4
  161. #define MSG_GPUREN 5
  162. #define MSG_GPUNON 6
  163. #define MSG_POOL 7
  164. #define MSG_NOPOOL 8
  165. #define MSG_DEVS 9
  166. #define MSG_NODEVS 10
  167. #define MSG_SUMM 11
  168. #define MSG_GPUDIS 12
  169. #define MSG_GPUREI 13
  170. #define MSG_INVCMD 14
  171. #define MSG_MISID 15
  172. #define MSG_CPUNON 16
  173. #define MSG_GPUDEV 17
  174. #define MSG_CPUDEV 18
  175. #define MSG_INVCPU 19
  176. #define MSG_NUMGPU 20
  177. #define MSG_NUMCPU 21
  178. #define MSG_VERSION 22
  179. #define MSG_INVJSON 23
  180. #define MSG_MISSCMD 24
  181. enum code_severity {
  182. SEVERITY_ERR,
  183. SEVERITY_WARN,
  184. SEVERITY_INFO,
  185. SEVERITY_SUCC,
  186. SEVERITY_FAIL
  187. };
  188. enum code_parameters {
  189. PARAM_GPU,
  190. PARAM_CPU,
  191. PARAM_GPUMAX,
  192. PARAM_CPUMAX,
  193. PARAM_PMAX,
  194. PARAM_GCMAX,
  195. PARAM_CMD,
  196. PARAM_NONE
  197. };
  198. struct CODES {
  199. const enum code_severity severity;
  200. const int code;
  201. const enum code_parameters params;
  202. const char *description;
  203. } codes[] = {
  204. { SEVERITY_ERR, MSG_INVGPU, PARAM_GPUMAX, "Invalid GPU id %d - range is 0 - %d" },
  205. { SEVERITY_INFO, MSG_ALRENA, PARAM_GPU, "GPU %d already enabled" },
  206. { SEVERITY_INFO, MSG_ALRDIS, PARAM_GPU, "GPU %d already disabled" },
  207. { SEVERITY_WARN, MSG_GPUMRE, PARAM_GPU, "GPU %d must be restarted first" },
  208. { SEVERITY_INFO, MSG_GPUREN, PARAM_GPU, "GPU %d sent enable message" },
  209. { SEVERITY_ERR, MSG_GPUNON, PARAM_NONE, "No GPUs" },
  210. { SEVERITY_SUCC, MSG_POOL, PARAM_PMAX, "%d Pool(s)" },
  211. { SEVERITY_ERR, MSG_NOPOOL, PARAM_NONE, "No pools" },
  212. { SEVERITY_SUCC, MSG_DEVS, PARAM_GCMAX, "%d GPU(s) - %d CPU(s)" },
  213. { SEVERITY_ERR, MSG_NODEVS, PARAM_NONE, "No GPUs/CPUs" },
  214. { SEVERITY_SUCC, MSG_SUMM, PARAM_NONE, "Summary" },
  215. { SEVERITY_INFO, MSG_GPUDIS, PARAM_GPU, "GPU %d set disable flag" },
  216. { SEVERITY_INFO, MSG_GPUREI, PARAM_GPU, "GPU %d restart attempted" },
  217. { SEVERITY_ERR, MSG_INVCMD, PARAM_NONE, "Invalid command" },
  218. { SEVERITY_ERR, MSG_MISID, PARAM_NONE, "Missing device id parameter" },
  219. { SEVERITY_ERR, MSG_CPUNON, PARAM_NONE, "No CPUs" },
  220. { SEVERITY_SUCC, MSG_GPUDEV, PARAM_GPU, "GPU%d" },
  221. { SEVERITY_SUCC, MSG_CPUDEV, PARAM_CPU, "CPU%d" },
  222. { SEVERITY_ERR, MSG_INVCPU, PARAM_CPUMAX, "Invalid CPU id %d - range is 0 - %d" },
  223. { SEVERITY_SUCC, MSG_NUMGPU, PARAM_NONE, "GPU count" },
  224. { SEVERITY_SUCC, MSG_NUMCPU, PARAM_NONE, "CPU count" },
  225. { SEVERITY_SUCC, MSG_VERSION, PARAM_CPU, "CGMiner versions" },
  226. { SEVERITY_ERR, MSG_INVJSON, PARAM_NONE, "Invalid JSON" },
  227. { SEVERITY_ERR, MSG_MISSCMD, PARAM_CMD, "Missing JSON '%s'" },
  228. { SEVERITY_FAIL }
  229. };
  230. static const char *APIVERSION = "0.7";
  231. static const char *DEAD = "Dead";
  232. static const char *SICK = "Sick";
  233. static const char *NOSTART = "NoStart";
  234. static const char *DISABLED = "Disabled";
  235. static const char *ALIVE = "Alive";
  236. static const char *DYNAMIC = "D";
  237. static const char *YES = "Y";
  238. static const char *NO = "N";
  239. static int bye = 0;
  240. static bool ping = true;
  241. // All replies (except BYE) start with a message
  242. // thus for JSON, message() inserts JSON_START at the front
  243. // and send_result() adds JSON_END at the end
  244. static char *message(int messageid, int gpuid, bool isjson)
  245. {
  246. char severity;
  247. char *ptr;
  248. int cpu;
  249. int i;
  250. for (i = 0; codes[i].severity != SEVERITY_FAIL; i++) {
  251. if (codes[i].code == messageid) {
  252. switch (codes[i].severity) {
  253. case SEVERITY_WARN:
  254. severity = 'W';
  255. break;
  256. case SEVERITY_INFO:
  257. severity = 'I';
  258. break;
  259. case SEVERITY_SUCC:
  260. severity = 'S';
  261. break;
  262. case SEVERITY_ERR:
  263. default:
  264. severity = 'E';
  265. break;
  266. }
  267. if (isjson)
  268. sprintf(msg_buffer, JSON_START JSON_STATUS "{\"" _STATUS "\":\"%c\",\"Code\":%d,\"Msg\":\"", severity, messageid);
  269. else
  270. sprintf(msg_buffer, _STATUS "=%c,Code=%d,Msg=", severity, messageid);
  271. ptr = msg_buffer + strlen(msg_buffer);
  272. switch(codes[i].params) {
  273. case PARAM_GPU:
  274. sprintf(ptr, codes[i].description, gpuid);
  275. break;
  276. case PARAM_CPU:
  277. sprintf(ptr, codes[i].description, gpuid);
  278. break;
  279. case PARAM_GPUMAX:
  280. sprintf(ptr, codes[i].description, gpuid, nDevs - 1);
  281. break;
  282. case PARAM_PMAX:
  283. sprintf(ptr, codes[i].description, total_pools);
  284. break;
  285. case PARAM_GCMAX:
  286. if (opt_n_threads > 0)
  287. cpu = num_processors;
  288. else
  289. cpu = 0;
  290. sprintf(ptr, codes[i].description, nDevs, cpu);
  291. break;
  292. case PARAM_CMD:
  293. sprintf(ptr, codes[i].description, JSON_COMMAND);
  294. break;
  295. case PARAM_NONE:
  296. default:
  297. strcpy(ptr, codes[i].description);
  298. }
  299. ptr = msg_buffer + strlen(msg_buffer);
  300. if (isjson)
  301. sprintf(ptr, "\",\"Description\":\"%s\"}" JSON_CLOSE, opt_api_description);
  302. else
  303. sprintf(ptr, ",Description=%s%c", opt_api_description, SEPARATOR);
  304. return msg_buffer;
  305. }
  306. }
  307. if (isjson)
  308. sprintf(msg_buffer, JSON_START JSON_STATUS "{\"" _STATUS "\":\"F\",\"Code\":-1,\"Msg\":\"%d\",\"Description\":\"%s\"}" JSON_CLOSE,
  309. messageid, opt_api_description);
  310. else
  311. sprintf(msg_buffer, _STATUS "=F,Code=-1,Msg=%d,Description=%s%c",
  312. messageid, opt_api_description, SEPARATOR);
  313. return msg_buffer;
  314. }
  315. void apiversion(SOCKETTYPE c, char *param, bool isjson)
  316. {
  317. if (isjson)
  318. sprintf(io_buffer, "%s," JSON_VERSION "{\"CGMiner\":\"%s\",\"API\":\"%s\"}" JSON_CLOSE,
  319. message(MSG_VERSION, 0, isjson),
  320. VERSION, APIVERSION);
  321. else
  322. sprintf(io_buffer, "%s" _VERSION ",CGMiner=%s,API=%s%c",
  323. message(MSG_VERSION, 0, isjson),
  324. VERSION, APIVERSION, SEPARATOR);
  325. }
  326. void gpustatus(int gpu, bool isjson)
  327. {
  328. char intensity[20];
  329. char buf[BUFSIZ];
  330. char *enabled;
  331. char *status;
  332. float gt, gv;
  333. int ga, gf, gp, gc, gm, pt;
  334. if (gpu >= 0 && gpu < nDevs) {
  335. struct cgpu_info *cgpu = &gpus[gpu];
  336. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  337. #ifdef HAVE_ADL
  338. if (!gpu_stats(gpu, &gt, &gc, &gm, &gv, &ga, &gf, &gp, &pt))
  339. #endif
  340. gt = gv = gm = gc = ga = gf = gp = pt = 0;
  341. if (gpu_devices[gpu])
  342. enabled = (char *)YES;
  343. else
  344. enabled = (char *)NO;
  345. if (cgpu->status == LIFE_DEAD)
  346. status = (char *)DEAD;
  347. else if (cgpu->status == LIFE_SICK)
  348. status = (char *)SICK;
  349. else if (cgpu->status == LIFE_NOSTART)
  350. status = (char *)NOSTART;
  351. else
  352. status = (char *)ALIVE;
  353. if (cgpu->dynamic)
  354. strcpy(intensity, DYNAMIC);
  355. else
  356. sprintf(intensity, "%d", gpus->intensity);
  357. if (isjson)
  358. sprintf(buf, "{\"GPU\":%d,\"Enabled\":\"%s\",\"Status\":\"%s\",\"Temperature\":%.2f,\"Fan Speed\":%d,\"Fan Percent\":%d,\"GPU Clock\":%d,\"Memory Clock\":%d,\"GPU Voltage\":%.3f,\"GPU Activity\":%d,\"Powertune\":%d,\"MHS av\":%.2f,\"MHS %ds\":%.2f,\"Accepted\":%d,\"Rejected\":%d,\"Hardware Errors\":%d,\"Utility\":%.2f,\"Intensity\":\"%s\"}",
  359. gpu, enabled, status, gt, gf, gp, gc, gm, gv, ga, pt,
  360. cgpu->total_mhashes / total_secs, opt_log_interval, cgpu->rolling,
  361. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  362. cgpu->utility, intensity);
  363. else
  364. sprintf(buf, "GPU=%d,Enabled=%s,Status=%s,Temperature=%.2f,Fan Speed=%d,Fan Percent=%d,GPU Clock=%d,Memory Clock=%d,GPU Voltage=%.3f,GPU Activity=%d,Powertune=%d,MHS av=%.2f,MHS %ds=%.2f,Accepted=%d,Rejected=%d,Hardware Errors=%d,Utility=%.2f,Intensity=%s%c",
  365. gpu, enabled, status, gt, gf, gp, gc, gm, gv, ga, pt,
  366. cgpu->total_mhashes / total_secs, opt_log_interval, cgpu->rolling,
  367. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  368. cgpu->utility, intensity, SEPARATOR);
  369. strcat(io_buffer, buf);
  370. }
  371. }
  372. void cpustatus(int cpu, bool isjson)
  373. {
  374. char buf[BUFSIZ];
  375. if (opt_n_threads > 0 && cpu >= 0 && cpu < num_processors) {
  376. struct cgpu_info *cgpu = &cpus[cpu];
  377. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  378. if (isjson)
  379. sprintf(buf, "{\"CPU\":%d,\"MHS av\":%.2f,\"MHS %ds\":%.2f,\"Accepted\":%d,\"Rejected\":%d,\"Utility\":%.2f}",
  380. cpu, cgpu->total_mhashes / total_secs,
  381. opt_log_interval, cgpu->rolling,
  382. cgpu->accepted, cgpu->rejected,
  383. cgpu->utility);
  384. else
  385. sprintf(buf, "CPU=%d,MHS av=%.2f,MHS %ds=%.2f,Accepted=%d,Rejected=%d,Utility=%.2f%c",
  386. cpu, cgpu->total_mhashes / total_secs,
  387. opt_log_interval, cgpu->rolling,
  388. cgpu->accepted, cgpu->rejected,
  389. cgpu->utility, SEPARATOR);
  390. strcat(io_buffer, buf);
  391. }
  392. }
  393. void devstatus(SOCKETTYPE c, char *param, bool isjson)
  394. {
  395. int i;
  396. if (nDevs == 0 && opt_n_threads == 0) {
  397. strcpy(io_buffer, message(MSG_NODEVS, 0, isjson));
  398. return;
  399. }
  400. strcpy(io_buffer, message(MSG_DEVS, 0, isjson));
  401. if (isjson) {
  402. strcat(io_buffer, COMMA);
  403. strcat(io_buffer, JSON_DEVS);
  404. }
  405. for (i = 0; i < nDevs; i++) {
  406. if (isjson && i > 0)
  407. strcat(io_buffer, COMMA);
  408. gpustatus(i, isjson);
  409. }
  410. if (opt_n_threads > 0)
  411. for (i = 0; i < num_processors; i++) {
  412. if (isjson && (i > 0 || nDevs > 0))
  413. strcat(io_buffer, COMMA);
  414. cpustatus(i, isjson);
  415. }
  416. if (isjson)
  417. strcat(io_buffer, JSON_CLOSE);
  418. }
  419. void gpudev(SOCKETTYPE c, char *param, bool isjson)
  420. {
  421. int id;
  422. if (nDevs == 0) {
  423. strcpy(io_buffer, message(MSG_GPUNON, 0, isjson));
  424. return;
  425. }
  426. if (param == NULL || *param == '\0') {
  427. strcpy(io_buffer, message(MSG_MISID, 0, isjson));
  428. return;
  429. }
  430. id = atoi(param);
  431. if (id < 0 || id >= nDevs) {
  432. strcpy(io_buffer, message(MSG_INVGPU, id, isjson));
  433. return;
  434. }
  435. strcpy(io_buffer, message(MSG_GPUDEV, id, isjson));
  436. if (isjson) {
  437. strcat(io_buffer, COMMA);
  438. strcat(io_buffer, JSON_GPU);
  439. }
  440. gpustatus(id, isjson);
  441. if (isjson)
  442. strcat(io_buffer, JSON_CLOSE);
  443. }
  444. void cpudev(SOCKETTYPE c, char *param, bool isjson)
  445. {
  446. int id;
  447. if (opt_n_threads == 0) {
  448. strcpy(io_buffer, message(MSG_CPUNON, 0, isjson));
  449. return;
  450. }
  451. if (param == NULL || *param == '\0') {
  452. strcpy(io_buffer, message(MSG_MISID, 0, isjson));
  453. return;
  454. }
  455. id = atoi(param);
  456. if (id < 0 || id >= num_processors) {
  457. strcpy(io_buffer, message(MSG_INVCPU, id, isjson));
  458. return;
  459. }
  460. strcpy(io_buffer, message(MSG_CPUDEV, id, isjson));
  461. if (isjson) {
  462. strcat(io_buffer, COMMA);
  463. strcat(io_buffer, JSON_CPU);
  464. }
  465. cpustatus(id, isjson);
  466. if (isjson)
  467. strcat(io_buffer, JSON_CLOSE);
  468. }
  469. void poolstatus(SOCKETTYPE c, char *param, bool isjson)
  470. {
  471. char buf[BUFSIZ];
  472. char *status, *lp;
  473. int i;
  474. if (total_pools == 0) {
  475. strcpy(io_buffer, message(MSG_NOPOOL, 0, isjson));
  476. return;
  477. }
  478. strcpy(io_buffer, message(MSG_POOL, 0, isjson));
  479. if (isjson) {
  480. strcat(io_buffer, COMMA);
  481. strcat(io_buffer, JSON_POOLS);
  482. }
  483. for (i = 0; i < total_pools; i++) {
  484. struct pool *pool = pools[i];
  485. if (!pool->enabled)
  486. status = (char *)DISABLED;
  487. else {
  488. if (pool->idle)
  489. status = (char *)DEAD;
  490. else
  491. status = (char *)ALIVE;
  492. }
  493. if (pool->hdr_path)
  494. lp = (char *)YES;
  495. else
  496. lp = (char *)NO;
  497. if (isjson)
  498. sprintf(buf, "%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}",
  499. (i > 0) ? COMMA : "",
  500. i, pool->rpc_url, status, pool->prio, lp,
  501. pool->getwork_requested,
  502. pool->accepted, pool->rejected,
  503. pool->discarded_work,
  504. pool->stale_shares,
  505. pool->getfail_occasions,
  506. pool->remotefail_occasions);
  507. else
  508. sprintf(buf, "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%c",
  509. i, pool->rpc_url, status, pool->prio, lp,
  510. pool->getwork_requested,
  511. pool->accepted, pool->rejected,
  512. pool->discarded_work,
  513. pool->stale_shares,
  514. pool->getfail_occasions,
  515. pool->remotefail_occasions, SEPARATOR);
  516. strcat(io_buffer, buf);
  517. }
  518. if (isjson)
  519. strcat(io_buffer, JSON_CLOSE);
  520. }
  521. void summary(SOCKETTYPE c, char *param, bool isjson)
  522. {
  523. double utility, mhs;
  524. char *algo = (char *)(algo_names[opt_algo]);
  525. if (algo == NULL)
  526. algo = "(null)";
  527. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  528. mhs = total_mhashes_done / total_secs;
  529. if (isjson)
  530. sprintf(io_buffer, "%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}" JSON_CLOSE,
  531. message(MSG_SUMM, 0, isjson),
  532. total_secs, algo, mhs, found_blocks,
  533. total_getworks, total_accepted, total_rejected,
  534. hw_errors, utility, total_discarded, total_stale,
  535. total_go, local_work, total_ro, new_blocks);
  536. else
  537. sprintf(io_buffer, "%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%c",
  538. message(MSG_SUMM, 0, isjson),
  539. total_secs, algo, mhs, found_blocks,
  540. total_getworks, total_accepted, total_rejected,
  541. hw_errors, utility, total_discarded, total_stale,
  542. total_go, local_work, total_ro, new_blocks, SEPARATOR);
  543. }
  544. void gpuenable(SOCKETTYPE c, char *param, bool isjson)
  545. {
  546. struct thr_info *thr;
  547. int gpu;
  548. int id;
  549. int i;
  550. if (gpu_threads == 0) {
  551. strcpy(io_buffer, message(MSG_GPUNON, 0, isjson));
  552. return;
  553. }
  554. if (param == NULL || *param == '\0') {
  555. strcpy(io_buffer, message(MSG_MISID, 0, isjson));
  556. return;
  557. }
  558. id = atoi(param);
  559. if (id < 0 || id >= nDevs) {
  560. strcpy(io_buffer, message(MSG_INVGPU, id, isjson));
  561. return;
  562. }
  563. if (gpu_devices[id]) {
  564. strcpy(io_buffer, message(MSG_ALRENA, id, isjson));
  565. return;
  566. }
  567. for (i = 0; i < gpu_threads; i++) {
  568. gpu = thr_info[i].cgpu->cpu_gpu;
  569. if (gpu == id) {
  570. thr = &thr_info[i];
  571. if (thr->cgpu->status != LIFE_WELL) {
  572. strcpy(io_buffer, message(MSG_GPUMRE, id, isjson));
  573. return;
  574. }
  575. gpu_devices[id] = true;
  576. tq_push(thr->q, &ping);
  577. }
  578. }
  579. strcpy(io_buffer, message(MSG_GPUREN, id, isjson));
  580. }
  581. void gpudisable(SOCKETTYPE c, char *param, bool isjson)
  582. {
  583. int id;
  584. if (nDevs == 0) {
  585. strcpy(io_buffer, message(MSG_GPUNON, 0, isjson));
  586. return;
  587. }
  588. if (param == NULL || *param == '\0') {
  589. strcpy(io_buffer, message(MSG_MISID, 0, isjson));
  590. return;
  591. }
  592. id = atoi(param);
  593. if (id < 0 || id >= nDevs) {
  594. strcpy(io_buffer, message(MSG_INVGPU, id, isjson));
  595. return;
  596. }
  597. if (!gpu_devices[id]) {
  598. strcpy(io_buffer, message(MSG_ALRDIS, id, isjson));
  599. return;
  600. }
  601. gpu_devices[id] = false;
  602. strcpy(io_buffer, message(MSG_GPUDIS, id, isjson));
  603. }
  604. void gpurestart(SOCKETTYPE c, char *param, bool isjson)
  605. {
  606. int id;
  607. if (nDevs == 0) {
  608. strcpy(io_buffer, message(MSG_GPUNON, 0, isjson));
  609. return;
  610. }
  611. if (param == NULL || *param == '\0') {
  612. strcpy(io_buffer, message(MSG_MISID, 0, isjson));
  613. return;
  614. }
  615. id = atoi(param);
  616. if (id < 0 || id >= nDevs) {
  617. strcpy(io_buffer, message(MSG_INVGPU, id, isjson));
  618. return;
  619. }
  620. reinit_device(&gpus[id]);
  621. strcpy(io_buffer, message(MSG_GPUREI, id, isjson));
  622. }
  623. void gpucount(SOCKETTYPE c, char *param, bool isjson)
  624. {
  625. char buf[BUFSIZ];
  626. strcpy(io_buffer, message(MSG_NUMGPU, 0, isjson));
  627. if (isjson)
  628. sprintf(buf, "," JSON_GPUS "{\"Count\":%d}" JSON_CLOSE, nDevs);
  629. else
  630. sprintf(buf, _GPUS ",Count=%d%c", nDevs, SEPARATOR);
  631. strcat(io_buffer, buf);
  632. }
  633. void cpucount(SOCKETTYPE c, char *param, bool isjson)
  634. {
  635. char buf[BUFSIZ];
  636. strcpy(io_buffer, message(MSG_NUMCPU, 0, isjson));
  637. if (isjson)
  638. sprintf(buf, "," JSON_CPUS "{\"Count\":%d}" JSON_CLOSE, opt_n_threads > 0 ? num_processors : 0);
  639. else
  640. sprintf(buf, _CPUS ",Count=%d%c", opt_n_threads > 0 ? num_processors : 0, SEPARATOR);
  641. strcat(io_buffer, buf);
  642. }
  643. void send_result(SOCKETTYPE c, bool isjson);
  644. void doquit(SOCKETTYPE c, char *param, bool isjson)
  645. {
  646. if (isjson)
  647. strcpy(io_buffer, JSON_START JSON_BYE);
  648. else
  649. strcpy(io_buffer, _BYE);
  650. send_result(c, isjson);
  651. *io_buffer = '\0';
  652. bye = 1;
  653. kill_work();
  654. }
  655. struct CMDS {
  656. char *name;
  657. void (*func)(SOCKETTYPE, char *, bool);
  658. } cmds[] = {
  659. { "version", apiversion },
  660. { "devs", devstatus },
  661. { "pools", poolstatus },
  662. { "summary", summary },
  663. { "gpuenable", gpuenable },
  664. { "gpudisable", gpudisable },
  665. { "gpurestart", gpurestart },
  666. { "gpu", gpudev },
  667. { "cpu", cpudev },
  668. { "gpucount", gpucount },
  669. { "cpucount", cpucount },
  670. { "quit", doquit },
  671. { NULL }
  672. };
  673. void send_result(SOCKETTYPE c, bool isjson)
  674. {
  675. int n;
  676. int len;
  677. if (isjson)
  678. strcat(io_buffer, JSON_END);
  679. len = strlen(io_buffer);
  680. if (opt_debug)
  681. applog(LOG_DEBUG, "DBG: send reply: (%d) '%.10s%s'", len+1, io_buffer, len > 10 ? "..." : "");
  682. // ignore failure - it's closed immediately anyway
  683. n = send(c, io_buffer, len+1, 0);
  684. if (opt_debug) {
  685. if (SOCKETFAIL(n))
  686. applog(LOG_DEBUG, "DBG: send failed: %s", SOCKERRMSG);
  687. else
  688. applog(LOG_DEBUG, "DBG: sent %d", n);
  689. }
  690. }
  691. void tidyup()
  692. {
  693. bye = 1;
  694. if (sock != INVSOCK) {
  695. shutdown(sock, SHUT_RDWR);
  696. CLOSESOCKET(sock);
  697. sock = INVSOCK;
  698. }
  699. if (msg_buffer != NULL) {
  700. free(msg_buffer);
  701. msg_buffer = NULL;
  702. }
  703. if (io_buffer != NULL) {
  704. free(io_buffer);
  705. io_buffer = NULL;
  706. }
  707. }
  708. void api(void)
  709. {
  710. char buf[BUFSIZ];
  711. char param_buf[BUFSIZ];
  712. const char *localaddr = "127.0.0.1";
  713. SOCKETTYPE c;
  714. int n, bound;
  715. char *connectaddr;
  716. char *binderror;
  717. time_t bindstart;
  718. short int port = opt_api_port;
  719. struct sockaddr_in serv;
  720. struct sockaddr_in cli;
  721. socklen_t clisiz;
  722. char *cmd;
  723. char *param;
  724. bool addrok;
  725. json_error_t json_err;
  726. json_t *json_config;
  727. json_t *json_val;
  728. bool isjson;
  729. bool did;
  730. int i;
  731. /* This should be done first to ensure curl has already called WSAStartup() in windows */
  732. sleep(opt_log_interval);
  733. if (!opt_api_listen) {
  734. applog(LOG_DEBUG, "API not running%s", UNAVAILABLE);
  735. return;
  736. }
  737. sock = socket(AF_INET, SOCK_STREAM, 0);
  738. if (sock == INVSOCK) {
  739. applog(LOG_ERR, "API1 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  740. return;
  741. }
  742. memset(&serv, 0, sizeof(serv));
  743. serv.sin_family = AF_INET;
  744. if (!opt_api_network) {
  745. serv.sin_addr.s_addr = inet_addr(localaddr);
  746. if (serv.sin_addr.s_addr == INVINETADDR) {
  747. applog(LOG_ERR, "API2 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  748. return;
  749. }
  750. }
  751. serv.sin_port = htons(port);
  752. // try for more than 1 minute ... in case the old one hasn't completely gone yet
  753. bound = 0;
  754. bindstart = time(NULL);
  755. while (bound == 0) {
  756. if (SOCKETFAIL(bind(sock, (struct sockaddr *)(&serv), sizeof(serv)))) {
  757. binderror = SOCKERRMSG;
  758. if ((time(NULL) - bindstart) > 61)
  759. break;
  760. else {
  761. applog(LOG_WARNING, "API bind to port %d failed - trying again in 15sec", port);
  762. sleep(15);
  763. }
  764. }
  765. else
  766. bound = 1;
  767. }
  768. if (bound == 0) {
  769. applog(LOG_ERR, "API bind to port %d failed (%s)%s", port, binderror, UNAVAILABLE);
  770. return;
  771. }
  772. if (SOCKETFAIL(listen(sock, QUEUE))) {
  773. applog(LOG_ERR, "API3 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  774. CLOSESOCKET(sock);
  775. return;
  776. }
  777. if (opt_api_network)
  778. applog(LOG_WARNING, "API running in UNRESTRICTED access mode");
  779. else
  780. applog(LOG_WARNING, "API running in restricted access mode");
  781. io_buffer = malloc(MYBUFSIZ+1);
  782. msg_buffer = malloc(MYBUFSIZ+1);
  783. while (bye == 0) {
  784. clisiz = sizeof(cli);
  785. if (SOCKETFAIL(c = accept(sock, (struct sockaddr *)(&cli), &clisiz))) {
  786. applog(LOG_ERR, "API failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  787. goto die;
  788. }
  789. if (opt_api_network)
  790. addrok = true;
  791. else {
  792. connectaddr = inet_ntoa(cli.sin_addr);
  793. addrok = (strcmp(connectaddr, localaddr) == 0);
  794. }
  795. if (opt_debug) {
  796. connectaddr = inet_ntoa(cli.sin_addr);
  797. applog(LOG_DEBUG, "DBG: connection from %s - %s", connectaddr, addrok ? "Accepted" : "Ignored");
  798. }
  799. if (addrok) {
  800. n = recv(c, &buf[0], BUFSIZ-1, 0);
  801. if (SOCKETFAIL(n))
  802. buf[0] = '\0';
  803. else
  804. buf[n] = '\0';
  805. if (opt_debug) {
  806. if (SOCKETFAIL(n))
  807. applog(LOG_DEBUG, "DBG: recv failed: %s", SOCKERRMSG);
  808. else
  809. applog(LOG_DEBUG, "DBG: recv command: (%d) '%s'", n, buf);
  810. }
  811. if (!SOCKETFAIL(n)) {
  812. did = false;
  813. if (*buf != ISJSON) {
  814. isjson = false;
  815. param = strchr(buf, SEPARATOR);
  816. if (param != NULL)
  817. *(param++) = '\0';
  818. cmd = buf;
  819. }
  820. else {
  821. isjson = true;
  822. param = NULL;
  823. json_config = json_loadb(buf, n, 0, &json_err);
  824. if (!json_is_object(json_config)) {
  825. strcpy(io_buffer, message(MSG_INVJSON, 0, isjson));
  826. send_result(c, isjson);
  827. did = true;
  828. }
  829. else {
  830. json_val = json_object_get(json_config, JSON_COMMAND);
  831. if (json_val == NULL) {
  832. strcpy(io_buffer, message(MSG_MISSCMD, 0, isjson));
  833. send_result(c, isjson);
  834. did = true;
  835. }
  836. else {
  837. if (!json_is_string(json_val)) {
  838. strcpy(io_buffer, message(MSG_INVCMD, 0, isjson));
  839. send_result(c, isjson);
  840. did = true;
  841. }
  842. else {
  843. cmd = (char *)json_string_value(json_val);
  844. json_val = json_object_get(json_config, JSON_PARAMETER);
  845. if (json_is_string(json_val))
  846. param = (char *)json_string_value(json_val);
  847. else if (json_is_integer(json_val)) {
  848. sprintf(param_buf, "%d", (int)json_integer_value(json_val));
  849. param = param_buf;
  850. } else if (json_is_real(json_val)) {
  851. sprintf(param_buf, "%f", (double)json_real_value(json_val));
  852. param = param_buf;
  853. }
  854. }
  855. }
  856. }
  857. }
  858. if (!did)
  859. for (i = 0; cmds[i].name != NULL; i++) {
  860. if (strcmp(cmd, cmds[i].name) == 0) {
  861. (cmds[i].func)(c, param, isjson);
  862. send_result(c, isjson);
  863. did = true;
  864. break;
  865. }
  866. }
  867. if (!did) {
  868. strcpy(io_buffer, message(MSG_INVCMD, 0, isjson));
  869. send_result(c, isjson);
  870. }
  871. }
  872. }
  873. CLOSESOCKET(c);
  874. }
  875. die:
  876. tidyup();
  877. }