zhangmeng
2024-04-22 16935f4aebffdd1b6580b844391a0aa0f4f3012b
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
//
// Copyright 2021 Staysail Systems, Inc. <info@staysail.tech>
// Copyright 2018 Capitar IT Group BV <info@capitar.com>
//
// This software is supplied under the terms of the MIT License, a
// copy of which should be located in the distribution where this
// file was obtained (LICENSE.txt).  A copy of the license may also be
// found online at https://opensource.org/licenses/MIT.
//
 
#ifdef _WIN32
 
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
 
#include <io.h>
#include <windows.h>
#include <winsock2.h>
#else
#include <fcntl.h>
#include <poll.h>
#include <stdint.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#endif
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
 
#define TEST_NO_MAIN
#include "nuts.h"
 
void
nuts_scratch_addr(const char *scheme, size_t sz, char *addr)
{
    if ((strcmp(scheme, "inproc") == 0) ||
        (strcmp(scheme, "abstract") == 0)) {
        (void) snprintf(addr, sz, "%s://nuts%04x%04x%04x%04x", scheme,
            nng_random(), nng_random(), nng_random(), nng_random());
        return;
    }
 
    if ((strncmp(scheme, "tcp", 3) == 0) ||
        (strncmp(scheme, "tls", 3) == 0)) {
        (void) snprintf(
            addr, sz, "%s://127.0.0.1:%u", scheme, nuts_next_port());
        return;
    }
 
    if (strncmp(scheme, "ws", 2) == 0) {
        (void) snprintf(addr, sz,
            "%s://127.0.0.1:%u/nuts%04x%04x%04x%04x", scheme,
            nuts_next_port(), nng_random(), nng_random(), nng_random(),
            nng_random());
        return;
    }
 
    if ((strncmp(scheme, "ipc", 3) == 0) ||
        (strncmp(scheme, "unix", 4) == 0)) {
#ifdef _WIN32
        // Windows doesn't place IPC names in the filesystem.
        (void) snprintf(addr, sz, "%s://nuts%04x%04x%04x%04x", scheme,
            nng_random(), nng_random(), nng_random(), nng_random());
        return;
#else
        char *tmpdir;
 
        if (((tmpdir = getenv("TMPDIR")) == NULL) &&
            ((tmpdir = getenv("TEMP")) == NULL) &&
            ((tmpdir = getenv("TMP")) == NULL)) {
            tmpdir = "/tmp";
        }
 
        (void) snprintf(addr, sz, "%s://%s/nuts%04x%04x%04x%04x",
            scheme, tmpdir, nng_random(), nng_random(), nng_random(),
            nng_random());
        return;
#endif
    }
 
    // We should not be here.
    abort();
}
 
// nuts_next_port returns a "next" allocation port.
// Ports are chosen by starting from a random point within a
// range (normally 38000-40000, but other good places to choose
// might be 36000-37000, 42000-43000, 45000-47000, 48000-49000.
// These are non-ephemeral ports.  Successive calls to this function
// will return the next port in the range (wrapping).  This works even
// across process boundaries, as the range is tracked in a file named
// by $TEST_PORT_FILE.  The range of ports can be configured by using
// $TEST_PORT_RANGE (the range is specified as "lo:hi" where the actual
// port will be in the range [lo,hi).
uint16_t
nuts_next_port(void)
{
    char *   name;
    FILE *   f;
    uint16_t port;
    uint16_t base;
    uint16_t end;
    char *   str;
#ifdef _WIN32
    OVERLAPPED olp;
    HANDLE     h;
#endif
 
    if ((name = getenv("NUTS_PORT_FILE")) == NULL) {
        name = ".nuts_ports";
    }
    if (((str = getenv("NUTS_PORT_RANGE")) == NULL) ||
        ((sscanf(str, "%hu:%hu", &base, &end)) != 1) ||
        ((int) end - (int) base) < 1) {
        base = 38000;
        end  = 40000;
    }
 
    if (((f = fopen(name, "r+")) == NULL) &&
        ((f = fopen(name, "w+")) == NULL)) {
        return (0);
    }
    (void) fseek(f, 0, SEEK_SET);
 
#ifdef _WIN32
    h = (HANDLE) _get_osfhandle(_fileno(f));
 
    // This contains the offset information for LockFileEx.
    ZeroMemory(&olp, sizeof(olp));
 
    if (LockFileEx(h, LOCKFILE_EXCLUSIVE_LOCK, 0, MAXDWORD, MAXDWORD,
            &olp) == FALSE) {
        fclose(f);
        return (0);
    }
#else
    if (lockf(fileno(f), 0, F_LOCK) != 0) {
        (void) fclose(f);
        return (0);
    }
#endif
    if (fscanf(f, "%hu", &port) != 1) {
        unsigned seed = (unsigned) time(NULL);
 
#ifdef _WIN32
        port = base + rand_s(&seed) % (end - base);
#else
        port = base + rand_r(&seed) % (end - base);
#endif
    }
    port++;
    if ((port < base) || (port >= (base + end))) {
        port = base;
    }
 
#ifdef _WIN32
    fseek(f, 0, SEEK_SET);
    SetEndOfFile(h);
    (void) fprintf(f, "%u", port);
    ZeroMemory(&olp, sizeof(olp));
    (void) UnlockFileEx(h, 0, MAXDWORD, MAXDWORD, &olp);
#else
    fseek(f, 0, SEEK_SET);
    if (ftruncate(fileno(f), 0) != 0) {
        (void) fclose(f);
        return (0);
    }
 
    (void) fprintf(f, "%u", port);
    (void) lockf(fileno(f), 0, F_ULOCK);
 
#endif
    (void) fclose(f);
    return (port);
}
 
