2 * forward_api_calls.c: forward XMLRPC calls to the Node Manager
3 * Used as a shell, this code works in tandem with sshd
4 * to allow authenticated remote access to a localhost-only service.
7 * Doesn't handle Unicode properly. UTF-8 is probably OK.
10 * 2007/05/02: [deisenst] Increased buffer space to 1MiB.
11 * Increased TIMEOUT_SECS to 2min.
12 * 2006/10/30: [deisenst] Changed location of Unix socket.
13 * 2006/09/14: [deisenst] Switched to PF_UNIX sockets so that SO_PEERCRED works
14 * 2006/09/08: [deisenst] First version.
17 static const int TIMEOUT_SECS = 120;
18 const char *API_addr = "/tmp/nodemanager.api";
20 static const char *Header =
22 "Content-Type: text/xml\r\n"
23 "Content-Length: %d\r\n"
26 static const char *Error_template =
27 "<?xml version='1.0'?>\n"
32 "<name>faultCode</name>\n"
33 "<value><int>1</int></value>\n"
36 "<name>faultString</name>\n"
37 "<value><string>%s: %s</string></value>\n"
41 "</methodResponse>\n";
48 #include <sys/socket.h>
49 #include <sys/types.h>
53 static void ERROR(const char *s) {
54 printf(Error_template, s, strerror(errno));
58 int main(int argc, char **argv, char **envp) {
60 char header_buf[1<<20];
61 char content_buf[1<<20];
64 struct sockaddr_un addr;
65 int consecutive_newlines;
69 /* read xmlrpc request from stdin
70 * 4 KiB ought to be enough for anyone
71 * 2007/05/02: [deisenst] It wasn't.
74 while(content_len < sizeof content_buf) {
76 content_buf + content_len,
77 sizeof content_buf - content_len);
78 if(len < 0) ERROR("read()");
79 else if(0 == len) break;
83 /* connect to the API server */
84 sockfd = socket(PF_UNIX, SOCK_STREAM, 0);
87 memset(&addr, 0, sizeof addr);
88 addr.sun_family = AF_UNIX;
89 strncpy(addr.sun_path, API_addr, sizeof addr.sun_path);
90 if(connect(sockfd, (struct sockaddr *)&addr, sizeof addr) < 0)
93 /* send the request */
94 snprintf(header_buf, sizeof header_buf, Header, content_len, &len);
95 write(sockfd, header_buf, len);
96 write(sockfd, content_buf, content_len);
97 shutdown(sockfd, SHUT_WR);
99 /* forward the response */
100 consecutive_newlines = 0;
101 while((len = read(sockfd, content_buf, sizeof content_buf)) != 0) {
102 size_t processed_len = 0;
104 /* "Connection reset by peer" is not worth bothering the user. */
105 if(ECONNRESET == errno) break;
106 else ERROR("read()");
110 while(consecutive_newlines < 2 && processed_len < content_len) {
111 char ch = content_buf[processed_len++];
112 if(ch == '\n') consecutive_newlines++;
113 else if(!isspace(ch)) consecutive_newlines = 0;
116 if(processed_len < content_len) {
117 len = fwrite(content_buf + processed_len, sizeof (char),
118 content_len - processed_len, stdout);
119 /* make sure faults don't mess up previously sent xml */
120 if(len < content_len - processed_len) ERROR("fwrite()");
125 shutdown(sockfd, SHUT_RD);