Merge from vendor branch BINUTILS:
[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.1 2004/09/21 21:25:28 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/param.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 int Debug_Level;
61 int Use_Rdns;
62 in_addr_t Bind_Addr = INADDR_NONE;
63
64 void            debuglog(int debug_level, const char *fmt, ...);
65
66 void
67 debuglog(int debug_level, const char *fmt, ...)
68 {
69         va_list ap;
70         va_start(ap, fmt);
71
72         if (Debug_Level >= debug_level)
73                 vsyslog(LOG_DEBUG, fmt, ap);
74         va_end(ap);
75 }
76
77 int
78 get_proxy_env(int connected_fd, struct sockaddr_in *real_server_sa_ptr,
79     struct sockaddr_in *client_sa_ptr)
80 {
81         struct pfioc_natlook natlook;
82         socklen_t slen;
83         int fd;
84
85         slen = sizeof(*real_server_sa_ptr);
86         if (getsockname(connected_fd, (struct sockaddr *)real_server_sa_ptr,
87             &slen) != 0) {
88                 syslog(LOG_ERR, "getsockname() failed (%m)");
89                 return(-1);
90         }
91         slen = sizeof(*client_sa_ptr);
92         if (getpeername(connected_fd, (struct sockaddr *)client_sa_ptr,
93             &slen) != 0) {
94                 syslog(LOG_ERR, "getpeername() failed (%m)");
95                 return(-1);
96         }
97
98         /*
99          * Build up the pf natlook structure.
100          * Just for IPv4 right now
101          */
102         memset((void *)&natlook, 0, sizeof(natlook));
103         natlook.af = AF_INET;
104         natlook.saddr.addr32[0] = client_sa_ptr->sin_addr.s_addr;
105         natlook.daddr.addr32[0] = real_server_sa_ptr->sin_addr.s_addr;
106         natlook.proto = IPPROTO_TCP;
107         natlook.sport = client_sa_ptr->sin_port;
108         natlook.dport = real_server_sa_ptr->sin_port;
109         natlook.direction = PF_OUT;
110
111         /*
112          * Open the pf device and lookup the mapping pair to find
113          * the original address we were supposed to connect to.
114          */
115         fd = open("/dev/pf", O_RDWR);
116         if (fd == -1) {
117                 syslog(LOG_ERR, "cannot open /dev/pf (%m)");
118                 exit(EX_UNAVAILABLE);
119         }
120
121         if (ioctl(fd, DIOCNATLOOK, &natlook) == -1) {
122                 syslog(LOG_INFO,
123                     "pf nat lookup failed %s:%hu (%m)",
124                     inet_ntoa(client_sa_ptr->sin_addr),
125                     ntohs(client_sa_ptr->sin_port));
126                 close(fd);
127                 return(-1);
128         }
129         close(fd);
130
131         /*
132          * Now jam the original address and port back into the into
133          * destination sockaddr_in for the proxy to deal with.
134          */
135         memset((void *)real_server_sa_ptr, 0, sizeof(struct sockaddr_in));
136         real_server_sa_ptr->sin_port = natlook.rdport;
137         real_server_sa_ptr->sin_addr.s_addr = natlook.rdaddr.addr32[0];
138         real_server_sa_ptr->sin_len = sizeof(struct sockaddr_in);
139         real_server_sa_ptr->sin_family = AF_INET;
140         return(0);
141 }
142
143
144 /*
145  * Transfer one unit of data across a pair of sockets
146  *
147  * A unit of data is as much as we get with a single read(2) call.
148  */
149 int
150 xfer_data(const char *what_read,int from_fd, int to_fd)
151 {
152         int rlen, offset, xerrno, mark, flags = 0;
153         char tbuf[4096];
154
155         /*
156          * Are we at the OOB mark?
157          */
158         if (ioctl(from_fd, SIOCATMARK, &mark) < 0) {
159                 xerrno = errno;
160                 syslog(LOG_ERR, "cannot ioctl(SIOCATMARK) socket from %s (%m)",
161                     what_read);
162                 errno = xerrno;
163                 return(-1);
164         }
165         if (mark)
166                 flags = MSG_OOB;        /* Yes - at the OOB mark */
167
168 snarf:
169         rlen = recv(from_fd, tbuf, sizeof(tbuf), flags);
170         if (rlen == -1 && flags == MSG_OOB && errno == EINVAL) {
171                 /* OOB didn't work */
172                 flags = 0;
173                 rlen = recv(from_fd, tbuf, sizeof(tbuf), flags);
174         }
175         if (rlen == 0) {
176                 debuglog(3, "EOF on read socket");
177                 return(0);
178         } else if (rlen == -1) {
179                 if (errno == EAGAIN || errno == EINTR)
180                         goto snarf;
181                 xerrno = errno;
182                 syslog(LOG_ERR, "xfer_data (%s): failed (%m) with flags 0%o",
183                     what_read, flags);
184                 errno = xerrno;
185                 return(-1);
186         } else {
187                 offset = 0;
188                 debuglog(3, "got %d bytes from socket", rlen);
189
190                 while (offset < rlen) {
191                         int wlen;
192                 fling:
193                         wlen = send(to_fd, &tbuf[offset], rlen - offset,
194                             flags);
195                         if (wlen == 0) {
196                                 debuglog(3, "zero-length write");
197                                 goto fling;
198                         } else if (wlen == -1) {
199                                 if (errno == EAGAIN || errno == EINTR)
200                                         goto fling;
201                                 xerrno = errno;
202                                 syslog(LOG_INFO, "write failed (%m)");
203                                 errno = xerrno;
204                                 return(-1);
205                         } else {
206                                 debuglog(3, "wrote %d bytes to socket",wlen);
207                                 offset += wlen;
208                         }
209                 }
210                 return(offset);
211         }
212 }
213
214 /*
215  * get_backchannel_socket gets us a socket bound somewhere in a
216  * particular range of ports
217  */
218 int
219 get_backchannel_socket(int type, int min_port, int max_port, int start_port,
220     int direction, struct sockaddr_in *sap)
221 {
222         int count;
223
224         /*
225          * Make sure that direction is 'defined' and that min_port is not
226          * greater than max_port.
227          */
228         if (direction != -1)
229                 direction = 1;
230
231         /* by default we go up by one port until we find one */
232         if (min_port > max_port) {
233                 errno = EINVAL;
234                 return(-1);
235         }
236
237         count = 1 + max_port - min_port;
238
239         /*
240          * Pick a port we can bind to from within the range we want.
241          * If the caller specifies -1 as the starting port number then
242          * we pick one somewhere in the range to try.
243          * This is an optimization intended to speedup port selection and
244          * has NOTHING to do with security.
245          */
246         if (start_port == -1)
247                 start_port = (arc4random() % count) + min_port;
248
249         if (start_port < min_port || start_port > max_port) {
250                 errno = EINVAL;
251                 return(-1);
252         }
253
254         while (count-- > 0) {
255                 struct sockaddr_in sa;
256                 int one, fd;
257
258                 fd = socket(AF_INET, type, 0);
259
260                 bzero(&sa, sizeof sa);
261                 sa.sin_family = AF_INET;
262                 if (Bind_Addr == INADDR_NONE)
263                         if (sap == NULL)
264                                 sa.sin_addr.s_addr = INADDR_ANY;
265                         else
266                                 sa.sin_addr.s_addr = sap->sin_addr.s_addr;
267                 else
268                         sa.sin_addr.s_addr = Bind_Addr;
269
270                 /*
271                  * Indicate that we want to reuse a port if it happens that the
272                  * port in question was a listen port recently.
273                  */
274                 one = 1;
275                 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one,
276                     sizeof(one))  == -1)
277                         return(-1);
278
279                 sa.sin_port = htons(start_port);
280
281                 if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) == 0) {
282                         if (sap != NULL)
283                                 *sap = sa;
284                         return(fd);
285                 }
286
287                 if (errno != EADDRINUSE)
288                         return(-1);
289
290                 /* if it's in use, try the next port */
291                 close(fd);
292
293                 start_port += direction;
294                 if (start_port < min_port)
295                         start_port = max_port;
296                 else if (start_port > max_port)
297                         start_port = min_port;
298         }
299         errno = EAGAIN;
300         return(-1);
301 }