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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright(c) 2018-2025, Stefan Meislinger <sm@opengate.at>                 |
| 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/net/platform/socket_api.h"
#include "gate/results.h"

#if defined(GATE_SYS_WIN)
#	define GATE_NET_PLATFORM_SOCKET_API_WINSOCK	1
#elif defined(GATE_SYS_DOS)
#	define GATE_NET_PLATFORM_SOCKET_API_SOCOP 1
#elif defined(GATE_SYS_POSIX)
#	define GATE_NET_PLATFORM_SOCKET_API_LINKED	1
#else
#	define GATE_NET_PLATFORM_SOCKET_API_NOIMPL	1
#endif



#if defined(GATE_NET_PLATFORM_SOCKET_API_WINSOCK)

#if defined(GATE_SYS_WIN16)
#	include <tchar.h>
#endif

static HMODULE hmod_winsock = (HMODULE)NULL;

struct hostent* (SOCK_API* gethostbyname_func)(const char* name);

#if (defined(GATE_COMPILER_MSVC98) || defined(GATE_WIN32_ANSI)) && !defined(GATE_COMPILER_TCC)
struct sockaddr_storage
{
    char	buffer[128];
};

#endif

struct addrinfo_buffer
{
    struct addrinfo			ai;
    struct sockaddr_storage	addr;
};

#ifndef ERROR_NOT_ENOUGH_MEMORY
#define ERROR_NOT_ENOUGH_MEMORY 0x8
#endif 

static int WINAPI getaddrinfo_hbn(const char* nodename, const char* servname, const struct addrinfo* hints, struct addrinfo** res)
{
    struct hostent* h;
    struct addrinfo_buffer* ptr_info;
    struct sockaddr_in* ptr_addr_in = NULL;
    gate_size_t info_len;

    GATE_UNUSED_ARG(servname);
    GATE_UNUSED_ARG(hints);

    if (!nodename || !res)
    {
        gate_win32_setlasterror(ERROR_INVALID_PARAMETER);
        return -1;
    }

    *res = NULL;

    h = gethostbyname_func(nodename);
    if (NULL == h)
    {
        return -1;
    }

    info_len = sizeof(struct addrinfo_buffer);
    ptr_info = (struct addrinfo_buffer*)gate_mem_alloc(info_len);
    if (!ptr_info)
    {
        gate_win32_setlasterror(ERROR_NOT_ENOUGH_MEMORY);
        return -1;
    }

    ptr_info->ai.ai_flags = AI_CANONNAME;
    ptr_info->ai.ai_family = AF_INET;
    ptr_info->ai.ai_socktype = SOCK_STREAM;
    ptr_info->ai.ai_protocol = IPPROTO_TCP;
    ptr_info->ai.ai_addrlen = 0;
    ptr_info->ai.ai_canonname = NULL;
    if (h->h_addrtype == AF_INET)
    {
        ptr_addr_in = (struct sockaddr_in*)&ptr_info->addr;
        ptr_addr_in->sin_family = AF_INET;
        ptr_addr_in->sin_port = 0;
        ptr_addr_in->sin_addr.S_un.S_un_b.s_b1 = h->h_addr_list[0][0];
        ptr_addr_in->sin_addr.S_un.S_un_b.s_b2 = h->h_addr_list[0][1];
        ptr_addr_in->sin_addr.S_un.S_un_b.s_b3 = h->h_addr_list[0][2];
        ptr_addr_in->sin_addr.S_un.S_un_b.s_b4 = h->h_addr_list[0][3];
    }
    ptr_info->ai.ai_addr = (struct sockaddr*)ptr_addr_in;
    ptr_info->ai.ai_next = NULL;

    *res = &ptr_info->ai;
    return 0;
}
static void WINAPI freeaddrinfo_hbn(struct addrinfo* ai)
{
    if (ai)
    {
        gate_mem_dealloc(ai);
    }
}

