blob: 47778e746ac24c54bb403a1cf97f8bb7eb1500b8 [file] [log] [blame]
Jonathan Santos03fd8d02011-05-25 13:54:02 -04001/* OpenBSC sokcet code, taken from Abis input driver for ip.access */
2
3/* (C) 2009 by Harald Welte <laforge@gnumonks.org>
4 * (C) 2010 by Holger Hans Peter Freyther
5 * (C) 2010 by On-Waves
6 *
7 * All Rights Reserved
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
18 *
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 *
22 */
23
24#include <stdio.h>
25#include <unistd.h>
26#include <stdlib.h>
27#include <errno.h>
28#include <string.h>
29#include <time.h>
30#include <sys/fcntl.h>
31#include <sys/types.h>
32#include <sys/socket.h>
33#include <sys/ioctl.h>
34#include <arpa/inet.h>
35
36#include <osmocore/select.h>
37#include <osmocore/tlv.h>
38#include <osmocore/msgb.h>
39#include <openbsc/debug.h>
40#include <openbsc/gsm_data.h>
41#include <osmocore/talloc.h>
42
43int make_sock(struct bsc_fd *bfd, int proto, u_int32_t ip, u_int16_t port,
44 int (*cb)(struct bsc_fd *fd, unsigned int what))
45{
46 struct sockaddr_in addr;
47 int ret, on = 1;
48 int type = SOCK_STREAM;
49
50 switch (proto) {
51 case IPPROTO_TCP:
52 type = SOCK_STREAM;
53 break;
54 case IPPROTO_UDP:
55 type = SOCK_DGRAM;
56 break;
57 case IPPROTO_GRE:
58 type = SOCK_RAW;
59 break;
60 default:
61 return -EINVAL;
62 }
63
64 bfd->fd = socket(AF_INET, type, proto);
65 bfd->cb = cb;
66 bfd->when = BSC_FD_READ;
67 //bfd->data = line;
68
69 if (bfd->fd < 0) {
70 LOGP(DINP, LOGL_ERROR, "could not create socket.\n");
71 return -EIO;
72 }
73
74 memset(&addr, 0, sizeof(addr));
75 addr.sin_family = AF_INET;
76 addr.sin_port = htons(port);
77 if (ip)
78 addr.sin_addr.s_addr = htonl(ip);
79 else
80 addr.sin_addr.s_addr = INADDR_ANY;
81
82 setsockopt(bfd->fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
83
84 ret = bind(bfd->fd, (struct sockaddr *) &addr, sizeof(addr));
85 if (ret < 0) {
86 LOGP(DINP, LOGL_ERROR, "could not bind socket %s\n",
87 strerror(errno));
88 close(bfd->fd);
89 return -EIO;
90 }
91
92 if (proto == IPPROTO_TCP) {
93 ret = listen(bfd->fd, 1);
94 if (ret < 0) {
95 perror("listen");
96 close(bfd->fd);
97 return ret;
98 }
99 }
100
101 ret = bsc_register_fd(bfd);
102 if (ret < 0) {
103 perror("register_listen_fd");
104 close(bfd->fd);
105 return ret;
106 }
107 return 0;
108}