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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright(c) 2018-2025, Stefan Meislinger                                  |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. Redistributions in binary form must reproduce the above copyright       |
|    notice, this list of conditions and the following disclaimer in the     |
|    documentation and/or other materials provided with the distribution.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/tech/portmapping.h"
#include "gate/debugging.h"

typedef struct gate_portmapper_connection_class
{
    gate_uint32_t       connection_id;
    gate_uint32_t       service_id;

    gate_channel_id_t   source_id;
    gate_bool_t         source_read_closed;
    gate_bool_t         source_write_closed;
    gate_bool_t         source_error;

    gate_bool_t         destination_connected;
    gate_channel_id_t   destination_id;
    gate_bool_t         destination_read_closed;
    gate_bool_t         destination_write_closed;
    gate_bool_t         destination_error;
} gate_portmapper_connection_t;

typedef struct gate_portmapper_service_class
{
    gate_uint32_t       service_id;
    gate_channel_id_t   server;
    char                remote_address[128];
} gate_portmapper_service_t;


static gate_portmapper_service_t* resolve_service(gate_portmapper_t* mapper, gate_channel_id_t channel)
{
    gate_portmapper_service_t* service;
    gate_map_iterator_t iter;
    for (iter = gate_map_first(&mapper->services); gate_map_iterator_valid(iter); iter = gate_map_iterator_next(iter))
    {
        service = (gate_portmapper_service_t*)iter->mapping.value;
        if (service && (service->server == channel))
        {
            return service;
        }
    }
    return NULL;    /* not found */
}

static gate_atomic_int_t connection_id_counter = 0;

static void gate_portmapper_remove_connection(gate_portmapper_t* mapper, gate_uint32_t connection_id)
{
    gate_portmapper_connection_t* conn = (gate_portmapper_connection_t*)gate_map_get_value(&mapper->connections, &connection_id);
    if (conn)
    {
        gate_socketqueue_close(mapper->queue, conn->source_id);
        gate_map_remove(&mapper->channels, &conn->source_id);

        gate_socketqueue_close(mapper->queue, conn->destination_id);
        gate_map_remove(&mapper->channels, &conn->destination_id);

        gate_map_remove(&mapper->connections, &connection_id);
    }
}

static gate_bool_t gate_portmapper_remove_invalid_connection_valid(gate_portmapper_t* mapper, gate_portmapper_connection_t* conn)
{
    if (conn->source_error || conn->destination_error ||
        (conn->source_read_closed && conn->source_write_closed && conn->destination_read_closed && conn->destination_write_closed))
    {
        gate_portmapper_remove_connection(mapper, conn->connection_id);
        return true;    /* connection was removed */
    }
    return false;
}

