api-example.c 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. * Copyright 2011 Kano
  3. *
  4. * This program is free software; you can redistribute it and/or modify it
  5. * under the terms of the GNU General Public License as published by the Free
  6. * Software Foundation; either version 3 of the License, or (at your option)
  7. * any later version. See COPYING for more details.
  8. */
  9. /* Compile:
  10. * gcc api-example.c -Icompat/jansson-2.9/src -Icompat/libusb-1.0/libusb -o cgminer-api
  11. */
  12. #include "config.h"
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include <string.h>
  16. #include <ctype.h>
  17. #include <unistd.h>
  18. #include <stdbool.h>
  19. #include <stdint.h>
  20. #include <sys/types.h>
  21. #include "compat.h"
  22. #include "util.h"
  23. #if defined(unix) || defined(__APPLE__)
  24. #include <errno.h>
  25. #include <sys/socket.h>
  26. #include <netinet/in.h>
  27. #include <arpa/inet.h>
  28. #include <netdb.h>
  29. #define SOCKETFAIL(a) ((a) < 0)
  30. #define INVSOCK -1
  31. #define CLOSESOCKET close
  32. #define SOCKETINIT {}
  33. #define SOCKERRMSG strerror(errno)
  34. #endif
  35. #ifdef WIN32
  36. #include <winsock2.h>
  37. #define SOCKETTYPE SOCKET
  38. #define SOCKETFAIL(a) ((a) == SOCKET_ERROR)
  39. #define INVSOCK INVALID_SOCKET
  40. #define CLOSESOCKET closesocket
  41. static char WSAbuf[1024];
  42. struct WSAERRORS {
  43. int id;
  44. char *code;
  45. } WSAErrors[] = {
  46. { 0, "No error" },
  47. { WSAEINTR, "Interrupted system call" },
  48. { WSAEBADF, "Bad file number" },
  49. { WSAEACCES, "Permission denied" },
  50. { WSAEFAULT, "Bad address" },
  51. { WSAEINVAL, "Invalid argument" },
  52. { WSAEMFILE, "Too many open sockets" },
  53. { WSAEWOULDBLOCK, "Operation would block" },
  54. { WSAEINPROGRESS, "Operation now in progress" },
  55. { WSAEALREADY, "Operation already in progress" },
  56. { WSAENOTSOCK, "Socket operation on non-socket" },
  57. { WSAEDESTADDRREQ, "Destination address required" },
  58. { WSAEMSGSIZE, "Message too long" },
  59. { WSAEPROTOTYPE, "Protocol wrong type for socket" },
  60. { WSAENOPROTOOPT, "Bad protocol option" },
  61. { WSAEPROTONOSUPPORT, "Protocol not supported" },
  62. { WSAESOCKTNOSUPPORT, "Socket type not supported" },
  63. { WSAEOPNOTSUPP, "Operation not supported on socket" },
  64. { WSAEPFNOSUPPORT, "Protocol family not supported" },
  65. { WSAEAFNOSUPPORT, "Address family not supported" },
  66. { WSAEADDRINUSE, "Address already in use" },
  67. { WSAEADDRNOTAVAIL, "Can't assign requested address" },
  68. { WSAENETDOWN, "Network is down" },
  69. { WSAENETUNREACH, "Network is unreachable" },
  70. { WSAENETRESET, "Net connection reset" },
  71. { WSAECONNABORTED, "Software caused connection abort" },
  72. { WSAECONNRESET, "Connection reset by peer" },
  73. { WSAENOBUFS, "No buffer space available" },
  74. { WSAEISCONN, "Socket is already connected" },
  75. { WSAENOTCONN, "Socket is not connected" },
  76. { WSAESHUTDOWN, "Can't send after socket shutdown" },
  77. { WSAETOOMANYREFS, "Too many references, can't splice" },
  78. { WSAETIMEDOUT, "Connection timed out" },
  79. { WSAECONNREFUSED, "Connection refused" },
  80. { WSAELOOP, "Too many levels of symbolic links" },
  81. { WSAENAMETOOLONG, "File name too long" },
  82. { WSAEHOSTDOWN, "Host is down" },
  83. { WSAEHOSTUNREACH, "No route to host" },
  84. { WSAENOTEMPTY, "Directory not empty" },
  85. { WSAEPROCLIM, "Too many processes" },
  86. { WSAEUSERS, "Too many users" },
  87. { WSAEDQUOT, "Disc quota exceeded" },
  88. { WSAESTALE, "Stale NFS file handle" },
  89. { WSAEREMOTE, "Too many levels of remote in path" },
  90. { WSASYSNOTREADY, "Network system is unavailable" },
  91. { WSAVERNOTSUPPORTED, "Winsock version out of range" },
  92. { WSANOTINITIALISED, "WSAStartup not yet called" },
  93. { WSAEDISCON, "Graceful shutdown in progress" },
  94. { WSAHOST_NOT_FOUND, "Host not found" },
  95. { WSANO_DATA, "No host data of that type was found" },
  96. { -1, "Unknown error code" }
  97. };
  98. static char *WSAErrorMsg()
  99. {
  100. char *msg;
  101. int i;
  102. int id = WSAGetLastError();
  103. /* Assume none of them are actually -1 */
  104. for (i = 0; WSAErrors[i].id != -1; i++)
  105. if (WSAErrors[i].id == id)
  106. break;
  107. sprintf(WSAbuf, "Socket Error: (%d) %s", id, WSAErrors[i].code);
  108. return &(WSAbuf[0]);
  109. }
  110. #define SOCKERRMSG WSAErrorMsg()
  111. static WSADATA WSA_Data;
  112. #define SOCKETINIT int wsa; \
  113. if (wsa = WSAStartup(0x0202, &WSA_Data)) { \
  114. printf("Socket startup failed: %d\n", wsa); \
  115. return 1; \
  116. }
  117. #ifndef SHUT_RDWR
  118. #define SHUT_RDWR SD_BOTH
  119. #endif
  120. #endif
  121. static const char SEPARATOR = '|';
  122. static const char COMMA = ',';
  123. static const char EQ = '=';
  124. static int ONLY;
  125. void display(char *buf)
  126. {
  127. char *nextobj, *item, *nextitem, *eq;
  128. int itemcount;
  129. while (buf != NULL) {
  130. nextobj = strchr(buf, SEPARATOR);
  131. if (nextobj != NULL)
  132. *(nextobj++) = '\0';
  133. if (*buf) {
  134. item = buf;
  135. itemcount = 0;
  136. while (item != NULL) {
  137. nextitem = strchr(item, COMMA);
  138. if (nextitem != NULL)
  139. *(nextitem++) = '\0';
  140. if (*item) {
  141. eq = strchr(item, EQ);
  142. if (eq != NULL)
  143. *(eq++) = '\0';
  144. if (itemcount == 0)
  145. printf("[%s%s] =>\n(\n", item, (eq != NULL && isdigit(*eq)) ? eq : "");
  146. if (eq != NULL)
  147. printf(" [%s] => %s\n", item, eq);
  148. else
  149. printf(" [%d] => %s\n", itemcount, item);
  150. }
  151. item = nextitem;
  152. itemcount++;
  153. }
  154. if (itemcount > 0)
  155. puts(")");
  156. }
  157. buf = nextobj;
  158. }
  159. }
  160. #define SOCKSIZ 65535
  161. int callapi(char *command, char *host, short int port)
  162. {
  163. struct hostent *ip;
  164. struct sockaddr_in serv;
  165. SOCKETTYPE sock;
  166. int ret = 0;
  167. int n;
  168. char *buf = NULL;
  169. size_t len, p;
  170. SOCKETINIT;
  171. ip = gethostbyname(host);
  172. if (!ip) {
  173. printf("Couldn't get hostname: '%s'\n", host);
  174. return 1;
  175. }
  176. sock = socket(AF_INET, SOCK_STREAM, 0);
  177. if (sock == INVSOCK) {
  178. printf("Socket initialisation failed: %s\n", SOCKERRMSG);
  179. return 1;
  180. }
  181. memset(&serv, 0, sizeof(serv));
  182. serv.sin_family = AF_INET;
  183. serv.sin_addr = *((struct in_addr *)ip->h_addr);
  184. serv.sin_port = htons(port);
  185. if (SOCKETFAIL(connect(sock, (struct sockaddr *)&serv, sizeof(struct sockaddr)))) {
  186. printf("Socket connect failed: %s\n", SOCKERRMSG);
  187. return 1;
  188. }
  189. n = send(sock, command, strlen(command), 0);
  190. if (SOCKETFAIL(n)) {
  191. printf("Send failed: %s\n", SOCKERRMSG);
  192. ret = 1;
  193. }
  194. else {
  195. len = SOCKSIZ;
  196. buf = malloc(len+1);
  197. if (!buf) {
  198. printf("Err: OOM (%d)\n", (int)(len+1));
  199. return 1;
  200. }
  201. p = 0;
  202. while (42) {
  203. if ((len - p) < 1) {
  204. len += SOCKSIZ;
  205. buf = realloc(buf, len+1);
  206. if (!buf) {
  207. printf("Err: OOM (%d)\n", (int)(len+1));
  208. return 1;
  209. }
  210. }
  211. n = recv(sock, &buf[p], len - p , 0);
  212. if (SOCKETFAIL(n)) {
  213. printf("Recv failed: %s\n", SOCKERRMSG);
  214. ret = 1;
  215. break;
  216. }
  217. if (n == 0)
  218. break;
  219. p += n;
  220. }
  221. buf[p] = '\0';
  222. if (ONLY)
  223. printf("%s\n", buf);
  224. else {
  225. printf("Reply was '%s'\n", buf);
  226. display(buf);
  227. }
  228. }
  229. CLOSESOCKET(sock);
  230. return ret;
  231. }
  232. static char *trim(char *str)
  233. {
  234. char *ptr;
  235. while (isspace(*str))
  236. str++;
  237. ptr = strchr(str, '\0');
  238. while (ptr-- > str) {
  239. if (isspace(*ptr))
  240. *ptr = '\0';
  241. }
  242. return str;
  243. }
  244. int main(int argc, char *argv[])
  245. {
  246. char *command = "summary";
  247. char *host = "127.0.0.1";
  248. short int port = 4028;
  249. char *ptr;
  250. int i = 1;
  251. if (argc > 1)
  252. if (strcmp(argv[1], "-?") == 0
  253. || strcmp(argv[1], "-h") == 0
  254. || strcmp(argv[1], "--help") == 0) {
  255. fprintf(stderr, "usAge: %s [command [ip/host [port]]]\n", argv[0]);
  256. return 1;
  257. }
  258. if (argc > 1)
  259. if (strcmp(argv[1], "-o") == 0) {
  260. ONLY = 1;
  261. i = 2;
  262. }
  263. if (argc > i) {
  264. ptr = trim(argv[i++]);
  265. if (strlen(ptr) > 0)
  266. command = ptr;
  267. }
  268. if (argc > i) {
  269. ptr = trim(argv[i++]);
  270. if (strlen(ptr) > 0)
  271. host = ptr;
  272. }
  273. if (argc > i) {
  274. ptr = trim(argv[i]);
  275. if (strlen(ptr) > 0)
  276. port = atoi(ptr);
  277. }
  278. return callapi(command, host, port);
  279. }