Imported Upstream version 3.2.0
[debian/amanda] / common-src / security-util.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1999 University of Maryland
4  * All Rights Reserved.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of U.M. not be used in advertising or
11  * publicity pertaining to distribution of the software without specific,
12  * written prior permission.  U.M. makes no representations about the
13  * suitability of this software for any purpose.  It is provided "as is"
14  * without express or implied warranty.
15  *
16  * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
18  * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
20  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  *
23  * Authors: the Amanda Development Team.  Its members are listed in a
24  * file named AUTHORS, in the root directory of this distribution.
25  */
26
27 /*
28  * $Id: security-util.c,v 1.25 2006/07/22 12:04:47 martinea Exp $
29  *
30  * sec-security.c - security and transport over sec or a sec-like command.
31  *
32  * XXX still need to check for initial keyword on connect so we can skip
33  * over shell garbage and other stuff that sec might want to spew out.
34  */
35
36 #include "amanda.h"
37 #include "util.h"
38 #include "event.h"
39 #include "packet.h"
40 #include "security.h"
41 #include "security-util.h"
42 #include "stream.h"
43 #include "sockaddr-util.h"
44
45 /*
46  * This is a queue of open connections
47  */
48 GSList *connq = NULL;
49 static int newhandle = 1;
50 static int newevent = 1;
51
52 /*
53  * Local functions
54  */
55 static void recvpkt_callback(void *, void *, ssize_t);
56 static void stream_read_callback(void *);
57 static void stream_read_sync_callback(void *);
58
59 static void sec_tcp_conn_read_cancel(struct tcp_conn *);
60 static void sec_tcp_conn_read_callback(void *);
61
62
63 /*
64  * Authenticate a stream
65  * Nothing needed for sec.  The connection is authenticated by secd
66  * on startup.
67  */
68 int
69 sec_stream_auth(
70     void *      s)
71 {
72     (void)s;    /* Quiet unused parameter warning */
73     return (0);
74 }
75
76 /*
77  * Returns the stream id for this stream.  This is just the local
78  * port.
79  */
80 int
81 sec_stream_id(
82     void *      s)
83 {
84     struct sec_stream *rs = s;
85
86     assert(rs != NULL);
87
88     return (rs->handle);
89 }
90
91 /*
92  * Setup to handle new incoming connections
93  */
94 void
95 sec_accept(
96     const security_driver_t *driver,
97     char       *(*conf_fn)(char *, void *),
98     int         in,
99     int         out,
100     void        (*fn)(security_handle_t *, pkt_t *),
101     void       *datap)
102 {
103     struct tcp_conn *rc;
104
105     rc = sec_tcp_conn_get("",0); /* no hostname yet */
106     rc->read = in;
107     rc->write = out;
108     rc->accept_fn = fn;
109     rc->driver = driver;
110     rc->conf_fn = conf_fn;
111     rc->datap = datap;
112     sec_tcp_conn_read(rc);
113 }
114
115 /*
116  * frees a handle allocated by the above
117  */
118 void
119 sec_close(
120     void *      inst)
121 {
122     struct sec_handle *rh = inst;
123
124     assert(rh != NULL);
125
126     auth_debug(1, _("sec: closing handle to %s\n"), rh->hostname);
127
128     if (rh->rs != NULL) {
129         /* This may be null if we get here on an error */
130         stream_recvpkt_cancel(rh);
131         security_stream_close(&rh->rs->secstr);
132     }
133     /* keep us from getting here again */
134     rh->sech.driver = NULL;
135     amfree(rh->hostname);
136     amfree(rh);
137 }
138
139 /*
140  * Called when a sec connection is finished connecting and is ready
141  * to be authenticated.
142  */
143 void
144 sec_connect_callback(
145     void *      cookie)
146 {
147     struct sec_handle *rh = cookie;
148
149     event_release(rh->rs->ev_read);
150     rh->rs->ev_read = NULL;
151     event_release(rh->ev_timeout);
152     rh->ev_timeout = NULL;
153
154     (*rh->fn.connect)(rh->arg, &rh->sech, S_OK);
155 }
156
157 /*
158  * Called if a connection times out before completion.
159  */
160 void
161 sec_connect_timeout(
162     void *      cookie)
163 {
164     struct sec_handle *rh = cookie;
165
166     event_release(rh->rs->ev_read);
167     rh->rs->ev_read = NULL;
168     event_release(rh->ev_timeout);
169     rh->ev_timeout = NULL;
170
171     (*rh->fn.connect)(rh->arg, &rh->sech, S_TIMEOUT);
172 }
173
174 void
175 sec_close_connection_none(
176     void *h,
177     char *hostname)
178 {
179     h = h;
180     hostname = hostname;
181
182     return;
183 }
184
185
186
187 /*
188  * Transmit a packet.
189  */
190 ssize_t
191 stream_sendpkt(
192     void *      cookie,
193     pkt_t *     pkt)
194 {
195     char *buf;
196     struct sec_handle *rh = cookie;
197     size_t len;
198     char *s;
199
200     assert(rh != NULL);
201     assert(pkt != NULL);
202
203     auth_debug(1, _("sec: stream_sendpkt: enter\n"));
204
205     if (rh->rc->prefix_packet)
206         s = rh->rc->prefix_packet(rh, pkt);
207     else
208         s = "";
209     len = strlen(pkt->body) + strlen(s) + 2;
210     buf = alloc(len);
211     buf[0] = (char)pkt->type;
212     strncpy(&buf[1], s, len - 1);
213     strncpy(&buf[1 + strlen(s)], pkt->body, (len - strlen(s) - 1));
214     if (strlen(s) > 0)
215         amfree(s);
216
217     auth_debug(1,
218      _("sec: stream_sendpkt: %s (%d) pkt_t (len %zu) contains:\n\n\"%s\"\n\n"),
219       pkt_type2str(pkt->type), pkt->type, strlen(pkt->body), pkt->body);
220
221     if (security_stream_write(&rh->rs->secstr, buf, len) < 0) {
222         security_seterror(&rh->sech, "%s", security_stream_geterror(&rh->rs->secstr));
223         amfree(buf);
224         return (-1);
225     }
226     amfree(buf);
227     return (0);
228 }
229
230 /*
231  * Set up to receive a packet asyncronously, and call back when
232  * it has been read.
233  */
234 void
235 stream_recvpkt(
236     void *      cookie,
237     void        (*fn)(void *, pkt_t *, security_status_t),
238     void *      arg,
239     int         timeout)
240 {
241     struct sec_handle *rh = cookie;
242
243     assert(rh != NULL);
244
245     auth_debug(1, _("sec: recvpkt registered for %s\n"), rh->hostname);
246
247     /*
248      * Reset any pending timeout on this handle
249      */
250     if (rh->ev_timeout != NULL)
251         event_release(rh->ev_timeout);
252
253     /*
254      * Negative timeouts mean no timeout
255      */
256     if (timeout < 0) {
257         rh->ev_timeout = NULL;
258     } else {
259         rh->ev_timeout = event_register((event_id_t)timeout, EV_TIME,
260                 stream_recvpkt_timeout, rh);
261     }
262     rh->fn.recvpkt = fn;
263     rh->arg = arg;
264     security_stream_read(&rh->rs->secstr, recvpkt_callback, rh);
265 }
266
267 /*
268  * This is called when a handle times out before receiving a packet.
269  */
270 void
271 stream_recvpkt_timeout(
272     void *      cookie)
273 {
274     struct sec_handle *rh = cookie;
275
276     assert(rh != NULL);
277
278     auth_debug(1, _("sec: recvpkt timeout for %s\n"), rh->hostname);
279
280     stream_recvpkt_cancel(rh);
281     (*rh->fn.recvpkt)(rh->arg, NULL, S_TIMEOUT);
282 }
283
284 /*
285  * Remove a async receive request from the queue
286  */
287 void
288 stream_recvpkt_cancel(
289     void *      cookie)
290 {
291     struct sec_handle *rh = cookie;
292
293     auth_debug(1, _("sec: cancelling recvpkt for %s\n"), rh->hostname);
294
295     assert(rh != NULL);
296
297     security_stream_read_cancel(&rh->rs->secstr);
298     if (rh->ev_timeout != NULL) {
299         event_release(rh->ev_timeout);
300         rh->ev_timeout = NULL;
301     }
302 }
303
304 /*
305  * Write a chunk of data to a stream.  Blocks until completion.
306  */
307 int
308 tcpm_stream_write(
309     void *      s,
310     const void *buf,
311     size_t      size)
312 {
313     struct sec_stream *rs = s;
314
315     assert(rs != NULL);
316     assert(rs->rc != NULL);
317
318     auth_debug(1, _("sec: stream_write: writing %zu bytes to %s:%d %d\n"),
319                    size, rs->rc->hostname, rs->handle,
320                    rs->rc->write);
321
322     if (tcpm_send_token(rs->rc, rs->rc->write, rs->handle, &rs->rc->errmsg,
323                              buf, size)) {
324         security_stream_seterror(&rs->secstr, "%s", rs->rc->errmsg);
325         return (-1);
326     }
327     return (0);
328 }
329
330 /*
331  * Submit a request to read some data.  Calls back with the given
332  * function and arg when completed.
333  */
334 void
335 tcpm_stream_read(
336     void *      s,
337     void        (*fn)(void *, void *, ssize_t),
338     void *      arg)
339 {
340     struct sec_stream *rs = s;
341
342     assert(rs != NULL);
343
344     /*
345      * Only one read request can be active per stream.
346      */
347     if (rs->ev_read == NULL) {
348         rs->ev_read = event_register((event_id_t)rs->rc->event_id, EV_WAIT,
349             stream_read_callback, rs);
350         sec_tcp_conn_read(rs->rc);
351     }
352     rs->fn = fn;
353     rs->arg = arg;
354 }
355
356 /* buffer for tcpm_stream_read_sync function */
357 static ssize_t  sync_pktlen;
358 static void    *sync_pkt;
359
360 /*
361  * Write a chunk of data to a stream.  Blocks until completion.
362  */
363 ssize_t
364 tcpm_stream_read_sync(
365     void *      s,
366     void **     buf)
367 {
368     struct sec_stream *rs = s;
369
370     assert(rs != NULL);
371
372     /*
373      * Only one read request can be active per stream.
374      */
375     if (rs->ev_read != NULL) {
376         return -1;
377     }
378     sync_pktlen = 0;
379     sync_pkt = NULL;
380     rs->ev_read = event_register((event_id_t)rs->rc->event_id, EV_WAIT,
381         stream_read_sync_callback, rs);
382     sec_tcp_conn_read(rs->rc);
383     event_wait(rs->ev_read);
384     /* Can't use rs or rc, they can be freed */
385     *buf = sync_pkt;
386     return (sync_pktlen);
387 }
388
389 /*
390  * Cancel a previous stream read request.  It's ok if we didn't have a read
391  * scheduled.
392  */
393 void
394 tcpm_stream_read_cancel(
395     void *      s)
396 {
397     struct sec_stream *rs = s;
398
399     assert(rs != NULL);
400
401     if (rs->ev_read != NULL) {
402         event_release(rs->ev_read);
403         rs->ev_read = NULL;
404         sec_tcp_conn_read_cancel(rs->rc);
405     }
406 }
407
408 /*
409  * Transmits a chunk of data over a rsh_handle, adding
410  * the necessary headers to allow the remote end to decode it.
411  */
412 ssize_t
413 tcpm_send_token(
414     struct tcp_conn *rc,
415     int         fd,
416     int         handle,
417     char **     errmsg,
418     const void *buf,
419     size_t      len)
420 {
421     guint32             nethandle;
422     guint32             netlength;
423     struct iovec        iov[3];
424     int                 nb_iov = 3;
425     int                 rval;
426     char                *encbuf;
427     ssize_t             encsize;
428     int                 save_errno;
429     time_t              logtime;
430
431     assert(SIZEOF(netlength) == 4);
432
433     logtime = time(NULL);
434     if (rc && logtime > rc->logstamp + 10) {
435         g_debug("tcpm_send_token: data is still flowing");
436         rc->logstamp = logtime;
437     }
438
439     auth_debug(1, "tcpm_send_token: write %zd bytes to handle %d\n",
440                len, handle);
441     /*
442      * Format is:
443      *   32 bit length (network byte order)
444      *   32 bit handle (network byte order)
445      *   data
446      */
447     netlength = htonl(len);
448     iov[0].iov_base = (void *)&netlength;
449     iov[0].iov_len = SIZEOF(netlength);
450
451     nethandle = htonl((guint32)handle);
452     iov[1].iov_base = (void *)&nethandle;
453     iov[1].iov_len = SIZEOF(nethandle);
454
455     encbuf = (char *)buf;
456     encsize = len;
457
458     if(len == 0) {
459         nb_iov = 2;
460     }
461     else {
462         if (rc->driver->data_encrypt == NULL) {
463             iov[2].iov_base = (void *)buf;
464             iov[2].iov_len = len;
465         } else {
466             /* (the extra (void *) cast is to quiet type-punning warnings) */
467             rc->driver->data_encrypt(rc, (void *)buf, len, (void **)(void *)&encbuf, &encsize);
468             iov[2].iov_base = (void *)encbuf;
469             iov[2].iov_len = encsize;
470             netlength = htonl(encsize);
471         }
472         nb_iov = 3;
473     }
474
475     rval = full_writev(fd, iov, nb_iov);
476     save_errno = errno;
477     if (len != 0 && rc->driver->data_encrypt != NULL && buf != encbuf) {
478         amfree(encbuf);
479     }
480
481     if (rval < 0) {
482         if (errmsg)
483             *errmsg = newvstrallocf(*errmsg, _("write error to: %s"),
484                                    strerror(save_errno));
485         return (-1);
486     }
487     return (0);
488 }
489
490 /*
491  *  return -2 for incomplete packet
492  *  return -1 on error
493  *  return  0 on EOF:   *handle = H_EOF  && *size = 0    if socket closed
494  *  return  0 on EOF:   *handle = handle && *size = 0    if stream closed
495  *  return size     :   *handle = handle && *size = size for data read
496  */
497
498 ssize_t
499 tcpm_recv_token(
500     struct tcp_conn    *rc,
501     int         fd,
502     int *       handle,
503     char **     errmsg,
504     char **     buf,
505     ssize_t *   size)
506 {
507     ssize_t     rval;
508
509     assert(SIZEOF(rc->netint) == 8);
510     if (rc->size_header_read < (ssize_t)SIZEOF(rc->netint)) {
511         rval = read(fd, ((char *)&rc->netint) + rc->size_header_read,
512                         SIZEOF(rc->netint) - rc->size_header_read);
513         if (rval == -1) {
514             if (errmsg)
515                 *errmsg = newvstrallocf(*errmsg, _("recv error: %s"),
516                                         strerror(errno));
517             auth_debug(1, _("tcpm_recv_token: A return(-1)\n"));
518             return(-1);
519         } else if (rval == 0) {
520             *size = 0;
521             *handle = H_EOF;
522             *errmsg = newvstrallocf(*errmsg, _("SOCKET_EOF"));
523             auth_debug(1, _("tcpm_recv_token: A return(0)\n"));
524             return(0);
525         } else if (rval < (ssize_t)SIZEOF(rc->netint) - rc->size_header_read) {
526             rc->size_header_read += rval;
527             return(-2);
528         }
529         rc->size_header_read += rval;
530         amfree(rc->buffer);
531         *size = (ssize_t)ntohl(rc->netint[0]);
532         *handle = (int)ntohl(rc->netint[1]);
533         rc->buffer = NULL;
534         rc->size_buffer_read = 0;
535
536         /* amanda protocol packet can be above NETWORK_BLOCK_BYTES */
537         if (*size > 128*NETWORK_BLOCK_BYTES || *size < 0) {
538             if (isprint((int)(*size        ) & 0xFF) &&
539                 isprint((int)(*size   >> 8 ) & 0xFF) &&
540                 isprint((int)(*size   >> 16) & 0xFF) &&
541                 isprint((int)(*size   >> 24) & 0xFF) &&
542                 isprint((*handle      ) & 0xFF) &&
543                 isprint((*handle >> 8 ) & 0xFF) &&
544                 isprint((*handle >> 16) & 0xFF) &&
545                 isprint((*handle >> 24) & 0xFF)) {
546                 char s[201];
547                 char *s1;
548                 int i;
549                 s[0] = ((int)(*size)  >> 24) & 0xFF;
550                 s[1] = ((int)(*size)  >> 16) & 0xFF;
551                 s[2] = ((int)(*size)  >>  8) & 0xFF;
552                 s[3] = ((int)(*size)       ) & 0xFF;
553                 s[4] = (*handle >> 24) & 0xFF;
554                 s[5] = (*handle >> 16) & 0xFF;
555                 s[6] = (*handle >> 8 ) & 0xFF;
556                 s[7] = (*handle      ) & 0xFF;
557                 i = 8; s[i] = ' ';
558                 while(i<200 && isprint((int)s[i]) && s[i] != '\n') {
559                     switch(net_read(fd, &s[i], 1, 0)) {
560                     case -1: s[i] = '\0'; break;
561                     case  0: s[i] = '\0'; break;
562                     default:
563                          dbprintf(_("read: %c\n"), s[i]); i++; s[i]=' ';
564                          break;
565                     }
566                 }
567                 s[i] = '\0';
568                 s1 = quote_string(s);
569                 *errmsg = newvstrallocf(*errmsg,
570                                 _("tcpm_recv_token: invalid size: %s"), s1);
571                 dbprintf(_("tcpm_recv_token: invalid size %s\n"), s1);
572                 amfree(s1);
573             } else {
574                 *errmsg = newvstrallocf(*errmsg,
575                                         _("tcpm_recv_token: invalid size"));
576                 dbprintf(_("tcpm_recv_token: invalid size %zd\n"), *size);
577             }
578             *size = -1;
579             return -1;
580         }
581         rc->buffer = alloc((size_t)*size);
582
583         if (*size == 0) {
584             auth_debug(1, _("tcpm_recv_token: read EOF from %d\n"), *handle);
585             *errmsg = newvstrallocf(*errmsg, _("EOF"));
586             rc->size_header_read = 0;
587             return 0;
588         }
589     }
590
591     *size = (ssize_t)ntohl(rc->netint[0]);
592     *handle = (int)ntohl(rc->netint[1]);
593
594     rval = read(fd, rc->buffer + rc->size_buffer_read,
595                     (size_t)*size - rc->size_buffer_read);
596     if (rval == -1) {
597         if (errmsg)
598             *errmsg = newvstrallocf(*errmsg, _("recv error: %s"),
599                                     strerror(errno));
600         auth_debug(1, _("tcpm_recv_token: B return(-1)\n"));
601         return (-1);
602     } else if (rval == 0) {
603         *size = 0;
604         *errmsg = newvstrallocf(*errmsg, _("SOCKET_EOF"));
605         auth_debug(1, _("tcpm_recv_token: B return(0)\n"));
606         return (0);
607     } else if (rval < (ssize_t)*size - rc->size_buffer_read) {
608         rc->size_buffer_read += rval;
609         return (-2);
610     }
611     rc->size_buffer_read += rval;
612     amfree(*buf);
613     *buf = rc->buffer;
614     rc->size_header_read = 0;
615     rc->size_buffer_read = 0;
616     rc->buffer = NULL;
617
618     auth_debug(1, _("tcpm_recv_token: read %zd bytes from %d\n"), *size, *handle);
619
620     if (*size > 0 && rc->driver->data_decrypt != NULL) {
621         void *decbuf;
622         ssize_t decsize;
623         rc->driver->data_decrypt(rc, *buf, *size, &decbuf, &decsize);
624         if (*buf != (char *)decbuf) {
625             amfree(*buf);
626             *buf = (char *)decbuf;
627         }
628         *size = decsize;
629     }
630
631     return((*size));
632 }
633
634 void
635 tcpm_close_connection(
636     void *h,
637     char *hostname)
638 {
639     struct sec_handle *rh = h;
640
641     (void)hostname;
642
643     if (rh && rh->rc && rh->rc->read >= 0 && rh->rc->toclose == 0) {
644         rh->rc->toclose = 1;
645         sec_tcp_conn_put(rh->rc);
646     }
647 }
648
649
650
651 /*
652  * Accept an incoming connection on a stream_server socket
653  * Nothing needed for tcpma.
654  */
655 int
656 tcpma_stream_accept(
657     void *      s)
658 {
659     (void)s;    /* Quiet unused parameter warning */
660
661     return (0);
662 }
663
664 /*
665  * Return a connected stream.  For sec, this means setup a stream
666  * with the supplied handle.
667  */
668 void *
669 tcpma_stream_client(
670     void *      h,
671     int         id)
672 {
673     struct sec_handle *rh = h;
674     struct sec_stream *rs;
675
676     assert(rh != NULL);
677
678     if (id <= 0) {
679         security_seterror(&rh->sech,
680             _("%d: invalid security stream id"), id);
681         return (NULL);
682     }
683
684     rs = g_new0(struct sec_stream, 1);
685     security_streaminit(&rs->secstr, rh->sech.driver);
686     rs->handle = id;
687     rs->ev_read = NULL;
688     rs->closed_by_me = 0;
689     rs->closed_by_network = 0;
690     if (rh->rc) {
691         rs->rc = rh->rc;
692         rh->rc->refcnt++;
693     }
694     else {
695         rs->rc = sec_tcp_conn_get(rh->hostname, 0);
696         rs->rc->driver = rh->sech.driver;
697         rh->rc = rs->rc;
698     }
699
700     auth_debug(1, _("sec: stream_client: connected to stream %d\n"), id);
701
702     return (rs);
703 }
704
705 /*
706  * Create the server end of a stream.  For sec, this means setup a stream
707  * object and allocate a new handle for it.
708  */
709 void *
710 tcpma_stream_server(
711     void *      h)
712 {
713     struct sec_handle *rh = h;
714     struct sec_stream *rs;
715
716     assert(rh != NULL);
717
718     rs = g_new0(struct sec_stream, 1);
719     security_streaminit(&rs->secstr, rh->sech.driver);
720     rs->closed_by_me = 0;
721     rs->closed_by_network = 0;
722     if (rh->rc) {
723         rs->rc = rh->rc;
724         rs->rc->refcnt++;
725     }
726     else {
727         rs->rc = sec_tcp_conn_get(rh->hostname, 0);
728         rs->rc->driver = rh->sech.driver;
729         rh->rc = rs->rc;
730     }
731     /*
732      * Stream should already be setup!
733      */
734     if (rs->rc->read < 0) {
735         sec_tcp_conn_put(rs->rc);
736         amfree(rs);
737         security_seterror(&rh->sech, _("lost connection to %s"), rh->hostname);
738         return (NULL);
739     }
740     assert(strcmp(rh->hostname, rs->rc->hostname) == 0);
741     /*
742      * so as not to conflict with the amanda server's handle numbers,
743      * we start at 500000 and work down
744      */
745     rs->handle = 500000 - newhandle++;
746     rs->ev_read = NULL;
747     auth_debug(1, _("sec: stream_server: created stream %d\n"), rs->handle);
748     return (rs);
749 }
750
751 /*
752  * Close and unallocate resources for a stream.
753  */
754 void
755 tcpma_stream_close(
756     void *      s)
757 {
758     struct sec_stream *rs = s;
759     char buf = 0;
760
761     assert(rs != NULL);
762
763     auth_debug(1, _("sec: tcpma_stream_close: closing stream %d\n"), rs->handle);
764
765     if(rs->closed_by_network == 0 && rs->rc->write != -1)
766         tcpm_stream_write(rs, &buf, 0);
767     security_stream_read_cancel(&rs->secstr);
768     if(rs->closed_by_network == 0)
769         sec_tcp_conn_put(rs->rc);
770     amfree(((security_stream_t *)rs)->error);
771     amfree(rs);
772 }
773
774 /*
775  * Create the server end of a stream.  For bsdudp, this means setup a tcp
776  * socket for receiving a connection.
777  */
778 void *
779 tcp1_stream_server(
780     void *      h)
781 {
782     struct sec_stream *rs = NULL;
783     struct sec_handle *rh = h;
784
785     assert(rh != NULL);
786
787     rs = g_new0(struct sec_stream, 1);
788     security_streaminit(&rs->secstr, rh->sech.driver);
789     rs->closed_by_me = 0;
790     rs->closed_by_network = 0;
791     if (rh->rc) {
792         rs->rc = rh->rc;
793         rs->handle = 500000 - newhandle++;
794         rs->rc->refcnt++;
795         rs->socket = 0;         /* the socket is already opened */
796     }
797     else {
798         rh->rc = sec_tcp_conn_get(rh->hostname, 1);
799         rh->rc->driver = rh->sech.driver;
800         rs->rc = rh->rc;
801         rs->socket = stream_server(SU_GET_FAMILY(&rh->udp->peer), &rs->port,
802                                    STREAM_BUFSIZE, STREAM_BUFSIZE, 0);
803         if (rs->socket < 0) {
804             security_seterror(&rh->sech,
805                             _("can't create server stream: %s"), strerror(errno));
806             amfree(rs);
807             return (NULL);
808         }
809         rh->rc->read = rs->socket;
810         rh->rc->write = rs->socket;
811         rs->handle = (int)rs->port;
812     }
813     rs->fd = -1;
814     rs->ev_read = NULL;
815     return (rs);
816 }
817
818 /*
819  * Accepts a new connection on unconnected streams.  Assumes it is ok to
820  * block on accept()
821  */
822 int
823 tcp1_stream_accept(
824     void *      s)
825 {
826     struct sec_stream *bs = s;
827
828     assert(bs != NULL);
829     assert(bs->socket != -1);
830     assert(bs->fd < 0);
831
832     if (bs->socket > 0) {
833         bs->fd = stream_accept(bs->socket, 30, STREAM_BUFSIZE, STREAM_BUFSIZE);
834         if (bs->fd < 0) {
835             security_stream_seterror(&bs->secstr,
836                                      _("can't accept new stream connection: %s"),
837                                      strerror(errno));
838             return (-1);
839         }
840         bs->rc->read = bs->fd;
841         bs->rc->write = bs->fd;
842     }
843     return (0);
844 }
845
846 /*
847  * Return a connected stream
848  */
849 void *
850 tcp1_stream_client(
851     void *      h,
852     int         id)
853 {
854     struct sec_stream *rs = NULL;
855     struct sec_handle *rh = h;
856
857     assert(rh != NULL);
858
859     rs = g_new0(struct sec_stream, 1);
860     security_streaminit(&rs->secstr, rh->sech.driver);
861     rs->handle = id;
862     rs->ev_read = NULL;
863     rs->closed_by_me = 0;
864     rs->closed_by_network = 0;
865     if (rh->rc) {
866         rs->rc = rh->rc;
867         rh->rc->refcnt++;
868     }
869     else {
870         rh->rc = sec_tcp_conn_get(rh->hostname, 1);
871         rh->rc->driver = rh->sech.driver;
872         rs->rc = rh->rc;
873         rh->rc->read = stream_client(rh->hostname, (in_port_t)id,
874                         STREAM_BUFSIZE, STREAM_BUFSIZE, &rs->port, 0);
875         if (rh->rc->read < 0) {
876             security_seterror(&rh->sech,
877                               _("can't connect stream to %s port %d: %s"),
878                                rh->hostname, id, strerror(errno));
879             amfree(rs);
880             return (NULL);
881         }
882         rh->rc->write = rh->rc->read;
883     }
884     rs->socket = -1;    /* we're a client */
885     rh->rs = rs;
886     return (rs);
887 }
888
889 int
890 tcp_stream_write(
891     void *      s,
892     const void *buf,
893     size_t      size)
894 {
895     struct sec_stream *rs = s;
896     time_t             logtime;
897
898     assert(rs != NULL);
899
900     logtime = time(NULL);
901     if (rs && rs->rc && logtime > rs->rc->logstamp + 10) {
902         g_debug("tcp_stream_write: data is still flowing");
903         rs->rc->logstamp = logtime;
904     }
905
906     if (full_write(rs->fd, buf, size) < size) {
907         security_stream_seterror(&rs->secstr,
908             _("write error on stream %d: %s"), rs->port, strerror(errno));
909         return (-1);
910     }
911     return (0);
912 }
913
914 char *
915 bsd_prefix_packet(
916     void *      h,
917     pkt_t *     pkt)
918 {
919     struct sec_handle *rh = h;
920     struct passwd *pwd;
921     char *buf;
922
923     if (pkt->type != P_REQ)
924         return "";
925
926     if ((pwd = getpwuid(geteuid())) == NULL) {
927         security_seterror(&rh->sech,
928                           _("can't get login name for my uid %ld"),
929                           (long)geteuid());
930         return "";
931     }
932     buf = alloc(16+strlen(pwd->pw_name));
933     strncpy(buf, "SECURITY USER ", (16 + strlen(pwd->pw_name)));
934     strncpy(&buf[14], pwd->pw_name, (16 + strlen(pwd->pw_name) - 14));
935     buf[14 + strlen(pwd->pw_name)] = '\n';
936     buf[15 + strlen(pwd->pw_name)] = '\0';
937
938     return (buf);
939 }
940
941
942 /*
943  * Check the security of a received packet.  Returns negative on security
944  * violation, or returns 0 if ok.  Removes the security info from the pkt_t.
945  */
946 int
947 bsd_recv_security_ok(
948     struct sec_handle * rh,
949     pkt_t *             pkt)
950 {
951     char *tok, *security, *body, *result;
952     char *service = NULL, *serviceX, *serviceY;
953     char *security_line;
954     char *s, ch;
955     size_t len;
956     in_port_t port;
957
958     /*
959      * Now, find the SECURITY line in the body, and parse it out
960      * into an argv.
961      */
962     if (strncmp_const(pkt->body, "SECURITY ") == 0) {
963         security = pkt->body;
964         len = 0;
965         while(*security != '\n' && len < pkt->size) {
966             security++;
967             len++;
968         }
969         if(*security == '\n') {
970             body = security+1;
971             *security = '\0';
972             security_line = stralloc(pkt->body);
973             security = pkt->body + strlen("SECURITY ");
974         } else {
975             body = pkt->body;
976             security_line = NULL;
977             security = NULL;
978         }
979     } else {
980         body = pkt->body;
981         security_line = NULL;
982         security = NULL;
983     }
984
985     /*
986      * Now, find the SERVICE line in the body, and parse it out
987      * into an argv.
988      */
989     s = body;
990     if (strncmp_const_skip(s, "SERVICE ", s, ch) == 0) {
991         serviceX = stralloc(s);
992         serviceY = strtok(serviceX, "\n");
993         if (serviceY)
994             service  = stralloc(serviceY);
995         amfree(serviceX);
996     }
997
998     /*
999      * We need to do different things depending on which type of packet
1000      * this is.
1001      */
1002     switch (pkt->type) {
1003     case P_REQ:
1004         /*
1005          * Request packets must come from a reserved port
1006          */
1007     port = SU_GET_PORT(&rh->peer);
1008         if (port >= IPPORT_RESERVED) {
1009             security_seterror(&rh->sech,
1010                 _("host %s: port %u not secure"), rh->hostname,
1011                 (unsigned int)port);
1012             amfree(service);
1013             amfree(security_line);
1014             return (-1);
1015         }
1016
1017         if (!service) {
1018             security_seterror(&rh->sech,
1019                               _("packet as no SERVICE line"));
1020             amfree(security_line);
1021             return (-1);
1022         }
1023
1024         /*
1025          * Request packets contain a remote username.  We need to check
1026          * that we allow it in.
1027          *
1028          * They will look like:
1029          *      SECURITY USER [username]
1030          */
1031
1032         /* there must be some security info */
1033         if (security == NULL) {
1034             security_seterror(&rh->sech,
1035                 _("no bsd SECURITY for P_REQ"));
1036             amfree(service);
1037             return (-1);
1038         }
1039
1040         /* second word must be USER */
1041         if ((tok = strtok(security, " ")) == NULL) {
1042             security_seterror(&rh->sech,
1043                 _("SECURITY line: %s"), security_line);
1044             amfree(service);
1045             amfree(security_line);
1046             return (-1);        /* default errmsg */
1047         }
1048         if (strcmp(tok, "USER") != 0) {
1049             security_seterror(&rh->sech,
1050                 _("REQ SECURITY line parse error, expecting USER, got %s"), tok);
1051             amfree(service);
1052             amfree(security_line);
1053             return (-1);
1054         }
1055
1056         /* the third word is the username */
1057         if ((tok = strtok(NULL, "")) == NULL) {
1058             security_seterror(&rh->sech,
1059                 _("SECURITY line: %s"), security_line);
1060             amfree(service);
1061             amfree(security_line);
1062             return (-1);        /* default errmsg */
1063         }
1064         if ((result = check_user(rh, tok, service)) != NULL) {
1065             security_seterror(&rh->sech, "%s", result);
1066             amfree(service);
1067             amfree(result);
1068             amfree(security_line);
1069             return (-1);
1070         }
1071
1072         /* we're good to go */
1073         break;
1074     default:
1075         break;
1076     }
1077     amfree(service);
1078     amfree(security_line);
1079
1080     /*
1081      * If there is security info at the front of the packet, we need to
1082      * shift the rest of the data up and nuke it.
1083      */
1084     if (body != pkt->body)
1085         memmove(pkt->body, body, strlen(body) + 1);
1086     return (0);
1087 }
1088
1089 /*
1090  * Transmit a packet.  Add security information first.
1091  */
1092 ssize_t
1093 udpbsd_sendpkt(
1094     void *      cookie,
1095     pkt_t *     pkt)
1096 {
1097     struct sec_handle *rh = cookie;
1098     struct passwd *pwd;
1099
1100     assert(rh != NULL);
1101     assert(pkt != NULL);
1102
1103     auth_debug(1, _("udpbsd_sendpkt: enter\n"));
1104     /*
1105      * Initialize this datagram, and add the header
1106      */
1107     dgram_zero(&rh->udp->dgram);
1108     dgram_cat(&rh->udp->dgram, "%s", pkthdr2str(rh, pkt));
1109
1110     /*
1111      * Add the security info.  This depends on which kind of packet we're
1112      * sending.
1113      */
1114     switch (pkt->type) {
1115     case P_REQ:
1116         /*
1117          * Requests get sent with our username in the body
1118          */
1119         if ((pwd = getpwuid(geteuid())) == NULL) {
1120             security_seterror(&rh->sech,
1121                 _("can't get login name for my uid %ld"), (long)getuid());
1122             return (-1);
1123         }
1124         dgram_cat(&rh->udp->dgram, _("SECURITY USER %s\n"), pwd->pw_name);
1125         break;
1126
1127     default:
1128         break;
1129     }
1130
1131     /*
1132      * Add the body, and send it
1133      */
1134     dgram_cat(&rh->udp->dgram, "%s", pkt->body);
1135
1136     auth_debug(1,
1137      _("sec: udpbsd_sendpkt: %s (%d) pkt_t (len %zu) contains:\n\n\"%s\"\n\n"),
1138       pkt_type2str(pkt->type), pkt->type, strlen(pkt->body), pkt->body);
1139
1140     if (dgram_send_addr(&rh->peer, &rh->udp->dgram) != 0) {
1141         security_seterror(&rh->sech,
1142             _("send %s to %s failed: %s"), pkt_type2str(pkt->type),
1143             rh->hostname, strerror(errno));
1144         return (-1);
1145     }
1146     return (0);
1147 }
1148
1149 void
1150 udp_close(
1151     void *      cookie)
1152 {
1153     struct sec_handle *rh = cookie;
1154
1155     if (rh->proto_handle == NULL) {
1156         return;
1157     }
1158
1159     auth_debug(1, _("udp: close handle '%s'\n"), rh->proto_handle);
1160
1161     udp_recvpkt_cancel(rh);
1162     if (rh->next) {
1163         rh->next->prev = rh->prev;
1164     }
1165     else {
1166         rh->udp->bh_last = rh->prev;
1167     }
1168     if (rh->prev) {
1169         rh->prev->next = rh->next;
1170     }
1171     else {
1172         rh->udp->bh_first = rh->next;
1173     }
1174
1175     amfree(rh->proto_handle);
1176     amfree(rh->hostname);
1177     amfree(rh);
1178 }
1179
1180 /*
1181  * Set up to receive a packet asynchronously, and call back when it has
1182  * been read.
1183  */
1184 void
1185 udp_recvpkt(
1186     void *      cookie,
1187     void        (*fn)(void *, pkt_t *, security_status_t),
1188     void *      arg,
1189     int         timeout)
1190 {
1191     struct sec_handle *rh = cookie;
1192
1193     auth_debug(1, _("udp_recvpkt(cookie=%p, fn=%p, arg=%p, timeout=%u)\n"),
1194                    cookie, fn, arg, timeout);
1195     assert(rh != NULL);
1196     assert(fn != NULL);
1197
1198
1199     /*
1200      * Subsequent recvpkt calls override previous ones
1201      */
1202     if (rh->ev_read == NULL) {
1203         udp_addref(rh->udp, &udp_netfd_read_callback);
1204         rh->ev_read = event_register(rh->event_id, EV_WAIT,
1205             udp_recvpkt_callback, rh);
1206     }
1207     if (rh->ev_timeout != NULL)
1208         event_release(rh->ev_timeout);
1209     if (timeout < 0)
1210         rh->ev_timeout = NULL;
1211     else
1212         rh->ev_timeout = event_register((event_id_t)timeout, EV_TIME,
1213                                         udp_recvpkt_timeout, rh);
1214     rh->fn.recvpkt = fn;
1215     rh->arg = arg;
1216 }
1217
1218 /*
1219  * Remove a async receive request on this handle from the queue.
1220  * If it is the last one to be removed, then remove the event
1221  * handler for our network fd
1222  */
1223 void
1224 udp_recvpkt_cancel(
1225     void *      cookie)
1226 {
1227     struct sec_handle *rh = cookie;
1228
1229     assert(rh != NULL);
1230
1231     if (rh->ev_read != NULL) {
1232         udp_delref(rh->udp);
1233         event_release(rh->ev_read);
1234         rh->ev_read = NULL;
1235     }
1236
1237     if (rh->ev_timeout != NULL) {
1238         event_release(rh->ev_timeout);
1239         rh->ev_timeout = NULL;
1240     }
1241 }
1242
1243 /*
1244  * This is called when a handle is woken up because data read off of the
1245  * net is for it.
1246  */
1247 void
1248 udp_recvpkt_callback(
1249     void *      cookie)
1250 {
1251     struct sec_handle *rh = cookie;
1252     void (*fn)(void *, pkt_t *, security_status_t);
1253     void *arg;
1254
1255     auth_debug(1, _("udp: receive handle '%s' netfd '%s'\n"),
1256                    rh->proto_handle, rh->udp->handle);
1257     assert(rh != NULL);
1258
1259     /* if it doesn't correspond to this handle, something is wrong */
1260     assert(strcmp(rh->proto_handle, rh->udp->handle) == 0);
1261
1262     /* if it didn't come from the same host/port, forget it */
1263     if (cmp_sockaddr(&rh->peer, &rh->udp->peer, 0) != 0) {
1264         amfree(rh->udp->handle);
1265         dbprintf(_("not from same host\n"));
1266         dump_sockaddr(&rh->peer);
1267         dump_sockaddr(&rh->udp->peer);
1268         return;
1269     }
1270
1271     /*
1272      * We need to cancel the recvpkt request before calling the callback
1273      * because the callback may reschedule us.
1274      */
1275     fn = rh->fn.recvpkt;
1276     arg = rh->arg;
1277     udp_recvpkt_cancel(rh);
1278
1279     /*
1280      * Check the security of the packet.  If it is bad, then pass NULL
1281      * to the packet handling function instead of a packet.
1282      */
1283     if (rh->udp->recv_security_ok &&
1284         rh->udp->recv_security_ok(rh, &rh->udp->pkt) < 0) {
1285         (*fn)(arg, NULL, S_ERROR);
1286     } else {
1287         (*fn)(arg, &rh->udp->pkt, S_OK);
1288     }
1289 }
1290
1291 /*
1292  * This is called when a handle times out before receiving a packet.
1293  */
1294 void
1295 udp_recvpkt_timeout(
1296     void *      cookie)
1297 {
1298     struct sec_handle *rh = cookie;
1299     void (*fn)(void *, pkt_t *, security_status_t);
1300     void *arg;
1301
1302     assert(rh != NULL);
1303
1304     assert(rh->ev_timeout != NULL);
1305     fn = rh->fn.recvpkt;
1306     arg = rh->arg;
1307     udp_recvpkt_cancel(rh);
1308     (*fn)(arg, NULL, S_TIMEOUT);
1309 }
1310
1311 /*
1312  * Given a hostname and a port, setup a udp_handle
1313  */
1314 int
1315 udp_inithandle(
1316     udp_handle_t *      udp,
1317     struct sec_handle * rh,
1318     char *              hostname,
1319     sockaddr_union *addr,
1320     in_port_t           port,
1321     char *              handle,
1322     int                 sequence)
1323 {
1324     /*
1325      * Save the hostname and port info
1326      */
1327     auth_debug(1, _("udp_inithandle port %u handle %s sequence %d\n"),
1328                    (unsigned int)ntohs(port), handle, sequence);
1329     assert(addr != NULL);
1330
1331     rh->hostname = stralloc(hostname);
1332     copy_sockaddr(&rh->peer, addr);
1333     SU_SET_PORT(&rh->peer, port);
1334
1335
1336     rh->prev = udp->bh_last;
1337     if (udp->bh_last) {
1338         rh->prev->next = rh;
1339     }
1340     if (!udp->bh_first) {
1341         udp->bh_first = rh;
1342     }
1343     rh->next = NULL;
1344     udp->bh_last = rh;
1345
1346     rh->sequence = sequence;
1347     rh->event_id = (event_id_t)newevent++;
1348     amfree(rh->proto_handle);
1349     rh->proto_handle = stralloc(handle);
1350     rh->fn.connect = NULL;
1351     rh->arg = NULL;
1352     rh->ev_read = NULL;
1353     rh->ev_timeout = NULL;
1354
1355     auth_debug(1, _("udp: adding handle '%s'\n"), rh->proto_handle);
1356
1357     return(0);
1358 }
1359
1360
1361 /*
1362  * Callback for received packets.  This is the function bsd_recvpkt
1363  * registers with the event handler.  It is called when the event handler
1364  * realizes that data is waiting to be read on the network socket.
1365  */
1366 void
1367 udp_netfd_read_callback(
1368     void *      cookie)
1369 {
1370     struct udp_handle *udp = cookie;
1371     struct sec_handle *rh;
1372     int a;
1373     char hostname[NI_MAXHOST];
1374     in_port_t port;
1375     char *errmsg = NULL;
1376     int result;
1377
1378     auth_debug(1, _("udp_netfd_read_callback(cookie=%p)\n"), cookie);
1379     assert(udp != NULL);
1380     
1381 #ifndef TEST                                                    /* { */
1382     /*
1383      * Receive the packet.
1384      */
1385     dgram_zero(&udp->dgram);
1386     if (dgram_recv(&udp->dgram, 0, &udp->peer) < 0)
1387         return;
1388 #endif /* !TEST */                                              /* } */
1389
1390     /*
1391      * Parse the packet.
1392      */
1393     if (str2pkthdr(udp) < 0)
1394         return;
1395
1396     /*
1397      * If there are events waiting on this handle, we're done
1398      */
1399     rh = udp->bh_first;
1400     while(rh != NULL && (strcmp(rh->proto_handle, udp->handle) != 0 ||
1401                          rh->sequence != udp->sequence ||
1402                          cmp_sockaddr(&rh->peer, &udp->peer, 0) != 0)) {
1403         rh = rh->next;
1404     }
1405     if (rh && event_wakeup(rh->event_id) > 0)
1406         return;
1407
1408     /*
1409      * If we didn't find a handle, then check for a new incoming packet.
1410      * If no accept handler was setup, then just return.
1411      */
1412     if (udp->accept_fn == NULL) {
1413         dbprintf(_("Receive packet from unknown source"));
1414         return;
1415     }
1416
1417     rh = g_new0(struct sec_handle, 1);
1418     rh->proto_handle=NULL;
1419     rh->udp = udp;
1420     rh->rc = NULL;
1421     security_handleinit(&rh->sech, udp->driver);
1422
1423     result = getnameinfo((struct sockaddr *)&udp->peer, SS_LEN(&udp->peer),
1424                          hostname, sizeof(hostname), NULL, 0, 0);
1425     if (result != 0) {
1426         dbprintf("getnameinfo failed: %s\n",
1427                   gai_strerror(result));
1428         security_seterror(&rh->sech, "getnameinfo failed: %s",
1429                           gai_strerror(result));
1430         return;
1431     }
1432     if (check_name_give_sockaddr(hostname,
1433                                  (struct sockaddr *)&udp->peer, &errmsg) < 0) {
1434         security_seterror(&rh->sech, "%s",errmsg);
1435         amfree(errmsg);
1436         amfree(rh);
1437         return;
1438     }
1439
1440     port = SU_GET_PORT(&udp->peer);
1441     a = udp_inithandle(udp, rh,
1442                    hostname,
1443                    &udp->peer,
1444                    port,
1445                    udp->handle,
1446                    udp->sequence);
1447     if (a < 0) {
1448         auth_debug(1, _("bsd: closeX handle '%s'\n"), rh->proto_handle);
1449
1450         amfree(rh);
1451         return;
1452     }
1453     /*
1454      * Check the security of the packet.  If it is bad, then pass NULL
1455      * to the accept function instead of a packet.
1456      */
1457     if (rh->udp->recv_security_ok(rh, &udp->pkt) < 0)
1458         (*udp->accept_fn)(&rh->sech, NULL);
1459     else
1460         (*udp->accept_fn)(&rh->sech, &udp->pkt);
1461 }
1462
1463 /*
1464  * Locate an existing connection to the given host, or create a new,
1465  * unconnected entry if none exists.  The caller is expected to check
1466  * for the lack of a connection (rc->read == -1) and set one up.
1467  */
1468 struct tcp_conn *
1469 sec_tcp_conn_get(
1470     const char *hostname,
1471     int         want_new)
1472 {
1473     GSList *iter;
1474     struct tcp_conn *rc = NULL;
1475
1476     auth_debug(1, _("sec_tcp_conn_get: %s\n"), hostname);
1477
1478     if (want_new == 0) {
1479         for (iter = connq; iter != NULL; iter = iter->next) {
1480             rc = (struct tcp_conn *)iter->data;
1481             if (strcasecmp(hostname, rc->hostname) == 0)
1482                 break;
1483         }
1484
1485         if (iter != NULL) {
1486             rc->refcnt++;
1487             auth_debug(1,
1488                       _("sec_tcp_conn_get: exists, refcnt to %s is now %d\n"),
1489                        rc->hostname, rc->refcnt);
1490             return (rc);
1491         }
1492     }
1493
1494     auth_debug(1, _("sec_tcp_conn_get: creating new handle\n"));
1495     /*
1496      * We can't be creating a new handle if we are the client
1497      */
1498     rc = g_new0(struct tcp_conn, 1);
1499     rc->read = rc->write = -1;
1500     rc->driver = NULL;
1501     rc->pid = -1;
1502     rc->ev_read = NULL;
1503     rc->toclose = 0;
1504     rc->donotclose = 0;
1505     strncpy(rc->hostname, hostname, SIZEOF(rc->hostname) - 1);
1506     rc->hostname[SIZEOF(rc->hostname) - 1] = '\0';
1507     rc->errmsg = NULL;
1508     rc->refcnt = 1;
1509     rc->handle = -1;
1510     rc->pkt = NULL;
1511     rc->accept_fn = NULL;
1512     rc->recv_security_ok = NULL;
1513     rc->prefix_packet = NULL;
1514     rc->auth = 0;
1515     rc->conf_fn = NULL;
1516     rc->datap = NULL;
1517     rc->event_id = newevent++;
1518     connq = g_slist_append(connq, rc);
1519     return (rc);
1520 }
1521
1522 /*
1523  * Delete a reference to a connection, and close it if it is the last
1524  * reference.
1525  */
1526 void
1527 sec_tcp_conn_put(
1528     struct tcp_conn *   rc)
1529 {
1530     amwait_t status;
1531
1532     assert(rc->refcnt > 0);
1533     --rc->refcnt;
1534     auth_debug(1, _("sec_tcp_conn_put: decrementing refcnt for %s to %d\n"),
1535                    rc->hostname, rc->refcnt);
1536     if (rc->refcnt > 0) {
1537         return;
1538     }
1539     auth_debug(1, _("sec_tcp_conn_put: closing connection to %s\n"), rc->hostname);
1540     if (rc->read != -1)
1541         aclose(rc->read);
1542     if (rc->write != -1)
1543         aclose(rc->write);
1544     if (rc->pid != -1) {
1545         waitpid(rc->pid, &status, WNOHANG);
1546     }
1547     if (rc->ev_read != NULL)
1548         event_release(rc->ev_read);
1549     if (rc->errmsg != NULL)
1550         amfree(rc->errmsg);
1551     connq = g_slist_remove(connq, rc);
1552     amfree(rc->pkt);
1553     if(!rc->donotclose) {
1554         /* amfree(rc) */
1555         /* a memory leak occurs, but freeing it lead to memory
1556          * corruption because it can still be used.
1557          * We need to find a good place to free 'rc'.
1558          */
1559     }
1560 }
1561
1562 /*
1563  * Turn on read events for a conn.  Or, increase a ev_read_refcnt if we are
1564  * already receiving read events.
1565  */
1566 void
1567 sec_tcp_conn_read(
1568     struct tcp_conn *   rc)
1569 {
1570     assert (rc != NULL);
1571
1572     if (rc->ev_read != NULL) {
1573         rc->ev_read_refcnt++;
1574         auth_debug(1,
1575               _("sec: conn_read: incremented ev_read_refcnt to %d for %s\n"),
1576                rc->ev_read_refcnt, rc->hostname);
1577         return;
1578     }
1579     auth_debug(1, _("sec: conn_read registering event handler for %s\n"),
1580                    rc->hostname);
1581     rc->ev_read = event_register((event_id_t)rc->read, EV_READFD,
1582                 sec_tcp_conn_read_callback, rc);
1583     rc->ev_read_refcnt = 1;
1584 }
1585
1586 static void
1587 sec_tcp_conn_read_cancel(
1588     struct tcp_conn *   rc)
1589 {
1590
1591     --rc->ev_read_refcnt;
1592     auth_debug(1,
1593        _("sec: conn_read_cancel: decremented ev_read_refcnt to %d for %s\n"),
1594         rc->ev_read_refcnt, rc->hostname);
1595     if (rc->ev_read_refcnt > 0) {
1596         return;
1597     }
1598     auth_debug(1,
1599                 _("sec: conn_read_cancel: releasing event handler for %s\n"),
1600                  rc->hostname);
1601     event_release(rc->ev_read);
1602     rc->ev_read = NULL;
1603 }
1604
1605 /*
1606  * This is called when a handle is woken up because data read off of the
1607  * net is for it.
1608  */
1609 static void
1610 recvpkt_callback(
1611     void *      cookie,
1612     void *      buf,
1613     ssize_t     bufsize)
1614 {
1615     pkt_t pkt;
1616     struct sec_handle *rh = cookie;
1617
1618     assert(rh != NULL);
1619
1620     auth_debug(1, _("sec: recvpkt_callback: %zd\n"), bufsize);
1621     /*
1622      * We need to cancel the recvpkt request before calling
1623      * the callback because the callback may reschedule us.
1624      */
1625     stream_recvpkt_cancel(rh);
1626
1627     switch (bufsize) {
1628     case 0:
1629         security_seterror(&rh->sech,
1630             _("EOF on read from %s"), rh->hostname);
1631         (*rh->fn.recvpkt)(rh->arg, NULL, S_ERROR);
1632         return;
1633     case -1:
1634         security_seterror(&rh->sech, "%s", security_stream_geterror(&rh->rs->secstr));
1635         (*rh->fn.recvpkt)(rh->arg, NULL, S_ERROR);
1636         return;
1637     default:
1638         break;
1639     }
1640
1641     parse_pkt(&pkt, buf, (size_t)bufsize);
1642     auth_debug(1,
1643           _("sec: received %s packet (%d) from %s, contains:\n\n\"%s\"\n\n"),
1644            pkt_type2str(pkt.type), pkt.type,
1645            rh->hostname, pkt.body);
1646     if (rh->rc->recv_security_ok && (rh->rc->recv_security_ok)(rh, &pkt) < 0)
1647         (*rh->fn.recvpkt)(rh->arg, NULL, S_ERROR);
1648     else
1649         (*rh->fn.recvpkt)(rh->arg, &pkt, S_OK);
1650     amfree(pkt.body);
1651 }
1652
1653 /*
1654  * Callback for tcpm_stream_read_sync
1655  */
1656 static void
1657 stream_read_sync_callback(
1658     void *      s)
1659 {
1660     struct sec_stream *rs = s;
1661     assert(rs != NULL);
1662
1663     auth_debug(1, _("sec: stream_read_callback_sync: handle %d\n"), rs->handle);
1664
1665     /*
1666      * Make sure this was for us.  If it was, then blow away the handle
1667      * so it doesn't get claimed twice.  Otherwise, leave it alone.
1668      *
1669      * If the handle is EOF, pass that up to our callback.
1670      */
1671     if (rs->rc->handle == rs->handle) {
1672         auth_debug(1, _("sec: stream_read_callback_sync: it was for us\n"));
1673         rs->rc->handle = H_TAKEN;
1674     } else if (rs->rc->handle != H_EOF) {
1675         auth_debug(1, _("sec: stream_read_callback_sync: not for us\n"));
1676         return;
1677     }
1678
1679     /*
1680      * Remove the event first, and then call the callback.
1681      * We remove it first because we don't want to get in their
1682      * way if they reschedule it.
1683      */
1684     tcpm_stream_read_cancel(rs);
1685
1686     sync_pktlen = rs->rc->pktlen;
1687     sync_pkt = malloc(sync_pktlen);
1688     memcpy(sync_pkt, rs->rc->pkt, sync_pktlen);
1689
1690     if (rs->rc->pktlen <= 0) {
1691         auth_debug(1, _("sec: stream_read_sync_callback: %s\n"), rs->rc->errmsg);
1692         security_stream_seterror(&rs->secstr, "%s", rs->rc->errmsg);
1693         if(rs->closed_by_me == 0 && rs->closed_by_network == 0)
1694             sec_tcp_conn_put(rs->rc);
1695         rs->closed_by_network = 1;
1696         return;
1697     }
1698     auth_debug(1,
1699             _("sec: stream_read_callback_sync: read %zd bytes from %s:%d\n"),
1700             rs->rc->pktlen, rs->rc->hostname, rs->handle);
1701 }
1702
1703 /*
1704  * Callback for tcpm_stream_read
1705  */
1706 static void
1707 stream_read_callback(
1708     void *      arg)
1709 {
1710     struct sec_stream *rs = arg;
1711     time_t             logtime;
1712
1713     assert(rs != NULL);
1714
1715     logtime = time(NULL);
1716     if (rs && rs->rc && logtime > rs->rc->logstamp + 10) {
1717         g_debug("stream_read_callback: data is still flowing");
1718         rs->rc->logstamp = logtime;
1719     }
1720     auth_debug(1, _("sec: stream_read_callback: handle %d\n"), rs->handle);
1721
1722     /*
1723      * Make sure this was for us.  If it was, then blow away the handle
1724      * so it doesn't get claimed twice.  Otherwise, leave it alone.
1725      *
1726      * If the handle is EOF, pass that up to our callback.
1727      */
1728     if (rs->rc->handle == rs->handle) {
1729         auth_debug(1, _("sec: stream_read_callback: it was for us\n"));
1730         rs->rc->handle = H_TAKEN;
1731     } else if (rs->rc->handle != H_EOF) {
1732         auth_debug(1, _("sec: stream_read_callback: not for us\n"));
1733         return;
1734     }
1735
1736     /*
1737      * Remove the event first, and then call the callback.
1738      * We remove it first because we don't want to get in their
1739      * way if they reschedule it.
1740      */
1741     tcpm_stream_read_cancel(rs);
1742
1743     if (rs->rc->pktlen <= 0) {
1744         auth_debug(1, _("sec: stream_read_callback: %s\n"), rs->rc->errmsg);
1745         security_stream_seterror(&rs->secstr, "%s", rs->rc->errmsg);
1746         if(rs->closed_by_me == 0 && rs->closed_by_network == 0)
1747             sec_tcp_conn_put(rs->rc);
1748         rs->closed_by_network = 1;
1749         (*rs->fn)(rs->arg, NULL, rs->rc->pktlen);
1750         return;
1751     }
1752     auth_debug(1, _("sec: stream_read_callback: read %zd bytes from %s:%d\n"),
1753                    rs->rc->pktlen, rs->rc->hostname, rs->handle);
1754     (*rs->fn)(rs->arg, rs->rc->pkt, rs->rc->pktlen);
1755     auth_debug(1, _("sec: after callback stream_read_callback\n"));
1756 }
1757
1758 /*
1759  * The callback for the netfd for the event handler
1760  * Determines if this packet is for this security handle,
1761  * and does the real callback if so.
1762  */
1763 static void
1764 sec_tcp_conn_read_callback(
1765     void *      cookie)
1766 {
1767     struct tcp_conn *   rc = cookie;
1768     struct sec_handle * rh;
1769     pkt_t               pkt;
1770     ssize_t             rval;
1771     int                 revent;
1772
1773     assert(cookie != NULL);
1774
1775     auth_debug(1, _("sec: conn_read_callback\n"));
1776
1777     /* Read the data off the wire.  If we get errors, shut down. */
1778     rval = tcpm_recv_token(rc, rc->read, &rc->handle, &rc->errmsg, &rc->pkt,
1779                                 &rc->pktlen);
1780     auth_debug(1, _("sec: conn_read_callback: tcpm_recv_token returned %zd\n"),
1781                    rval);
1782
1783     if (rval == -2) {
1784         return;
1785     }
1786
1787     if (rval < 0 || rc->handle == H_EOF) {
1788         rc->pktlen = rval;
1789         rc->handle = H_EOF;
1790         revent = event_wakeup((event_id_t)rc->event_id);
1791         auth_debug(1, _("sec: conn_read_callback: event_wakeup return %d\n"),
1792                        revent);
1793         /* delete our 'accept' reference */
1794         if (rc->accept_fn != NULL) {
1795             if(rc->refcnt != 1) {
1796                 dbprintf(_("STRANGE, rc->refcnt should be 1, it is %d\n"),
1797                           rc->refcnt);
1798                 rc->refcnt=1;
1799             }
1800             rc->accept_fn = NULL;
1801             sec_tcp_conn_put(rc);
1802         }
1803         return;
1804     }
1805
1806     if(rval == 0) {
1807         rc->pktlen = 0;
1808         revent = event_wakeup((event_id_t)rc->event_id);
1809         auth_debug(1,
1810                    _("sec: conn_read_callback: event_wakeup return %d\n"), revent);
1811         return;
1812     }
1813
1814     /* If there are events waiting on this handle, we're done */
1815     rc->donotclose = 1;
1816     revent = event_wakeup((event_id_t)rc->event_id);
1817     auth_debug(1, _("sec: conn_read_callback: event_wakeup return %d\n"), revent);
1818     rc->donotclose = 0;
1819     if (rc->handle == H_TAKEN || rc->pktlen == 0) {
1820         if(rc->refcnt == 0) amfree(rc);
1821         return;
1822     }
1823
1824     assert(rc->refcnt > 0);
1825
1826     /* If there is no accept fn registered, then drop the packet */
1827     if (rc->accept_fn == NULL) {
1828         g_warning(
1829           _("sec: conn_read_callback: %zd bytes for handle %d went unclaimed!"),
1830           rc->pktlen, rc->handle);
1831         return;
1832     }
1833
1834     rh = g_new0(struct sec_handle, 1);
1835     security_handleinit(&rh->sech, rc->driver);
1836     rh->hostname = stralloc(rc->hostname);
1837     rh->ev_timeout = NULL;
1838     rh->rc = rc;
1839     rh->peer = rc->peer;
1840     rh->rs = tcpma_stream_client(rh, rc->handle);
1841
1842     auth_debug(1, _("sec: new connection\n"));
1843     pkt.body = NULL;
1844     parse_pkt(&pkt, rc->pkt, (size_t)rc->pktlen);
1845     auth_debug(1, _("sec: calling accept_fn\n"));
1846     if (rh->rc->recv_security_ok && (rh->rc->recv_security_ok)(rh, &pkt) < 0)
1847         (*rc->accept_fn)(&rh->sech, NULL);
1848     else
1849         (*rc->accept_fn)(&rh->sech, &pkt);
1850     amfree(pkt.body);
1851 }
1852
1853 void
1854 parse_pkt(
1855     pkt_t *     pkt,
1856     const void *buf,
1857     size_t      bufsize)
1858 {
1859     const unsigned char *bufp = buf;
1860
1861     auth_debug(1, _("sec: parse_pkt: parsing buffer of %zu bytes\n"), bufsize);
1862
1863     pkt->type = (pktype_t)*bufp++;
1864     bufsize--;
1865
1866     pkt->packet_size = bufsize+1;
1867     pkt->body = alloc(pkt->packet_size);
1868     if (bufsize == 0) {
1869         pkt->body[0] = '\0';
1870     } else {
1871         memcpy(pkt->body, bufp, bufsize);
1872         pkt->body[pkt->packet_size - 1] = '\0';
1873     }
1874     pkt->size = strlen(pkt->body);
1875
1876     auth_debug(1, _("sec: parse_pkt: %s (%d): \"%s\"\n"), pkt_type2str(pkt->type),
1877                    pkt->type, pkt->body);
1878 }
1879
1880 /*
1881  * Convert a packet header into a string
1882  */
1883 const char *
1884 pkthdr2str(
1885     const struct sec_handle *   rh,
1886     const pkt_t *               pkt)
1887 {
1888     static char retbuf[256];
1889
1890     assert(rh != NULL);
1891     assert(pkt != NULL);
1892
1893     g_snprintf(retbuf, SIZEOF(retbuf), _("Amanda %d.%d %s HANDLE %s SEQ %d\n"),
1894         VERSION_MAJOR, VERSION_MINOR, pkt_type2str(pkt->type),
1895         rh->proto_handle, rh->sequence);
1896
1897     auth_debug(1, _("bsd: pkthdr2str handle '%s'\n"), rh->proto_handle);
1898
1899     /* check for truncation.  If only we had asprintf()... */
1900     assert(retbuf[strlen(retbuf) - 1] == '\n');
1901
1902     return (retbuf);
1903 }
1904
1905 /*
1906  * Parses out the header line in 'str' into the pkt and handle
1907  * Returns negative on parse error.
1908  */
1909 int
1910 str2pkthdr(
1911     udp_handle_t *      udp)
1912 {
1913     char *str;
1914     const char *tok;
1915     pkt_t *pkt;
1916
1917     pkt = &udp->pkt;
1918
1919     assert(udp->dgram.cur != NULL);
1920     str = stralloc(udp->dgram.cur);
1921
1922     /* "Amanda %d.%d <ACK,NAK,...> HANDLE %s SEQ %d\n" */
1923
1924     /* Read in "Amanda" */
1925     if ((tok = strtok(str, " ")) == NULL || strcmp(tok, "Amanda") != 0)
1926         goto parse_error;
1927
1928     /* nothing is done with the major/minor numbers currently */
1929     if ((tok = strtok(NULL, " ")) == NULL || strchr(tok, '.') == NULL)
1930         goto parse_error;
1931
1932     /* Read in the packet type */
1933     if ((tok = strtok(NULL, " ")) == NULL)
1934         goto parse_error;
1935     amfree(pkt->body);
1936     pkt_init_empty(pkt, pkt_str2type(tok));
1937     if (pkt->type == (pktype_t)-1)    
1938         goto parse_error;
1939
1940     /* Read in "HANDLE" */
1941     if ((tok = strtok(NULL, " ")) == NULL || strcmp(tok, "HANDLE") != 0)
1942         goto parse_error;
1943
1944     /* parse the handle */
1945     if ((tok = strtok(NULL, " ")) == NULL)
1946         goto parse_error;
1947     amfree(udp->handle);
1948     udp->handle = stralloc(tok);
1949
1950     /* Read in "SEQ" */
1951     if ((tok = strtok(NULL, " ")) == NULL || strcmp(tok, "SEQ") != 0)   
1952         goto parse_error;
1953
1954     /* parse the sequence number */   
1955     if ((tok = strtok(NULL, "\n")) == NULL)
1956         goto parse_error;
1957     udp->sequence = atoi(tok);
1958
1959     /* Save the body, if any */       
1960     if ((tok = strtok(NULL, "")) != NULL)
1961         pkt_cat(pkt, "%s", tok);
1962
1963     amfree(str);
1964     return (0);
1965
1966 parse_error:
1967 #if 0 /* XXX we have no way of passing this back up */
1968     security_seterror(&rh->sech,
1969         "parse error in packet header : '%s'", origstr);
1970 #endif
1971     amfree(str);
1972     return (-1);
1973 }
1974
1975 char *
1976 check_user(
1977     struct sec_handle * rh,
1978     const char *        remoteuser,
1979     const char *        service)
1980 {
1981     struct passwd *pwd;
1982     char *r;
1983     char *result = NULL;
1984     char *localuser = NULL;
1985
1986     /* lookup our local user name */
1987     if ((pwd = getpwnam(CLIENT_LOGIN)) == NULL) {
1988         return vstrallocf(_("getpwnam(%s) failed."), CLIENT_LOGIN);
1989     }
1990
1991     /*
1992      * Make a copy of the user name in case getpw* is called by
1993      * any of the lower level routines.
1994      */
1995     localuser = stralloc(pwd->pw_name);
1996
1997 #ifndef USE_AMANDAHOSTS
1998     r = check_user_ruserok(rh->hostname, pwd, remoteuser);
1999 #else
2000     r = check_user_amandahosts(rh->hostname, &rh->peer, pwd, remoteuser, service);
2001 #endif
2002     if (r != NULL) {
2003         result = vstrallocf(
2004                 _("user %s from %s is not allowed to execute the service %s: %s"),
2005                 remoteuser, rh->hostname, service, r);
2006         amfree(r);
2007     }
2008     amfree(localuser);
2009     return result;
2010 }
2011
2012 /*
2013  * See if a remote user is allowed in.  This version uses ruserok()
2014  * and friends.
2015  *
2016  * Returns NULL on success, or error message on error.
2017  */
2018 char *
2019 check_user_ruserok(
2020     const char *        host,
2021     struct passwd *     pwd,
2022     const char *        remoteuser)
2023 {
2024     int saved_stderr;
2025     int fd[2];
2026     FILE *fError;
2027     amwait_t exitcode;
2028     pid_t ruserok_pid;
2029     pid_t pid;
2030     char *es;
2031     char *result;
2032     int ok;
2033     uid_t myuid = getuid();
2034
2035     /*
2036      * note that some versions of ruserok (eg SunOS 3.2) look in
2037      * "./.rhosts" rather than "~CLIENT_LOGIN/.rhosts", so we have to
2038      * chdir ourselves.  Sigh.
2039      *
2040      * And, believe it or not, some ruserok()'s try an initgroup just
2041      * for the hell of it.  Since we probably aren't root at this point
2042      * it'll fail, and initgroup "helpfully" will blatt "Setgroups: Not owner"
2043      * into our stderr output even though the initgroup failure is not a
2044      * problem and is expected.  Thanks a lot.  Not.
2045      */
2046     if (pipe(fd) != 0) {
2047         return stralloc2(_("pipe() fails: "), strerror(errno));
2048     }
2049     if ((ruserok_pid = fork()) < 0) {
2050         return stralloc2(_("fork() fails: "), strerror(errno));
2051     } else if (ruserok_pid == 0) {
2052         int ec;
2053
2054         close(fd[0]);
2055         fError = fdopen(fd[1], "w");
2056         if (!fError) {
2057             error(_("Can't fdopen: %s"), strerror(errno));
2058             /*NOTREACHED*/
2059         }
2060         /* pamper braindead ruserok's */
2061         if (chdir(pwd->pw_dir) != 0) {
2062             g_fprintf(fError, _("chdir(%s) failed: %s"),
2063                     pwd->pw_dir, strerror(errno));
2064             fclose(fError);
2065             exit(1);
2066         }
2067
2068         if (debug_auth >= 9) {
2069             char *dir = stralloc(pwd->pw_dir);
2070
2071             auth_debug(9, _("bsd: calling ruserok(%s, %d, %s, %s)\n"), host,
2072                            ((myuid == 0) ? 1 : 0), remoteuser, pwd->pw_name);
2073             if (myuid == 0) {
2074                 auth_debug(9, _("bsd: because you are running as root, "));
2075                 auth_debug(9, _("/etc/hosts.equiv will not be used\n"));
2076             } else {
2077                 show_stat_info("/etc/hosts.equiv", NULL);
2078             }
2079             show_stat_info(dir, "/.rhosts");
2080             amfree(dir);
2081         }
2082
2083         saved_stderr = dup(2);
2084         close(2);
2085         if (open("/dev/null", O_RDWR) == -1) {
2086             auth_debug(1, _("Could not open /dev/null: %s\n"), strerror(errno));
2087             ec = 1;
2088         } else {
2089             ok = ruserok(host, myuid == 0, remoteuser, CLIENT_LOGIN);
2090             if (ok < 0) {
2091                 ec = 1;
2092             } else {
2093                 ec = 0;
2094             }
2095         }
2096         (void)dup2(saved_stderr,2);
2097         close(saved_stderr);
2098         exit(ec);
2099     }
2100     close(fd[1]);
2101     fError = fdopen(fd[0], "r");
2102     if (!fError) {
2103         error(_("Can't fdopen: %s"), strerror(errno));
2104         /*NOTREACHED*/
2105     }
2106
2107     result = NULL;
2108     while ((es = agets(fError)) != NULL) {
2109         if (*es == 0) {
2110             amfree(es);
2111             continue;
2112         }
2113         if (result == NULL) {
2114             result = stralloc("");
2115         } else {
2116             strappend(result, ": ");
2117         }
2118         strappend(result, es);
2119         amfree(es);
2120     }
2121     close(fd[0]);
2122
2123     pid = wait(&exitcode);
2124     while (pid != ruserok_pid) {
2125         if ((pid == (pid_t) -1) && (errno != EINTR)) {
2126             amfree(result);
2127             return vstrallocf(_("ruserok wait failed: %s"), strerror(errno));
2128         }
2129         pid = wait(&exitcode);
2130     }
2131     if (!WIFEXITED(exitcode) || WEXITSTATUS(exitcode) != 0) {
2132         amfree(result);
2133         result = str_exit_status("ruserok child", exitcode);
2134     } else {
2135         amfree(result);
2136     }
2137
2138     return result;
2139 }
2140
2141 /*
2142  * Check to see if a user is allowed in.  This version uses .amandahosts
2143  * Returns an error message on failure, or NULL on success.
2144  */
2145 char *
2146 check_user_amandahosts(
2147     const char *        host,
2148     sockaddr_union *addr,
2149     struct passwd *     pwd,
2150     const char *        remoteuser,
2151     const char *        service)
2152 {
2153     char *line = NULL;
2154     char *filehost;
2155     const char *fileuser;
2156     char *ptmp = NULL;
2157     char *result = NULL;
2158     FILE *fp = NULL;
2159     int found;
2160     struct stat sbuf;
2161     int hostmatch;
2162     int usermatch;
2163     char *aservice = NULL;
2164 #ifdef WORKING_IPV6
2165     char ipstr[INET6_ADDRSTRLEN];
2166 #else
2167     char ipstr[INET_ADDRSTRLEN];
2168 #endif
2169
2170     auth_debug(1, _("check_user_amandahosts(host=%s, pwd=%p, "
2171                    "remoteuser=%s, service=%s)\n"),
2172                    host, pwd, remoteuser, service);
2173
2174     ptmp = stralloc2(pwd->pw_dir, "/.amandahosts");
2175     if (debug_auth >= 9) {
2176         show_stat_info(ptmp, "");;
2177     }
2178     if ((fp = fopen(ptmp, "r")) == NULL) {
2179         result = vstrallocf(_("cannot open %s: %s"), ptmp, strerror(errno));
2180         amfree(ptmp);
2181         return result;
2182     }
2183
2184     /*
2185      * Make sure the file is owned by the Amanda user and does not
2186      * have any group/other access allowed.
2187      */
2188     if (fstat(fileno(fp), &sbuf) != 0) {
2189         result = vstrallocf(_("cannot fstat %s: %s"), ptmp, strerror(errno));
2190         goto common_exit;
2191     }
2192     if (sbuf.st_uid != pwd->pw_uid) {
2193         result = vstrallocf(_("%s: owned by id %ld, should be %ld"),
2194                         ptmp, (long)sbuf.st_uid, (long)pwd->pw_uid);
2195         goto common_exit;
2196     }
2197     if ((sbuf.st_mode & 077) != 0) {
2198         result = vstrallocf(_("%s: incorrect permissions; file must be accessible only by its owner"), ptmp);
2199         goto common_exit;
2200     }
2201
2202     /*
2203      * Now, scan the file for the host/user/service.
2204      */
2205     found = 0;
2206     while ((line = agets(fp)) != NULL) {
2207         if (*line == 0) {
2208             amfree(line);
2209             continue;
2210         }
2211
2212         auth_debug(9, _("bsd: processing line: <%s>\n"), line);
2213         /* get the host out of the file */
2214         if ((filehost = strtok(line, " \t")) == NULL) {
2215             amfree(line);
2216             continue;
2217         }
2218
2219         /* get the username.  If no user specified, then use the local user */
2220         if ((fileuser = strtok(NULL, " \t")) == NULL) {
2221             fileuser = pwd->pw_name;
2222         }
2223
2224         hostmatch = (strcasecmp(filehost, host) == 0);
2225         /*  ok if addr=127.0.0.1 and
2226          *  either localhost or localhost.domain is in .amandahost */
2227         if (!hostmatch  &&
2228             (strcasecmp(filehost, "localhost")== 0 ||
2229              strcasecmp(filehost, "localhost.localdomain")== 0)) {
2230 #ifdef WORKING_IPV6
2231             if (SU_GET_FAMILY(addr) == (sa_family_t)AF_INET6)
2232                 inet_ntop(AF_INET6, &addr->sin6.sin6_addr,
2233                           ipstr, sizeof(ipstr));
2234             else
2235 #endif
2236                 inet_ntop(AF_INET, &addr->sin.sin_addr,
2237                           ipstr, sizeof(ipstr));
2238             if (strcmp(ipstr, "127.0.0.1") == 0 ||
2239                 strcmp(ipstr, "::1") == 0)
2240                 hostmatch = 1;
2241         }
2242         usermatch = (strcasecmp(fileuser, remoteuser) == 0);
2243         auth_debug(9, _("bsd: comparing \"%s\" with\n"), filehost);
2244         auth_debug(9, _("bsd:           \"%s\" (%s)\n"), host,
2245                        hostmatch ? _("match") : _("no match"));
2246         auth_debug(9, _("bsd:       and \"%s\" with\n"), fileuser);
2247         auth_debug(9, _("bsd:           \"%s\" (%s)\n"), remoteuser,
2248                        usermatch ? _("match") : _("no match"));
2249         /* compare */
2250         if (!hostmatch || !usermatch) {
2251             amfree(line);
2252             continue;
2253         }
2254
2255         if (!service) {
2256             /* success */
2257             amfree(line);
2258             found = 1;
2259             break;
2260         }
2261
2262         /* get the services.  If no service specified, then use
2263          * noop/selfcheck/sendsize/sendbackup
2264          */
2265         aservice = strtok(NULL, " \t,");
2266         if (!aservice) {
2267             if (strcmp(service,"noop") == 0 ||
2268                strcmp(service,"selfcheck") == 0 ||
2269                strcmp(service,"sendsize") == 0 ||
2270                strcmp(service,"sendbackup") == 0) {
2271                 /* success */
2272                 found = 1;
2273                 amfree(line);
2274                 break;
2275             }
2276             else {
2277                 amfree(line);
2278                 break;
2279             }
2280         }
2281
2282         do {
2283             if (strcmp(aservice,service) == 0) {
2284                 found = 1;
2285                 break;
2286             }
2287             if (strcmp(aservice, "amdump") == 0 && 
2288                (strcmp(service, "noop") == 0 ||
2289                 strcmp(service, "selfcheck") == 0 ||
2290                 strcmp(service, "sendsize") == 0 ||
2291                 strcmp(service, "sendbackup") == 0)) {
2292                 found = 1;
2293                 break;
2294             }
2295         } while((aservice = strtok(NULL, " \t,")) != NULL);
2296
2297         if (aservice && strcmp(aservice, service) == 0) {
2298             /* success */
2299             found = 1;
2300             amfree(line);
2301             break;
2302         }
2303         amfree(line);
2304     }
2305     if (! found) {
2306         if (strcmp(service, "amindexd") == 0 ||
2307             strcmp(service, "amidxtaped") == 0) {
2308             result = vstrallocf(_("Please add the line \"%s %s amindexd amidxtaped\" to %s on the server"), host, remoteuser, ptmp);
2309         } else if (strcmp(service, "amdump") == 0 ||
2310                    strcmp(service, "noop") == 0 ||
2311                    strcmp(service, "selfcheck") == 0 ||
2312                    strcmp(service, "sendsize") == 0 ||
2313                    strcmp(service, "sendbackup") == 0) {
2314             result = vstrallocf(_("Please add the line \"%s %s amdump\" to %s on the client"), host, remoteuser, ptmp);
2315         } else {
2316             result = vstrallocf(_("%s: invalid service %s"), ptmp, service);
2317         }
2318     }
2319
2320 common_exit:
2321
2322     afclose(fp);
2323     amfree(ptmp);
2324
2325     return result;
2326 }
2327
2328 /* return 1 on success, 0 on failure */
2329 int
2330 check_security(
2331     sockaddr_union *addr,
2332     char *              str,
2333     unsigned long       cksum,
2334     char **             errstr)
2335 {
2336     char *              remotehost = NULL, *remoteuser = NULL;
2337     char *              bad_bsd = NULL;
2338     struct passwd *     pwptr;
2339     uid_t               myuid;
2340     char *              s;
2341     char *              fp;
2342     int                 ch;
2343     char                hostname[NI_MAXHOST];
2344     in_port_t           port;
2345     int                 result;
2346
2347     (void)cksum;        /* Quiet unused parameter warning */
2348
2349     auth_debug(1,
2350                _("check_security(addr=%p, str='%s', cksum=%lu, errstr=%p\n"),
2351                 addr, str, cksum, errstr);
2352     dump_sockaddr(addr);
2353
2354     *errstr = NULL;
2355
2356     /* what host is making the request? */
2357     if ((result = getnameinfo((struct sockaddr *)addr, SS_LEN(addr),
2358                               hostname, NI_MAXHOST, NULL, 0, 0)) != 0) {
2359         dbprintf(_("getnameinfo failed: %s\n"),
2360                   gai_strerror(result));
2361         *errstr = vstralloc("[", "addr ", str_sockaddr(addr), ": ",
2362                             "getnameinfo failed: ", gai_strerror(result),
2363                             "]", NULL);
2364         return 0;
2365     }
2366     remotehost = stralloc(hostname);
2367     if( check_name_give_sockaddr(hostname,
2368                                  (struct sockaddr *)addr, errstr) < 0) {
2369         amfree(remotehost);
2370         return 0;
2371     }
2372
2373
2374     /* next, make sure the remote port is a "reserved" one */
2375     port = SU_GET_PORT(addr);
2376     if (port >= IPPORT_RESERVED) {
2377         *errstr = vstrallocf(_("[host %s: port %u not secure]"),
2378                         remotehost, (unsigned int)port);
2379         amfree(remotehost);
2380         return 0;
2381     }
2382
2383     /* extract the remote user name from the message */
2384
2385     s = str;
2386     ch = *s++;
2387
2388     bad_bsd = vstrallocf(_("[host %s: bad bsd security line]"), remotehost);
2389
2390     if (strncmp_const_skip(s - 1, "USER ", s, ch) != 0) {
2391         *errstr = bad_bsd;
2392         bad_bsd = NULL;
2393         amfree(remotehost);
2394         return 0;
2395     }
2396
2397     skip_whitespace(s, ch);
2398     if (ch == '\0') {
2399         *errstr = bad_bsd;
2400         bad_bsd = NULL;
2401         amfree(remotehost);
2402         return 0;
2403     }
2404     fp = s - 1;
2405     skip_non_whitespace(s, ch);
2406     s[-1] = '\0';
2407     remoteuser = stralloc(fp);
2408     s[-1] = (char)ch;
2409     amfree(bad_bsd);
2410
2411     /* lookup our local user name */
2412
2413     myuid = getuid();
2414     if ((pwptr = getpwuid(myuid)) == NULL)
2415         error(_("error [getpwuid(%d) fails]"), (int)myuid);
2416
2417     auth_debug(1, _("bsd security: remote host %s user %s local user %s\n"),
2418                    remotehost, remoteuser, pwptr->pw_name);
2419
2420 #ifndef USE_AMANDAHOSTS
2421     s = check_user_ruserok(remotehost, pwptr, remoteuser);
2422 #else
2423     s = check_user_amandahosts(remotehost, addr, pwptr, remoteuser, NULL);
2424 #endif
2425
2426     if (s != NULL) {
2427         *errstr = vstrallocf(_("[access as %s not allowed from %s@%s: %s]"),
2428                             pwptr->pw_name, remoteuser, remotehost, s);
2429     }
2430     amfree(s);
2431     amfree(remotehost);
2432     amfree(remoteuser);
2433     return *errstr == NULL;
2434 }
2435
2436 /*
2437  * Like read(), but waits until the entire buffer has been filled.
2438  */
2439 ssize_t
2440 net_read(
2441     int         fd,
2442     void *      vbuf,
2443     size_t      origsize,
2444     int         timeout)
2445 {
2446     char *buf = vbuf;   /* ptr arith */
2447     ssize_t nread;
2448     size_t size = origsize;
2449
2450     auth_debug(1, _("net_read: begin %zu\n"), origsize);
2451
2452     while (size > 0) {
2453         auth_debug(1, _("net_read: while %zu\n"), size);
2454         nread = net_read_fillbuf(fd, timeout, buf, size);
2455         if (nread < 0) {
2456             auth_debug(1, _("db: net_read: end return(-1)\n"));
2457             return (-1);
2458         }
2459         if (nread == 0) {
2460             auth_debug(1, _("net_read: end return(0)\n"));
2461             return (0);
2462         }
2463         buf += nread;
2464         size -= nread;
2465     }
2466     auth_debug(1, _("net_read: end %zu\n"), origsize);
2467     return ((ssize_t)origsize);
2468 }
2469
2470 /*
2471  * net_read likes to do a lot of little reads.  Buffer it.
2472  */
2473 ssize_t
2474 net_read_fillbuf(
2475     int         fd,
2476     int         timeout,
2477     void *      buf,
2478     size_t      size)
2479 {
2480     SELECT_ARG_TYPE readfds;
2481     struct timeval tv;
2482     ssize_t nread;
2483
2484     auth_debug(1, _("net_read_fillbuf: begin\n"));
2485     FD_ZERO(&readfds);
2486     FD_SET(fd, &readfds);
2487     tv.tv_sec = timeout;
2488     tv.tv_usec = 0;
2489     switch (select(fd + 1, &readfds, NULL, NULL, &tv)) {
2490     case 0:
2491         errno = ETIMEDOUT;
2492         /* FALLTHROUGH */
2493     case -1:
2494         auth_debug(1, _("net_read_fillbuf: case -1\n"));
2495         return (-1);
2496     case 1:
2497         auth_debug(1, _("net_read_fillbuf: case 1\n"));
2498         assert(FD_ISSET(fd, &readfds));
2499         break;
2500     default:
2501         auth_debug(1, _("net_read_fillbuf: case default\n"));
2502         assert(0);
2503         break;
2504     }
2505     nread = read(fd, buf, size);
2506     if (nread < 0)
2507         return (-1);
2508     auth_debug(1, _("net_read_fillbuf: end %zd\n"), nread);
2509     return (nread);
2510 }
2511
2512
2513 /*
2514  * Display stat() information about a file.
2515  */
2516
2517 void
2518 show_stat_info(
2519     char *      a,
2520     char *      b)
2521 {
2522     char *name = vstralloc(a, b, NULL);
2523     struct stat sbuf;
2524     struct passwd *pwptr G_GNUC_UNUSED;
2525     struct passwd pw G_GNUC_UNUSED;
2526     char *owner;
2527     struct group *grptr G_GNUC_UNUSED;
2528     struct group gr G_GNUC_UNUSED;
2529     char *group;
2530     int buflen G_GNUC_UNUSED;
2531     char *buf G_GNUC_UNUSED;
2532
2533     if (stat(name, &sbuf) != 0) {
2534         auth_debug(1, _("bsd: cannot stat %s: %s\n"), name, strerror(errno));
2535         amfree(name);
2536         return;
2537     }
2538
2539 #ifdef _SC_GETPW_R_SIZE_MAX
2540     buflen = sysconf(_SC_GETPW_R_SIZE_MAX);
2541     if (buflen == -1)
2542         buflen = 1024;
2543 #else
2544     buflen = 1024;
2545 #endif
2546     buf = malloc(buflen);
2547
2548 #ifdef HAVE_GETPWUID_R
2549     if (getpwuid_r(sbuf.st_uid, &pw, buf, buflen, &pwptr) == 0 &&
2550         pwptr != NULL) {
2551         owner = stralloc(pwptr->pw_name);
2552     } else
2553 #endif
2554     {
2555         owner = alloc(NUM_STR_SIZE + 1);
2556         g_snprintf(owner, NUM_STR_SIZE, "%ld", (long)sbuf.st_uid);
2557     }
2558 #ifdef HAVE_GETGRGID_R
2559     if (getgrgid_r(sbuf.st_gid, &gr, buf, buflen, &grptr) == 0 &&
2560         grptr != NULL) {
2561         group = stralloc(grptr->gr_name);
2562     } else
2563 #endif
2564     {
2565         group = alloc(NUM_STR_SIZE + 1);
2566         g_snprintf(group, NUM_STR_SIZE, "%ld", (long)sbuf.st_gid);
2567     }
2568
2569     auth_debug(1, _("bsd: processing file: %s\n"), name);
2570     auth_debug(1, _("bsd:                  owner=%s group=%s mode=%03o\n"),
2571                    owner, group,
2572                    (int) (sbuf.st_mode & 0777));
2573     amfree(name);
2574     amfree(owner);
2575     amfree(group);
2576     amfree(buf);
2577 }
2578
2579 int
2580 check_name_give_sockaddr(
2581     const char *hostname,
2582     struct sockaddr *addr,
2583     char **errstr)
2584 {
2585     int result;
2586     struct addrinfo *res = NULL, *res1;
2587     char *canonname;
2588
2589     result = resolve_hostname(hostname, 0, &res, &canonname);
2590     if (result != 0) {
2591         dbprintf(_("check_name_give_sockaddr: resolve_hostname('%s'): %s\n"), hostname, gai_strerror(result));
2592         *errstr = newvstrallocf(*errstr,
2593                                _("check_name_give_sockaddr: resolve_hostname('%s'): %s"),
2594                                hostname, gai_strerror(result));
2595         goto error;
2596     }
2597     if (canonname == NULL) {
2598         dbprintf(_("resolve_hostname('%s') did not return a canonical name\n"), hostname);
2599         *errstr = newvstrallocf(*errstr,
2600                 _("check_name_give_sockaddr: resolve_hostname('%s') did not return a canonical name"),
2601                 hostname);
2602         goto error;
2603     }
2604
2605     if (strncasecmp(hostname, canonname, strlen(hostname)) != 0) {
2606         dbprintf(_("%s doesn't resolve to itself, it resolves to %s\n"),
2607                        hostname, canonname);
2608         *errstr = newvstrallocf(*errstr,
2609                                _("%s doesn't resolve to itself, it resolves to %s"),
2610                                hostname, canonname);
2611         goto error;
2612     }
2613
2614     for(res1=res; res1 != NULL; res1 = res1->ai_next) {
2615         if (cmp_sockaddr((sockaddr_union *)res1->ai_addr, (sockaddr_union *)addr, 1) == 0) {
2616             freeaddrinfo(res);
2617             amfree(canonname);
2618             return 0;
2619         }
2620     }
2621
2622     g_debug("%s doesn't resolve to %s",
2623             hostname, str_sockaddr((sockaddr_union *)addr));
2624     *errstr = newvstrallocf(*errstr,
2625                            "%s doesn't resolve to %s",
2626                            hostname, str_sockaddr((sockaddr_union *)addr));
2627 error:
2628     if (res) freeaddrinfo(res);
2629     amfree(canonname);
2630     return -1;
2631 }
2632
2633 in_port_t
2634 find_port_for_service(
2635     char *service,
2636     char *proto)
2637 {
2638     in_port_t  port;
2639     char      *s;
2640     int        all_numeric = 1;
2641
2642     for (s=service; *s != '\0'; s++) {
2643         if (!isdigit((int)*s)) {
2644             all_numeric = 0;
2645         }
2646     }
2647
2648     if (all_numeric == 1) {
2649         port = atoi(service);
2650     } else {
2651         struct servent *sp;
2652
2653         if ((sp = getservbyname(service, proto)) == NULL) {
2654             port = 0;
2655         } else {
2656             port = (in_port_t)(ntohs((in_port_t)sp->s_port));
2657         }
2658     }
2659
2660     return port;
2661 }
2662
2663 char *
2664 sec_get_authenticated_peer_name_localhost(
2665     security_handle_t *hdl G_GNUC_UNUSED)
2666 {
2667     return "localhost";
2668 }
2669
2670 char *
2671 sec_get_authenticated_peer_name_hostname(
2672     security_handle_t *hdl)
2673 {
2674     char *hostname = ((struct sec_handle *)hdl)->hostname;
2675     if (!hostname)
2676         hostname = "";
2677     return hostname;
2678 }