Send and receive Unix creds.
[doldaconnect.git] / lib / uilib.c
1 /*
2  *  Dolda Connect - Modular multiuser Direct Connect-style client
3  *  Copyright (C) 2004 Fredrik Tolf (fredrik@dolda2000.com)
4  *  
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.
9  *  
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.
14  *  
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
18 */
19
20 /*
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.
24  */
25
26 #ifdef HAVE_CONFIG_H
27 #include <config.h>
28 #endif
29 #include <stdio.h>
30 #include <unistd.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <iconv.h>
34 #include <wchar.h>
35 #include <wctype.h>
36 #include <errno.h>
37 #include <stdarg.h>
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
41 #include <sys/un.h>
42 #include <fcntl.h>
43 #include <netdb.h>
44 #include <sys/poll.h>
45 #include <pwd.h>
46 #ifdef HAVE_RESOLVER
47 #include <arpa/nameser.h>
48 #include <resolv.h>
49 #endif
50
51 #include <doldaconnect/uilib.h>
52 #include <utils.h>
53
54 #define DOLCON_SRV_NAME "_dolcon._tcp"
55
56 #define RESP_END -1
57 #define RESP_DSC 0
58 #define RESP_STR 1
59 #define RESP_INT 2
60 #define RESP_FLOAT 3
61
62 struct respclass
63 {
64     struct respclass *next;
65     int code;
66     int nwords;
67     int *wordt;
68 };
69
70 struct command
71 {
72     struct command *next;
73     wchar_t *name;
74     struct respclass *classes;
75 };
76
77 struct qcmd
78 {
79     struct qcmd *next;
80     struct command *cmd;
81     int tag;
82     char *buf;
83     size_t buflen;
84     int (*callback)(struct dc_response *resp);
85     void *data;
86 };
87
88 void dc_uimisc_disconnected(void);
89
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;
96 static int fd = -1;
97 static iconv_t ichandle;
98 static int resetreader = 1;
99 static struct addrinfo *hostlist = NULL, *curhost = NULL;
100 struct {
101     char *hostname;
102     int family;
103     int sentcreds;
104 } servinfo;
105
106 static struct dc_response *makeresp(void)
107 {
108     struct dc_response *new;
109     
110     new = smalloc(sizeof(*new));
111     new->next = NULL;
112     new->prev = NULL;
113     new->code = 0;
114     new->cmdname = NULL;
115     new->rlines = NULL;
116     new->linessize = 0;
117     new->numlines = 0;
118     new->curline = 0;
119     new->data = NULL;
120     return(new);
121 }
122
123 static void freeqcmd(struct qcmd *qcmd)
124 {
125     if(qcmd->buf != NULL)
126         free(qcmd->buf);
127     free(qcmd);
128 }
129
130 static void unlinkqueue(void)
131 {
132     struct qcmd *qcmd;
133     
134     if((qcmd = queue) == NULL)
135         return;
136     queue = qcmd->next;
137     if(queue == NULL)
138         queueend = NULL;
139     freeqcmd(qcmd);
140 }
141
142 static struct qcmd *makeqcmd(wchar_t *name)
143 {
144     struct qcmd *new;
145     struct command *cmd;
146     static int tag = 0;
147     
148     if(name == NULL)
149     {
150         cmd = commands;
151     } else {
152         for(cmd = commands; cmd != NULL; cmd = cmd->next)
153         {
154             if((cmd->name != NULL) && !wcscmp(cmd->name, name))
155                 break;
156         }
157         if(cmd == NULL)
158             return(NULL);
159     }
160     new = smalloc(sizeof(*new));
161     new->tag = tag++;
162     new->cmd = cmd;
163     new->buf = NULL;
164     new->buflen = 0;
165     new->callback = NULL;
166     new->next = NULL;
167     new->data = NULL;
168     if(queueend == NULL)
169     {
170         queue = queueend = new;
171     } else {
172         queueend->next = new;
173         queueend = new;
174     }
175     return(new);
176 }
177
178 static wchar_t *quoteword(wchar_t *word)
179 {
180     wchar_t *wp, *buf, *bp;
181     int dq, numbs, numc;
182     
183     dq = 0;
184     numbs = 0;
185     numc = 0;
186     if(*word == L'\0')
187     {
188         dq = 1;
189     } else {
190         for(wp = word; *wp != L'\0'; wp++)
191         {
192             if(!dq && iswspace(*wp))
193                 dq = 1;
194             if((*wp == L'\\') || (*wp == L'\"'))
195                 numbs++;
196             numc++;
197         }
198     }
199     if(!dq && !numbs)
200         return(NULL);
201     bp = buf = smalloc(sizeof(wchar_t) * (numc + numbs + (dq?2:0) + 1));
202     if(dq)
203         *(bp++) = L'\"';
204     for(wp = word; *wp != L'\0'; wp++)
205     {
206         if((*wp == L'\\') || (*wp == L'\"'))
207             *(bp++) = L'\\';
208         *(bp++) = *wp;
209     }
210     if(dq)
211         *(bp++) = L'\"';
212     *(bp++) = L'\0';
213     return(buf);
214 }
215
216 static struct command *makecmd(wchar_t *name)
217 {
218     struct command *new;
219     
220     new = smalloc(sizeof(*new));
221     new->name = name;
222     new->classes = NULL;
223     new->next = commands;
224     commands = new;
225     return(new);
226 }
227
228 static struct respclass *addresp(struct command *cmd, int code, ...)
229 {
230     struct respclass *new;
231     int i;
232     int resps[128];
233     va_list args;
234         
235     va_start(args, code);
236     i = 0;
237     while((resps[i++] = va_arg(args, int)) != RESP_END);
238     i--;
239     va_end(args);
240     new = smalloc(sizeof(*new));
241     new->code = code;
242     new->nwords = i;
243     if(i > 0)
244     {
245         new->wordt = smalloc(sizeof(int) * i);
246         memcpy(new->wordt, resps, sizeof(int) * i);
247     } else {
248         new->wordt = NULL;
249     }
250     new->next = cmd->classes;
251     cmd->classes = new;
252     return(new);
253 }
254
255 #include "initcmds.h"
256
257 int dc_init(void)
258 {
259     if((ichandle = iconv_open("wchar_t", "utf-8")) == (iconv_t)-1)
260         return(-1);
261     initcmds();
262     return(0);
263 }
264
265 void dc_cleanup(void)
266 {
267     iconv_close(ichandle);
268 }
269
270 void dc_disconnect(void)
271 {
272     struct dc_response *resp;
273     
274     state = -1;
275     if(fd >= 0)
276         close(fd);
277     fd = -1;
278     while(queue != NULL)
279         unlinkqueue();
280     while((resp = dc_getresp()) != NULL)
281         dc_freeresp(resp);
282     dc_uimisc_disconnected();
283     if(servinfo.hostname != NULL)
284         free(servinfo.hostname);
285     memset(&servinfo, 0, sizeof(servinfo));
286 }
287
288 void dc_freeresp(struct dc_response *resp)
289 {
290     int i, o;
291     
292     for(i = 0; i < resp->numlines; i++)
293     {
294         for(o = 0; o < resp->rlines[i].argc; o++)
295             free(resp->rlines[i].argv[o]);
296         free(resp->rlines[i].argv);
297     }
298     free(resp->rlines);
299     free(resp);
300 }
301
302 struct dc_response *dc_getresp(void)
303 {
304     struct dc_response *ret;
305     
306     if((ret = respqueue) == NULL)
307         return(NULL);
308     respqueue = ret->next;
309     if(respqueue == NULL)
310         respqueueend = NULL;
311     else
312         respqueue->prev = NULL;
313     return(ret);
314 }
315
316 struct dc_response *dc_gettaggedresp(int tag)
317 {
318     struct dc_response *resp;
319     
320     for(resp = respqueue; resp != NULL; resp = resp->next)
321     {
322         if(resp->tag == tag)
323         {
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;
332             return(resp);
333         }
334     }
335     return(NULL);
336 }
337
338 struct dc_response *dc_gettaggedrespsync(int tag)
339 {
340     struct pollfd pfd;
341     struct dc_response *resp;
342     
343     while((resp = dc_gettaggedresp(tag)) == NULL)
344     {
345         pfd.fd = fd;
346         pfd.events = POLLIN;
347         if(dc_wantwrite())
348             pfd.events |= POLLOUT;
349         if(poll(&pfd, 1, -1) < 0)
350             return(NULL);
351         if((pfd.revents & POLLIN) && dc_handleread())
352             return(NULL);
353         if((pfd.revents & POLLOUT) && dc_handlewrite())
354             return(NULL);
355     }
356     return(resp);
357 }
358
359 int dc_wantwrite(void)
360 {
361     switch(state)
362     {
363     case 1:
364         if((queue != NULL) && (queue->buflen > 0))
365             return(1);
366         break;
367     }
368     return(0);
369 }
370
371 int dc_getstate(void)
372 {
373     return(state);
374 }
375
376 int dc_queuecmd(int (*callback)(struct dc_response *), void *data, ...)
377 {
378     struct qcmd *qcmd;
379     int num, freepart;
380     va_list al;
381     char *final;
382     wchar_t **toks;
383     wchar_t *buf;
384     wchar_t *part, *tpart;
385     size_t bufsize, bufdata;
386     
387     buf = NULL;
388     bufsize = bufdata = 0;
389     num = 0;
390     va_start(al, data);
391     while((part = va_arg(al, wchar_t *)) != NULL)
392     {
393         if(!wcscmp(part, L"%%a"))
394         {
395             for(toks = va_arg(al, wchar_t **); *toks != NULL; toks++)
396             {
397                 part = *toks;
398                 freepart = 0;
399                 if((tpart = quoteword(part)) != NULL)
400                 {
401                     freepart = 1;
402                     part = tpart;
403                 }
404                 addtobuf(buf, L' ');
405                 bufcat(buf, part, wcslen(part));
406                 num++;
407                 if(freepart)
408                     free(part);
409             }
410         } else {
411             if(*part == L'%')
412             {
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
418                  * it.
419                  */
420                 part = vswprintf2(tpart = (part + 1), al);
421                 for(; *tpart != L'\0'; tpart++)
422                 {
423                     if(*tpart == L'%')
424                     {
425                         if(tpart[1] == L'%')
426                             tpart++;
427                         else
428                             va_arg(al, int);
429                     }
430                 }
431                 freepart = 1;
432             } else {
433                 freepart = 0;
434             }
435             if((tpart = quoteword(part)) != NULL)
436             {
437                 if(freepart)
438                     free(part);
439                 part = tpart;
440                 freepart = 1;
441             }
442             if(num > 0)
443                 addtobuf(buf, L' ');
444             if(num == 0)
445             {
446                 if((qcmd = makeqcmd(part)) == NULL)
447                 {
448                     if(freepart)
449                         free(part);
450                     if(buf != NULL)
451                         free(buf);
452                     return(-1);
453                 } else {
454                     qcmd->callback = callback;
455                     qcmd->data = data;
456                 }
457             }
458             bufcat(buf, part, wcslen(part));
459             num++;
460             if(freepart)
461                 free(part);
462         }
463     }
464     bufcat(buf, L"\r\n\0", 3);
465     if((final = icwcstombs(buf, "utf-8")) == NULL)
466     {
467         free(buf);
468         return(-1);
469     }
470     va_end(al);
471     free(buf);
472     qcmd->buf = final;
473     qcmd->buflen = strlen(final);
474     return(qcmd->tag);
475 }
476
477 int dc_handleread(void)
478 {
479     int ret, done;
480     char *p1, *p2;
481     size_t len;
482     socklen_t optlen;
483     int errnobak;
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;
492     static int argc = 0;
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;
497     static int cont = 0;
498     static int unlink = 0;
499     
500     switch(state)
501     {
502     case -1:
503         return(-1);
504     case 0:
505         optlen = sizeof(ret);
506         getsockopt(fd, SOL_SOCKET, SO_ERROR, &ret, &optlen);
507         if(ret)
508         {
509             int newfd;
510
511             for(curhost = curhost->ai_next; curhost != NULL; curhost = curhost->ai_next)
512             {
513                 if((newfd = socket(curhost->ai_family, curhost->ai_socktype, curhost->ai_protocol)) < 0)
514                 {
515                     errnobak = errno;
516                     dc_disconnect();
517                     errno = errnobak;
518                     return(-1);
519                 }
520                 dup2(newfd, fd);
521                 close(newfd);
522                 fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
523                 if(connect(fd, (struct sockaddr *)curhost->ai_addr, curhost->ai_addrlen))
524                 {
525                     if(errno == EINPROGRESS)
526                         return(0);
527                 } else {
528                     break;
529                 }
530             }
531             if(curhost == NULL)
532             {
533                 dc_disconnect();
534                 errno = ret;
535                 return(-1);
536             }
537         }
538         if(curhost->ai_canonname != NULL)
539             servinfo.hostname = sstrdup(curhost->ai_canonname);
540         servinfo.family = curhost->ai_family;
541         state = 1;
542         resetreader = 1;
543         break;
544     case 1:
545         if(resetreader)
546         {
547             inbufdata = 0;
548             cbufdata = 0;
549             pptr = NULL;
550             pstate = 0;
551             resetreader = 0;
552             cont = 0;
553             if(curresp != NULL)
554                 dc_freeresp(curresp);
555             curresp = NULL;
556         }
557         if(inbufdata == 128)
558             inbufdata = 0;
559         ret = read(fd, inbuf + inbufdata, 128 - inbufdata);
560         if(ret < 0)
561         {
562             if((errno == EAGAIN) || (errno == EINTR))
563                 return(0);
564             errnobak = errno;
565             dc_disconnect();
566             errno = errnobak;
567             return(-1);
568         } else if(ret == 0) {
569             dc_disconnect();
570             errno = 0;
571             return(-1);
572         }
573         inbufdata += ret;
574         done = 0;
575         while(!done)
576         {
577             if(cbufsize == cbufdata)
578             {
579                 if(pptr != NULL)
580                     len = pptr - cbuf;
581                 if((cbuf = realloc(cbuf, sizeof(wchar_t) * (cbufsize += 256))) == NULL)
582                 {
583                     dc_disconnect();
584                     errno = ENOMEM;
585                     return(-1);
586                 }
587                 if(pptr != NULL)
588                     pptr = cbuf + len;
589             }
590             p1 = inbuf;
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));
596             if(ret < 0)
597             {
598                 switch(errno)
599                 {
600                 case EILSEQ:
601                     /* XXX Is this really OK? */
602                     inbufdata = 0;
603                     done = 1;
604                     break;
605                 case EINVAL:
606                     done = 1;
607                     break;
608                 case E2BIG:
609                     break;
610                 default:
611                     errnobak = errno;
612                     dc_disconnect();
613                     errno = errnobak;
614                     return(-1);
615                 }
616             } else {
617                 done = 1;
618             }
619         }
620         if(pptr == NULL)
621             pptr = cbuf;
622         done = 0;
623         while(!done && (pptr - cbuf < cbufdata))
624         {
625             switch(pstate)
626             {
627             case 0:
628                 if(iswspace(*pptr))
629                 {
630                     if(*pptr == L'\r')
631                     {
632                         if(pptr == cbuf + cbufdata - 1)
633                         {
634                             done = 1;
635                             break;
636                         }
637                         if(*(++pptr) == L'\n')
638                         {
639                             if(curresp == NULL)
640                             {
641                                 curresp = makeresp();
642                                 if((argc > 0) && ((curresp->code = wcstol(argv[0], NULL, 10)) >= 600))
643                                 {
644                                     curresp->cmdname = L".notify";
645                                     curresp->internal = commands->next;
646                                     curresp->tag = -1;
647                                     unlink = 0;
648                                 } else {
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);
654                                     unlink = 1;
655                                 }
656                             }
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;
660                             argv = NULL;
661                             argc = args = 0;
662                             curresp->numlines++;
663                             if(!cont)
664                             {
665                                 if((curresp->code >= 600) || (queue == NULL) || (queue->callback == NULL))
666                                     ret = 0;
667                                 else
668                                     ret = queue->callback(curresp);
669                                 if(ret == 0)
670                                 {
671                                     if(respqueue == NULL)
672                                     {
673                                         respqueue = respqueueend = curresp;
674                                     } else {
675                                         curresp->next = NULL;
676                                         curresp->prev = respqueueend;
677                                         respqueueend->next = curresp;
678                                         respqueueend = curresp;
679                                     }
680                                 } else if(ret == 1) {
681                                     dc_freeresp(curresp);
682                                 }
683                                 curresp = NULL;
684                                 if(unlink)
685                                     unlinkqueue();
686                             }
687                             wmemmove(cbuf, pptr, cbufdata -= (pptr - cbuf));
688                             pptr = cbuf;
689                         } else {
690                             pptr++;
691                         }
692                     } else {
693                         pptr++;
694                     }
695                 } else {
696                     pstate = 1;
697                     cwdata = 0;
698                 }
699                 break;
700             case 1:
701                 if(iswspace(*pptr) || ((argc == 0) && (*pptr == L'-')))
702                 {
703                     if(argc == 0)
704                     {
705                         if(*pptr == L'-')
706                         {
707                             cont = 1;
708                             pptr++;
709                         } else {
710                             cont = 0;
711                         }
712                     }
713                     addtobuf(cw, L'\0');
714                     sizebuf(&argv, &args, argc + 1, sizeof(*argv), 1);
715                     argv[argc++] = cw;
716                     cw = NULL;
717                     cwsize = cwdata = 0;
718                     pstate = 0;
719                 } else if(*pptr == L'\"') {
720                     pstate = 2;
721                     pptr++;
722                 } else if(*pptr == L'\\') {
723                     if(pptr == cbuf + cbufdata - 1)
724                     {
725                         done = 1;
726                         break;
727                     }
728                     addtobuf(cw, *(++pptr));
729                     pptr++;
730                 } else {
731                     addtobuf(cw, *(pptr++));
732                 }
733                 break;
734             case 2:
735                 if(*pptr == L'\"')
736                 {
737                     pstate = 1;
738                 } else if(*pptr == L'\\') {
739                     addtobuf(cw, *(++pptr));
740                 } else {
741                     addtobuf(cw, *pptr);
742                 }
743                 pptr++;
744                 break;
745             }
746         }
747         break;
748     }
749     return(0);
750 }
751
752 static void mkcreds(struct msghdr *msg)
753 {
754     struct ucred *ucred;
755     static char buf[CMSG_SPACE(sizeof(*ucred))];
756     struct cmsghdr *cmsg;
757     
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;
769 }
770
771 int dc_handlewrite(void)
772 {
773     int ret;
774     int errnobak;
775     struct msghdr msg;
776     struct iovec bufvec;
777     
778     switch(state)
779     {
780     case 1:
781         if(queue->buflen > 0)
782         {
783             memset(&msg, 0, sizeof(msg));
784             msg.msg_iov = &bufvec;
785             msg.msg_iovlen = 1;
786             bufvec.iov_base = queue->buf;
787             bufvec.iov_len = queue->buflen;
788             if((servinfo.family == PF_UNIX) && !servinfo.sentcreds)
789             {
790                 mkcreds(&msg);
791                 servinfo.sentcreds = 1;
792             }
793             ret = sendmsg(fd, &msg, MSG_NOSIGNAL | MSG_DONTWAIT);
794             if(ret < 0)
795             {
796                 if((errno == EAGAIN) || (errno == EINTR))
797                     return(0);
798                 errnobak = errno;
799                 dc_disconnect();
800                 errno = errnobak;
801                 return(-1);
802             }
803             if(ret > 0)
804                 memmove(queue->buf, queue->buf + ret, queue->buflen -= ret);
805         }
806         break;
807     }
808     return(0);
809 }
810
811 #ifdef HAVE_RESOLVER
812 /*
813  * It kind of sucks that libresolv doesn't have any DNS parsing
814  * routines. We'll have to do it manually.
815  */
816 static char *readname(unsigned char *msg, unsigned char *eom, unsigned char **p)
817 {
818     char *name, *tname;
819     unsigned char *tp;
820     size_t namesize, namedata, len;
821     
822     name = NULL;
823     namesize = namedata = 0;
824     while(1)
825     {
826         len = *((*p)++);
827         if(len == 0)
828         {
829             addtobuf(name, 0);
830             return(name);
831         } else if(len == 0xc0) {
832             tp = msg + *((*p)++);
833             if((tname = readname(msg, eom, &tp)) == NULL)
834             {
835                 if(name != NULL)
836                     free(name);
837                 return(NULL);
838             }
839             bufcat(name, tname, strlen(tname));
840             addtobuf(name, 0);
841             free(tname);
842             return(name);
843         } else if(*p + len >= eom) {
844             if(name != NULL)
845                 free(name);
846             return(NULL);
847         }
848         bufcat(name, *p, len);
849         *p += len;
850         addtobuf(name, '.');
851     }
852 }
853
854 static int skipname(unsigned char *msg, unsigned char *eom, unsigned char **p)
855 {
856     size_t len;
857     
858     while(1)
859     {
860         len = *((*p)++);
861         if(len == 0)
862         {
863             return(0);
864         } else if(len == 0xc0) {
865             (*p)++;
866             return(0);
867         } else if(*p + len >= eom) {
868             return(-1);
869         }
870         *p += len;
871     }
872 }
873
874 static int getsrvrr(char *name, char **host, int *port)
875 {
876     int i;
877     char *name2, *rrname;
878     unsigned char *eom, *p;
879     unsigned char buf[1024];
880     int flags, num, class, type;
881     size_t len;
882     int ret;
883     
884     if(!(_res.options & RES_INIT))
885     {
886         if(res_init() < 0)
887             return(-1);
888     }
889     /* res_querydomain doesn't work for some reason */
890     if(name[strlen(name) - 1] == '.')
891         name2 = sprintf2("%s.%s", DOLCON_SRV_NAME, name);
892     else
893         name2 = sprintf2("%s.%s.", DOLCON_SRV_NAME, name);
894     ret = res_query(name2, C_IN, T_SRV, buf, sizeof(buf));
895     if(ret < 0)
896     {
897         free(name2);
898         return(-1);
899     }
900     eom = buf + ret;
901     /*
902      * Assume transaction ID is correct.
903      *
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.
907      */
908     flags = (buf[2] << 8) + buf[3];
909     if((flags & 0xfa0f) != 0x8000)
910     {
911         free(name2);
912         return(-1);
913     }
914     /* Skip the query entries */
915     num = (buf[4] << 8) + buf[5];
916     p = buf + 12;
917     for(i = 0; i < num; i++)
918     {
919         if(skipname(buf, eom, &p))
920         {
921             free(name2);
922             return(-1);
923         }
924         p += 4; /* Type and class */
925     }
926     /* Parse answers */
927     num = (buf[6] << 8) + buf[7];
928     for(i = 0; i < num; i++)
929     {
930         if((rrname = readname(buf, eom, &p)) == NULL)
931         {
932             free(name2);
933             return(-1);
934         }
935         type = *(p++) << 8;
936         type += *(p++);
937         class = *(p++) << 8;
938         class += *(p++);
939         p += 4; /* TTL */
940         len = *(p++) << 8;
941         len += *(p++);
942         if((class == C_IN) && (type == T_SRV) && !strcmp(rrname, name2))
943         {
944             free(rrname);
945             free(name2);
946             /* Noone will want to have alternative DC servers, so
947              * don't care about priority and weigth */
948             p += 4;
949             if(port == NULL)
950             {
951                 p += 2;
952             } else {
953                 *port = *(p++) << 8;
954                 *port += *(p++);
955             }
956             if(host != NULL)
957             {
958                 if((rrname = readname(buf, eom, &p)) == NULL)
959                     return(-1);
960                 *host = rrname;
961             }
962             return(0);
963         }
964         p += len;
965         free(rrname);
966     }
967     free(name2);
968     return(-1);
969 }
970 #else
971 static int getsrvrr(char *name, char **host, int *port)
972 {
973     errno = EOPNOTSUPP;
974     return(-1);
975 }
976 #endif
977
978 static struct addrinfo *gaicat(struct addrinfo *l1, struct addrinfo *l2)
979 {
980     struct addrinfo *p;
981     
982     if(l1 == NULL)
983         return(l2);
984     for(p = l1; p->ai_next != NULL; p = p->ai_next);
985     p->ai_next = l2;
986     return(l1);
987 }
988
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
995  * the need arise. */
996 static struct addrinfo *unixgai(int type, char *path)
997 {
998     void *buf;
999     struct addrinfo *ai;
1000     struct sockaddr_un *un;
1001     
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));
1006     ai->ai_flags = 0;
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;
1013     ai->ai_next = NULL;
1014     un->sun_family = PF_UNIX;
1015     strncpy(un->sun_path, path, sizeof(un->sun_path) - 1);
1016     return(ai);
1017 }
1018
1019 static struct addrinfo *resolvtcp(char *name, int port)
1020 {
1021     struct addrinfo hint, *ret;
1022     char tmp[32];
1023     
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))
1029         return(ret);
1030     return(NULL);
1031 }
1032
1033 static struct addrinfo *resolvsrv(char *name)
1034 {
1035     struct addrinfo *ret;
1036     char *realname;
1037     int port;
1038     
1039     if(getsrvrr(name, &realname, &port))
1040         return(NULL);
1041     ret = resolvtcp(realname, port);
1042     free(realname);
1043     return(ret);
1044 }
1045
1046 static struct addrinfo *resolvhost(char *host)
1047 {
1048     char *p, *hp;
1049     struct addrinfo *ret;
1050     int port;
1051     
1052     if(strchr(host, '/'))
1053         return(unixgai(SOCK_STREAM, host));
1054     if((strchr(host, ':') == NULL) && ((ret = resolvsrv(host)) != NULL))
1055         return(ret);
1056     ret = NULL;
1057     if((*host == '[') && ((p = strchr(host, ']')) != NULL))
1058     {
1059         hp = memcpy(smalloc(p - host), host + 1, (p - host) - 1);
1060         hp[(p - host) - 1] = 0;
1061         if(strchr(hp, ':') != NULL) {
1062             port = 0;
1063             if(*(++p) == ':')
1064                 port = atoi(p + 1);
1065             if(port == 0)
1066                 port = 1500;
1067             ret = resolvtcp(hp, port);
1068         }
1069         free(hp);
1070     }
1071     if(ret != NULL)
1072         return(ret);
1073     hp = sstrdup(host);
1074     port = 0;
1075     if((p = strrchr(hp, ':')) != NULL) {
1076         *(p++) = 0;
1077         port = atoi(p);
1078     }
1079     if(port == 0)
1080         port = 1500;
1081     ret = resolvtcp(hp, port);
1082     free(hp);
1083     if(ret != NULL)
1084         return(ret);
1085     return(NULL);
1086 }
1087
1088 static struct addrinfo *defaulthost(void)
1089 {
1090     struct addrinfo *ret;
1091     struct passwd *pwd;
1092     char *tmp;
1093     char dn[1024];
1094     
1095     if(((tmp = getenv("DCSERVER")) != NULL) && *tmp)
1096         return(resolvhost(tmp));
1097     ret = NULL;
1098     if((getuid() != 0) && ((pwd = getpwuid(getuid())) != NULL))
1099     {
1100         tmp = sprintf2("/tmp/doldacond-%s", pwd->pw_name);
1101         ret = gaicat(ret, unixgai(SOCK_STREAM, tmp));
1102         free(tmp);
1103     }
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));
1108     return(ret);
1109 }
1110
1111 int dc_connect(char *host)
1112 {
1113     struct qcmd *qcmd;
1114     int errnobak;
1115     
1116     if(fd >= 0)
1117         dc_disconnect();
1118     state = -1;
1119     if(hostlist != NULL)
1120         freeaddrinfo(hostlist);
1121     if(!host || !*host)
1122         hostlist = defaulthost();
1123     else
1124         hostlist = resolvhost(host);
1125     if(hostlist == NULL)
1126         return(-1);
1127     for(curhost = hostlist; curhost != NULL; curhost = curhost->ai_next)
1128     {
1129         if((fd = socket(curhost->ai_family, curhost->ai_socktype, curhost->ai_protocol)) < 0)
1130         {
1131             errnobak = errno;
1132             errno = errnobak;
1133             return(-1);
1134         }
1135         fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
1136         if(connect(fd, (struct sockaddr *)curhost->ai_addr, curhost->ai_addrlen))
1137         {
1138             if(errno == EINPROGRESS)
1139             {
1140                 state = 0;
1141                 break;
1142             }
1143             close(fd);
1144             fd = -1;
1145         } else {
1146             if(curhost->ai_canonname != NULL)
1147                 servinfo.hostname = sstrdup(curhost->ai_canonname);
1148             servinfo.family = curhost->ai_family;
1149             state = 1;
1150             break;
1151         }
1152     }
1153     qcmd = makeqcmd(NULL);
1154     resetreader = 1;
1155     return(fd);
1156 }
1157
1158 struct dc_intresp *dc_interpret(struct dc_response *resp)
1159 {
1160     int i;
1161     struct dc_intresp *iresp;
1162     struct command *cmd;
1163     struct respclass *cls;
1164     int code;
1165     size_t args;
1166     
1167     if((resp->numlines == 0) || (resp->rlines[0].argc == 0) || (resp->curline >= resp->numlines))
1168         return(NULL);
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)
1172     {
1173         if(cls->code == code)
1174             break;
1175     }
1176     if(cls == NULL)
1177         return(NULL);
1178     if(cls->nwords >= resp->rlines[resp->curline].argc)
1179         return(NULL);
1180     iresp = smalloc(sizeof(*iresp));
1181     iresp->code = code;
1182     iresp->argv = NULL;
1183     iresp->argc = 0;
1184     args = 0;
1185     for(i = 0; i < cls->nwords; i++)
1186     {
1187         switch(cls->wordt[i])
1188         {
1189         case RESP_DSC:
1190             break;
1191         case RESP_STR:
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];
1195             iresp->argc++;
1196             break;
1197         case RESP_INT:
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];
1201             iresp->argc++;
1202             break;
1203         case RESP_FLOAT:
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];
1207             iresp->argc++;
1208             break;
1209         }
1210     }
1211     resp->curline++;
1212     return(iresp);
1213 }
1214
1215 void dc_freeires(struct dc_intresp *ires)
1216 {
1217     int i;
1218     
1219     for(i = 0; i < ires->argc; i++)
1220     {
1221         if(ires->argv[i].type == RESP_STR)
1222             free(ires->argv[i].val.str);
1223     }
1224     free(ires->argv);
1225     free(ires);
1226 }
1227
1228 const char *dc_gethostname(void)
1229 {
1230     return(servinfo.hostname);
1231 }