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;
106 static struct dc_response *makeresp(void)
108 struct dc_response *new;
110 new = smalloc(sizeof(*new));
123 static void freeqcmd(struct qcmd *qcmd)
125 if(qcmd->buf != NULL)
130 static void unlinkqueue(void)
134 if((qcmd = queue) == NULL)
142 static struct qcmd *makeqcmd(wchar_t *name)
152 for(cmd = commands; cmd != NULL; cmd = cmd->next)
154 if((cmd->name != NULL) && !wcscmp(cmd->name, name))
160 new = smalloc(sizeof(*new));
165 new->callback = NULL;
170 queue = queueend = new;
172 queueend->next = new;
178 static wchar_t *quoteword(wchar_t *word)
180 wchar_t *wp, *buf, *bp;
190 for(wp = word; *wp != L'\0'; wp++)
192 if(!dq && iswspace(*wp))
194 if((*wp == L'\\') || (*wp == L'\"'))
201 bp = buf = smalloc(sizeof(wchar_t) * (numc + numbs + (dq?2:0) + 1));
204 for(wp = word; *wp != L'\0'; wp++)
206 if((*wp == L'\\') || (*wp == L'\"'))
216 static struct command *makecmd(wchar_t *name)
220 new = smalloc(sizeof(*new));
223 new->next = commands;
228 static struct respclass *addresp(struct command *cmd, int code, ...)
230 struct respclass *new;
235 va_start(args, code);
237 while((resps[i++] = va_arg(args, int)) != RESP_END);
240 new = smalloc(sizeof(*new));
245 new->wordt = smalloc(sizeof(int) * i);
246 memcpy(new->wordt, resps, sizeof(int) * i);
250 new->next = cmd->classes;
255 #include "initcmds.h"
259 if((ichandle = iconv_open("wchar_t", "utf-8")) == (iconv_t)-1)
265 void dc_cleanup(void)
267 iconv_close(ichandle);
270 void dc_disconnect(void)
272 struct dc_response *resp;
280 while((resp = dc_getresp()) != NULL)
282 dc_uimisc_disconnected();
283 if(servinfo.hostname != NULL)
284 free(servinfo.hostname);
285 memset(&servinfo, 0, sizeof(servinfo));
288 void dc_freeresp(struct dc_response *resp)
292 for(i = 0; i < resp->numlines; i++)
294 for(o = 0; o < resp->rlines[i].argc; o++)
295 free(resp->rlines[i].argv[o]);
296 free(resp->rlines[i].argv);
302 struct dc_response *dc_getresp(void)
304 struct dc_response *ret;
306 if((ret = respqueue) == NULL)
308 respqueue = ret->next;
309 if(respqueue == NULL)
312 respqueue->prev = NULL;
316 struct dc_response *dc_gettaggedresp(int tag)
318 struct dc_response *resp;
320 for(resp = respqueue; resp != NULL; resp = resp->next)
324 if(resp->prev != NULL)
325 resp->prev->next = resp->next;
326 if(resp->next != NULL)
327 resp->next->prev = resp->prev;
328 if(resp == respqueue)
329 respqueue = resp->next;
330 if(resp == respqueueend)
331 respqueueend = resp->prev;
338 struct dc_response *dc_gettaggedrespsync(int tag)
341 struct dc_response *resp;
343 while((resp = dc_gettaggedresp(tag)) == NULL)
348 pfd.events |= POLLOUT;
349 if(poll(&pfd, 1, -1) < 0)
351 if((pfd.revents & POLLIN) && dc_handleread())
353 if((pfd.revents & POLLOUT) && dc_handlewrite())
359 int dc_wantwrite(void)
364 if((queue != NULL) && (queue->buflen > 0))
371 int dc_getstate(void)
376 int dc_queuecmd(int (*callback)(struct dc_response *), void *data, ...)
384 wchar_t *part, *tpart;
385 size_t bufsize, bufdata;
388 bufsize = bufdata = 0;
391 while((part = va_arg(al, wchar_t *)) != NULL)
393 if(!wcscmp(part, L"%%a"))
395 for(toks = va_arg(al, wchar_t **); *toks != NULL; toks++)
399 if((tpart = quoteword(part)) != NULL)
405 bufcat(buf, part, wcslen(part));
413 /* This demands that all arguments that are passed to the
414 * function are of equal length, that of an int. I know
415 * that GCC does that on IA32 platforms, but I do not know
416 * which other platforms and compilers that it applies
417 * to. If this breaks your platform, please mail me about
420 part = vswprintf2(tpart = (part + 1), al);
421 for(; *tpart != L'\0'; tpart++)
435 if((tpart = quoteword(part)) != NULL)
446 if((qcmd = makeqcmd(part)) == NULL)
454 qcmd->callback = callback;
458 bufcat(buf, part, wcslen(part));
464 bufcat(buf, L"\r\n\0", 3);
465 if((final = icwcstombs(buf, "utf-8")) == NULL)
473 qcmd->buflen = strlen(final);
477 int dc_handleread(void)
484 /* Ewww... this really is soo ugly. I need to clean this up some day. */
485 static int pstate = 0;
486 static char inbuf[128];
487 static size_t inbufdata = 0;
488 static wchar_t *cbuf = NULL;
489 static size_t cbufsize = 0, cbufdata = 0;
490 static wchar_t *pptr = NULL;
491 static wchar_t **argv = NULL;
493 static size_t args = 0;
494 static wchar_t *cw = NULL;
495 static size_t cwsize = 0, cwdata = 0;
496 static struct dc_response *curresp = NULL;
498 static int unlink = 0;
505 optlen = sizeof(ret);
506 getsockopt(fd, SOL_SOCKET, SO_ERROR, &ret, &optlen);
511 for(curhost = curhost->ai_next; curhost != NULL; curhost = curhost->ai_next)
513 if((newfd = socket(curhost->ai_family, curhost->ai_socktype, curhost->ai_protocol)) < 0)
522 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
523 if(connect(fd, (struct sockaddr *)curhost->ai_addr, curhost->ai_addrlen))
525 if(errno == EINPROGRESS)
538 if(curhost->ai_canonname != NULL)
539 servinfo.hostname = sstrdup(curhost->ai_canonname);
540 servinfo.family = curhost->ai_family;
554 dc_freeresp(curresp);
559 ret = read(fd, inbuf + inbufdata, 128 - inbufdata);
562 if((errno == EAGAIN) || (errno == EINTR))
568 } else if(ret == 0) {
577 if(cbufsize == cbufdata)
581 if((cbuf = realloc(cbuf, sizeof(wchar_t) * (cbufsize += 256))) == NULL)
591 p2 = (char *)(cbuf + cbufdata);
592 len = sizeof(wchar_t) * (cbufsize - cbufdata);
593 ret = iconv(ichandle, &p1, &inbufdata, &p2, &len);
594 memmove(inbuf, p1, inbufdata);
595 cbufdata = cbufsize - (len / sizeof(wchar_t));
601 /* XXX Is this really OK? */
623 while(!done && (pptr - cbuf < cbufdata))
632 if(pptr == cbuf + cbufdata - 1)
637 if(*(++pptr) == L'\n')
641 curresp = makeresp();
642 if((argc > 0) && ((curresp->code = wcstol(argv[0], NULL, 10)) >= 600))
644 curresp->cmdname = L".notify";
645 curresp->internal = commands->next;
649 if((curresp->cmdname = queue->cmd->name) == NULL)
650 curresp->cmdname = L".connect";
651 curresp->data = queue->data;
652 curresp->tag = queue->tag;
653 curresp->internal = (void *)(queue->cmd);
657 sizebuf(&curresp->rlines, &curresp->linessize, curresp->numlines + 1, sizeof(*(curresp->rlines)), 1);
658 curresp->rlines[curresp->numlines].argc = argc;
659 curresp->rlines[curresp->numlines].argv = argv;
665 if((curresp->code >= 600) || (queue == NULL) || (queue->callback == NULL))
668 ret = queue->callback(curresp);
671 if(respqueue == NULL)
673 respqueue = respqueueend = curresp;
675 curresp->next = NULL;
676 curresp->prev = respqueueend;
677 respqueueend->next = curresp;
678 respqueueend = curresp;
680 } else if(ret == 1) {
681 dc_freeresp(curresp);
687 wmemmove(cbuf, pptr, cbufdata -= (pptr - cbuf));
701 if(iswspace(*pptr) || ((argc == 0) && (*pptr == L'-')))
714 sizebuf(&argv, &args, argc + 1, sizeof(*argv), 1);
719 } else if(*pptr == L'\"') {
722 } else if(*pptr == L'\\') {
723 if(pptr == cbuf + cbufdata - 1)
728 addtobuf(cw, *(++pptr));
731 addtobuf(cw, *(pptr++));
738 } else if(*pptr == L'\\') {
739 addtobuf(cw, *(++pptr));
752 static void mkcreds(struct msghdr *msg)
755 static char buf[CMSG_SPACE(sizeof(*ucred))];
756 struct cmsghdr *cmsg;
758 msg->msg_control = buf;
759 msg->msg_controllen = sizeof(buf);
760 cmsg = CMSG_FIRSTHDR(msg);
761 cmsg->cmsg_level = SOL_SOCKET;
762 cmsg->cmsg_type = SCM_CREDENTIALS;
763 cmsg->cmsg_len = CMSG_LEN(sizeof(*ucred));
764 ucred = (struct ucred *)CMSG_DATA(cmsg);
765 ucred->pid = getpid();
766 ucred->uid = getuid();
767 ucred->gid = getgid();
768 msg->msg_controllen = cmsg->cmsg_len;
771 int dc_handlewrite(void)
781 if(queue->buflen > 0)
783 memset(&msg, 0, sizeof(msg));
784 msg.msg_iov = &bufvec;
786 bufvec.iov_base = queue->buf;
787 bufvec.iov_len = queue->buflen;
788 if((servinfo.family == PF_UNIX) && !servinfo.sentcreds)
791 servinfo.sentcreds = 1;
793 ret = sendmsg(fd, &msg, MSG_NOSIGNAL | MSG_DONTWAIT);
796 if((errno == EAGAIN) || (errno == EINTR))
804 memmove(queue->buf, queue->buf + ret, queue->buflen -= ret);
813 * It kind of sucks that libresolv doesn't have any DNS parsing
814 * routines. We'll have to do it manually.
816 static char *readname(unsigned char *msg, unsigned char *eom, unsigned char **p)
820 size_t namesize, namedata, len;
823 namesize = namedata = 0;
831 } else if(len == 0xc0) {
832 tp = msg + *((*p)++);
833 if((tname = readname(msg, eom, &tp)) == NULL)
839 bufcat(name, tname, strlen(tname));
843 } else if(*p + len >= eom) {
848 bufcat(name, *p, len);
854 static int skipname(unsigned char *msg, unsigned char *eom, unsigned char **p)
864 } else if(len == 0xc0) {
867 } else if(*p + len >= eom) {
874 static int getsrvrr(char *name, char **host, int *port)
877 char *name2, *rrname;
878 unsigned char *eom, *p;
879 unsigned char buf[1024];
880 int flags, num, class, type;
884 if(!(_res.options & RES_INIT))
889 /* res_querydomain doesn't work for some reason */
890 if(name[strlen(name) - 1] == '.')
891 name2 = sprintf2("%s.%s", DOLCON_SRV_NAME, name);
893 name2 = sprintf2("%s.%s.", DOLCON_SRV_NAME, name);
894 ret = res_query(name2, C_IN, T_SRV, buf, sizeof(buf));
902 * Assume transaction ID is correct.
904 * Flags check: FA0F masks in request/response flag, opcode,
905 * truncated flag and status code, and ignores authoritativeness,
906 * recursion flags and DNSSEC and reserved bits.
908 flags = (buf[2] << 8) + buf[3];
909 if((flags & 0xfa0f) != 0x8000)
914 /* Skip the query entries */
915 num = (buf[4] << 8) + buf[5];
917 for(i = 0; i < num; i++)
919 if(skipname(buf, eom, &p))
924 p += 4; /* Type and class */
927 num = (buf[6] << 8) + buf[7];
928 for(i = 0; i < num; i++)
930 if((rrname = readname(buf, eom, &p)) == NULL)
942 if((class == C_IN) && (type == T_SRV) && !strcmp(rrname, name2))
946 /* Noone will want to have alternative DC servers, so
947 * don't care about priority and weigth */
958 if((rrname = readname(buf, eom, &p)) == NULL)
971 static int getsrvrr(char *name, char **host, int *port)
978 static struct addrinfo *gaicat(struct addrinfo *l1, struct addrinfo *l2)
984 for(p = l1; p->ai_next != NULL; p = p->ai_next);
989 /* This isn't actually correct, in any sense of the word. It only
990 * works on systems whose getaddrinfo implementation saves the
991 * sockaddr in the same malloc block as the struct addrinfo. Those
992 * systems include at least FreeBSD and glibc-based systems, though,
993 * so it should not be any immediate threat, and it allows me to not
994 * implement a getaddrinfo wrapper. It can always be changed, should
996 static struct addrinfo *unixgai(int type, char *path)
1000 struct sockaddr_un *un;
1002 buf = smalloc(sizeof(*ai) + sizeof(*un));
1003 memset(buf, 0, sizeof(*ai) + sizeof(*un));
1004 ai = (struct addrinfo *)buf;
1005 un = (struct sockaddr_un *)(buf + sizeof(*ai));
1007 ai->ai_family = AF_UNIX;
1008 ai->ai_socktype = type;
1009 ai->ai_protocol = 0;
1010 ai->ai_addrlen = sizeof(*un);
1011 ai->ai_addr = (struct sockaddr *)un;
1012 ai->ai_canonname = NULL;
1014 un->sun_family = PF_UNIX;
1015 strncpy(un->sun_path, path, sizeof(un->sun_path) - 1);
1019 static struct addrinfo *resolvtcp(char *name, int port)
1021 struct addrinfo hint, *ret;
1024 memset(&hint, 0, sizeof(hint));
1025 hint.ai_socktype = SOCK_STREAM;
1026 hint.ai_flags = AI_NUMERICSERV | AI_CANONNAME;
1027 snprintf(tmp, sizeof(tmp), "%i", port);
1028 if(!getaddrinfo(name, tmp, &hint, &ret))
1033 static struct addrinfo *resolvsrv(char *name)
1035 struct addrinfo *ret;
1039 if(getsrvrr(name, &realname, &port))
1041 ret = resolvtcp(realname, port);
1046 static struct addrinfo *resolvhost(char *host)
1049 struct addrinfo *ret;
1052 if(strchr(host, '/'))
1053 return(unixgai(SOCK_STREAM, host));
1054 if((strchr(host, ':') == NULL) && ((ret = resolvsrv(host)) != NULL))
1057 if((*host == '[') && ((p = strchr(host, ']')) != NULL))
1059 hp = memcpy(smalloc(p - host), host + 1, (p - host) - 1);
1060 hp[(p - host) - 1] = 0;
1061 if(strchr(hp, ':') != NULL) {
1067 ret = resolvtcp(hp, port);
1075 if((p = strrchr(hp, ':')) != NULL) {
1081 ret = resolvtcp(hp, port);
1088 static struct addrinfo *defaulthost(void)
1090 struct addrinfo *ret;
1095 if(((tmp = getenv("DCSERVER")) != NULL) && *tmp)
1096 return(resolvhost(tmp));
1098 if((getuid() != 0) && ((pwd = getpwuid(getuid())) != NULL))
1100 tmp = sprintf2("/tmp/doldacond-%s", pwd->pw_name);
1101 ret = gaicat(ret, unixgai(SOCK_STREAM, tmp));
1104 ret = gaicat(ret, unixgai(SOCK_STREAM, "/var/run/doldacond.sock"));
1105 ret = gaicat(ret, resolvtcp("localhost", 1500));
1106 if(!getdomainname(dn, sizeof(dn)) && *dn && strcmp(dn, "(none)"))
1107 ret = gaicat(ret, resolvsrv(dn));
1111 int dc_connect(char *host)
1119 if(hostlist != NULL)
1120 freeaddrinfo(hostlist);
1122 hostlist = defaulthost();
1124 hostlist = resolvhost(host);
1125 if(hostlist == NULL)
1127 for(curhost = hostlist; curhost != NULL; curhost = curhost->ai_next)
1129 if((fd = socket(curhost->ai_family, curhost->ai_socktype, curhost->ai_protocol)) < 0)
1135 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
1136 if(connect(fd, (struct sockaddr *)curhost->ai_addr, curhost->ai_addrlen))
1138 if(errno == EINPROGRESS)
1146 if(curhost->ai_canonname != NULL)
1147 servinfo.hostname = sstrdup(curhost->ai_canonname);
1148 servinfo.family = curhost->ai_family;
1153 qcmd = makeqcmd(NULL);
1158 struct dc_intresp *dc_interpret(struct dc_response *resp)
1161 struct dc_intresp *iresp;
1162 struct command *cmd;
1163 struct respclass *cls;
1167 if((resp->numlines == 0) || (resp->rlines[0].argc == 0) || (resp->curline >= resp->numlines))
1169 code = wcstol(resp->rlines[0].argv[0], NULL, 10);
1170 cmd = (struct command *)(resp->internal);
1171 for(cls = cmd->classes; cls != NULL; cls = cls->next)
1173 if(cls->code == code)
1178 if(cls->nwords >= resp->rlines[resp->curline].argc)
1180 iresp = smalloc(sizeof(*iresp));
1185 for(i = 0; i < cls->nwords; i++)
1187 switch(cls->wordt[i])
1192 sizebuf(&(iresp->argv), &args, iresp->argc + 1, sizeof(*(iresp->argv)), 1);
1193 iresp->argv[iresp->argc].val.str = swcsdup(resp->rlines[resp->curline].argv[i + 1]);
1194 iresp->argv[iresp->argc].type = cls->wordt[i];
1198 sizebuf(&(iresp->argv), &args, iresp->argc + 1, sizeof(*(iresp->argv)), 1);
1199 iresp->argv[iresp->argc].val.num = wcstol(resp->rlines[resp->curline].argv[i + 1], NULL, 0);
1200 iresp->argv[iresp->argc].type = cls->wordt[i];
1204 sizebuf(&(iresp->argv), &args, iresp->argc + 1, sizeof(*(iresp->argv)), 1);
1205 iresp->argv[iresp->argc].val.flnum = wcstod(resp->rlines[resp->curline].argv[i + 1], NULL);
1206 iresp->argv[iresp->argc].type = cls->wordt[i];
1215 void dc_freeires(struct dc_intresp *ires)
1219 for(i = 0; i < ires->argc; i++)
1221 if(ires->argv[i].type == RESP_STR)
1222 free(ires->argv[i].val.str);
1228 const char *dc_gethostname(void)
1230 return(servinfo.hostname);