2 * Dolda Connect - Modular multiuser Direct Connect-style client
3 * Copyright (C) 2004 Fredrik Tolf <fredrik@dolda2000.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * Note: This code is still ugly, since I copied it almost verbatim
22 * from the daemon's parser. It would need serious cleanups, but at
23 * least it works for now.
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
47 #include <arpa/nameser.h>
51 #include <doldaconnect/uilib.h>
54 #define DOLCON_SRV_NAME "_dolcon._tcp"
64 struct respclass *next;
74 struct respclass *classes;
84 int (*callback)(struct dc_response *resp);
88 void dc_uimisc_disconnected(void);
90 /* The first command must be the nameless connect command and second
91 * the notification command. */
92 static struct command *commands = NULL;
93 static struct qcmd *queue = NULL, *queueend = NULL;
94 static struct dc_response *respqueue = NULL, *respqueueend = NULL;
95 static int state = -1;
97 static iconv_t ichandle;
98 static int resetreader = 1;
99 static struct addrinfo *hostlist = NULL, *curhost = NULL;
107 static void message(int bits, char *format, ...)
116 if((v = getenv("LIBDCUI_MSG")) != NULL)
117 hb = strtol(v, NULL, 0) & 65535;
121 va_start(args, format);
122 vfprintf(stderr, format, args);
127 static char *formataddress(struct sockaddr *arg, socklen_t arglen)
129 struct sockaddr_in *ipv4;
131 struct sockaddr_in6 *ipv6;
133 static char *ret = NULL;
139 switch(arg->sa_family)
142 ret = sprintf2("Unix socket (%s)", ((struct sockaddr_un *)arg)->sun_path);
145 ipv4 = (struct sockaddr_in *)arg;
146 if(inet_ntop(AF_INET, &ipv4->sin_addr, buf, sizeof(buf)) == NULL)
148 ret = sprintf2("%s:%i", buf, (int)ntohs(ipv4->sin_port));
152 ipv6 = (struct sockaddr_in6 *)arg;
153 if(inet_ntop(AF_INET6, &ipv6->sin6_addr, buf, sizeof(buf)) == NULL)
155 ret = sprintf2("[%s]:%i", buf, (int)ntohs(ipv6->sin6_port));
159 errno = EPFNOSUPPORT;
164 static struct dc_response *makeresp(void)
166 struct dc_response *new;
168 new = smalloc(sizeof(*new));
181 static void freeqcmd(struct qcmd *qcmd)
183 if(qcmd->buf != NULL)
188 static void unlinkqueue(void)
192 if((qcmd = queue) == NULL)
200 static struct qcmd *makeqcmd(wchar_t *name)
210 for(cmd = commands; cmd != NULL; cmd = cmd->next)
212 if((cmd->name != NULL) && !wcscmp(cmd->name, name))
216 errno = ENOSYS; /* Bleh */
220 new = smalloc(sizeof(*new));
225 new->callback = NULL;
230 queue = queueend = new;
232 queueend->next = new;
238 static wchar_t *quoteword(wchar_t *word)
240 wchar_t *wp, *buf, *bp;
250 for(wp = word; *wp != L'\0'; wp++)
252 if(!dq && iswspace(*wp))
254 if((*wp == L'\\') || (*wp == L'\"'))
261 bp = buf = smalloc(sizeof(wchar_t) * (numc + numbs + (dq?2:0) + 1));
264 for(wp = word; *wp != L'\0'; wp++)
266 if((*wp == L'\\') || (*wp == L'\"'))
276 static struct command *makecmd(wchar_t *name)
280 new = smalloc(sizeof(*new));
283 new->next = commands;
288 static struct respclass *addresp(struct command *cmd, int code, ...)
290 struct respclass *new;
295 va_start(args, code);
297 while((resps[i++] = va_arg(args, int)) != RESP_END);
300 new = smalloc(sizeof(*new));
305 new->wordt = smalloc(sizeof(int) * i);
306 memcpy(new->wordt, resps, sizeof(int) * i);
310 new->next = cmd->classes;
315 #include "initcmds.h"
319 if((ichandle = iconv_open("wchar_t", "utf-8")) == (iconv_t)-1)
321 dc_srv_local = sstrdup("");
326 void dc_cleanup(void)
328 iconv_close(ichandle);
331 void dc_disconnect(void)
333 struct dc_response *resp;
341 while((resp = dc_getresp()) != NULL)
343 dc_uimisc_disconnected();
344 if(servinfo.hostname != NULL)
345 free(servinfo.hostname);
346 memset(&servinfo, 0, sizeof(servinfo));
349 void dc_freeresp(struct dc_response *resp)
353 for(i = 0; i < resp->numlines; i++)
355 for(o = 0; o < resp->rlines[i].argc; o++)
356 free(resp->rlines[i].argv[o]);
357 free(resp->rlines[i].argv);
363 struct dc_response *dc_getresp(void)
365 struct dc_response *ret;
367 if((ret = respqueue) == NULL)
369 respqueue = ret->next;
370 if(respqueue == NULL)
373 respqueue->prev = NULL;
377 struct dc_response *dc_gettaggedresp(int tag)
379 struct dc_response *resp;
381 for(resp = respqueue; resp != NULL; resp = resp->next)
385 if(resp->prev != NULL)
386 resp->prev->next = resp->next;
387 if(resp->next != NULL)
388 resp->next->prev = resp->prev;
389 if(resp == respqueue)
390 respqueue = resp->next;
391 if(resp == respqueueend)
392 respqueueend = resp->prev;
399 struct dc_response *dc_gettaggedrespsync(int tag)
402 struct dc_response *resp;
404 while((resp = dc_gettaggedresp(tag)) == NULL)
409 pfd.events |= POLLOUT;
410 if(poll(&pfd, 1, -1) < 0)
412 if((pfd.revents & POLLIN) && dc_handleread())
414 if((pfd.revents & POLLOUT) && dc_handlewrite())
420 int dc_wantwrite(void)
425 if((queue != NULL) && (queue->buflen > 0))
432 int dc_getstate(void)
437 int dc_queuecmd(int (*callback)(struct dc_response *), void *data, ...)
445 wchar_t *part, *tpart;
446 size_t bufsize, bufdata;
449 bufsize = bufdata = 0;
452 while((part = va_arg(al, wchar_t *)) != NULL)
454 if(!wcscmp(part, L"%a"))
456 for(toks = va_arg(al, wchar_t **); *toks != NULL; toks++)
460 if((tpart = quoteword(part)) != NULL)
466 bufcat(buf, part, wcslen(part));
475 if(!wcscmp(tpart, L"i"))
478 part = swprintf2(L"%i", va_arg(al, int));
479 } else if(!wcscmp(tpart, L"s")) {
481 part = icmbstowcs(sarg = va_arg(al, char *), NULL);
488 } else if(!wcscmp(tpart, L"ls")) {
489 part = va_arg(al, wchar_t *);
490 } else if(!wcscmp(tpart, L"ll")) {
492 part = swprintf2(L"%lli", va_arg(al, long long));
493 } else if(!wcscmp(tpart, L"f")) {
495 part = swprintf2(L"%f", va_arg(al, double));
496 } else if(!wcscmp(tpart, L"x")) {
498 part = swprintf2(L"%x", va_arg(al, int));
508 if((tpart = quoteword(part)) != NULL)
519 if((qcmd = makeqcmd(part)) == NULL)
527 qcmd->callback = callback;
531 bufcat(buf, part, wcslen(part));
537 bufcat(buf, L"\r\n\0", 3);
538 if((final = icwcstombs(buf, "utf-8")) == NULL)
546 qcmd->buflen = strlen(final);
550 int dc_handleread(void)
557 /* Ewww... this really is soo ugly. I need to clean this up some day. */
558 static int pstate = 0;
559 static char inbuf[128];
560 static size_t inbufdata = 0;
561 static wchar_t *cbuf = NULL;
562 static size_t cbufsize = 0, cbufdata = 0;
563 static wchar_t *pptr = NULL;
564 static wchar_t **argv = NULL;
566 static size_t args = 0;
567 static wchar_t *cw = NULL;
568 static size_t cwsize = 0, cwdata = 0;
569 static struct dc_response *curresp = NULL;
571 static int unlink = 0;
578 optlen = sizeof(ret);
579 getsockopt(fd, SOL_SOCKET, SO_ERROR, &ret, &optlen);
584 message(2, "could not connect to %s: %s\n", formataddress(curhost->ai_addr, curhost->ai_addrlen), strerror(ret));
585 for(curhost = curhost->ai_next; curhost != NULL; curhost = curhost->ai_next)
587 if((newfd = socket(curhost->ai_family, curhost->ai_socktype, curhost->ai_protocol)) < 0)
596 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
597 message(4, "connecting to %s\n", formataddress(curhost->ai_addr, curhost->ai_addrlen));
598 if(connect(fd, (struct sockaddr *)curhost->ai_addr, curhost->ai_addrlen))
600 if(errno == EINPROGRESS)
602 message(2, "could not connect to %s: %s\n", formataddress(curhost->ai_addr, curhost->ai_addrlen), strerror(ret));
614 if(curhost->ai_canonname != NULL)
615 servinfo.hostname = sstrdup(curhost->ai_canonname);
616 servinfo.family = curhost->ai_family;
630 dc_freeresp(curresp);
635 ret = read(fd, inbuf + inbufdata, 128 - inbufdata);
638 if((errno == EAGAIN) || (errno == EINTR))
644 } else if(ret == 0) {
653 if(cbufsize == cbufdata)
657 if((cbuf = realloc(cbuf, sizeof(wchar_t) * (cbufsize += 256))) == NULL)
667 p2 = (char *)(cbuf + cbufdata);
668 len = sizeof(wchar_t) * (cbufsize - cbufdata);
669 ret = iconv(ichandle, &p1, &inbufdata, &p2, &len);
670 memmove(inbuf, p1, inbufdata);
671 cbufdata = cbufsize - (len / sizeof(wchar_t));
677 /* XXX Is this really OK? */
699 while(!done && (pptr - cbuf < cbufdata))
708 if(pptr == cbuf + cbufdata - 1)
713 if(*(++pptr) == L'\n')
717 curresp = makeresp();
718 if((argc > 0) && ((curresp->code = wcstol(argv[0], NULL, 10)) >= 600))
720 curresp->cmdname = L".notify";
721 curresp->internal = commands->next;
725 if((curresp->cmdname = queue->cmd->name) == NULL)
726 curresp->cmdname = L".connect";
727 curresp->data = queue->data;
728 curresp->tag = queue->tag;
729 curresp->internal = (void *)(queue->cmd);
733 sizebuf(&curresp->rlines, &curresp->linessize, curresp->numlines + 1, sizeof(*(curresp->rlines)), 1);
734 curresp->rlines[curresp->numlines].argc = argc;
735 curresp->rlines[curresp->numlines].argv = argv;
741 if((curresp->code >= 600) || (queue == NULL) || (queue->callback == NULL))
744 ret = queue->callback(curresp);
747 if(respqueue == NULL)
749 respqueue = respqueueend = curresp;
751 curresp->next = NULL;
752 curresp->prev = respqueueend;
753 respqueueend->next = curresp;
754 respqueueend = curresp;
756 } else if(ret == 1) {
757 dc_freeresp(curresp);
763 wmemmove(cbuf, pptr, cbufdata -= (pptr - cbuf));
777 if(iswspace(*pptr) || ((argc == 0) && (*pptr == L'-')))
790 sizebuf(&argv, &args, argc + 1, sizeof(*argv), 1);
795 } else if(*pptr == L'\"') {
798 } else if(*pptr == L'\\') {
799 if(pptr == cbuf + cbufdata - 1)
804 addtobuf(cw, *(++pptr));
807 addtobuf(cw, *(pptr++));
814 } else if(*pptr == L'\\') {
815 addtobuf(cw, *(++pptr));
828 #if UNIX_AUTH_STYLE == 1
829 static void mkcreds(struct msghdr *msg)
832 static char buf[CMSG_SPACE(sizeof(*ucred))];
833 struct cmsghdr *cmsg;
835 msg->msg_control = buf;
836 msg->msg_controllen = sizeof(buf);
837 cmsg = CMSG_FIRSTHDR(msg);
838 cmsg->cmsg_level = SOL_SOCKET;
839 cmsg->cmsg_type = SCM_CREDENTIALS;
840 cmsg->cmsg_len = CMSG_LEN(sizeof(*ucred));
841 ucred = (struct ucred *)CMSG_DATA(cmsg);
842 ucred->pid = getpid();
843 ucred->uid = getuid();
844 ucred->gid = getgid();
845 msg->msg_controllen = cmsg->cmsg_len;
849 int dc_handlewrite(void)
859 if(queue->buflen > 0)
861 memset(&msg, 0, sizeof(msg));
862 msg.msg_iov = &bufvec;
864 bufvec.iov_base = queue->buf;
865 bufvec.iov_len = queue->buflen;
866 #if UNIX_AUTH_STYLE == 1
867 if((servinfo.family == PF_UNIX) && !servinfo.sentcreds)
870 servinfo.sentcreds = 1;
873 ret = sendmsg(fd, &msg, MSG_NOSIGNAL | MSG_DONTWAIT);
876 if((errno == EAGAIN) || (errno == EINTR))
884 memmove(queue->buf, queue->buf + ret, queue->buflen -= ret);
893 * It kind of sucks that libresolv doesn't have any DNS parsing
894 * routines. We'll have to do it manually.
896 static char *readname(unsigned char *msg, unsigned char *eom, unsigned char **p)
900 size_t namesize, namedata, len;
903 namesize = namedata = 0;
911 } else if(len == 0xc0) {
912 tp = msg + *((*p)++);
913 if((tname = readname(msg, eom, &tp)) == NULL)
919 bufcat(name, tname, strlen(tname));
923 } else if(*p + len >= eom) {
928 bufcat(name, *p, len);
934 static int skipname(unsigned char *msg, unsigned char *eom, unsigned char **p)
944 } else if(len == 0xc0) {
947 } else if(*p + len >= eom) {
954 static int getsrvrr(char *name, char **host, int *port)
957 char *name2, *rrname;
958 unsigned char *eom, *p;
959 unsigned char buf[1024];
960 int flags, num, class, type;
964 if(!(_res.options & RES_INIT))
969 /* res_querydomain doesn't work for some reason */
970 if(name[strlen(name) - 1] == '.')
971 name2 = sprintf2("%s.%s", DOLCON_SRV_NAME, name);
973 name2 = sprintf2("%s.%s.", DOLCON_SRV_NAME, name);
974 ret = res_query(name2, C_IN, T_SRV, buf, sizeof(buf));
982 * Assume transaction ID is correct.
984 * Flags check: FA0F masks in request/response flag, opcode,
985 * truncated flag and status code, and ignores authoritativeness,
986 * recursion flags and DNSSEC and reserved bits.
988 flags = (buf[2] << 8) + buf[3];
989 if((flags & 0xfa0f) != 0x8000)
994 /* Skip the query entries */
995 num = (buf[4] << 8) + buf[5];
997 for(i = 0; i < num; i++)
999 if(skipname(buf, eom, &p))
1004 p += 4; /* Type and class */
1007 num = (buf[6] << 8) + buf[7];
1008 for(i = 0; i < num; i++)
1010 if((rrname = readname(buf, eom, &p)) == NULL)
1017 class = *(p++) << 8;
1022 if((class == C_IN) && (type == T_SRV) && !strcmp(rrname, name2))
1026 /* Noone will want to have alternative DC servers, so
1027 * don't care about priority and weigth */
1033 *port = *(p++) << 8;
1038 if((rrname = readname(buf, eom, &p)) == NULL)
1051 static int getsrvrr(char *name, char **host, int *port)
1058 static struct addrinfo *gaicat(struct addrinfo *l1, struct addrinfo *l2)
1064 for(p = l1; p->ai_next != NULL; p = p->ai_next);
1069 /* This isn't actually correct, in any sense of the word. It only
1070 * works on systems whose getaddrinfo implementation saves the
1071 * sockaddr in the same malloc block as the struct addrinfo. Those
1072 * systems include at least FreeBSD and glibc-based systems, though,
1073 * so it should not be any immediate threat, and it allows me to not
1074 * implement a getaddrinfo wrapper. It can always be changed, should
1075 * the need arise. */
1076 static struct addrinfo *unixgai(int type, char *path)
1079 struct addrinfo *ai;
1080 struct sockaddr_un *un;
1082 buf = smalloc(sizeof(*ai) + sizeof(*un));
1083 memset(buf, 0, sizeof(*ai) + sizeof(*un));
1084 ai = (struct addrinfo *)buf;
1085 un = (struct sockaddr_un *)(buf + sizeof(*ai));
1087 ai->ai_family = AF_UNIX;
1088 ai->ai_socktype = type;
1089 ai->ai_protocol = 0;
1090 ai->ai_addrlen = sizeof(*un);
1091 ai->ai_addr = (struct sockaddr *)un;
1092 ai->ai_canonname = NULL;
1094 un->sun_family = PF_UNIX;
1095 strncpy(un->sun_path, path, sizeof(un->sun_path) - 1);
1099 static struct addrinfo *resolvtcp(char *name, int port)
1101 struct addrinfo hint, *ret;
1104 memset(&hint, 0, sizeof(hint));
1105 hint.ai_socktype = SOCK_STREAM;
1106 hint.ai_flags = AI_NUMERICSERV | AI_CANONNAME;
1107 snprintf(tmp, sizeof(tmp), "%i", port);
1108 if(!getaddrinfo(name, tmp, &hint, &ret))
1113 static struct addrinfo *resolvsrv(char *name)
1115 struct addrinfo *ret;
1119 if(getsrvrr(name, &realname, &port))
1121 message(4, "SRV RR resolved: %s -> %s\n", name, realname);
1122 ret = resolvtcp(realname, port);
1127 static struct addrinfo *resolvhost(char *host)
1130 struct addrinfo *ret;
1133 if(strchr(host, '/'))
1134 return(unixgai(SOCK_STREAM, host));
1135 if((strchr(host, ':') == NULL) && ((ret = resolvsrv(host)) != NULL))
1138 if((*host == '[') && ((p = strchr(host, ']')) != NULL))
1140 hp = memcpy(smalloc(p - host), host + 1, (p - host) - 1);
1141 hp[(p - host) - 1] = 0;
1142 if(strchr(hp, ':') != NULL) {
1148 ret = resolvtcp(hp, port);
1156 if((p = strrchr(hp, ':')) != NULL) {
1162 ret = resolvtcp(hp, port);
1169 static struct addrinfo *getlocalai(void)
1171 struct addrinfo *ret;
1176 if((getuid() != 0) && ((pwd = getpwuid(getuid())) != NULL))
1178 tmp = sprintf2("/tmp/doldacond-%s", pwd->pw_name);
1179 ret = unixgai(SOCK_STREAM, tmp);
1182 ret = gaicat(ret, unixgai(SOCK_STREAM, "/var/run/doldacond.sock"));
1186 static struct addrinfo *defaulthost(void)
1188 struct addrinfo *ret;
1192 if(((tmp = getenv("DCSERVER")) != NULL) && *tmp) {
1193 message(4, "using DCSERVER: %s\n", tmp);
1194 return(resolvhost(tmp));
1197 ret = gaicat(ret, resolvtcp("localhost", 1500));
1198 if(!getdomainname(dn, sizeof(dn)) && *dn && strcmp(dn, "(none)"))
1199 ret = gaicat(ret, resolvsrv(dn));
1203 static int dc_connectai(struct addrinfo *hosts, struct qcmd **cnctcmd)
1211 if(hostlist != NULL)
1212 freeaddrinfo(hostlist);
1214 for(curhost = hostlist; curhost != NULL; curhost = curhost->ai_next)
1216 if((fd = socket(curhost->ai_family, curhost->ai_socktype, curhost->ai_protocol)) < 0)
1219 freeaddrinfo(hostlist);
1224 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
1225 message(4, "connecting to %s\n", formataddress(curhost->ai_addr, curhost->ai_addrlen));
1226 if(connect(fd, (struct sockaddr *)curhost->ai_addr, curhost->ai_addrlen))
1228 if(errno == EINPROGRESS)
1233 message(2, "could not connect to %s: %s\n", formataddress(curhost->ai_addr, curhost->ai_addrlen), strerror(errno));
1237 if(curhost->ai_canonname != NULL)
1238 servinfo.hostname = sstrdup(curhost->ai_canonname);
1239 servinfo.family = curhost->ai_family;
1246 qcmd = makeqcmd(NULL);
1257 static int dc_connect2(char *host, struct qcmd **cnctcmd)
1259 struct addrinfo *ai;
1263 if(host == dc_srv_local) {
1264 message(4, "connect start: Unix\n");
1266 } else if(!host || !*host) {
1267 message(4, "connect start: default\n");
1270 message(4, "connect start: host %s\n", host);
1271 ai = resolvhost(host);
1275 ret = dc_connectai(ai, &qcmd);
1276 if((ret >= 0) && (cnctcmd != NULL))
1281 int dc_connect(char *host)
1283 return(dc_connect2(host, NULL));
1286 int dc_connectsync(char *host, struct dc_response **respbuf)
1290 struct dc_response *resp;
1292 if((ret = dc_connect2(host, &cc)) < 0)
1294 resp = dc_gettaggedrespsync(cc->tag);
1306 int dc_connectsync2(char *host, int rev)
1309 struct dc_response *resp;
1311 if((ret = dc_connectsync(host, &resp)) < 0)
1313 if(dc_checkprotocol(resp, rev))
1317 errno = EPROTONOSUPPORT;
1324 struct dc_intresp *dc_interpret(struct dc_response *resp)
1327 struct dc_intresp *iresp;
1328 struct command *cmd;
1329 struct respclass *cls;
1333 if((resp->numlines == 0) || (resp->rlines[0].argc == 0) || (resp->curline >= resp->numlines))
1335 code = wcstol(resp->rlines[0].argv[0], NULL, 10);
1336 cmd = (struct command *)(resp->internal);
1337 for(cls = cmd->classes; cls != NULL; cls = cls->next)
1339 if(cls->code == code)
1344 if(cls->nwords >= resp->rlines[resp->curline].argc)
1346 iresp = smalloc(sizeof(*iresp));
1351 for(i = 0; i < cls->nwords; i++)
1353 switch(cls->wordt[i])
1358 sizebuf(&(iresp->argv), &args, iresp->argc + 1, sizeof(*(iresp->argv)), 1);
1359 iresp->argv[iresp->argc].val.str = swcsdup(resp->rlines[resp->curline].argv[i + 1]);
1360 iresp->argv[iresp->argc].type = cls->wordt[i];
1364 sizebuf(&(iresp->argv), &args, iresp->argc + 1, sizeof(*(iresp->argv)), 1);
1365 iresp->argv[iresp->argc].val.num = wcstol(resp->rlines[resp->curline].argv[i + 1], NULL, 0);
1366 iresp->argv[iresp->argc].type = cls->wordt[i];
1370 sizebuf(&(iresp->argv), &args, iresp->argc + 1, sizeof(*(iresp->argv)), 1);
1371 iresp->argv[iresp->argc].val.flnum = wcstod(resp->rlines[resp->curline].argv[i + 1], NULL);
1372 iresp->argv[iresp->argc].type = cls->wordt[i];
1381 void dc_freeires(struct dc_intresp *ires)
1385 for(i = 0; i < ires->argc; i++)
1387 if(ires->argv[i].type == RESP_STR)
1388 free(ires->argv[i].val.str);
1394 int dc_checkprotocol(struct dc_response *resp, int revision)
1396 struct dc_intresp *ires;
1399 if(resp->code != 201)
1402 if((ires = dc_interpret(resp)) == NULL)
1404 low = ires->argv[0].val.num;
1405 high = ires->argv[1].val.num;
1407 if((revision < low) || (revision > high))
1412 const char *dc_gethostname(void)
1414 return(servinfo.hostname);