api-example.c 7.1 KB

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