static void gate_portmapper_queue_callback(void* callback_data, gate_uint32_t result_type, gate_channel_id_t channel_id,
    gate_result_t result_code, char const* buffer, gate_size_t buffer_length, void* user_param)
{
    gate_result_t result;
    gate_portmapper_t* mapper = (gate_portmapper_t*)callback_data;
    gate_uint32_t const* ptr_connection_id = (gate_uint32_t const*)gate_map_get_value(&mapper->channels, &channel_id);
    gate_portmapper_connection_t* conn = NULL;

    if (!ptr_connection_id)
    {
        if (result_type != GATE_DATAQUEUE_RESULT_OPENNEW)
        {
            GATE_DEBUG_TRACE("Portmapper queue failed to resolve connection ID from channel");
            GATE_DEBUG_TRACE_VALUE(channel_id);
            GATE_DEBUG_TRACE_VALUE(result_type);
            GATE_DEBUG_TRACE_VALUE(result_code);

            gate_socketqueue_close(mapper->queue, channel_id);
            return;
        }
    }
    else
    {
        conn = (gate_portmapper_connection_t*)gate_map_get_value(&mapper->connections, ptr_connection_id);
        if (!conn)
        {
            /* internal error or data corruption -> close connection and channel */
            GATE_DEBUG_TRACE("Portmapper queue failed to resolve connection from connection ID");
            GATE_DEBUG_TRACE_VALUE(channel_id);
            GATE_DEBUG_TRACE_VALUE(result_type);
            GATE_DEBUG_TRACE_VALUE(result_code);

            gate_map_remove(&mapper->channels, &channel_id);
            gate_socketqueue_close(mapper->queue, channel_id);
            return;
        }
    }

    if (GATE_FAILED(result_code))
    {
        GATE_DEBUG_TRACE("Portmapper queue operation failed");
        GATE_DEBUG_TRACE_VALUE(channel_id);
        GATE_DEBUG_TRACE_VALUE(result_type);
        GATE_DEBUG_TRACE_VALUE(result_code);
        if (conn)
        {
            GATE_DEBUG_TRACE_VALUE(conn->connection_id);
            gate_portmapper_remove_connection(mapper, conn->connection_id);
        }
        return;
    }

    switch (result_type)
    {
    case GATE_DATAQUEUE_RESULT_OPEN:	/* socket connect */
    {
        GATE_DEBUG_ASSERT(conn != NULL);
        conn->destination_connected = true;
        result = gate_socketqueue_begin_read(mapper->queue, conn->source_id, 4096, 0);
        if (GATE_SUCCEEDED(result))
        {
            result = gate_socketqueue_begin_read(mapper->queue, conn->destination_id, 4096, 0);
        }
        if (GATE_FAILED(result))
        {
            conn->destination_error = true;
        }

        gate_portmapper_remove_invalid_connection_valid(mapper, conn);
        break;
    }
    case GATE_DATAQUEUE_RESULT_OPENNEW:	/* socket accept */
    {
        /* channel ID of originating service is published in data buffer */
        gate_portmapper_service_t* service = resolve_service(mapper, *(gate_channel_id_t const*)buffer);
        if (service)
        {
            gate_string_t remote_addr;
            gate_portmapper_connection_t new_conn;
            gate_mem_clear(&new_conn, sizeof(new_conn));
            new_conn.connection_id = gate_atomic_int_inc(&connection_id_counter);
            new_conn.source_id = channel_id;
            new_conn.source_read_closed = false;
            new_conn.source_write_closed = false;
            new_conn.destination_connected = false;
            new_conn.destination_read_closed = false;
            new_conn.destination_write_closed = false;
            new_conn.service_id = service->service_id;
            gate_string_create_static(&remote_addr, service->remote_address);
            result = gate_socketqueue_open(mapper->queue, &remote_addr, GATE_SOCKETQUEUE_OPEN_CLIENT, mapper, &new_conn.destination_id);
            if (GATE_SUCCEEDED(result))
            {
                gate_map_add(&mapper->connections, &new_conn.connection_id, &new_conn);
                gate_map_add(&mapper->channels, &new_conn.source_id, &new_conn.connection_id);
                gate_map_add(&mapper->channels, &new_conn.destination_id, &new_conn.connection_id);
            }
            else
            {
                GATE_DEBUG_TRACE("Portmapper failed to connect to remote client");
                GATE_DEBUG_TRACE_VALUE(result);
                gate_socketqueue_close(mapper->queue, new_conn.source_id);
            }
        }
        else
        {
            /* close all unknown service channels */
            GATE_DEBUG_TRACE("Portmapper failed to resolve ACCEPTING service from channel ID");
            gate_socketqueue_close(mapper->queue, channel_id);
        }
        break;
    }
    case GATE_DATAQUEUE_RESULT_READ:	/* socket receive completed*/
    {
        GATE_DEBUG_ASSERT(conn != NULL);
        if (conn->source_id == channel_id)
        {
            /* receive from source -> send to destination */
            result = gate_socketqueue_begin_write(mapper->queue, conn->destination_id, buffer, buffer_length, user_param);
            if (GATE_FAILED(result))
            {
                GATE_DEBUG_TRACE("Portmapper failed to write to DESTINATION in SOURCE-READ event");
                conn->destination_error = true;
            }
        }
        else if (conn->destination_id == channel_id)
        {
            /* receive from destination -> send to source */
            result = gate_socketqueue_begin_write(mapper->queue, conn->source_id, buffer, buffer_length, user_param);
            if (GATE_FAILED(result))
            {
                GATE_DEBUG_TRACE("Portmapper failed to write to SOURCE in DESTINATION-READ event");
                conn->source_error = true;
            }
        }
        else
        {
            /* internal error or data corruption -> close connection and channel */
            GATE_DEBUG_TRACE("Portmapper cannot select connection channel in READ event");
            GATE_DEBUG_TRACE_VALUE(channel_id);
            conn->source_error = true;
            conn->destination_error = true;
            gate_socketqueue_close(mapper->queue, channel_id);
        }

        gate_portmapper_remove_invalid_connection_valid(mapper, conn);
        break;
    }
    case GATE_DATAQUEUE_RESULT_CLOSE:	/* socket receive completed, length == 0*/
    {
        GATE_DEBUG_ASSERT(conn != NULL);
        if (conn->source_id == channel_id)
        {
            /* end of stream of source -> shutdown send of destination */
            conn->source_read_closed = true;
            result = gate_socketqueue_begin_write(mapper->queue, conn->destination_id, NULL, 0, user_param);
            if (GATE_FAILED(result))
            {
                GATE_DEBUG_TRACE("Portmapper failed to shutdown DESTINATION in SOURCE-CLOSE event");
                conn->destination_error = true;
            }
        }
        else if (conn->destination_id == channel_id)
        {
            /* end of stream of destination -> shutdown send of source */
            conn->destination_read_closed = true;
            result = gate_socketqueue_begin_write(mapper->queue, conn->source_id, NULL, 0, user_param);
            if (GATE_FAILED(result))
            {
                GATE_DEBUG_TRACE("Portmapper failed to shutdown SOURCE in DESTINATION-CLOSE event");
                conn->source_error = true;
            }
        }
        else
        {
            /* internal error or data corruption -> close connection and channel */
            GATE_DEBUG_TRACE("Portmapper cannot select connection channel in CLOSE event");
            GATE_DEBUG_TRACE_VALUE(channel_id);
            conn->source_error = true;
            conn->destination_error = true;
            gate_socketqueue_close(mapper->queue, channel_id);
        }

        gate_portmapper_remove_invalid_connection_valid(mapper, conn);
        break;
    }
    case GATE_DATAQUEUE_RESULT_WRITE:	/* socket send completed */
    {
        GATE_DEBUG_ASSERT(conn != NULL);
        if (conn->source_id == channel_id)
        {
            /* write to source succeeded */
            if (buffer_length == 0)
            {
                /* socket write shutdown received */
                conn->source_write_closed = true;
            }
            else
            {
                /* initiate next read from destination */
                result = gate_socketqueue_begin_read(mapper->queue, conn->destination_id, 4096, user_param);
                if (GATE_FAILED(result))
                {
                    GATE_DEBUG_TRACE("Portmapper failed to read from DESTINATION in SOURCE-WRITE event");
                    conn->destination_error = true;
                }
            }

        }
        else if (conn->destination_id == channel_id)
        {
            /* write to destination succeeded */
            if (buffer_length == 0)
            {
                /* socket write shutdown received */
                conn->destination_write_closed = true;
            }
            else
            {
                /* initiate next read from source */
                result = gate_socketqueue_begin_read(mapper->queue, conn->source_id, 4096, user_param);
                if (GATE_FAILED(result))
                {
                    GATE_DEBUG_TRACE("Portmapper failed to read from SOURCE in DESTINATION-WRITE event");
                    conn->source_error = true;
                }
            }

        }
        else
        {
            /* internal error or data corruption -> close connection and channel */
            GATE_DEBUG_TRACE("Portmapper cannot select connection channel in WRITE event");
            GATE_DEBUG_TRACE_VALUE(channel_id);
            conn->source_error = true;
            conn->destination_error = true;
            gate_socketqueue_close(mapper->queue, channel_id);
        }

        gate_portmapper_remove_invalid_connection_valid(mapper, conn);
        break;
    }
    case GATE_DATAQUEUE_RESULT_ERROR:
    {
        GATE_DEBUG_ASSERT(conn != NULL);
        break;
    }
    default:
    {
        /* unsupported result -> ignore */
        break;
    }
    }
}


