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))
218 new = smalloc(sizeof(*new));
223 new->callback = NULL;
228 queue = queueend = new;
230 queueend->next = new;
236 static wchar_t *quoteword(wchar_t *word)
238 wchar_t *wp, *buf, *bp;
248 for(wp = word; *wp != L'\0'; wp++)
250 if(!dq && iswspace(*wp))
252 if((*wp == L'\\') || (*wp == L'\"'))
259 bp = buf = smalloc(sizeof(wchar_t) * (numc + numbs + (dq?2:0) + 1));
262 for(wp = word; *wp != L'\0'; wp++)
264 if((*wp == L'\\') || (*wp == L'\"'))
274 static struct command *makecmd(wchar_t *name)
278 new = smalloc(sizeof(*new));
281 new->next = commands;
286 static struct respclass *addresp(struct command *cmd, int code, ...)
288 struct respclass *new;
293 va_start(args, code);
295 while((resps[i++] = va_arg(args, int)) != RESP_END);
298 new = smalloc(sizeof(*new));
303 new->wordt = smalloc(sizeof(int) * i);
304 memcpy(new->wordt, resps, sizeof(int) * i);
308 new->next = cmd->classes;
313 #include "initcmds.h"
317 if((ichandle = iconv_open("wchar_t", "utf-8")) == (iconv_t)-1)
319 dc_srv_local = sstrdup("");
324 void dc_cleanup(void)
326 iconv_close(ichandle);
329 void dc_disconnect(void)
331 struct dc_response *resp;
339 while((resp = dc_getresp()) != NULL)
341 dc_uimisc_disconnected();
342 if(servinfo.hostname != NULL)
343 free(servinfo.hostname);
344 memset(&servinfo, 0, sizeof(servinfo));
347 void dc_freeresp(struct dc_response *resp)
351 for(i = 0; i < resp->numlines; i++)
353 for(o = 0; o < resp->rlines[i].argc; o++)
354 free(resp->rlines[i].argv[o]);
355 free(resp->rlines[i].argv);
361 struct dc_response *dc_getresp(void)
363 struct dc_response *ret;
365 if((ret = respqueue) == NULL)
367 respqueue = ret->next;
368 if(respqueue == NULL)
371 respqueue->prev = NULL;
375 struct dc_response *dc_gettaggedresp(int tag)
377 struct dc_response *resp;
379 for(resp = respqueue; resp != NULL; resp = resp->next)
383 if(resp->prev != NULL)
384 resp->prev->next = resp->next;
385 if(resp->next != NULL)
386 resp->next->prev = resp->prev;
387 if(resp == respqueue)
388 respqueue = resp->next;
389 if(resp == respqueueend)
390 respqueueend = resp->prev;
397 struct dc_response *dc_gettaggedrespsync(int tag)
400 struct dc_response *resp;
402 while((resp = dc_gettaggedresp(tag)) == NULL)
407 pfd.events |= POLLOUT;
408 if(poll(&pfd, 1, -1) < 0)
410 if((pfd.revents & POLLIN) && dc_handleread())
412 if((pfd.revents & POLLOUT) && dc_handlewrite())
418 int dc_wantwrite(void)
423 if((queue != NULL) && (queue->buflen > 0))
430 int dc_getstate(void)
435 int dc_queuecmd(int (*callback)(struct dc_response *), void *data, ...)
443 wchar_t *part, *tpart;
444 size_t bufsize, bufdata;
447 bufsize = bufdata = 0;
450 while((part = va_arg(al, wchar_t *)) != NULL)
452 if(!wcscmp(part, L"%a"))
454 for(toks = va_arg(al, wchar_t **); *toks != NULL; toks++)
458 if((tpart = quoteword(part)) != NULL)
464 bufcat(buf, part, wcslen(part));
473 if(!wcscmp(tpart, L"i"))
476 part = swprintf2(L"%i", va_arg(al, int));
477 } else if(!wcscmp(tpart, L"s")) {
479 part = icmbstowcs(sarg = va_arg(al, char *), NULL);
486 } else if(!wcscmp(tpart, L"ls")) {
487 part = va_arg(al, wchar_t *);
488 } else if(!wcscmp(tpart, L"ll")) {
490 part = swprintf2(L"%lli", va_arg(al, long long));
491 } else if(!wcscmp(tpart, L"f")) {
493 part = swprintf2(L"%f", va_arg(al, double));
494 } else if(!wcscmp(tpart, L"x")) {
496 part = swprintf2(L"%x", va_arg(al, int));
505 if((tpart = quoteword(part)) != NULL)
516 if((qcmd = makeqcmd(part)) == NULL)
524 qcmd->callback = callback;
528 bufcat(buf, part, wcslen(part));
534 bufcat(buf, L"\r\n\0", 3);
535 if((final = icwcstombs(buf, "utf-8")) == NULL)
543 qcmd->buflen = strlen(final);
547 int dc_handleread(void)
554 /* Ewww... this really is soo ugly. I need to clean this up some day. */
555 static int pstate = 0;
556 static char inbuf[128];
557 static size_t inbufdata = 0;
558 static wchar_t *cbuf = NULL;
559 static size_t cbufsize = 0, cbufdata = 0;
560 static wchar_t *pptr = NULL;
561 static wchar_t **argv = NULL;
563 static size_t args = 0;
564 static wchar_t *cw = NULL;
565 static size_t cwsize = 0, cwdata = 0;
566 static struct dc_response *curresp = NULL;
568 static int unlink = 0;
575 optlen = sizeof(ret);
576 getsockopt(fd, SOL_SOCKET, SO_ERROR, &ret, &optlen);
581 message(2, "could not connect to %s: %s\n", formataddress(curhost->ai_addr, curhost->ai_addrlen), strerror(ret));
582 for(curhost = curhost->ai_next; curhost != NULL; curhost = curhost->ai_next)
584 if((newfd = socket(curhost->ai_family, curhost->ai_socktype, curhost->ai_protocol)) < 0)
593 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
594 message(4, "connecting to %s\n", formataddress(curhost->ai_addr, curhost->ai_addrlen));
595 if(connect(fd, (struct sockaddr *)curhost->ai_addr, curhost->ai_addrlen))
597 if(errno == EINPROGRESS)
599 message(2, "could not connect to %s: %s\n", formataddress(curhost->ai_addr, curhost->ai_addrlen), strerror(ret));
611 if(curhost->ai_canonname != NULL)
612 servinfo.hostname = sstrdup(curhost->ai_canonname);
613 servinfo.family = curhost->ai_family;
627 dc_freeresp(curresp);
632 ret = read(fd, inbuf + inbufdata, 128 - inbufdata);
635 if((errno == EAGAIN) || (errno == EINTR))
641 } else if(ret == 0) {
650 if(cbufsize == cbufdata)
654 if((cbuf = realloc(cbuf, sizeof(wchar_t) * (cbufsize += 256))) == NULL)
664 p2 = (char *)(cbuf + cbufdata);
665 len = sizeof(wchar_t) * (cbufsize - cbufdata);
666 ret = iconv(ichandle, &p1, &inbufdata, &p2, &len);
667 memmove(inbuf, p1, inbufdata);
668 cbufdata = cbufsize - (len / sizeof(wchar_t));
674 /* XXX Is this really OK? */
696 while(!done && (pptr - cbuf < cbufdata))
705 if(pptr == cbuf + cbufdata - 1)
710 if(*(++pptr) == L'\n')
714 curresp = makeresp();
715 if((argc > 0) && ((curresp->code = wcstol(argv[0], NULL, 10)) >= 600))
717 curresp->cmdname = L".notify";
718 curresp->internal = commands->next;
722 if((curresp->cmdname = queue->cmd->name) == NULL)
723 curresp->cmdname = L".connect";
724 curresp->data = queue->data;
725 curresp->tag = queue->tag;
726 curresp->internal = (void *)(queue->cmd);
730 sizebuf(&curresp->rlines, &curresp->linessize, curresp->numlines + 1, sizeof(*(curresp->rlines)), 1);
731 curresp->rlines[curresp->numlines].argc = argc;
732 curresp->rlines[curresp->numlines].argv = argv;
738 if((curresp->code >= 600) || (queue == NULL) || (queue->callback == NULL))
741 ret = queue->callback(curresp);
744 if(respqueue == NULL)
746 respqueue = respqueueend = curresp;
748 curresp->next = NULL;
749 curresp->prev = respqueueend;
750 respqueueend->next = curresp;
751 respqueueend = curresp;
753 } else if(ret == 1) {
754 dc_freeresp(curresp);
760 wmemmove(cbuf, pptr, cbufdata -= (pptr - cbuf));
774 if(iswspace(*pptr) || ((argc == 0) && (*pptr == L'-')))
787 sizebuf(&argv, &args, argc + 1, sizeof(*argv), 1);
792 } else if(*pptr == L'\"') {
795 } else if(*pptr == L'\\') {
796 if(pptr == cbuf + cbufdata - 1)
801 addtobuf(cw, *(++pptr));
804 addtobuf(cw, *(pptr++));
811 } else if(*pptr == L'\\') {
812 addtobuf(cw, *(++pptr));
825 #if UNIX_AUTH_STYLE == 1
826 static void mkcreds(struct msghdr *msg)
829 static char buf[CMSG_SPACE(sizeof(*ucred))];
830 struct cmsghdr *cmsg;
832 msg->msg_control = buf;
833 msg->msg_controllen = sizeof(buf);
834 cmsg = CMSG_FIRSTHDR(msg);
835 cmsg->cmsg_level = SOL_SOCKET;
836 cmsg->cmsg_type = SCM_CREDENTIALS;
837 cmsg->cmsg_len = CMSG_LEN(sizeof(*ucred));
838 ucred = (struct ucred *)CMSG_DATA(cmsg);
839 ucred->pid = getpid();
840 ucred->uid = getuid();
841 ucred->gid = getgid();
842 msg->msg_controllen = cmsg->cmsg_len;
846 int dc_handlewrite(void)
856 if(queue->buflen > 0)
858 memset(&msg, 0, sizeof(msg));
859 msg.msg_iov = &bufvec;
861 bufvec.iov_base = queue->buf;
862 bufvec.iov_len = queue->buflen;
863 #if UNIX_AUTH_STYLE == 1
864 if((servinfo.family == PF_UNIX) && !servinfo.sentcreds)
867 servinfo.sentcreds = 1;
870 ret = sendmsg(fd, &msg, MSG_NOSIGNAL | MSG_DONTWAIT);
873 if((errno == EAGAIN) || (errno == EINTR))
881 memmove(queue->buf, queue->buf + ret, queue->buflen -= ret);
890 * It kind of sucks that libresolv doesn't have any DNS parsing
891 * routines. We'll have to do it manually.
893 static char *readname(unsigned char *msg, unsigned char *eom, unsigned char **p)
897 size_t namesize, namedata, len;
900 namesize = namedata = 0;
908 } else if(len == 0xc0) {
909 tp = msg + *((*p)++);
910 if((tname = readname(msg, eom, &tp)) == NULL)
916 bufcat(name, tname, strlen(tname));
920 } else if(*p + len >= eom) {
925 bufcat(name, *p, len);
931 static int skipname(unsigned char *msg, unsigned char *eom, unsigned char **p)
941 } else if(len == 0xc0) {
944 } else if(*p + len >= eom) {
951 static int getsrvrr(char *name, char **host, int *port)
954 char *name2, *rrname;
955 unsigned char *eom, *p;
956 unsigned char buf[1024];
957 int flags, num, class, type;
961 if(!(_res.options & RES_INIT))
966 /* res_querydomain doesn't work for some reason */
967 if(name[strlen(name) - 1] == '.')
968 name2 = sprintf2("%s.%s", DOLCON_SRV_NAME, name);
970 name2 = sprintf2("%s.%s.", DOLCON_SRV_NAME, name);
971 ret = res_query(name2, C_IN, T_SRV, buf, sizeof(buf));
979 * Assume transaction ID is correct.
981 * Flags check: FA0F masks in request/response flag, opcode,
982 * truncated flag and status code, and ignores authoritativeness,
983 * recursion flags and DNSSEC and reserved bits.
985 flags = (buf[2] << 8) + buf[3];
986 if((flags & 0xfa0f) != 0x8000)
991 /* Skip the query entries */
992 num = (buf[4] << 8) + buf[5];
994 for(i = 0; i < num; i++)
996 if(skipname(buf, eom, &p))
1001 p += 4; /* Type and class */
1004 num = (buf[6] << 8) + buf[7];
1005 for(i = 0; i < num; i++)
1007 if((rrname = readname(buf, eom, &p)) == NULL)
1014 class = *(p++) << 8;
1019 if((class == C_IN) && (type == T_SRV) && !strcmp(rrname, name2))
1023 /* Noone will want to have alternative DC servers, so
1024 * don't care about priority and weigth */
1030 *port = *(p++) << 8;
1035 if((rrname = readname(buf, eom, &p)) == NULL)
1048 static int getsrvrr(char *name, char **host, int *port)
1055 static struct addrinfo *gaicat(struct addrinfo *l1, struct addrinfo *l2)
1061 for(p = l1; p->ai_next != NULL; p = p->ai_next);
1066 /* This isn't actually correct, in any sense of the word. It only
1067 * works on systems whose getaddrinfo implementation saves the
1068 * sockaddr in the same malloc block as the struct addrinfo. Those
1069 * systems include at least FreeBSD and glibc-based systems, though,
1070 * so it should not be any immediate threat, and it allows me to not
1071 * implement a getaddrinfo wrapper. It can always be changed, should
1072 * the need arise. */
1073 static struct addrinfo *unixgai(int type, char *path)
1076 struct addrinfo *ai;
1077 struct sockaddr_un *un;
1079 buf = smalloc(sizeof(*ai) + sizeof(*un));
1080 memset(buf, 0, sizeof(*ai) + sizeof(*un));
1081 ai = (struct addrinfo *)buf;
1082 un = (struct sockaddr_un *)(buf + sizeof(*ai));
1084 ai->ai_family = AF_UNIX;
1085 ai->ai_socktype = type;
1086 ai->ai_protocol = 0;
1087 ai->ai_addrlen = sizeof(*un);
1088 ai->ai_addr = (struct sockaddr *)un;
1089 ai->ai_canonname = NULL;
1091 un->sun_family = PF_UNIX;
1092 strncpy(un->sun_path, path, sizeof(un->sun_path) - 1);
1096 static struct addrinfo *resolvtcp(char *name, int port)
1098 struct addrinfo hint, *ret;
1101 memset(&hint, 0, sizeof(hint));
1102 hint.ai_socktype = SOCK_STREAM;
1103 hint.ai_flags = AI_NUMERICSERV | AI_CANONNAME;
1104 snprintf(tmp, sizeof(tmp), "%i", port);
1105 if(!getaddrinfo(name, tmp, &hint, &ret))
1110 static struct addrinfo *resolvsrv(char *name)
1112 struct addrinfo *ret;
1116 if(getsrvrr(name, &realname, &port))
1118 message(4, "SRV RR resolved: %s -> %s\n", name, realname);
1119 ret = resolvtcp(realname, port);
1124 static struct addrinfo *resolvhost(char *host)
1127 struct addrinfo *ret;
1130 if(strchr(host, '/'))
1131 return(unixgai(SOCK_STREAM, host));
1132 if((strchr(host, ':') == NULL) && ((ret = resolvsrv(host)) != NULL))
1135 if((*host == '[') && ((p = strchr(host, ']')) != NULL))
1137 hp = memcpy(smalloc(p - host), host + 1, (p - host) - 1);
1138 hp[(p - host) - 1] = 0;
1139 if(strchr(hp, ':') != NULL) {
1145 ret = resolvtcp(hp, port);
1153 if((p = strrchr(hp, ':')) != NULL) {
1159 ret = resolvtcp(hp, port);
1166 static struct addrinfo *getlocalai(void)
1168 struct addrinfo *ret;
1173 if((getuid() != 0) && ((pwd = getpwuid(getuid())) != NULL))
1175 tmp = sprintf2("/tmp/doldacond-%s", pwd->pw_name);
1176 ret = unixgai(SOCK_STREAM, tmp);
1179 ret = gaicat(ret, unixgai(SOCK_STREAM, "/var/run/doldacond.sock"));
1183 static struct addrinfo *defaulthost(void)
1185 struct addrinfo *ret;
1189 if(((tmp = getenv("DCSERVER")) != NULL) && *tmp) {
1190 message(4, "using DCSERVER: %s\n", tmp);
1191 return(resolvhost(tmp));
1194 ret = gaicat(ret, resolvtcp("localhost", 1500));
1195 if(!getdomainname(dn, sizeof(dn)) && *dn && strcmp(dn, "(none)"))
1196 ret = gaicat(ret, resolvsrv(dn));
1200 static int dc_connectai(struct addrinfo *hosts, struct qcmd **cnctcmd)
1208 if(hostlist != NULL)
1209 freeaddrinfo(hostlist);
1211 for(curhost = hostlist; curhost != NULL; curhost = curhost->ai_next)
1213 if((fd = socket(curhost->ai_family, curhost->ai_socktype, curhost->ai_protocol)) < 0)
1216 freeaddrinfo(hostlist);
1221 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
1222 message(4, "connecting to %s\n", formataddress(curhost->ai_addr, curhost->ai_addrlen));
1223 if(connect(fd, (struct sockaddr *)curhost->ai_addr, curhost->ai_addrlen))
1225 if(errno == EINPROGRESS)
1230 message(2, "could not connect to %s: %s\n", formataddress(curhost->ai_addr, curhost->ai_addrlen), strerror(errno));
1234 if(curhost->ai_canonname != NULL)
1235 servinfo.hostname = sstrdup(curhost->ai_canonname);
1236 servinfo.family = curhost->ai_family;
1243 qcmd = makeqcmd(NULL);
1254 static int dc_connect2(char *host, struct qcmd **cnctcmd)
1256 struct addrinfo *ai;
1260 if(host == dc_srv_local) {
1261 message(4, "connect start: Unix\n");
1263 } else if(!host || !*host) {
1264 message(4, "connect start: default\n");
1267 message(4, "connect start: host %s\n", host);
1268 ai = resolvhost(host);
1272 ret = dc_connectai(ai, &qcmd);
1273 if((ret >= 0) && (cnctcmd != NULL))
1278 int dc_connect(char *host)
1280 return(dc_connect2(host, NULL));
1283 int dc_connectsync(char *host, struct dc_response **respbuf)
1287 struct dc_response *resp;
1289 if((ret = dc_connect2(host, &cc)) < 0)
1291 resp = dc_gettaggedrespsync(cc->tag);
1303 int dc_connectsync2(char *host, int rev)
1306 struct dc_response *resp;
1308 if((ret = dc_connectsync(host, &resp)) < 0)
1310 if(dc_checkprotocol(resp, rev))
1314 errno = EPROTONOSUPPORT;
1321 struct dc_intresp *dc_interpret(struct dc_response *resp)
1324 struct dc_intresp *iresp;
1325 struct command *cmd;
1326 struct respclass *cls;
1330 if((resp->numlines == 0) || (resp->rlines[0].argc == 0) || (resp->curline >= resp->numlines))
1332 code = wcstol(resp->rlines[0].argv[0], NULL, 10);
1333 cmd = (struct command *)(resp->internal);
1334 for(cls = cmd->classes; cls != NULL; cls = cls->next)
1336 if(cls->code == code)
1341 if(cls->nwords >= resp->rlines[resp->curline].argc)
1343 iresp = smalloc(sizeof(*iresp));
1348 for(i = 0; i < cls->nwords; i++)
1350 switch(cls->wordt[i])
1355 sizebuf(&(iresp->argv), &args, iresp->argc + 1, sizeof(*(iresp->argv)), 1);
1356 iresp->argv[iresp->argc].val.str = swcsdup(resp->rlines[resp->curline].argv[i + 1]);
1357 iresp->argv[iresp->argc].type = cls->wordt[i];
1361 sizebuf(&(iresp->argv), &args, iresp->argc + 1, sizeof(*(iresp->argv)), 1);
1362 iresp->argv[iresp->argc].val.num = wcstol(resp->rlines[resp->curline].argv[i + 1], NULL, 0);
1363 iresp->argv[iresp->argc].type = cls->wordt[i];
1367 sizebuf(&(iresp->argv), &args, iresp->argc + 1, sizeof(*(iresp->argv)), 1);
1368 iresp->argv[iresp->argc].val.flnum = wcstod(resp->rlines[resp->curline].argv[i + 1], NULL);
1369 iresp->argv[iresp->argc].type = cls->wordt[i];
1378 void dc_freeires(struct dc_intresp *ires)
1382 for(i = 0; i < ires->argc; i++)
1384 if(ires->argv[i].type == RESP_STR)
1385 free(ires->argv[i].val.str);
1391 int dc_checkprotocol(struct dc_response *resp, int revision)
1393 struct dc_intresp *ires;
1396 if(resp->code != 201)
1399 if((ires = dc_interpret(resp)) == NULL)
1401 low = ires->argv[0].val.num;
1402 high = ires->argv[1].val.num;
1404 if((revision < low) || (revision > high))
1409 const char *dc_gethostname(void)
1411 return(servinfo.hostname);