gate_result_t gate_socket_api_load(gate_net_platform_socket_api_t* ptr)
{

    if (!hmod_winsock)
    {
        hmod_winsock = gate_win32_load_library(_T("ws2_32"), 0);
        if (!hmod_winsock)
        {
            hmod_winsock = gate_win32_load_library(_T("wsock32"), 0);
        }
    }

    if (!hmod_winsock)
    {
        return GATE_RESULT_NOTAVAILABLE;
    }

    if (ptr)
    {
        gate_win32_get_proc_address(hmod_winsock, "socket", &ptr->sock_socket);
        gate_win32_get_proc_address(hmod_winsock, "closesocket", &ptr->sock_close);
        gate_win32_get_proc_address(hmod_winsock, "connect", &ptr->sock_connect);
        gate_win32_get_proc_address(hmod_winsock, "accept", &ptr->sock_accept);
        gate_win32_get_proc_address(hmod_winsock, "bind", &ptr->sock_bind);
        gate_win32_get_proc_address(hmod_winsock, "listen", &ptr->sock_listen);
        gate_win32_get_proc_address(hmod_winsock, "recv", &ptr->sock_recv);
        gate_win32_get_proc_address(hmod_winsock, "recvfrom", &ptr->sock_recvfrom);
        gate_win32_get_proc_address(hmod_winsock, "send", &ptr->sock_send);
        gate_win32_get_proc_address(hmod_winsock, "sendto", &ptr->sock_sendto);
        gate_win32_get_proc_address(hmod_winsock, "shutdown", &ptr->sock_shutdown);
        gate_win32_get_proc_address(hmod_winsock, "getsockopt", &ptr->sock_getsockopt);
        gate_win32_get_proc_address(hmod_winsock, "setsockopt", &ptr->sock_setsockopt);
        gate_win32_get_proc_address(hmod_winsock, "getsockname", &ptr->sock_getsockname);
        gate_win32_get_proc_address(hmod_winsock, "getpeername", &ptr->sock_getpeername);
        gate_win32_get_proc_address(hmod_winsock, "ioctlsocket", &ptr->sock_ioctl);
        gate_win32_get_proc_address(hmod_winsock, "select", &ptr->sock_select);
        gate_win32_get_proc_address(hmod_winsock, "__WSAFDIsSet", &ptr->sock_isset);

        gate_win32_get_proc_address(hmod_winsock, "htonl", &ptr->sock_htonl);
        gate_win32_get_proc_address(hmod_winsock, "htons", &ptr->sock_htons);
        gate_win32_get_proc_address(hmod_winsock, "ntohl", &ptr->sock_ntohl);
        gate_win32_get_proc_address(hmod_winsock, "ntohs", &ptr->sock_ntohs);
        gate_win32_get_proc_address(hmod_winsock, "WSAGetLastError", &ptr->sock_errno);

        gate_win32_get_proc_address(hmod_winsock, "gethostbyname", &ptr->sock_gethostbyname);
        gate_win32_get_proc_address(hmod_winsock, "getaddrinfo", &ptr->sock_getaddrinfo);
        gate_win32_get_proc_address(hmod_winsock, "freeaddrinfo", &ptr->sock_freeaddrinfo);

        if (!ptr->sock_getaddrinfo && ptr->sock_gethostbyname)
        {
            gethostbyname_func = ptr->sock_gethostbyname;
            ptr->sock_getaddrinfo = &getaddrinfo_hbn;
            ptr->sock_freeaddrinfo = &freeaddrinfo_hbn;
        }
    }

    return GATE_RESULT_OK;
}

gate_result_t gate_socket_session_init()
{
    static int(WINAPI * startup)(WORD version_requested, LPWSADATA ptr_wsa_data) = NULL;
    static WORD versions[] = {
        MAKEWORD(2,2),
        MAKEWORD(2,0),
        MAKEWORD(1,1),
        MAKEWORD(1,0)
    };
    static unsigned const versions_count = sizeof(versions) / sizeof(versions[0]);
    unsigned ndx;
    WSADATA wsa_data;
    int result;
    gate_result_t ret;

    gate_socket_api_load(NULL);

    if (!startup)
    {
        if (!hmod_winsock)
        {
            return GATE_RESULT_NOTAVAILABLE;
        }
        gate_win32_get_proc_address(hmod_winsock, "WSAStartup", &startup);
        if (!startup)
        {
            return GATE_RESULT_NOTAVAILABLE;
        }
    }

    for (ndx = 0; ndx != versions_count; ++ndx)
    {
        result = startup(versions[ndx], &wsa_data);
        if (result == 0)
        {
            /* WINSOCK initialized */
            return GATE_RESULT_OK;
        }
    }
    gate_win32_print_lasterror(&ret, NULL, 0);
    return ret;
}