gate_result_t gate_portmapper_create(gate_portmapper_t* mapper)
{
    gate_result_t ret = GATE_RESULT_OK;
    gate_mem_clear(mapper, sizeof(gate_portmapper_t));

    do
    {
        if (NULL == gate_map_create(&mapper->services, &gate_compare_uint32, sizeof(gate_uint32_t), NULL, NULL, sizeof(gate_portmapper_service_t), NULL, NULL))
        {
            ret = GATE_RESULT_OUTOFMEMORY;
            break;
        }
        if (NULL == gate_map_create(&mapper->connections, &gate_compare_uint32, sizeof(gate_uint32_t), NULL, NULL, sizeof(gate_portmapper_connection_t), NULL, NULL))
        {
            gate_map_destroy(&mapper->services);
            ret = GATE_RESULT_OUTOFMEMORY;
            break;
        }

        if (NULL == gate_map_create(&mapper->channels, &gate_compare_uintptr, sizeof(gate_channel_id_t), NULL, NULL, sizeof(gate_uint32_t), NULL, NULL))
        {
            gate_map_destroy(&mapper->services);
            gate_map_destroy(&mapper->connections);
            ret = GATE_RESULT_OUTOFMEMORY;
            break;
        }

        ret = gate_socketqueue_create(&mapper->queue, 500);
        if (GATE_FAILED(ret))
        {
            gate_map_destroy(&mapper->services);
            gate_map_destroy(&mapper->channels);
            gate_map_destroy(&mapper->connections);
            break;
        }

        ret = gate_socketqueue_set_callback(mapper->queue, &gate_portmapper_queue_callback, mapper);
        if (GATE_FAILED(ret))
        {
            gate_object_release(mapper->queue);
            gate_map_destroy(&mapper->services);
            gate_map_destroy(&mapper->channels);
            gate_map_destroy(&mapper->connections);
            break;
        }

        ret = gate_socketqueue_start(mapper->queue);
        if (GATE_FAILED(ret))
        {
            gate_object_release(mapper->queue);
            gate_map_destroy(&mapper->services);
            gate_map_destroy(&mapper->channels);
            gate_map_destroy(&mapper->connections);
            break;
        }
    } while (0);
    return ret;
}

