api-example.c 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <ctype.h>
  14. #include <unistd.h>
  15. #include <stdbool.h>
  16. #include <stdint.h>
  17. #include <sys/types.h>
  18. #include "compat.h"
  19. #if defined(unix)
  20. #include <errno.h>
  21. #include <sys/socket.h>
  22. #include <netinet/in.h>
  23. #include <arpa/inet.h>
  24. #include <netdb.h>
  25. #define SOCKETTYPE int
  26. #define SOCKETFAIL(a) ((a) < 0)
  27. #define INVSOCK -1
  28. #define CLOSESOCKET close
  29. #define SOCKETINIT {}
  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 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. char *msg;
  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 int wsa; \
  110. if (wsa = WSAStartup(0x0202, &WSA_Data)) { \
  111. printf("Socket startup failed: %d\n", wsa); \
  112. return 1; \
  113. }
  114. #ifndef SHUT_RDWR
  115. #define SHUT_RDWR SD_BOTH
  116. #endif
  117. #endif
  118. #define RECVSIZE 65500
  119. static const char SEPARATOR = '|';
  120. static const char COMMA = ',';
  121. static const char EQ = '=';
  122. void display(char *buf)
  123. {
  124. char *nextobj, *item, *nextitem, *eq;
  125. int itemcount;
  126. while (buf != NULL) {
  127. nextobj = strchr(buf, SEPARATOR);
  128. if (nextobj != NULL)
  129. *(nextobj++) = '\0';
  130. if (*buf) {
  131. item = buf;
  132. itemcount = 0;
  133. while (item != NULL) {
  134. nextitem = strchr(item, COMMA);
  135. if (nextitem != NULL)
  136. *(nextitem++) = '\0';
  137. if (*item) {
  138. eq = strchr(item, EQ);
  139. if (eq != NULL)
  140. *(eq++) = '\0';
  141. if (itemcount == 0)
  142. printf("[%s%s] =>\n(\n", item, (eq != NULL && isdigit(*eq)) ? eq : "");
  143. if (eq != NULL)
  144. printf(" [%s] => %s\n", item, eq);
  145. else
  146. printf(" [%d] => %s\n", itemcount, item);
  147. }
  148. item = nextitem;
  149. itemcount++;
  150. }
  151. if (itemcount > 0)
  152. puts(")");
  153. }
  154. buf = nextobj;
  155. }
  156. }
  157. int callapi(char *command, char *host, short int port)
  158. {
  159. char buf[RECVSIZE+1];
  160. struct hostent *ip;
  161. struct sockaddr_in serv;
  162. SOCKETTYPE sock;
  163. int ret = 0;
  164. int n, p;
  165. SOCKETINIT;
  166. ip = gethostbyname(host);
  167. sock = socket(AF_INET, SOCK_STREAM, 0);
  168. if (sock == INVSOCK) {
  169. printf("Socket initialisation failed: %s\n", SOCKERRMSG);
  170. return 1;
  171. }
  172. memset(&serv, 0, sizeof(serv));
  173. serv.sin_family = AF_INET;
  174. serv.sin_addr = *((struct in_addr *)ip->h_addr);
  175. serv.sin_port = htons(port);
  176. if (SOCKETFAIL(connect(sock, (struct sockaddr *)&serv, sizeof(struct sockaddr)))) {
  177. printf("Socket connect failed: %s\n", SOCKERRMSG);
  178. return 1;
  179. }
  180. n = send(sock, command, strlen(command), 0);
  181. if (SOCKETFAIL(n)) {
  182. printf("Send failed: %s\n", SOCKERRMSG);
  183. ret = 1;
  184. }
  185. else {
  186. p = 0;
  187. buf[0] = '\0';
  188. while (p < RECVSIZE) {
  189. n = recv(sock, &buf[p], RECVSIZE - p , 0);
  190. if (SOCKETFAIL(n)) {
  191. printf("Recv failed: %s\n", SOCKERRMSG);
  192. ret = 1;
  193. break;
  194. }
  195. if (n == 0)
  196. break;
  197. p += n;
  198. buf[p] = '\0';
  199. }
  200. printf("Reply was '%s'\n", buf);
  201. display(buf);
  202. }
  203. CLOSESOCKET(sock);
  204. return ret;
  205. }
  206. static char *trim(char *str)
  207. {
  208. char *ptr;
  209. while (isspace(*str))
  210. str++;
  211. ptr = strchr(str, '\0');
  212. while (ptr-- > str) {
  213. if (isspace(*ptr))
  214. *ptr = '\0';
  215. }
  216. return str;
  217. }
  218. int main(int argc, char *argv[])
  219. {
  220. char *command = "summary";
  221. char *host = "127.0.0.1";
  222. short int port = 4028;
  223. char *ptr;
  224. if (argc > 1)
  225. if (strcmp(argv[1], "-?") == 0
  226. || strcmp(argv[1], "-h") == 0
  227. || strcmp(argv[1], "--help") == 0) {
  228. fprintf(stderr, "usAge: %s [command [ip/host [port]]]\n", argv[0]);
  229. return 1;
  230. }
  231. if (argc > 1) {
  232. ptr = trim(argv[1]);
  233. if (strlen(ptr) > 0)
  234. command = ptr;
  235. }
  236. if (argc > 2) {
  237. ptr = trim(argv[2]);
  238. if (strlen(ptr) > 0)
  239. host = ptr;
  240. }
  241. if (argc > 3) {
  242. ptr = trim(argv[3]);
  243. if (strlen(ptr) > 0)
  244. port = atoi(ptr);
  245. }
  246. return callapi(command, host, port);
  247. }