gate_result_t gate_socket_session_uninit()
{
    static int(WINAPI * cleanup)(void) = NULL;

    int result;
    gate_result_t ret = GATE_RESULT_OK;

    if (!cleanup)
    {
        if (!hmod_winsock)
        {
            return GATE_RESULT_NOTAVAILABLE;
        }

        gate_win32_get_proc_address(hmod_winsock, "WSACleanup", &cleanup);
        if (!cleanup)
        {
            return GATE_RESULT_NOTAVAILABLE;
        }
    }

    result = cleanup();
    if (result != 0)
    {
        gate_win32_print_lasterror(&ret, NULL, 0);
    }
    return ret;
}

#endif /* GATE_NET_PLATFORM_SOCKET_API_WINSOCK */




#if defined(GATE_NET_PLATFORM_SOCKET_API_LINKED)

static int sock_errno_impl(void)
{
    return errno;
}
static int sock_isset_impl(sock_fd_t fd, fd_set* set)
{
    return FD_ISSET(fd, set);
}
static int sock_ioctl_impl(sock_fd_t fd, unsigned long request, void* argp)
{
    return ioctl(fd, request, argp);
}

gate_result_t gate_socket_session_init()
{
    return GATE_RESULT_OK;
}
gate_result_t gate_socket_session_uninit()
{
    return GATE_RESULT_OK;
}

/* some platforms use macros for htoX and ntoX (e.g android) */
static sock_ulong_t disp_htonl(sock_ulong_t hostlong)
{
    return htonl(hostlong);
}
static sock_ushort_t disp_htons(sock_ushort_t hostshort)
{
    return htons(hostshort);
}
static sock_ulong_t disp_ntohl(sock_ulong_t netlong)
{
    return ntohl(netlong);
}
static sock_ushort_t disp_ntohs(sock_ushort_t netshort)
{
    return ntohs(netshort);
}

gate_result_t gate_socket_api_load(gate_net_platform_socket_api_t* ptr)
{
    ptr->sock_socket = &socket;
    ptr->sock_close = &close;
    ptr->sock_connect = &connect;
    ptr->sock_accept = &accept;
    ptr->sock_bind = &bind;
    ptr->sock_listen = &listen;
    ptr->sock_recv = &recv;
    ptr->sock_recvfrom = &recvfrom;
    ptr->sock_send = &send;
    ptr->sock_sendto = &sendto;
    ptr->sock_shutdown = &shutdown;
    ptr->sock_getsockopt = &getsockopt;
    ptr->sock_setsockopt = &setsockopt;
    ptr->sock_getsockname = &getsockname;
    ptr->sock_getpeername = &getpeername;
    ptr->sock_ioctl = &sock_ioctl_impl;
    ptr->sock_select = &select;
    ptr->sock_isset = &sock_isset_impl;

    ptr->sock_htonl = &disp_htonl;
    ptr->sock_htons = &disp_htons;
    ptr->sock_ntohl = &disp_ntohl;
    ptr->sock_ntohs = &disp_ntohs;
    ptr->sock_errno = &sock_errno_impl;

    ptr->sock_gethostbyname = &gethostbyname;
    ptr->sock_getaddrinfo = &getaddrinfo;
    ptr->sock_freeaddrinfo = &freeaddrinfo;

    return GATE_RESULT_OK;
}

#endif	/* GATE_NET_PLATFORM_SOCKET_API_LINKED */




#if defined(GATE_NET_PLATFORM_SOCKET_API_SOCOP)

#include "gate/interfaces/socop.h"
#include "gate/interfaces/socop_impl.c"

#include "gate/atomics.h"
#include "gate/environments.h"
#include "gate/streams.h"
#include "gate/io/serialports.h"

typedef struct socl_class
{
    int sockfd;
    socop_socket_t	sockhandle;
} socl_t;

static socl_t socl_pool[64];
static unsigned const socl_pool_length = 64;
static int volatile socl_next_fd = 0;

