summaryrefslogtreecommitdiff
path: root/src/util/virportallocator.c
blob: 87835a3ed764198f5cf0a99b0a71d5e17410fab7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
/*
 * virportallocator.c: Allocate & track TCP port allocations
 *
 * Copyright (C) 2013-2014 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 */

#include <config.h>

#include <unistd.h>

#include "virsocket.h"
#include "virbitmap.h"
#include "virportallocator.h"
#include "virthread.h"
#include "virerror.h"
#include "virutil.h"

#define VIR_FROM_THIS VIR_FROM_NONE

#define VIR_PORT_ALLOCATOR_NUM_PORTS 65536

typedef struct _virPortAllocator virPortAllocator;
struct _virPortAllocator {
    virObjectLockable parent;
    virBitmap *bitmap;
};

struct _virPortAllocatorRange {
    char *name;

    unsigned short start;
    unsigned short end;
};

static virClass *virPortAllocatorClass;
static virPortAllocator *virPortAllocatorInstance;

static void
virPortAllocatorDispose(void *obj)
{
    virPortAllocator *pa = obj;

    virBitmapFree(pa->bitmap);
}

static virPortAllocator *
virPortAllocatorNew(void)
{
    virPortAllocator *pa;

    if (!(pa = virObjectLockableNew(virPortAllocatorClass)))
        return NULL;

    pa->bitmap = virBitmapNew(VIR_PORT_ALLOCATOR_NUM_PORTS);

    return pa;
}

static int
virPortAllocatorOnceInit(void)
{
    if (!VIR_CLASS_NEW(virPortAllocator, virClassForObjectLockable()))
        return -1;

    if (!(virPortAllocatorInstance = virPortAllocatorNew()))
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(virPortAllocator);

virPortAllocatorRange *
virPortAllocatorRangeNew(const char *name,
                         unsigned short start,
                         unsigned short end)
{
    virPortAllocatorRange *range;

    if (start >= end) {
        virReportInvalidArg(start, "start port %d must be less than end port %d",
                            start, end);
        return NULL;
    }

    range = g_new0(virPortAllocatorRange, 1);

    range->start = start;
    range->end = end;
    range->name = g_strdup(name);

    return range;
}

void
virPortAllocatorRangeFree(virPortAllocatorRange *range)
{
    if (!range)
        return;

    g_free(range->name);
    g_free(range);
}

static int
virPortAllocatorBindToPort(bool *used,
                           unsigned short port,
                           int family)
{
    struct sockaddr_in6 addr6 = {
        .sin6_family = AF_INET6,
        .sin6_port = htons(port),
        .sin6_addr = in6addr_any
    };
    struct sockaddr_in addr4 = {
        .sin_family = AF_INET,
        .sin_port = htons(port),
        .sin_addr.s_addr = htonl(INADDR_ANY)
    };
    struct sockaddr* addr;
    size_t addrlen;
    int v6only = 1;
    int ret = -1;
    int fd = -1;
    bool ipv6 = false;

    if (family == AF_INET6) {
        addr = (struct sockaddr*)&addr6;
        addrlen = sizeof(addr6);
        ipv6 = true;
    } else if (family == AF_INET) {
        addr = (struct sockaddr*)&addr4;
        addrlen = sizeof(addr4);
    } else {
        virReportError(VIR_ERR_INTERNAL_ERROR, _("Unknown family %d"), family);
        return -1;
    }

    *used = false;

    fd = socket(family, SOCK_STREAM, 0);
    if (fd < 0) {
        if (errno == EAFNOSUPPORT)
            return 0;
        virReportSystemError(errno, "%s", _("Unable to open test socket"));
        goto cleanup;
    }

    if (virSetSockReuseAddr(fd, true) < 0)
        goto cleanup;

    if (ipv6 && setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&v6only,
                           sizeof(v6only)) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to set IPV6_V6ONLY flag"));
        goto cleanup;
    }

    if (bind(fd, addr, addrlen) < 0) {
        if (errno == EADDRINUSE) {
            *used = true;
            ret = 0;
        } else {
            virReportSystemError(errno, _("Unable to bind to port %d"), port);
        }
        goto cleanup;
    }

    ret = 0;
 cleanup:
    if (fd != -1)
        closesocket(fd);
    return ret;
}

static virPortAllocator *
virPortAllocatorGet(void)
{
    if (virPortAllocatorInitialize() < 0)
        return NULL;

    return virPortAllocatorInstance;
}

int
virPortAllocatorAcquire(const virPortAllocatorRange *range,
                        unsigned short *port)
{
    size_t i;
    virPortAllocator *pa = virPortAllocatorGet();

    *port = 0;

    if (!pa)
        return -1;

    VIR_WITH_OBJECT_LOCK_GUARD(pa) {
        for (i = range->start; i <= range->end; i++) {
            bool used = false, v6used = false;

            if (virBitmapIsBitSet(pa->bitmap, i))
                continue;

            if (virPortAllocatorBindToPort(&v6used, i, AF_INET6) < 0 ||
                virPortAllocatorBindToPort(&used, i, AF_INET) < 0)
                return -1;

            if (!used && !v6used) {
                /* Add port to bitmap of reserved ports */
                if (virBitmapSetBit(pa->bitmap, i) < 0) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Failed to reserve port %zu"), i);
                    return -1;
                }
                *port = i;
                return 0;
            }
        }
    }

    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Unable to find an unused port in range '%s' (%d-%d)"),
                   range->name, range->start, range->end);
    return -1;
}

int
virPortAllocatorRelease(unsigned short port)
{
    virPortAllocator *pa = virPortAllocatorGet();

    if (!pa)
        return -1;

    if (!port)
        return 0;

    VIR_WITH_OBJECT_LOCK_GUARD(pa) {
        ignore_value(virBitmapClearBit(pa->bitmap, port));
    }

    return 0;
}

int
virPortAllocatorSetUsed(unsigned short port)
{
    virPortAllocator *pa = virPortAllocatorGet();

    if (!pa)
        return -1;

    if (!port)
        return 0;

    VIR_WITH_OBJECT_LOCK_GUARD(pa) {
        if (virBitmapIsBitSet(pa->bitmap, port) ||
            virBitmapSetBit(pa->bitmap, port) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to reserve port %d"), port);
            return -1;
        }
    }

    return 0;
}