api.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. /*
  2. * Copyright 2011 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 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 (cgpu->enabled)
  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. #ifdef WANT_CPUMINE
  525. char *algo = (char *)(algo_names[opt_algo]);
  526. if (algo == NULL)
  527. algo = "(null)";
  528. #endif
  529. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  530. mhs = total_mhashes_done / total_secs;
  531. #ifdef WANT_CPUMINE
  532. if (isjson)
  533. 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,
  534. message(MSG_SUMM, 0, isjson),
  535. total_secs, algo, mhs, found_blocks,
  536. total_getworks, total_accepted, total_rejected,
  537. hw_errors, utility, total_discarded, total_stale,
  538. total_go, local_work, total_ro, new_blocks);
  539. else
  540. 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",
  541. message(MSG_SUMM, 0, isjson),
  542. total_secs, algo, mhs, found_blocks,
  543. total_getworks, total_accepted, total_rejected,
  544. hw_errors, utility, total_discarded, total_stale,
  545. total_go, local_work, total_ro, new_blocks, SEPARATOR);
  546. #else
  547. if (isjson)
  548. sprintf(io_buffer, "%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}" JSON_CLOSE,
  549. message(MSG_SUMM, 0, isjson),
  550. total_secs, mhs, found_blocks,
  551. total_getworks, total_accepted, total_rejected,
  552. hw_errors, utility, total_discarded, total_stale,
  553. total_go, local_work, total_ro, new_blocks);
  554. else
  555. sprintf(io_buffer, "%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%c",
  556. message(MSG_SUMM, 0, isjson),
  557. total_secs, mhs, found_blocks,
  558. total_getworks, total_accepted, total_rejected,
  559. hw_errors, utility, total_discarded, total_stale,
  560. total_go, local_work, total_ro, new_blocks, SEPARATOR);
  561. #endif
  562. }
  563. void gpuenable(SOCKETTYPE c, char *param, bool isjson)
  564. {
  565. struct thr_info *thr;
  566. int gpu;
  567. int id;
  568. int i;
  569. if (gpu_threads == 0) {
  570. strcpy(io_buffer, message(MSG_GPUNON, 0, isjson));
  571. return;
  572. }
  573. if (param == NULL || *param == '\0') {
  574. strcpy(io_buffer, message(MSG_MISID, 0, isjson));
  575. return;
  576. }
  577. id = atoi(param);
  578. if (id < 0 || id >= nDevs) {
  579. strcpy(io_buffer, message(MSG_INVGPU, id, isjson));
  580. return;
  581. }
  582. if (gpus[id].enabled) {
  583. strcpy(io_buffer, message(MSG_ALRENA, id, isjson));
  584. return;
  585. }
  586. for (i = 0; i < gpu_threads; i++) {
  587. gpu = thr_info[i].cgpu->device_id;
  588. if (gpu == id) {
  589. thr = &thr_info[i];
  590. if (thr->cgpu->status != LIFE_WELL) {
  591. strcpy(io_buffer, message(MSG_GPUMRE, id, isjson));
  592. return;
  593. }
  594. gpus[id].enabled = true;
  595. tq_push(thr->q, &ping);
  596. }
  597. }
  598. strcpy(io_buffer, message(MSG_GPUREN, id, isjson));
  599. }
  600. void gpudisable(SOCKETTYPE c, char *param, bool isjson)
  601. {
  602. int id;
  603. if (nDevs == 0) {
  604. strcpy(io_buffer, message(MSG_GPUNON, 0, isjson));
  605. return;
  606. }
  607. if (param == NULL || *param == '\0') {
  608. strcpy(io_buffer, message(MSG_MISID, 0, isjson));
  609. return;
  610. }
  611. id = atoi(param);
  612. if (id < 0 || id >= nDevs) {
  613. strcpy(io_buffer, message(MSG_INVGPU, id, isjson));
  614. return;
  615. }
  616. if (!gpus[id].enabled) {
  617. strcpy(io_buffer, message(MSG_ALRDIS, id, isjson));
  618. return;
  619. }
  620. gpus[id].enabled = false;
  621. strcpy(io_buffer, message(MSG_GPUDIS, id, isjson));
  622. }
  623. void gpurestart(SOCKETTYPE c, char *param, bool isjson)
  624. {
  625. int id;
  626. if (nDevs == 0) {
  627. strcpy(io_buffer, message(MSG_GPUNON, 0, isjson));
  628. return;
  629. }
  630. if (param == NULL || *param == '\0') {
  631. strcpy(io_buffer, message(MSG_MISID, 0, isjson));
  632. return;
  633. }
  634. id = atoi(param);
  635. if (id < 0 || id >= nDevs) {
  636. strcpy(io_buffer, message(MSG_INVGPU, id, isjson));
  637. return;
  638. }
  639. reinit_device(&gpus[id]);
  640. strcpy(io_buffer, message(MSG_GPUREI, id, isjson));
  641. }
  642. void gpucount(SOCKETTYPE c, char *param, bool isjson)
  643. {
  644. char buf[BUFSIZ];
  645. strcpy(io_buffer, message(MSG_NUMGPU, 0, isjson));
  646. if (isjson)
  647. sprintf(buf, "," JSON_GPUS "{\"Count\":%d}" JSON_CLOSE, nDevs);
  648. else
  649. sprintf(buf, _GPUS ",Count=%d%c", nDevs, SEPARATOR);
  650. strcat(io_buffer, buf);
  651. }
  652. void cpucount(SOCKETTYPE c, char *param, bool isjson)
  653. {
  654. char buf[BUFSIZ];
  655. strcpy(io_buffer, message(MSG_NUMCPU, 0, isjson));
  656. if (isjson)
  657. sprintf(buf, "," JSON_CPUS "{\"Count\":%d}" JSON_CLOSE, opt_n_threads > 0 ? num_processors : 0);
  658. else
  659. sprintf(buf, _CPUS ",Count=%d%c", opt_n_threads > 0 ? num_processors : 0, SEPARATOR);
  660. strcat(io_buffer, buf);
  661. }
  662. void send_result(SOCKETTYPE c, bool isjson);
  663. void doquit(SOCKETTYPE c, char *param, bool isjson)
  664. {
  665. if (isjson)
  666. strcpy(io_buffer, JSON_START JSON_BYE);
  667. else
  668. strcpy(io_buffer, _BYE);
  669. send_result(c, isjson);
  670. *io_buffer = '\0';
  671. bye = 1;
  672. kill_work();
  673. }
  674. struct CMDS {
  675. char *name;
  676. void (*func)(SOCKETTYPE, char *, bool);
  677. } cmds[] = {
  678. { "version", apiversion },
  679. { "devs", devstatus },
  680. { "pools", poolstatus },
  681. { "summary", summary },
  682. { "gpuenable", gpuenable },
  683. { "gpudisable", gpudisable },
  684. { "gpurestart", gpurestart },
  685. { "gpu", gpudev },
  686. { "cpu", cpudev },
  687. { "gpucount", gpucount },
  688. { "cpucount", cpucount },
  689. { "quit", doquit },
  690. { NULL }
  691. };
  692. void send_result(SOCKETTYPE c, bool isjson)
  693. {
  694. int n;
  695. int len;
  696. if (isjson)
  697. strcat(io_buffer, JSON_END);
  698. len = strlen(io_buffer);
  699. if (opt_debug)
  700. applog(LOG_DEBUG, "DBG: send reply: (%d) '%.10s%s'", len+1, io_buffer, len > 10 ? "..." : "");
  701. // ignore failure - it's closed immediately anyway
  702. n = send(c, io_buffer, len+1, 0);
  703. if (opt_debug) {
  704. if (SOCKETFAIL(n))
  705. applog(LOG_DEBUG, "DBG: send failed: %s", SOCKERRMSG);
  706. else
  707. applog(LOG_DEBUG, "DBG: sent %d", n);
  708. }
  709. }
  710. void tidyup()
  711. {
  712. bye = 1;
  713. if (sock != INVSOCK) {
  714. shutdown(sock, SHUT_RDWR);
  715. CLOSESOCKET(sock);
  716. sock = INVSOCK;
  717. }
  718. if (msg_buffer != NULL) {
  719. free(msg_buffer);
  720. msg_buffer = NULL;
  721. }
  722. if (io_buffer != NULL) {
  723. free(io_buffer);
  724. io_buffer = NULL;
  725. }
  726. }
  727. void api(void)
  728. {
  729. char buf[BUFSIZ];
  730. char param_buf[BUFSIZ];
  731. const char *localaddr = "127.0.0.1";
  732. SOCKETTYPE c;
  733. int n, bound;
  734. char *connectaddr;
  735. char *binderror;
  736. time_t bindstart;
  737. short int port = opt_api_port;
  738. struct sockaddr_in serv;
  739. struct sockaddr_in cli;
  740. socklen_t clisiz;
  741. char *cmd;
  742. char *param;
  743. bool addrok;
  744. json_error_t json_err;
  745. json_t *json_config;
  746. json_t *json_val;
  747. bool isjson;
  748. bool did;
  749. int i;
  750. /* This should be done first to ensure curl has already called WSAStartup() in windows */
  751. sleep(opt_log_interval);
  752. if (!opt_api_listen) {
  753. applog(LOG_DEBUG, "API not running%s", UNAVAILABLE);
  754. return;
  755. }
  756. sock = socket(AF_INET, SOCK_STREAM, 0);
  757. if (sock == INVSOCK) {
  758. applog(LOG_ERR, "API1 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  759. return;
  760. }
  761. memset(&serv, 0, sizeof(serv));
  762. serv.sin_family = AF_INET;
  763. if (!opt_api_network) {
  764. serv.sin_addr.s_addr = inet_addr(localaddr);
  765. if (serv.sin_addr.s_addr == INVINETADDR) {
  766. applog(LOG_ERR, "API2 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  767. return;
  768. }
  769. }
  770. serv.sin_port = htons(port);
  771. // try for more than 1 minute ... in case the old one hasn't completely gone yet
  772. bound = 0;
  773. bindstart = time(NULL);
  774. while (bound == 0) {
  775. if (SOCKETFAIL(bind(sock, (struct sockaddr *)(&serv), sizeof(serv)))) {
  776. binderror = SOCKERRMSG;
  777. if ((time(NULL) - bindstart) > 61)
  778. break;
  779. else {
  780. applog(LOG_WARNING, "API bind to port %d failed - trying again in 15sec", port);
  781. sleep(15);
  782. }
  783. }
  784. else
  785. bound = 1;
  786. }
  787. if (bound == 0) {
  788. applog(LOG_ERR, "API bind to port %d failed (%s)%s", port, binderror, UNAVAILABLE);
  789. return;
  790. }
  791. if (SOCKETFAIL(listen(sock, QUEUE))) {
  792. applog(LOG_ERR, "API3 initialisation failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  793. CLOSESOCKET(sock);
  794. return;
  795. }
  796. if (opt_api_network)
  797. applog(LOG_WARNING, "API running in UNRESTRICTED access mode");
  798. else
  799. applog(LOG_WARNING, "API running in restricted access mode");
  800. io_buffer = malloc(MYBUFSIZ+1);
  801. msg_buffer = malloc(MYBUFSIZ+1);
  802. while (bye == 0) {
  803. clisiz = sizeof(cli);
  804. if (SOCKETFAIL(c = accept(sock, (struct sockaddr *)(&cli), &clisiz))) {
  805. applog(LOG_ERR, "API failed (%s)%s", SOCKERRMSG, UNAVAILABLE);
  806. goto die;
  807. }
  808. if (opt_api_network)
  809. addrok = true;
  810. else {
  811. connectaddr = inet_ntoa(cli.sin_addr);
  812. addrok = (strcmp(connectaddr, localaddr) == 0);
  813. }
  814. if (opt_debug) {
  815. connectaddr = inet_ntoa(cli.sin_addr);
  816. applog(LOG_DEBUG, "DBG: connection from %s - %s", connectaddr, addrok ? "Accepted" : "Ignored");
  817. }
  818. if (addrok) {
  819. n = recv(c, &buf[0], BUFSIZ-1, 0);
  820. if (SOCKETFAIL(n))
  821. buf[0] = '\0';
  822. else
  823. buf[n] = '\0';
  824. if (opt_debug) {
  825. if (SOCKETFAIL(n))
  826. applog(LOG_DEBUG, "DBG: recv failed: %s", SOCKERRMSG);
  827. else
  828. applog(LOG_DEBUG, "DBG: recv command: (%d) '%s'", n, buf);
  829. }
  830. if (!SOCKETFAIL(n)) {
  831. did = false;
  832. if (*buf != ISJSON) {
  833. isjson = false;
  834. param = strchr(buf, SEPARATOR);
  835. if (param != NULL)
  836. *(param++) = '\0';
  837. cmd = buf;
  838. }
  839. else {
  840. isjson = true;
  841. param = NULL;
  842. json_config = json_loadb(buf, n, 0, &json_err);
  843. if (!json_is_object(json_config)) {
  844. strcpy(io_buffer, message(MSG_INVJSON, 0, isjson));
  845. send_result(c, isjson);
  846. did = true;
  847. }
  848. else {
  849. json_val = json_object_get(json_config, JSON_COMMAND);
  850. if (json_val == NULL) {
  851. strcpy(io_buffer, message(MSG_MISSCMD, 0, isjson));
  852. send_result(c, isjson);
  853. did = true;
  854. }
  855. else {
  856. if (!json_is_string(json_val)) {
  857. strcpy(io_buffer, message(MSG_INVCMD, 0, isjson));
  858. send_result(c, isjson);
  859. did = true;
  860. }
  861. else {
  862. cmd = (char *)json_string_value(json_val);
  863. json_val = json_object_get(json_config, JSON_PARAMETER);
  864. if (json_is_string(json_val))
  865. param = (char *)json_string_value(json_val);
  866. else if (json_is_integer(json_val)) {
  867. sprintf(param_buf, "%d", (int)json_integer_value(json_val));
  868. param = param_buf;
  869. } else if (json_is_real(json_val)) {
  870. sprintf(param_buf, "%f", (double)json_real_value(json_val));
  871. param = param_buf;
  872. }
  873. }
  874. }
  875. }
  876. }
  877. if (!did)
  878. for (i = 0; cmds[i].name != NULL; i++) {
  879. if (strcmp(cmd, cmds[i].name) == 0) {
  880. (cmds[i].func)(c, param, isjson);
  881. send_result(c, isjson);
  882. did = true;
  883. break;
  884. }
  885. }
  886. if (!did) {
  887. strcpy(io_buffer, message(MSG_INVCMD, 0, isjson));
  888. send_result(c, isjson);
  889. }
  890. }
  891. }
  892. CLOSESOCKET(c);
  893. }
  894. die:
  895. tidyup();
  896. }