File: simple_server_windows.c

package info (click to toggle)
libest 3.2.0%2Bds-1.1
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,792 kB
  • sloc: ansic: 60,980; java: 12,082; sh: 4,956; python: 4,474; xml: 385; makefile: 290
file content (422 lines) | stat: -rw-r--r-- 10,935 bytes parent folder | download
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/*------------------------------------------------------------------
 * simple_server_windows.c - 
 *                   This is a very simple Windows API 
 *                   multi-threaded  TCP server used by the 
 *                   example EST server and EST proxy 
 *                   applications when built on Windows. 
 *
 * April, 2016
 *
 * Copyright (c) 2016 by cisco Systems, Inc.
 * All rights reserved.
 **------------------------------------------------------------------
 */
#include <stdio.h>
#include <WS2tcpip.h>
#include <fcntl.h>
#include <sys/types.h>
#include <est.h>
#include <signal.h>
#include <stdint.h>

#pragma comment(lib, "Ws2_32.lib")

#define NON_BLOCKING_SOCKET 1

volatile int stop_flag = 0;
int sock;
static int tcp_port = 8085;
static int family = AF_INET;
volatile int num_threads;
static EST_CTX *ctx;
CONDITION_VARIABLE cond;
CONDITION_VARIABLE BufferNotEmpty;
CONDITION_VARIABLE BufferNotFull;
CRITICAL_SECTION BufferLock;
int queue[20];
volatile int head;
volatile int tail;

#define SLEEP(x) Sleep(x*1000)

#define close(socket) closesocket(socket)
#define snprintf _snprintf

#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
#define NUM_WORKER_THREADS 5

static int grab_work (int *sp)
{
    EnterCriticalSection(&BufferLock);

    // Check for new work
    while (head == tail && stop_flag == 0) {
        SleepConditionVariableCS(&BufferNotEmpty, &BufferLock, INFINITE);
    }

    if (head > tail) {
        *sp = queue[tail % ARRAY_SIZE(queue)];
        tail++;

        // Keep our pointers aligned
        while (tail > (int) ARRAY_SIZE(queue)) {
            tail -= ARRAY_SIZE(queue);
            head -= ARRAY_SIZE(queue);
        }
    }

    WakeConditionVariable(&BufferNotFull);
    LeaveCriticalSection(&BufferLock);

    return !stop_flag;
}

DWORD WINAPI worker_thread (void* args)
{
    int sock = 0;

    while (grab_work(&sock)) {
        /*
         * Both SERVER and PROXY modes use the
         * same entry point to hand off the socket
         * to libest
         */
        est_server_handle_request(ctx, sock);
        close(sock);
    }

    // Tell the boss that we're finishing 
    EnterCriticalSection(&BufferLock);
    num_threads--;
    WakeConditionVariable(&cond);
    LeaveCriticalSection(&BufferLock);
    return 0;
}

static void process_socket (int fd)
{
    EnterCriticalSection(&BufferLock);

    // Check if work queue is full and wait
    while (stop_flag == 0 && head - tail >= (int) ARRAY_SIZE(queue)) {
        SleepConditionVariableCS(&BufferNotFull, &BufferLock, INFINITE);
    }

    if (head - tail < (int) ARRAY_SIZE(queue)) {
        // Put the accepted socket on to the work queue
        queue[head % ARRAY_SIZE(queue)] = fd;
        head++;
    }

    WakeConditionVariable(&BufferNotEmpty);
    LeaveCriticalSection(&BufferLock);
}

static DWORD WINAPI master_thread_v4(LPVOID lpParam)
{
    int sock;
    struct sockaddr_in addr;
    int on = 1;
    int rc;
    int new;
    int unsigned len;

    u_long iMode = NON_BLOCKING_SOCKET;

    memset(&addr, 0x0, sizeof(struct sockaddr_in));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(tcp_port);

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock == -1) {
        fprintf(stderr, "\nsocket call failed\n");
        exit(1);
    }
    // Needs to be done to bind to both :: and 0.0.0.0 to the same port

    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
    setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&on, sizeof(on));

    /*
	Replace POSIX code with Windows equivalent for setting non-blocking socket
     */
    ioctlsocket(sock, FIONBIO, &iMode);

    rc = bind(sock, (const struct sockaddr*)&addr, sizeof(addr));
    if (rc == -1) {
        fprintf(stderr, "\nbind call failed\n");
        exit(1);
    }
    listen(sock, SOMAXCONN);
    stop_flag = 0;

    while (stop_flag == 0) {
        len = sizeof(addr);
        new = accept(sock, (struct sockaddr*)&addr, &len);
        if (new < 0) {
            /*
             * this is a bit cheesy, but much easier to implement than using select()
             */

            SLEEP(1);
        }
        else {
            if (stop_flag == 0) {
                est_server_handle_request(ctx, new);
                close(new);
            }
        }
    }
    close(sock);
    return 0;
}

static DWORD WINAPI master_thread_v6 (LPVOID lpParam)
{
    int sock;
    struct sockaddr_in6 addr;
    int on = 1;
    int rc;
    int new;
    int unsigned len;

    u_long iMode = NON_BLOCKING_SOCKET;

    memset(&addr, 0x0, sizeof(struct sockaddr_in6));
    addr.sin6_family = AF_INET6;
    addr.sin6_port = htons((uint16_t)tcp_port);

    sock = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
    if (sock == -1) {
        fprintf(stderr, "\nsocket call failed\n");
        exit(1);
    }
    // Needs to be done to bind to both :: and 0.0.0.0 to the same port
    int no = 0;
    setsockopt(sock, SOL_SOCKET, IPV6_V6ONLY, (void *)&no, sizeof(no));

    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on));
    setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&on, sizeof(on));

    /*
	Replace POSIX code with Windows equivalent for setting non-blocking socket
     */
    ioctlsocket(sock, FIONBIO, &iMode);

    rc = bind(sock, (const struct sockaddr*)&addr, sizeof(addr));
    if (rc == -1) {
        fprintf(stderr, "\nbind call failed\n");
        exit(1);
    }
    listen(sock, SOMAXCONN);
    stop_flag = 0;

    while (stop_flag == 0) {
        len = sizeof(addr);
        new = accept(sock, (struct sockaddr*)&addr, &len);
        if (new < 0) {
            /*
             * this is a bit cheesy, but much easier to implement than using select()
             */

            SLEEP(1);
        }
        else {
            if (stop_flag == 0) {
                est_server_handle_request(ctx, new);
                close(new);
            }
        }
    }
    close(sock);
    return 0;
}