static socop_client_t global_socop_client;
static gate_atomic_int_t global_socop_client_used;

static gate_stream_t* global_socop_stream = NULL;

static int gate_socop_read_byte(unsigned char* num, unsigned want_more, void* user_param)
{
    gate_size_t retrieved = 0;
    gate_result_t result;
    if (!global_socop_stream)
    {
        return SOCOP_ERROR_IO;
    }
    result = gate_stream_read(global_socop_stream, (char*)&num, 1, &retrieved);
    if (GATE_FAILED(result))
    {
        return SOCOP_ERROR_IO;
    }
    if (retrieved == 0)
    {
        return SOCOP_ERROR_TIMEOUT;
    }
    return SOCOP_OK;
}
static int gate_socop_write_byte(unsigned char num, unsigned send_more, void* user_param)
{
    gate_size_t written = 0;
    gate_result_t result;
    if (!global_socop_stream)
    {
        return SOCOP_ERROR_IO;
    }
    result = gate_stream_write(global_socop_stream, (char const*)&num, 1, &written);
    if (GATE_FAILED(result))
    {
        return SOCOP_ERROR_IO;
    }
    if (written == 0)
    {
        return SOCOP_ERROR_TIMEOUT;
    }
    return SOCOP_OK;
}

static sock_fd_t get_next_sock_fd()
{
    /* TODO: ensure unique fd */
    return (sock_fd_t)++socl_next_fd;
}

static socl_t* allocate_socket()
{
    socl_t* ret = NULL;
    unsigned ndx;
    for (ndx = 0; ndx != socl_pool_length; ++ndx)
    {
        if (socl_pool[ndx].sockfd == 0)
        {
            ret = &socl_pool[ndx];
            ret->sockfd = get_next_sock_fd();
            ret->sockhandle = 0;
            break;
        }
    }
    return ret;
}
static void deallocate_socket(socl_t* ptr_socl)
{
    ptr_socl->sockfd = 0;
    ptr_socl->sockhandle = 0;
}
static socl_t* resolve_fd(int fd)
{
    socl_t* ret = NULL;
    unsigned ndx;
    for (ndx = 0; ndx != socl_pool_length; ++ndx)
    {
        if (socl_pool[ndx].sockfd == fd)
        {
            ret = &socl_pool[ndx];
            break;
        }
    }
    return ret;
}

static socop_client_t* get_session()
{
    return &global_socop_client;
}

static sock_fd_t SOCK_API socl_socket(int domain, int type, int protocol)
{
    socl_t* ptr_socl;

    switch (domain)
    {
    case AF_INET:
    case AF_INET6:	break;	/* OK */
    default:		return -1;
    }
    switch (type)
    {
    case SOCK_STREAM:
    case SOCK_DGRAM:	break; /* OK */
    default:			return -1;
    }
    switch (protocol)
    {
    case IPPROTO_TCP:
    case IPPROTO_UDP:	break; /* OK */
    default:			return -1;
    }

    ptr_socl = allocate_socket();
    if (!ptr_socl)
    {
        return -1;
    }
    return ptr_socl->sockfd;
}
static int SOCK_API socl_close(sock_fd_t fd)
{
    int result;
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;

    socl->sockfd = 0;
    if (socl->sockhandle)
    {
        result = socop_client_close(session, socl->sockhandle);
        socl->sockhandle = 0;
        return (result == SOCOP_OK) ? 0 : -1;
    }
    return 0;
}

static void SOCK_API sockaddr_2_socop_addr(const struct sockaddr* ptr_src, sock_socklen_t srclen, socop_addr_t* ptr_target)
{
    struct sockaddr_in const* addr_in = (struct sockaddr_in const*)ptr_src;
    ptr_target->port = addr_in->sin_port;
    ptr_target->ip[0] = (unsigned char)((addr_in->sin_addr.s_addr & 0xff000000) >> 24);
    ptr_target->ip[1] = (unsigned char)((addr_in->sin_addr.s_addr & 0x00ff0000) >> 16);
    ptr_target->ip[2] = (unsigned char)((addr_in->sin_addr.s_addr & 0x0000ff00) >> 8);
    ptr_target->ip[3] = (unsigned char)((addr_in->sin_addr.s_addr & 0x000000ff));
}

