Merge from vendor branch CVS:
[dragonfly.git] / libexec / ftp-proxy / util.c
1 /*      $OpenBSD: util.c,v 1.18 2004/01/22 16:10:30 beck Exp $ */
2 /*      $DragonFly: src/libexec/ftp-proxy/util.c,v 1.2 2005/02/24 15:38:09 joerg Exp $ */
3
4 /*
5  * Copyright (c) 1996-2001
6  *      Obtuse Systems Corporation.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the Obtuse Systems nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE OBTUSE SYSTEMS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL OBTUSE
24  * SYSTEMS CORPORATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
25  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
26  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
27  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
29  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
31  * OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  */
34
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <sys/ioctl.h>
38 #include <sys/file.h>
39 #include <netinet/in.h>
40 #include <netinet/in_systm.h>
41 #include <net/if.h>
42 #include <net/pf/pfvar.h>
43
44 #include <arpa/inet.h>
45
46 #include <ctype.h>
47 #include <errno.h>
48 #include <netdb.h>
49 #include <signal.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <stdarg.h>
54 #include <sysexits.h>
55 #include <syslog.h>
56 #include <unistd.h>
57
58 #include "util.h"
59
60 extern int ReverseMode;
61
62 int Debug_Level;
63 int Use_Rdns;
64 in_addr_t Bind_Addr = INADDR_NONE;
65
66 void            debuglog(int debug_level, const char *fmt, ...);
67
68 void
69 debuglog(int debug_level, const char *fmt, ...)
70 {
71         va_list ap;
72         va_start(ap, fmt);
73
74         if (Debug_Level >= debug_level)
75                 vsyslog(LOG_DEBUG, fmt, ap);
76         va_end(ap);
77 }
78
79 int
80 get_proxy_env(int connected_fd, struct sockaddr_in *real_server_sa_ptr,
81     struct sockaddr_in *client_sa_ptr, struct sockaddr_in *proxy_sa_ptr)
82 {
83         struct pfioc_natlook natlook;
84         socklen_t slen;
85         int fd;
86
87         slen = sizeof(*proxy_sa_ptr);
88         if (getsockname(connected_fd, (struct sockaddr *)proxy_sa_ptr,
89             &slen) != 0) {
90                 syslog(LOG_ERR, "getsockname() failed (%m)");
91                 return(-1);
92         }
93         slen = sizeof(*client_sa_ptr);
94         if (getpeername(connected_fd, (struct sockaddr *)client_sa_ptr,
95             &slen) != 0) {
96                 syslog(LOG_ERR, "getpeername() failed (%m)");
97                 return(-1);
98         }
99
100         if (ReverseMode)
101                 return(0);
102
103         /*
104          * Build up the pf natlook structure.
105          * Just for IPv4 right now
106          */
107         memset((void *)&natlook, 0, sizeof(natlook));
108         natlook.af = AF_INET;
109         natlook.saddr.addr32[0] = client_sa_ptr->sin_addr.s_addr;
110         natlook.daddr.addr32[0] = proxy_sa_ptr->sin_addr.s_addr;
111         natlook.proto = IPPROTO_TCP;
112         natlook.sport = client_sa_ptr->sin_port;
113         natlook.dport = proxy_sa_ptr->sin_port;
114         natlook.direction = PF_OUT;
115
116         /*
117          * Open the pf device and lookup the mapping pair to find
118          * the original address we were supposed to connect to.
119          */
120         fd = open("/dev/pf", O_RDWR);
121         if (fd == -1) {
122                 syslog(LOG_ERR, "cannot open /dev/pf (%m)");
123                 exit(EX_UNAVAILABLE);
124         }
125
126         if (ioctl(fd, DIOCNATLOOK, &natlook) == -1) {
127                 syslog(LOG_INFO,
128                     "pf nat lookup failed %s:%hu (%m)",
129                     inet_ntoa(client_sa_ptr->sin_addr),
130                     ntohs(client_sa_ptr->sin_port));
131                 close(fd);
132                 return(-1);
133         }
134         close(fd);
135
136         /*
137          * Now jam the original address and port back into the into
138          * destination sockaddr_in for the proxy to deal with.
139          */
140         memset((void *)real_server_sa_ptr, 0, sizeof(struct sockaddr_in));
141         real_server_sa_ptr->sin_port = natlook.rdport;
142         real_server_sa_ptr->sin_addr.s_addr = natlook.rdaddr.addr32[0];
143         real_server_sa_ptr->sin_len = sizeof(struct sockaddr_in);
144         real_server_sa_ptr->sin_family = AF_INET;
145         return(0);
146 }
147
148
149 /*
150  * Transfer one unit of data across a pair of sockets
151  *
152  * A unit of data is as much as we get with a single read(2) call.
153  */
154 int
155 xfer_data(const char *what_read,int from_fd, int to_fd,
156           struct in_addr from __unused, struct in_addr to __unused)
157 {
158         int rlen, offset, xerrno, mark, flags = 0;
159         char tbuf[4096];
160
161         /*
162          * Are we at the OOB mark?
163          */
164         if (ioctl(from_fd, SIOCATMARK, &mark) < 0) {
165                 xerrno = errno;
166                 syslog(LOG_ERR, "cannot ioctl(SIOCATMARK) socket from %s (%m)",
167                     what_read);
168                 errno = xerrno;
169                 return(-1);
170         }
171         if (mark)
172                 flags = MSG_OOB;        /* Yes - at the OOB mark */
173
174 snarf:
175         rlen = recv(from_fd, tbuf, sizeof(tbuf), flags);
176         if (rlen == -1 && flags == MSG_OOB && errno == EINVAL) {
177                 /* OOB didn't work */
178                 flags = 0;
179                 rlen = recv(from_fd, tbuf, sizeof(tbuf), flags);
180         }
181         if (rlen == 0) {
182                 debuglog(3, "EOF on read socket");
183                 return(0);
184         } else if (rlen == -1) {
185                 if (errno == EAGAIN || errno == EINTR)
186                         goto snarf;
187                 xerrno = errno;
188                 syslog(LOG_ERR, "xfer_data (%s): failed (%m) with flags 0%o",
189                     what_read, flags);
190                 errno = xerrno;
191                 return(-1);
192         } else {
193                 offset = 0;
194                 debuglog(3, "got %d bytes from socket", rlen);
195
196                 while (offset < rlen) {
197                         int wlen;
198                 fling:
199                         wlen = send(to_fd, &tbuf[offset], rlen - offset,
200                             flags);
201                         if (wlen == 0) {
202                                 debuglog(3, "zero-length write");
203                                 goto fling;
204                         } else if (wlen == -1) {
205                                 if (errno == EAGAIN || errno == EINTR)
206                                         goto fling;
207                                 xerrno = errno;
208                                 syslog(LOG_INFO, "write failed (%m)");
209                                 errno = xerrno;
210                                 return(-1);
211                         } else {
212                                 debuglog(3, "wrote %d bytes to socket",wlen);
213                                 offset += wlen;
214                         }
215                 }
216                 return(offset);
217         }
218 }
219
220 /*
221  * get_backchannel_socket gets us a socket bound somewhere in a
222  * particular range of ports
223  */
224 int
225 get_backchannel_socket(int type, int min_port, int max_port, int start_port,
226     int direction, struct sockaddr_in *sap)
227 {
228         int count;
229
230         /*
231          * Make sure that direction is 'defined' and that min_port is not
232          * greater than max_port.
233          */
234         if (direction != -1)
235                 direction = 1;
236
237         /* by default we go up by one port until we find one */
238         if (min_port > max_port) {
239                 errno = EINVAL;
240                 return(-1);
241         }
242
243         count = 1 + max_port - min_port;
244
245         /*
246          * Pick a port we can bind to from within the range we want.
247          * If the caller specifies -1 as the starting port number then
248          * we pick one somewhere in the range to try.
249          * This is an optimization intended to speedup port selection and
250          * has NOTHING to do with security.
251          */
252         if (start_port == -1)
253                 start_port = (arc4random() % count) + min_port;
254
255         if (start_port < min_port || start_port > max_port) {
256                 errno = EINVAL;
257                 return(-1);
258         }
259
260         while (count-- > 0) {
261                 struct sockaddr_in sa;
262                 int one, fd;
263
264                 fd = socket(AF_INET, type, 0);
265
266                 bzero(&sa, sizeof sa);
267                 sa.sin_family = AF_INET;
268                 if (Bind_Addr == INADDR_NONE)
269                         if (sap == NULL)
270                                 sa.sin_addr.s_addr = INADDR_ANY;
271                         else
272                                 sa.sin_addr.s_addr = sap->sin_addr.s_addr;
273                 else
274                         sa.sin_addr.s_addr = Bind_Addr;
275
276                 /*
277                  * Indicate that we want to reuse a port if it happens that the
278                  * port in question was a listen port recently.
279                  */
280                 one = 1;
281                 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one,
282                     sizeof(one))  == -1)
283                         return(-1);
284
285                 sa.sin_port = htons(start_port);
286
287                 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) == 0) {
288                         if (sap != NULL)
289                                 *sap = sa;
290                         return(fd);
291                 }
292
293                 if (errno != EADDRINUSE)
294                         return(-1);
295
296                 /* if it's in use, try the next port */
297                 close(fd);
298
299                 start_port += direction;
300                 if (start_port < min_port)
301                         start_port = max_port;
302                 else if (start_port > max_port)
303                         start_port = min_port;
304         }
305         errno = EAGAIN;
306         return(-1);
307 }