gate_result_t gate_portmapper_destroy(gate_portmapper_t* mapper)
{
    gate_socketqueue_stop(mapper->queue);
    gate_socketqueue_close_all(mapper->queue);
    gate_object_release(mapper->queue);
    gate_map_destroy(&mapper->channels);
    gate_map_destroy(&mapper->connections);
    gate_map_destroy(&mapper->services);
    gate_mem_clear(mapper, sizeof(gate_portmapper_t));
    return GATE_RESULT_OK;
}

static gate_atomic_int_t mapping_id_counter = 0;

gate_result_t gate_portmapper_add(gate_portmapper_t* mapper, gate_string_t const* source_address, gate_string_t const* dest_address, gate_uint32_t* mapping_id)
{
    gate_result_t ret;
    gate_portmapper_service_t service;

    do
    {
        gate_mem_clear(&service, sizeof(service));
        service.service_id = gate_atomic_int_inc(&mapping_id_counter);

        gate_string_to_buffer(dest_address, service.remote_address, sizeof(service.remote_address));

        ret = gate_socketqueue_open(mapper->queue, source_address, GATE_SOCKETQUEUE_OPEN_SERVER, mapper, &service.server);
        if (GATE_FAILED(ret))
        {
            break;
        }

        if (!gate_map_add(&mapper->services, &service.service_id, &service))
        {
            gate_socketqueue_close(mapper->queue, service.server);
            ret = GATE_RESULT_OUTOFMEMORY;
            break;
        }
        if (mapping_id)
        {
            *mapping_id = service.service_id;
        }

        ret = GATE_RESULT_OK;
    } while (0);

    return ret;
}

gate_result_t gate_portmapper_remove(gate_portmapper_t* mapper, gate_uint32_t service_id)
{
    gate_portmapper_service_t* service = (gate_portmapper_service_t*)gate_map_get_value(&mapper->services, &service_id);
    if (service)
    {
        gate_socketqueue_close(mapper->queue, service->server);
        gate_map_remove(&mapper->services, &service_id);
        return GATE_RESULT_OK;
    }
    return GATE_RESULT_NOMATCH;
}