static int SOCK_API socl_connect(sock_fd_t fd, const struct sockaddr* addr, sock_socklen_t addrlen)
{
    socop_addr_t socop_addr;
    int result;
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;

    sockaddr_2_socop_addr(addr, addrlen, &socop_addr);
    result = socop_client_connect(session, &socop_addr, &socl->sockhandle);
    if (SOCOP_OK == result)
    {
        return 0;
    }
    return -1;
}
static sock_fd_t SOCK_API socl_accept(sock_fd_t fd, struct sockaddr* addr, sock_socklen_t* addrlen)
{
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    socl_t* new_socl = NULL;
    socop_socket_t new_sock;
    int result;

    if (!session || !socl) return -1;

    result = socop_client_accept(session, socl->sockhandle, &new_sock);
    if (SOCOP_OK == result)
    {
        new_socl = allocate_socket();
        if (new_socl == NULL)
        {
            socop_client_close(session, new_sock);
        }
        else
        {
            /* success case */
            /* TODO: fill peer addr */
            new_socl->sockhandle = new_sock;
            return (sock_fd_t)new_socl->sockfd;
        }
    }
    return -1;
}
static int SOCK_API socl_bind(sock_fd_t fd, const struct sockaddr* addr, sock_socklen_t addrlen)
{
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    socop_addr_t socop_addr;
    int result;
    if (!session || !socl) return -1;

    sockaddr_2_socop_addr(addr, addrlen, &socop_addr);
    result = socop_client_bind(session, &socop_addr, &socl->sockhandle);
    if (SOCOP_OK == result)
    {
        return 0;
    }
    return -1;
}
static int SOCK_API socl_listen(sock_fd_t fd, int backlog)
{
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;
    /* TODO */
    return -1;
}
static sock_ssize_t SOCK_API socl_recv(sock_fd_t fd, void* buf, size_t len, int flags)
{
    unsigned int buf_used = 0;
    int result;

    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;

    result = socop_client_receive(session, socl->sockhandle, buf, len, &buf_used);
    if (SOCOP_OK == result)
    {
        return (sock_ssize_t)buf_used;
    }
    return -1;
}
static sock_ssize_t SOCK_API socl_recvfrom(sock_fd_t fd, void* buf, size_t len, int flags, struct sockaddr* src_addr, sock_socklen_t* addrlen)
{
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;
    /* TODO */
    return -1;
}
static sock_ssize_t SOCK_API socl_send(sock_fd_t fd, const void* buf, size_t len, int flags)
{
    unsigned int buf_used = 0;
    int result;

    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;

    result = socop_client_send(session, socl->sockhandle, buf, len, &buf_used);
    if (SOCOP_OK == result)
    {
        return (sock_ssize_t)buf_used;
    }
    return -1;
}
static sock_ssize_t SOCK_API socl_sendto(sock_fd_t fd, const void* buf, size_t len, int flags, const struct sockaddr* dest_addr, sock_socklen_t addrlen)
{
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;
    /* TODO */
    return -1;
}
static int SOCK_API socl_shutdown(sock_fd_t fd, int how)
{
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    int result;
    if (!session || !socl) return -1;
    /* TODO */
    result = socop_client_shutdown(session, socl->sockhandle, SOCOP_MSG_FLAG_RECV | SOCOP_MSG_FLAG_SEND);
    if (SOCOP_OK == result)
    {
        return 0;
    }
    return -1;
}
static int SOCK_API socl_getsockopt(sock_fd_t fd, int level, int optname, void* optval, sock_socklen_t* optlen)
{
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;
    /* TODO */
    return -1;
}
static int SOCK_API socl_setsockopt(sock_fd_t fd, int level, int optname, const void* optval, sock_socklen_t optlen)
{
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;
    /* TODO */
    return -1;
}
static int SOCK_API socl_getsockname(sock_fd_t fd, struct sockaddr* addr, sock_socklen_t* addrlen)
{
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;
    /* TODO */
    return -1;
}
static int SOCK_API socl_getpeername(sock_fd_t fd, struct sockaddr* addr, sock_socklen_t* addrlen)
{
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;
    /* TODO */
    return -1;
}
static int SOCK_API socl_ioctl(sock_fd_t fd, unsigned long request, void* argp)
{
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;
    /* TODO */
    return -1;
}
static int SOCK_API socl_select(int nfds, fd_set* readfds, fd_set* writefds, fd_set* exceptfds, sock_timeval_t* timeout)
{
    socop_client_t* session = get_session();
    if (!session) return -1;
    /* TODO */
    return -1;

}
static int SOCK_API socl_isset(sock_fd_t fd, fd_set* set)
{
    socop_client_t* session = get_session();
    socl_t* socl = resolve_fd(fd);
    if (!session || !socl) return -1;
    /* TODO */
    return -1;
}

