1/*-
2 * Copyright (c) 1999 Brian Somers <brian@Awfulhak.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24 * SUCH DAMAGE.
25 *
26 * $FreeBSD: src/usr.sbin/ppp/udp.c,v 1.20.26.1 2010/12/21 17:10:29 kensmith Exp $
27 */
28
29#include <sys/types.h>
30#include <sys/socket.h>
31#include <netinet/in.h>
32#include <arpa/inet.h>
33#include <netdb.h>
34
35#include <errno.h>
36#include <stdio.h>
37#include <stdlib.h>
38#include <string.h>
39#include <sysexits.h>
40#include <sys/stat.h>
41#include <sys/uio.h>
42#include <termios.h>
43#include <unistd.h>
44
45#include "layer.h"
46#include "defs.h"
47#include "mbuf.h"
48#include "log.h"
49#include "timer.h"
50#include "lqr.h"
51#include "hdlc.h"
52#include "throughput.h"
53#include "fsm.h"
54#include "lcp.h"
55#include "ccp.h"
56#include "link.h"
57#include "async.h"
58#include "descriptor.h"
59#include "physical.h"
60#include "main.h"
61#include "udp.h"
62
63
64#define UDP_CONNECTED		1
65#define UDP_UNCONNECTED		2
66#define UDP_MAYBEUNCONNECTED	3
67
68struct udpdevice {
69  struct device dev;		/* What struct physical knows about */
70  struct sockaddr_in sock;	/* peer address */
71  unsigned connected : 2;	/* Have we connect()d ? */
72};
73
74#define device2udp(d) ((d)->type == UDP_DEVICE ? (struct udpdevice *)d : NULL)
75
76unsigned
77udp_DeviceSize(void)
78{
79  return sizeof(struct udpdevice);
80}
81
82static ssize_t
83udp_Sendto(struct physical *p, const void *v, size_t n)
84{
85  struct udpdevice *dev = device2udp(p->handler);
86  int ret;
87
88  switch (dev->connected) {
89    case UDP_CONNECTED:
90      ret = write(p->fd, v, n);
91      break;
92
93    case UDP_UNCONNECTED:
94    default:
95      ret = sendto(p->fd, v, n, 0, (struct sockaddr *)&dev->sock,
96                   sizeof dev->sock);
97      break;
98  }
99  if (dev->connected == UDP_MAYBEUNCONNECTED) {
100    if (ret == -1 && errno == EISCONN) {
101      dev->connected = UDP_CONNECTED;
102      ret = write(p->fd, v, n);
103    } else
104      dev->connected = UDP_UNCONNECTED;
105  }
106
107  return ret;
108}
109
110static ssize_t
111udp_Recvfrom(struct physical *p, void *v, size_t n)
112{
113  struct udpdevice *dev = device2udp(p->handler);
114  int sz, ret;
115
116  if (dev->connected == UDP_CONNECTED)
117    return read(p->fd, v, n);
118
119  sz = sizeof dev->sock;
120  ret = recvfrom(p->fd, v, n, 0, (struct sockaddr *)&dev->sock, &sz);
121
122  if (*p->name.full == '\0') {
123    snprintf(p->name.full, sizeof p->name.full, "%s:%d/udp",
124             inet_ntoa(dev->sock.sin_addr), ntohs(dev->sock.sin_port));
125    p->name.base = p->name.full;
126  }
127
128  return ret;
129}
130
131static void
132udp_Free(struct physical *p)
133{
134  struct udpdevice *dev = device2udp(p->handler);
135
136  free(dev);
137}
138
139static void
140udp_device2iov(struct device *d, struct iovec *iov, int *niov,
141               int maxiov __unused, int *auxfd __unused, int *nauxfd __unused)
142{
143  int sz = physical_MaxDeviceSize();
144
145  iov[*niov].iov_base = realloc(d, sz);
146  if (iov[*niov].iov_base == NULL) {
147    log_Printf(LogALERT, "Failed to allocate memory: %d\n", sz);
148    AbortProgram(EX_OSERR);
149  }
150  iov[*niov].iov_len = sz;
151  (*niov)++;
152}
153
154static const struct device baseudpdevice = {
155  UDP_DEVICE,
156  "udp",
157  0,
158  { CD_NOTREQUIRED, 0 },
159  NULL,
160  NULL,
161  NULL,
162  NULL,
163  NULL,
164  NULL,
165  NULL,
166  udp_Free,
167  udp_Recvfrom,
168  udp_Sendto,
169  udp_device2iov,
170  NULL,
171  NULL,
172  NULL
173};
174
175struct device *
176udp_iov2device(int type, struct physical *p, struct iovec *iov, int *niov,
177               int maxiov __unused, int *auxfd __unused, int *nauxfd __unused)
178{
179  if (type == UDP_DEVICE) {
180    struct udpdevice *dev = (struct udpdevice *)iov[(*niov)++].iov_base;
181
182    dev = realloc(dev, sizeof *dev);	/* Reduce to the correct size */
183    if (dev == NULL) {
184      log_Printf(LogALERT, "Failed to allocate memory: %d\n",
185                 (int)(sizeof *dev));
186      AbortProgram(EX_OSERR);
187    }
188
189    /* Refresh function pointers etc */
190    memcpy(&dev->dev, &baseudpdevice, sizeof dev->dev);
191
192    physical_SetupStack(p, dev->dev.name, PHYSICAL_FORCE_SYNC);
193    return &dev->dev;
194  }
195
196  return NULL;
197}
198
199static struct udpdevice *
200udp_CreateDevice(struct physical *p, char *host, char *port)
201{
202  struct udpdevice *dev;
203  struct servent *sp;
204
205  if ((dev = malloc(sizeof *dev)) == NULL) {
206    log_Printf(LogWARN, "%s: Cannot allocate a udp device: %s\n",
207               p->link.name, strerror(errno));
208    return NULL;
209  }
210
211  dev->sock.sin_family = AF_INET;
212  dev->sock.sin_addr = GetIpAddr(host);
213  if (dev->sock.sin_addr.s_addr == INADDR_NONE) {
214    log_Printf(LogWARN, "%s: %s: unknown host\n", p->link.name, host);
215    free(dev);
216    return NULL;
217  }
218  dev->sock.sin_port = htons(atoi(port));
219  if (dev->sock.sin_port == 0) {
220    sp = getservbyname(port, "udp");
221    if (sp)
222      dev->sock.sin_port = sp->s_port;
223    else {
224      log_Printf(LogWARN, "%s: %s: unknown service\n", p->link.name, port);
225      free(dev);
226      return NULL;
227    }
228  }
229
230  log_Printf(LogPHASE, "%s: Connecting to %s:%s/udp\n", p->link.name,
231             host, port);
232
233  p->fd = socket(PF_INET, SOCK_DGRAM, 0);
234  if (p->fd >= 0) {
235    log_Printf(LogDEBUG, "%s: Opened udp socket %s\n", p->link.name,
236               p->name.full);
237    if (connect(p->fd, (struct sockaddr *)&dev->sock, sizeof dev->sock) == 0) {
238      dev->connected = UDP_CONNECTED;
239      return dev;
240    } else
241      log_Printf(LogWARN, "%s: connect: %s\n", p->name.full, strerror(errno));
242  } else
243    log_Printf(LogWARN, "%s: socket: %s\n", p->name.full, strerror(errno));
244
245  close(p->fd);
246  p->fd = -1;
247  free(dev);
248
249  return NULL;
250}
251
252struct device *
253udp_Create(struct physical *p)
254{
255  char *cp, *host, *port, *svc;
256  struct udpdevice *dev;
257
258  dev = NULL;
259  if (p->fd < 0) {
260    if ((cp = strchr(p->name.full, ':')) != NULL && !strchr(cp + 1, ':')) {
261      *cp = '\0';
262      host = p->name.full;
263      port = cp + 1;
264      svc = strchr(port, '/');
265      if (svc && strcasecmp(svc, "/udp")) {
266        *cp = ':';
267        return NULL;
268      }
269      if (svc) {
270        p->fd--;     /* We own the device but maybe can't use it - change fd */
271        *svc = '\0';
272      }
273
274      if (*host && *port)
275        dev = udp_CreateDevice(p, host, port);
276
277      *cp = ':';
278      if (svc)
279        *svc = '/';
280    }
281  } else {
282    /* See if we're a connected udp socket */
283    struct stat st;
284
285    if (fstat(p->fd, &st) != -1 && (st.st_mode & S_IFSOCK)) {
286      int type, sz;
287
288      sz = sizeof type;
289      if (getsockopt(p->fd, SOL_SOCKET, SO_TYPE, &type, &sz) == -1) {
290        log_Printf(LogPHASE, "%s: Link is a closed socket !\n", p->link.name);
291        close(p->fd);
292        p->fd = -1;
293        return NULL;
294      }
295
296      if (sz == sizeof type && type == SOCK_DGRAM) {
297        struct sockaddr_in sock;
298        struct sockaddr *sockp = (struct sockaddr *)&sock;
299
300        if ((dev = malloc(sizeof *dev)) == NULL) {
301          log_Printf(LogWARN, "%s: Cannot allocate a udp device: %s\n",
302                     p->link.name, strerror(errno));
303          return NULL;
304        }
305
306        if (getpeername(p->fd, sockp, &sz) == 0) {
307          log_Printf(LogPHASE, "%s: Link is a connected udp socket\n",
308                     p->link.name);
309          dev->connected = UDP_CONNECTED;
310	} else {
311          log_Printf(LogPHASE, "%s: Link is a disconnected udp socket\n",
312                     p->link.name);
313
314          dev->connected = UDP_MAYBEUNCONNECTED;
315
316          if (p->link.lcp.cfg.openmode != OPEN_PASSIVE) {
317            log_Printf(LogPHASE, "%s:   Changing openmode to PASSIVE\n",
318                       p->link.name);
319            p->link.lcp.cfg.openmode = OPEN_PASSIVE;
320          }
321        }
322      }
323    }
324  }
325
326  if (dev) {
327    memcpy(&dev->dev, &baseudpdevice, sizeof dev->dev);
328    physical_SetupStack(p, dev->dev.name, PHYSICAL_FORCE_SYNC);
329    if (p->cfg.cd.necessity != CD_DEFAULT)
330      log_Printf(LogWARN, "Carrier settings ignored\n");
331    return &dev->dev;
332  }
333
334  return NULL;
335}
336