#if 0
DWORD WINAPI master_thread (void *arg)
{
    struct addrinfo hints, *ai, *aiptr;
    char portstr[12];
    int on = 1;
    int rc;
    int new;

    u_long iMode = NON_BLOCKING_SOCKET;

    /*
     * Lookup the local address we'll use to bind too
     */
    memset(&hints, '\0', sizeof(struct addrinfo));
    hints.ai_family = family;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    snprintf(portstr, sizeof(portstr), "%u", tcp_port);
    rc = getaddrinfo(NULL, portstr, &hints, &aiptr);
    if (rc) {
        printf("\ngetaddrinfo call failed\n");
        printf("getaddrinfo(): %s\n", gai_strerror(rc));
        exit(1);
    }
    for (ai = aiptr; ai; ai = ai->ai_next) {
        sock = socket(family, SOCK_STREAM, IPPROTO_TCP);
        if (sock == -1) {
            /* If we can't create a socket using this address, then
             * try the next address */
            continue;
        }
        /*
         * Set some socket options for our server
         */
        if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*) &on,
            sizeof(on))) {
            printf("\nsetsockopt REUSEADDR call failed\n");
            exit(1);
        }
        if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*) &on,
            sizeof(on))) {
            printf("\nsetsockopt KEEPALIAVE call failed\n");
            exit(1);
        }

        ioctlsocket(sock, FIONBIO, &iMode);

        /*
         * Bind to the socket 
         */
        rc = bind(sock, ai->ai_addr, ai->ai_addrlen);
        if (rc == -1) {
            printf("\nbind call failed\n");
            exit(1);
        }
        break;
    }
    if (ai) {
        listen(sock, SOMAXCONN);
    } else {
        printf("\nNo address info found\n");
        exit(1);
    }

    while (stop_flag == 0) {
        new = accept(sock, NULL, NULL);
        if (new < 0) {
            if (stop_flag != 0) {
                break;
            }
            /*
             * this is a bit cheesy, but much easier to implement than using select()
             */
            SLEEP(1);
        } else {
            if (stop_flag == 0) {
                process_socket(new);
            }
        }
    }

    close(sock);
    freeaddrinfo(aiptr);

    // Notify all the workers that it's time to shutdown
    WakeAllConditionVariable(&BufferNotEmpty);

    // Wait for the workers to finish
    EnterCriticalSection(&BufferLock);
    while (num_threads > 0) {
        SleepConditionVariableCS(&cond, &BufferLock, INFINITE);
    }
    LeaveCriticalSection(&BufferLock);

    DeleteCriticalSection(&BufferLock);

    stop_flag = 2;
    return 0;
}
#endif

static HANDLE start_thread (LPTHREAD_START_ROUTINE func)
{
    DWORD mThreadID;

    return CreateThread(NULL, 0, func, NULL, 0, &mThreadID);
}

static void catch_int (int signo)
{
    stop_flag = 1;
}

/*
 * This is the entry point into the Simple TCP server.
 * This is designed to work with either the EST server
 * or EST proxy example applications.  This creates
 * a multi-threaded TCP server.  It opens a socket,
 * waits for incoming connections on the socket,
 * and dispatches work to a separate thread to process
 * the incoming EST request.
 *
 * Parameters:
 *     ectx     Pointer to the EST_CTX that was provided from
 *              calling est_server_init().
 *     port     The TCP port to listen too.
 *     delay    The number of seconds to wait before 
 *              automatically shutting down the server.
 *              Pass in 0 to run until keyboard input is 
 *              detected.
 *     v6       Set to non-zero value to enable IPv6
 */
void start_simple_server (EST_CTX *ectx, int port, int delay, int v6)
{
    int i;

    /*
     * Save a global reference to the context.
     * This code only supports running a single 
     * instance of the server.
     */
    ctx = ectx;
    tcp_port = port;
    if (v6) {
        family = AF_INET6;
    }

    /*
     * Install handler to catch ctrl-C to stop the process gracefully
     */
    signal(SIGINT, catch_int);

    InitializeCriticalSection(&BufferLock);
    InitializeConditionVariable(&cond);
    InitializeConditionVariable(&BufferNotEmpty);
    InitializeConditionVariable(&BufferNotFull);

    // Start master (listening) thread
    if (v6) {
        start_thread(master_thread_v6);
    } else {
        start_thread(master_thread_v4);
    }   

    // Start worker threads
    for (i = 0; i < NUM_WORKER_THREADS; i++) {
        if (start_thread(worker_thread) == NULL) {
            printf("\nCannot start worker thread\n");
        } else {
            EnterCriticalSection(&BufferLock);
            num_threads++;
            LeaveCriticalSection(&BufferLock);
        }
    }

    if (delay > 0) {
        /* We will automatically shut down the server
         * after <delay> seconds */
        SLEEP(delay);
        stop_flag = 1;
    }

    while (!stop_flag) {
        SLEEP(1);
    }
}