union host_types
{
    sock_ulong_t	l;
    sock_ushort_t	s;
    unsigned char	c[sizeof(unsigned long)];
};

static sock_ulong_t SOCK_API socl_htonl(sock_ulong_t hostlong)
{
    unsigned ndx;
    union host_types a, b;
    a.l = hostlong;
    for (ndx = 0; ndx != sizeof(sock_ulong_t); ++ndx)
    {
        b.c[ndx] = a.c[sizeof(sock_ulong_t) - 1 - ndx];
    }
    return b.l;
}
static sock_ushort_t SOCK_API socl_htons(sock_ushort_t hostshort)
{
    unsigned ndx;
    union host_types a, b;
    a.s = hostshort;
    for (ndx = 0; ndx != sizeof(sock_ushort_t); ++ndx)
    {
        b.c[ndx] = a.c[sizeof(sock_ushort_t) - 1 - ndx];
    }
    return b.s;
}
static sock_ulong_t SOCK_API socl_ntohl(sock_ulong_t netlong)
{
    return socl_htonl(netlong);
}
static sock_ushort_t SOCK_API socl_ntohs(sock_ushort_t netshort)
{
    return socl_htons(netshort);
}
static int SOCK_API socl_errno(void)
{
    /* TODO */
    return -1;
}

static struct hostent* SOCK_API socl_gethostbyname(const char* name)
{
    socop_client_t* session = get_session();
    if (!session) return NULL;
    /* TODO */
    return NULL;
}
static int SOCK_API socl_getaddrinfo(const char* nodename, const char* servname, const struct addrinfo* hints, struct addrinfo** res)
{
    socop_client_t* session = get_session();
    if (!session) return -1;
    /* TODO */
    return -1;
}
static void SOCK_API socl_freeaddrinfo(struct addrinfo* ai)
{
    if (ai)
    {
        gate_mem_dealloc(ai);
    }
}


gate_result_t gate_socket_api_load(gate_net_platform_socket_api_t* ptr)
{
    gate_result_t ret = GATE_RESULT_OK;

    ptr->sock_socket = &socl_socket;
    ptr->sock_close = &socl_close;
    ptr->sock_connect = &socl_connect;
    ptr->sock_accept = &socl_accept;
    ptr->sock_bind = &socl_bind;
    ptr->sock_listen = &socl_listen;
    ptr->sock_recv = &socl_recv;
    ptr->sock_recvfrom = &socl_recvfrom;
    ptr->sock_send = &socl_send;
    ptr->sock_sendto = &socl_sendto;
    ptr->sock_shutdown = &socl_shutdown;
    ptr->sock_getsockopt = &socl_getsockopt;
    ptr->sock_setsockopt = &socl_setsockopt;
    ptr->sock_getsockname = &socl_getsockname;
    ptr->sock_getpeername = &socl_getpeername;
    ptr->sock_ioctl = &socl_ioctl;
    ptr->sock_select = &socl_select;
    ptr->sock_isset = &socl_isset;

    ptr->sock_htonl = &socl_htonl;
    ptr->sock_htons = &socl_htons;
    ptr->sock_ntohl = &socl_ntohl;
    ptr->sock_ntohs = &socl_ntohs;
    ptr->sock_errno = &socl_errno;

    ptr->sock_gethostbyname = &socl_gethostbyname;
    ptr->sock_getaddrinfo = &socl_getaddrinfo;
    ptr->sock_freeaddrinfo = &socl_freeaddrinfo;

    return ret;
}

