00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035 #include <config.h>
00036
00037 #include <ctype.h>
00038 #include <errno.h>
00039 #include <stdio.h>
00040 #include <stdlib.h>
00041 #include <string.h>
00042 #ifndef _WIN32
00043 #include <sys/types.h>
00044 #include <sys/socket.h>
00045 #include <unistd.h>
00046 #endif
00047 #include "misc.h"
00048 #include "proto.h"
00049
00050 #ifdef _WIN32
00051 #define read(sock, buffer, buf_size) \
00052 w32_recv((sock), (buffer), (buf_size), 0)
00053 #define write(sock, buffer, buf_size) \
00054 w32_send((sock), (buffer), (buf_size), 0)
00055 #endif
00056
00057 int
00058 recvline(int s, char *buf)
00059 {
00060 int sz = 1024;
00061 char *bp;
00062 char ch;
00063 ssize_t n;
00064
00065 bp = buf;
00066 for (;;) {
00067 n = read(s, &ch, 1);
00068 if (n < 0) {
00069 if (errno != EINTR) {
00070 perror("read");
00071 exit(1);
00072 }
00073 continue;
00074 }
00075 if (n == 0)
00076 return -1;
00077 if (ch == '\n')
00078 break;
00079 if (bp < buf + sz - 2)
00080 *bp++ = ch;
00081
00082 }
00083
00084 *bp++ = ch;
00085 *bp = 0;
00086 return parseid(buf);
00087 }
00088
00089 int
00090 parseid(char *line)
00091 {
00092 char *end;
00093 long id;
00094
00095 id = strtol(line, &end, 36);
00096 if (end == line || *end != ' ') {
00097 fprintf(stderr, "Malformed id in line %s", line);
00098 id = -1;
00099 }
00100 if (id > C_LAST)
00101 id = -1;
00102 return id;
00103 }
00104
00105 int
00106 expect(int s, int match, char *buf)
00107 {
00108 return recvline(s, buf) == match;
00109 }
00110
00111 void
00112 sendcmd(int s, char *cmd, char *arg)
00113 {
00114 char buf[128];
00115 char *p;
00116 ssize_t n;
00117 int len;
00118
00119 len = snprintf(buf, sizeof(buf), "%s %s\n",
00120 cmd, arg != NULL ? arg : "");
00121 if (len >= (int)sizeof(buf)) {
00122 fprintf(stderr, "%s too long\n", cmd);
00123 exit(1);
00124 }
00125 p = buf;
00126 while (len > 0) {
00127 n = write(s, buf, len);
00128 if (n < 0) {
00129 if (errno != EINTR) {
00130 perror("sendcmd: write");
00131 exit(1);
00132 }
00133 n = 0;
00134 }
00135 p += n;
00136 len -= n;
00137 }
00138 }