api-example.c 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /*
  2. * Copyright 2011 Kano
  3. * Copyright 2013 Luke Dashjr
  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. #include "config.h"
  11. #include <assert.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <ctype.h>
  16. #include <unistd.h>
  17. #include <stdbool.h>
  18. #include <stdint.h>
  19. #include <sys/types.h>
  20. #include "compat.h"
  21. #ifndef WIN32
  22. #include <errno.h>
  23. #include <sys/socket.h>
  24. #include <netinet/in.h>
  25. #include <arpa/inet.h>
  26. #include <netdb.h>
  27. #define SOCKETTYPE int
  28. #define SOCKETFAIL(a) ((a) < 0)
  29. #define INVSOCK -1
  30. #define CLOSESOCKET close
  31. #define SOCKETINIT do{}while(0)
  32. #define SOCKERRMSG strerror(errno)
  33. #else
  34. #include <winsock2.h>
  35. #define SOCKETTYPE SOCKET
  36. #define SOCKETFAIL(a) ((a) == SOCKET_ERROR)
  37. #define INVSOCK INVALID_SOCKET
  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. int i;
  99. int id = WSAGetLastError();
  100. /* Assume none of them are actually -1 */
  101. for (i = 0; WSAErrors[i].id != -1; i++)
  102. if (WSAErrors[i].id == id)
  103. break;
  104. sprintf(WSAbuf, "Socket Error: (%d) %s", id, WSAErrors[i].code);
  105. return &(WSAbuf[0]);
  106. }
  107. #define SOCKERRMSG WSAErrorMsg()
  108. static WSADATA WSA_Data;
  109. #define SOCKETINIT do { \
  110. int wsa; \
  111. if ( (wsa = WSAStartup(0x0202, &WSA_Data)) ) { \
  112. printf("Socket startup failed: %d\n", wsa); \
  113. return 1; \
  114. } \
  115. } while (0)
  116. #ifndef SHUT_RDWR
  117. #define SHUT_RDWR SD_BOTH
  118. #endif
  119. #endif
  120. #define RECVSIZE 65500
  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. int callapi(char *command, char *host, short int port)
  161. {
  162. size_t bufsz = RECVSIZE;
  163. char *buf = malloc(bufsz+1);
  164. struct hostent *ip;
  165. struct sockaddr_in serv;
  166. SOCKETTYPE sock;
  167. int ret = 0;
  168. int n, p;
  169. assert(buf);
  170. SOCKETINIT;
  171. ip = gethostbyname(host);
  172. sock = socket(AF_INET, SOCK_STREAM, 0);
  173. if (sock == INVSOCK) {
  174. printf("Socket initialisation failed: %s\n", SOCKERRMSG);
  175. return 1;
  176. }
  177. memset(&serv, 0, sizeof(serv));
  178. serv.sin_family = AF_INET;
  179. serv.sin_addr = *((struct in_addr *)ip->h_addr);
  180. serv.sin_port = htons(port);
  181. if (SOCKETFAIL(connect(sock, (struct sockaddr *)&serv, sizeof(struct sockaddr)))) {
  182. printf("Socket connect failed: %s\n", SOCKERRMSG);
  183. return 1;
  184. }
  185. n = send(sock, command, strlen(command), 0);
  186. if (SOCKETFAIL(n)) {
  187. printf("Send failed: %s\n", SOCKERRMSG);
  188. ret = 1;
  189. }
  190. else {
  191. p = 0;
  192. buf[0] = '\0';
  193. while (true)
  194. {
  195. if (bufsz < RECVSIZE + p)
  196. {
  197. bufsz *= 2;
  198. buf = realloc(buf, bufsz);
  199. assert(buf);
  200. }
  201. n = recv(sock, &buf[p], RECVSIZE, 0);
  202. if (SOCKETFAIL(n)) {
  203. printf("Recv failed: %s\n", SOCKERRMSG);
  204. ret = 1;
  205. break;
  206. }
  207. if (n == 0)
  208. break;
  209. p += n;
  210. buf[p] = '\0';
  211. }
  212. if (!ONLY)
  213. printf("Reply was '%s'\n", buf);
  214. else
  215. printf("%s\n", buf);
  216. if (!ONLY)
  217. display(buf);
  218. }
  219. CLOSESOCKET(sock);
  220. return ret;
  221. }
  222. static char *trim(char *str)
  223. {
  224. char *ptr;
  225. while (isspace(*str))
  226. str++;
  227. ptr = strchr(str, '\0');
  228. while (ptr-- > str) {
  229. if (isspace(*ptr))
  230. *ptr = '\0';
  231. }
  232. return str;
  233. }
  234. int main(int argc, char *argv[])
  235. {
  236. char *command = "summary";
  237. char *host = "127.0.0.1";
  238. short int port = 4028;
  239. char *ptr;
  240. int i = 1;
  241. if (argc > 1)
  242. if (strcmp(argv[1], "-?") == 0
  243. || strcmp(argv[1], "-h") == 0
  244. || strcmp(argv[1], "--help") == 0) {
  245. fprintf(stderr, "Usage: %s [command [ip/host [port]]]\n", argv[0]);
  246. return 1;
  247. }
  248. if (argc > 1)
  249. if (strcmp(argv[1], "-o") == 0) {
  250. ONLY = 1;
  251. i = 2;
  252. }
  253. if (argc > i) {
  254. ptr = trim(argv[i++]);
  255. if (strlen(ptr) > 0)
  256. command = ptr;
  257. }
  258. if (argc > i) {
  259. ptr = trim(argv[i++]);
  260. if (strlen(ptr) > 0)
  261. host = ptr;
  262. }
  263. if (argc > i) {
  264. ptr = trim(argv[i]);
  265. if (strlen(ptr) > 0)
  266. port = atoi(ptr);
  267. }
  268. return callapi(command, host, port);
  269. }