static gate_result_t open_socop_com_port()
{
    static gate_string_t const var_socop_port = GATE_STRING_INIT_STATIC("SOCOP_PORT");
    static gate_string_t const var_socop_baud = GATE_STRING_INIT_STATIC("SOCOP_BAUD");
    static gate_string_t const default_port = GATE_STRING_INIT_STATIC("COM1");
    static gate_string_t const default_baud = GATE_STRING_INIT_STATIC("9600");

    gate_result_t result;
    gate_string_t com_port_name = GATE_STRING_INIT_EMPTY;
    gate_string_t com_port_baud = GATE_STRING_INIT_EMPTY;
    gate_int64_t baud_value = 0;
    gate_stream_t* ptr_strm = NULL;

    result = gate_env_get_var(&var_socop_port, &com_port_name);
    if (GATE_FAILED(result))
    {
        gate_string_duplicate(&com_port_name, &default_port);
    }

    result = gate_env_get_var(&var_socop_baud, &com_port_baud);
    if (GATE_FAILED(result))
    {
        gate_string_duplicate(&com_port_baud, &default_baud);
    }

    gate_string_parse_int(&com_port_baud, &baud_value);
    result = gate_serialport_openstream(&com_port_name, (gate_uint32_t)baud_value,
        8, GATE_SERIALPORT_PARITY_NONE, GATE_SERIALPORT_STOPBITS_1_0, GATE_SERIALPORT_FLOWCTRL_NONE,
        &ptr_strm
    );
    if (GATE_SUCCEEDED(result) && (ptr_strm != NULL))
    {
        if (ptr_strm != NULL)
        {
            global_socop_stream = ptr_strm;
        }
        else
        {
            result = GATE_RESULT_NULLPOINTER;
        }
    }
    return result;
}

gate_result_t gate_socket_session_init()
{
    gate_result_t ret = GATE_RESULT_NOTIMPLEMENTED;
    int result;
    gate_int32_t use_count = gate_atomic_int_inc(&global_socop_client_used);
    if (use_count == 1)
    {
        result = socop_client_init(
            &global_socop_client,
            &gate_socop_read_byte, NULL,
            &gate_socop_write_byte, NULL);
        if (SOCOP_OK != result)
        {
            gate_atomic_int_dec(&global_socop_client_used);
            ret = GATE_RESULT_FAILED;
        }
        else
        {
            ret = open_socop_com_port();
            if (GATE_FAILED(ret))
            {
                gate_atomic_int_dec(&global_socop_client_used);
            }
        }
    }
    else
    {
        ret = GATE_RESULT_OK;
    }
    return ret;
}

gate_result_t gate_socket_session_uninit()
{
    gate_result_t ret = GATE_RESULT_OK;
    gate_uint32_t use_count = gate_atomic_int_dec(&global_socop_client_used);
    unsigned ndx;
    if (use_count == 0)
    {
        if (global_socop_stream != NULL)
        {
            gate_object_release(global_socop_stream);
            global_socop_stream = NULL;
        }

        socop_client_reset(&global_socop_client);
        for (ndx = 0; ndx != sizeof(socl_pool) / sizeof(socl_pool[0]); ++ndx)
        {
            socl_pool[ndx].sockfd = 0;
            socl_pool[ndx].sockhandle = 0;
        }
    }
    return ret;
}

#endif /* GATE_NET_PLATFORM_SOCKET_API_SOCOP */




#if defined(GATE_NET_PLATFORM_SOCKET_API_NOIMPL)

gate_result_t gate_socket_api_load(gate_net_platform_socket_api_t* ptr)
{
    gate_result_t ret = GATE_RESULT_NOTIMPLEMENTED;
    GATE_UNUSED_ARG(ptr);
    return ret;
}

gate_result_t gate_socket_session_init()
{
    gate_result_t ret = GATE_RESULT_NOTIMPLEMENTED;
    return ret;
}

gate_result_t gate_socket_session_uninit()
{
    gate_result_t ret = GATE_RESULT_NOTIMPLEMENTED;
    return ret;
}

#endif /* GATE_NET_PLATFORM_SOCKET_API_NOIMPL */