struct marriage_notice {
    nng_mtx *mx;
    nng_cv * cv;
    int      s1;
    int      s2;
    int      cnt1;
    int      cnt2;
    nng_pipe p1;
    nng_pipe p2;
};
 
static void
married(nng_pipe p, nng_pipe_ev ev, void *arg)
{
    struct marriage_notice *notice = arg;
    (void) ev;
 
    nng_mtx_lock(notice->mx);
    if (nng_socket_id(nng_pipe_socket(p)) == notice->s1) {
        notice->cnt1++;
        notice->p1 = p;
    } else if (nng_socket_id(nng_pipe_socket(p)) == notice->s2) {
        notice->cnt2++;
        notice->p2 = p;
    }
    nng_cv_wake(notice->cv);
    nng_mtx_unlock(notice->mx);
}
 
int
nuts_marry(nng_socket s1, nng_socket s2)
{
    return (nuts_marry_ex(s1, s2, NULL, NULL, NULL));
}
 
// NB: This function is always called with sufficient space to
// hold the resulting expansion.
static void
replace_port_zero(const char *addr, char *buf, int port)
{
    int  i;
    int  j;
    bool colon = false;
    char c;
 
    for (i = 0, j = 0; (c = addr[i]) != '\0'; i++) {
 
        if (colon && c == '0') {
            char num[16];
            (void) snprintf(num, sizeof(num), "%d", port);
            memcpy(&buf[j], num, strlen(num));
            j += (int) strlen(num);
            colon = false;
            continue;
        }
        colon    = c == ':';
        buf[j++] = c;
    }
    buf[j] = '\0';
}
 
int
nuts_marry_ex(
    nng_socket s1, nng_socket s2, const char *url, nng_pipe *p1, nng_pipe *p2)
{
    struct marriage_notice note;
    nng_time               timeout;
    int                    rv;
    char                   addr[64];
    nng_listener           l;
    int                    port;
 
    if (url == NULL) {
        (void) snprintf(addr, sizeof(addr),
            "inproc://marry%04x%04x%04x%04x", nng_random(),
            nng_random(), nng_random(), nng_random());
        url = addr;
    }
 
    note.cnt1 = 0;
    note.cnt2 = 0;
    note.s1   = nng_socket_id(s1);
    note.s2   = nng_socket_id(s2);
    timeout   = nng_clock() + 1000; // 1 second
 
    if (((rv = nng_mtx_alloc(&note.mx)) != 0) ||
        ((rv = nng_cv_alloc(&note.cv, note.mx)) != 0) ||
        ((rv = nng_pipe_notify(
              s1, NNG_PIPE_EV_ADD_POST, married, &note)) != 0) ||
        ((rv = nng_pipe_notify(
              s2, NNG_PIPE_EV_ADD_POST, married, &note)) != 0) ||
        ((rv = nng_listen(s1, url, &l, 0)) != 0)) {
        goto done;
    }
 
    // If a TCP port of zero was selected, let's ask for the actual
    // port bound.
    if ((strstr(url, ":0") != NULL) &&
        (nng_listener_get_int(l, NNG_OPT_TCP_BOUND_PORT, &port) == 0) &&
        (port > 0)) {
        replace_port_zero(url, addr, port);
        url = addr;
    }
    if ((rv = nng_dial(s2, url, NULL, 0)) != 0) {
        goto done;
    }
 
    nng_mtx_lock(note.mx);
    while ((note.cnt1 == 0) || (note.cnt2 == 0)) {
        if ((rv = nng_cv_until(note.cv, timeout)) != 0) {
            break;
        }
    }
    nng_mtx_unlock(note.mx);
    if (p1 != NULL) {
        *p1 = note.p1;
    }
    if (p2 != NULL) {
        *p2 = note.p2;
    }
 
done:
    nng_pipe_notify(s1, NNG_PIPE_EV_ADD_POST, NULL, NULL);
    nng_pipe_notify(s2, NNG_PIPE_EV_ADD_POST, NULL, NULL);
    if (note.cv != NULL) {
        nng_cv_free(note.cv);
    }
    if (note.mx != NULL) {
        nng_mtx_free(note.mx);
    }
    return (rv);
}