forked from MewX/Psiphon3-for-Linux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindows.c
8941 lines (8209 loc) · 203 KB
/
windows.c
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const char *SIGN_windows_c="{FILESIGN=windows.c:20141031194211+0900:735eebc51ee5cd0a:[email protected]:LnJbSRH+NJcIG4Zr/IJHr3hs8AjWPl9B4F0RVDTHZwuwrzESzIKPxvUre0Uz4eBfgzdZ2vnQB1Z9kYnT4WrqdP6A3kkhkFiUxAEisSUeuSAF/iGsxPmsgsvceAYuaD82CgXsz6FceA21hDG7YKhoASU/EC0qbBWICCLOPaI4Po8=}";
/*////////////////////////////////////////////////////////////////////////
Copyright (c) 2007-2008 National Institute of Advanced Industrial Science and Technology (AIST)
AIST-Product-ID: H18PRO-443
Permission to use this material for noncommercial and/or evaluation
purpose, copy this material for your own use,
without fee, is hereby granted
provided that the above copyright notice and this permission notice
appear in all copies.
AIST MAKES NO REPRESENTATIONS ABOUT THE ACCURACY OR SUITABILITY OF THIS
MATERIAL FOR ANY PURPOSE. IT IS PROVIDED "AS IS", WITHOUT ANY EXPRESS
OR IMPLIED WARRANTIES.
//////////////////////////////////////////////////////////////////////////
Content-Type: program/C; charset=US-ASCII
Program: windows.c
Author: Yutaka Sato <[email protected]>
Description:
A collection of functions to make DeleGate work on Windows.
History:
970202 created
TODO:
to be LIBDGWIN.DLL
//////////////////////////////////////////////////////////////////////#*/
/* '"DiGEST-OFF"' */
int win_simple_send;
int RunningAsService;
/* FrOM-HERE
##########################################################################
CAUTION: re-distributing the copy of this file is not permitted.
##########################################################################
*/
//////////////////////////////////////////////////////////////////////////
#ifdef _MSC_VER
//////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include "ystring.h"
#include "fpoll.h"
#undef socket
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#define FL_Par const char *FL_F,int FL_L
#define FL_Bar FL_F,FL_L
#define FL_Arg __FILE__,__LINE__
#define FL_Arg0 "",0
int dup2_FL(FL_Par,int fd1,int fd2);
int dup_FL(FL_Par,int fd);
int close_FL(FL_Par,int fd);
#if defined UNDER_CE
int _dup_FL(FL_Par,int fd);
int _dup2_FL(FL_Par,int sfd,int dfd);
#define _dup(fd) _dup_FL(FL_Arg,fd)
#define _dup2(fd1,fd2) _dup2_FL(FL_Arg,fd1,fd2)
extern int WCE_sDEBUG();
#define WCE_sDBG WCE_sDEBUG()==0?0:fprintf
int setosf_FL(const char *wh,const char *path,int fd,FILE *fp,FL_Par);
#define isWindowsCE() 1
#else
#define _dup_FL(FL_Par,fd) _dup(fd)
#define _dup2_FL(FL_Par,sfd,dfd) _dup2(sfd,dfd)
#define isWindowsCE() 0
#define setosf_FL(wh,path,fd,fp,FL_Par) 0
#define WCE_sDBG 1?0:
#endif
int curLogFd();
typedef struct sockaddr *SAP0;
void socklog(PCStr(where),int fd,const SAP0 addr,int rcode,int csock);
int setCFIshared();
extern int (*fullpath_cmd)(PCStr(path),PCStr(mode),PVStr(xpath));
void env2arg(PCStr(prefix));
extern int MAIN_argc;
extern const char **MAIN_argv;
void DO_INITIALIZE(int ac,const char *av[]);
void DO_FINALIZE(int code);
void DO_STARTUP(int ac,const char *av[]);
#include "config.h"
#include "log.h"
void wlfprintf(PCStr(fmt),...);
#define WLE (LOGLEVEL<0) ? 0:syslog_ERROR
int porting_dbg(PCStr(fmt),...);
#define LE (LOGLEVEL<0) ? 0:porting_dbg
#define LT (LOGLEVEL<1) ? 0:porting_dbg
#define LV (LOGLEVEL<2) ? 0:porting_dbg
#define LW (LOGLEVEL<4) ? 0:porting_dbg
#define LS (!lSOCKET() && LOGLEVEL<4) ? 0:porting_dbg
char *FILEOWNER = "";
char *FILEACL = "SYSTEM";
#ifdef _MSC_VER
extern int errorECONNRESET;
extern int LastCpid;
extern const char *BINSHELL;
void deltmpfiles();
static int STARTED;
static int tmpLogFd = -1;
int winCP; /* xspawn().CreateProcess() instead of spawnvp() */
int SPAWN_TIMEOUT = 10*1000;
int MIN_DGSPAWN_WAIT = 100; /* expecting when a child is a DeleGate */
int _waitspawn = 10*1000;
int setwaitspawn(int ws){
int ows = _waitspawn;
_waitspawn = ws;
return ows;
}
#include "vsignal.h"
#undef DBGWRITE
#define DBGWRITE __write
#undef SYST
#define SYST "WIN"
#define WINSOCKVER "2.2"
const char *WinSockVer = WINSOCKVER;
#include "ywinsock.h"
#include <sys/timeb.h> /* for ftime() */
#include <share.h> /* _SH_DENYNO */
#include <shlobj.h>
#include <stdio.h>
/*
these are included in "ystring.h"
#include <io.h>
#include <process.h>
#include <direct.h>
*/
#include <crtdbg.h>
#if 1400 <= _MSC_VER
void invalid_parameter_handler(const wchar_t* expression,
const wchar_t*function,const wchar_t*file,unsigned int line,uintptr_t reserved
){
if( 2 < LOGLEVEL ){
fprintf(stderr,"--CRT ERROR\n");
fflush(stderr);
}
}
#else
#define _set_invalid_parameter_handler(func)
#endif
int getppid();
int pipe(int*);
int getserversock();
int getclientsock();
FileSize Lseek(int fd,FileSize off,int wh);
int wait3(int *statusp,int options,void *rusage);
static int sessionfd();
static int acceptsocket(int asock);
static int bindsocket(int sock,int *portp);
static int connectsocket(int sock,int port);
int Isend(int sock,const void *buf,unsigned int len,int flags){
return send(sock,(const char*)buf,len,flags);
}
int Irecv(int sock,void *buf,unsigned int len,int flags){
return recv(sock,(char*)buf,len,flags);
}
static int sends(int fd,PCStr(buf),int len,int flags)
{ int rem,wcc,mtu,wcc1;
int xerr;
rem = len;
wcc = 0;
while( 0 < rem ){
mtu = rem;
if( WIN_MTU && WIN_MTU < mtu )
mtu = WIN_MTU;
wcc1 = send(fd,buf+wcc,mtu,flags);
if( 0 < wcc1 ){
LOGX_sentBytes += wcc1;
}
if( wcc1 <= 0 ){
xerr = WSAGetLastError();
if( 1 < LOGLEVEL || xerr != WSAEWOULDBLOCK )
if( xerr == WSAECONNRESET || xerr == WSAECONNABORTED )
LV("send(%d) = %d+%d errno=%d",len,wcc1,wcc,xerr);
else
LE("send(%d) = %d+%d errno=%d [%d]",len,wcc1,wcc,xerr,fd);
if( wcc == 0 )
wcc = -1;
if( xerr == WSAEWOULDBLOCK ){
errno = EAGAIN;
}else{
LV("Emulating SIGPIPE: send(%d/%d/%d) err=%d",
wcc1,wcc,len,xerr);
errno = EPIPE;
if( lSINGLEP() ){
LE("-- NO Emulating SIGPIPE: send(%d/%d/%d) err=%d",wcc1,wcc,len,xerr);
}else
raise(SIGPIPE);
}
break;
}
wcc += wcc1;
rem -= wcc1;
}
return wcc;
}
typedef union {
struct sockaddr_in _sin;
char _sab[64]; /**/
} VSAddr;
typedef struct sockaddr *SAP;
/* vsocket.h */
int VSA_atosa(VSAddr *sa,int port,PCStr(addr));
int VSA_port(VSAddr *sap);
const char *VSA_ntoa(VSAddr *sap);
char *VSA_xtoap(VSAddr *sa,PVStr(buf),int siz);
int start_service(int ac,const char *av[]);
void WINthread();
void setBinaryIO();
#define MAXHANDLE 4096
#define MIS 8 /* the max. number of inherited sockets */
int fd2handle(int fd){
return _get_osfhandle(fd);
}
int handle2fd(int oh){
return _open_osfhandle(oh,0);
}
/*
int duposf2(int src,int dst){
HANDLE sh,dh;
sh = (HANDLE)_get_osfhandle(src);
dh = (HANDLE)_get_osfhandle(dst);
nh = (HANDLE)duphandle(0,dh,0,0,1);
DuplicateHandle(SELF(),sh,SELF(),&dh,0,1,DUPLICATE_SAME_ACCESS);
retrun (int)nh;
}
*/
/*
FILE *_fdopen(int fd,const char *mode){
short wmode[32];
FILE *fp;
int mi;
for( mi = 0; mode[mi] && mi < elnumof(wmode)-1; mi++ )
wmode[mi] = mode[mi];
wmode[mi] = 0;
fp = _wfdopen(fd,(const unsigned short*)wmode);
return fp;
}
*/
static int __write(int fd,PCStr(buf),int size)
{ int oh;
int ok;
unsigned long wcc;
oh = _get_osfhandle(fd);
ok = WriteFile((HANDLE)oh,buf,size,&wcc,NULL);
return wcc;
}
static int __read(int fd,char *buf,int size)
{ int oh;
int ok;
unsigned long rcc;
oh = _get_osfhandle(fd);
ok = ReadFile((HANDLE)oh,buf,size,&rcc,NULL);
return rcc;
}
/*######## CLOCK ########*/
int gettimeofday(struct timeval *tp, struct timezone *tzp)
{ struct timeb timeb;
ftime(&timeb);
tp->tv_sec = timeb.time;
tp->tv_usec = timeb.millitm * 1000;
LW("gettimeofday(%x,%x) = [%d,%d]",tp,tzp,tp->tv_sec,tp->tv_usec);
return 0;
}
/*######## SIGNAL ########*/
#undef sigsetmask
int sigsetmask(int mask){
/*
LV("sigsetmask() not supported");
*/
return -1;
}
#undef sigblock
int sigblock(int mask){
/*
LV("sigblock() not supported");
*/
return -1;
}
int killWin(int pid,int sig){
int rcode = -9;
HANDLE ph;
ph = OpenProcess(PROCESS_ALL_ACCESS,0,pid);
if( ph != INVALID_HANDLE_VALUE ){
rcode = kill((int)ph,sig);
CloseHandle(ph);
}
return rcode;
}
int kill(int pid,int sig){
HANDLE ph;
unsigned long int xcode;
int ok;
if( sig == 0 ){
errno = 0;
if( isWindowsCE() ){
if( pid == getpid() )
return 0;
fprintf(stderr,"----WinCE kill(%X,%d)\n",pid,sig);fflush(stderr);
return 0;
}
ph = OpenProcess(PROCESS_QUERY_INFORMATION,0,pid);
if( ph == NULL ){
errno = ESRCH;
return -1;
}
xcode = -1;
ok = GetExitCodeProcess(ph,&xcode);
CloseHandle(ph);
if( ok && xcode != STILL_ACTIVE ){
LV("kill(%d)=-1 the process did exit(%d)",pid,xcode);
errno = ESRCH;
return -2;
}
return 0;
}
ph = (HANDLE)pid;
/* it should be ph = OpenProcess(pid), but because the pid
* argument given is a process handle which is got at spawnvp()...
*/
if( !GetExitCodeProcess(ph,&xcode) )
{ LE("kill(%d,%d) = -1, failed GetExitCodeProcess()",pid,sig);
return -1;
}
if( xcode != STILL_ACTIVE )
{ LE("kill(%d,%d) = -1, not active (xcode=%d)",pid,sig,xcode);
return -1;
}
if( sig == SIGTERM ){
if( TerminateProcess(ph,0) )
return 0;
else{
LE("kill(%d,%d) = -1, failed TerminateProcess()",pid,sig);
return -1;
}
}
LE("kill(%d,%d) not supported",pid,sig);
return -1;
}
unsigned int alarm(unsigned int sec){
LE("alarm(%d) not supported",sec);
return 0;
}
void sleep(unsigned int sec){
LW("sleep(%d)",sec);
_sleep(sec*1000);
}
/*######## USER and GROUP ########*/
#include "passwd.h"
static struct passwd passwd;
void setpwent(){
LV("setpwent()");
}
void endpwent(){
LV("endpwent()");
}
struct passwd *getpwuid(int uid){
LV("getpwuid(%d)",uid);
passwd.pw_name = "windows";
passwd.pw_passwd = "";
passwd.pw_uid = 0;
passwd.pw_gid = 0;
passwd.pw_quota = 0;
passwd.pw_comment = "";
passwd.pw_gecos = "Windows";
passwd.pw_dir = "/users/default";
passwd.pw_shell = "";
return &passwd;
}
int getgrnam(PCStr(name))
{
LV("getgrnam(%s)",name);
return 0;
}
int getpwnam(PCStr(name))
{
LV("getpwnam(%s)",name);
return 0;
}
int getgrgid(int gid){
LV("getgrgid(%d)",gid);
return 0;
}
char *getlogin(void){
return 0;
}
int setlogin(const char *name){
return -1;
}
/* ######## PROCESS OWNER ######## */
int getegid(){
LW("getegid() = 0");
return 0;
}
int geteuid(){
LW("geteuid() = 0");
return 0;
}
int getuid(){
LW("getuid() = 0");
return 0;
}
int getgid(){
LW("getgid() = 0");
return 0;
}
int setuid(int uid){
int rcode;
if( uid == 0 )
rcode = 0;
else rcode = -1;
LW("setuid(%d) = %d",uid,rcode);
return rcode;
}
int setgid(int gid){
int rcode;
if( gid == 0 )
rcode = 0;
else rcode = -1;
LW("setgid(%d) = %d",gid,rcode);
return rcode;
}
int initgroups(const char *user,int group){
LW("initgroups() = -1");
return -1;
}
/*######## FILE ########*/
#include <WINDOWS.H>
#include <WINBASE.H>
#if isWindowsCE()
#include "wince.h"
#endif
static HANDLE _SELF;
static HANDLE SELF()
{
if( _SELF == 0 ){
_SELF = OpenProcess(PROCESS_ALL_ACCESS,0,getpid());
LV("PID=%d SELF_HANDLE=%d",getpid(),_SELF);
}
return _SELF;
}
int duphandle(HANDLE sproc,HANDLE shandle,HANDLE dproc,int closesrc,int noinherit)
{ HANDLE dhandle;
DWORD access;
BOOL inherit;
DWORD options;
access = 0;
inherit = !noinherit; /* FALSE may be good for some sockets... */
options = DUPLICATE_SAME_ACCESS;
if( closesrc )
options |= DUPLICATE_CLOSE_SOURCE;
if( sproc == NULL ) sproc = SELF();
if( dproc == NULL ) dproc = SELF();
dhandle = NULL;
DuplicateHandle(sproc,shandle,dproc,&dhandle,
access,inherit,options);
if( dhandle == NULL )
LT("DUPHANDLE: %d,%d => %d,%d",sproc,shandle,dproc,dhandle);
return (int)dhandle;
}
int duphandlei(int shandle,int closesrc,int noinherit){
return duphandle(0,(HANDLE)shandle,0,closesrc,noinherit);
}
int WITH_symlink(){ return 1; }
int symlink(PCStr(dst),PCStr(src))
{ HRESULT Rc;
WCHAR wsrc[MAX_PATH]; /**/
IShellLink* Sl;
IPersistFile* pf;
int rcode = -1;
CStr(dstx,MAX_PATH);
CoInitialize(NULL);
MultiByteToWideChar(CP_ACP,0,src,-1,wsrc,MAX_PATH);
Sl = 0;
Rc = CoCreateInstance(CLSID_ShellLink,NULL,
CLSCTX_INPROC_SERVER,IID_IShellLink,(LPVOID *)&Sl);
if( FAILED(Rc) )
goto EXIT;
if( Sl == 0 )
goto EXIT;
if( strchr(dst,':') == 0 ){
if( getcwd(dstx,sizeof(dstx)) == dstx )
if( dstx[0] != 0 && dstx[1] == ':' )
{
Xstrcpy(DVStr(dstx,2),dst);
dst = dstx;
}
}
Rc = Sl->SetPath(dst);
Sl->SetDescription("");
Rc = Sl->QueryInterface(IID_IPersistFile,(LPVOID*)&pf);
if( SUCCEEDED(Rc) ){
Rc = pf->Save(wsrc,FALSE);
pf->Release();
rcode = 0;
}
Sl->Release();
EXIT: CoUninitialize();
return rcode;
}
int File_is(PCStr(path));
int File_size(PCStr(path));
int File_mtime(PCStr(path));
int readlink(PCStr(src),char dst[],unsigned int siz)
{ HRESULT Rc;
WCHAR wsrc[MAX_PATH]; /**/
IShellLink* Sl;
IPersistFile* Pf;
WIN32_FIND_DATA Fd;
int rcode = -1;
if( File_size(src) <= 0 && File_mtime(src) <= 0 ){
/* 9.9.1 Load() can freeze on device file like "con" */
LV("ERROR readlink(%s) is=%d siz=%d mtm=%d",src,
File_is(src),File_size(src),File_mtime(src));
return -1;
}
CoInitialize(NULL);
MultiByteToWideChar(CP_ACP,0,src,-1,wsrc,MAX_PATH);
*dst = 0;
Sl = 0;
Rc = CoCreateInstance(CLSID_ShellLink,NULL,
CLSCTX_INPROC_SERVER,IID_IShellLink,(LPVOID *)&Sl);
if( FAILED(Rc) )
goto EXIT;
if( Sl == 0 )
goto EXIT;
Rc = Sl->QueryInterface(IID_IPersistFile,(void**)&Pf);
if( SUCCEEDED(Rc) ){
Rc = Pf->Load(wsrc,STGM_READ);
if( SUCCEEDED(Rc) ){
Rc = Sl->GetPath(dst,siz,
(WIN32_FIND_DATA *)&Fd,SLGP_SHORTPATH);
if( SUCCEEDED(Rc) )
rcode = 0;
}
Pf->Release();
}
Sl->Release();
EXIT: CoUninitialize();
if( rcode != 0 ){
}
return rcode;
}
/*######## SOCKET ########*/
static WORD wVersionRequested;
static WSADATA wsaData;
static struct {
int ws_qver;
int ws_code;
int ws_errno;
} wsaStat;
static int _nullsock = -1;
#undef socket
#undef accept
static int setSockInh(PCStr(wh),int sock){
int dsock;
int on;
int ok1,ok2;
int flag;
if( lDOSOCKINH() ) on = 1; else
if( lNOSOCKINH() ) on = 0; else
if( lWOSOCKINH() ) on = 0; else{
SetHandleInformation((HANDLE)sock,HANDLE_FLAG_INHERIT,
HANDLE_FLAG_INHERIT);
return sock;
}
flag = on ? HANDLE_FLAG_INHERIT : 0;
/*
ok1 = SetHandleInformation((HANDLE)dsock,flag,on);
*/
ok1 = SetHandleInformation((HANDLE)sock,flag,on);
if( ok2 = DuplicateHandle(GetCurrentProcess(),(HANDLE)sock,
GetCurrentProcess(),(HANDLE*)&dsock,0,on,DUPLICATE_SAME_ACCESS)
){
closesocket(sock);
}else{
dsock = sock;
}
LV("--Eis %s INHERIT[%d]%d = %d %d",wh,sock,on,ok1,ok2);
return dsock;
}
static int socketX(int dom,int type,int proto){
int sock;
sock = socket(dom,type,proto);
if( 0 <= sock ){
sock = setSockInh("socket",sock);
}
return sock;
}
static int acceptX(int sock,SAP addr,int *len){
int csock;
csock = accept(sock,addr,len);
if( 0 <= csock ){
csock = setSockInh("accept",csock);
}
return csock;
}
#define socket socketX
#define accept acceptX
void socket_init(){
int err;
int qvmaj,qvmin;
if( wsaData.szDescription[0] != 0 )
return;
qvmaj = 1;
qvmin = 0;
sscanf(WinSockVer,"%d.%d",&qvmaj,&qvmin);
wVersionRequested = MAKEWORD(qvmaj,qvmin);
/*
wVersionRequested = MAKEWORD(1,1);
*/
err = WSAStartup(wVersionRequested,&wsaData);
wsaStat.ws_qver = wVersionRequested;
wsaStat.ws_code = err;
wsaStat.ws_errno = WSAGetLastError();
_nullsock = socket(AF_INET,SOCK_STREAM,0);
}
int nullsock(){
return _nullsock;
}
#ifndef UNDER_CE
static void dumpWSAstat()
{ int hi,nh,nhi,nsh,nshi,len,type;
CStr(sockets,MAXHANDLE*8);
refQStr(sp,sockets); /**/
unsigned long int flags;
if( LOGLEVEL < 4 )
return;
LV("WinSock option \"-WSAV:%s\" ReqVer:%x Result:%x Errno:%d",
WinSockVer,wsaStat.ws_qver,wsaStat.ws_code,wsaStat.ws_errno);
LV("Version:%x HighVersion:%x Description:%s",
wsaData.wVersion,wsaData.wHighVersion,wsaData.szDescription);
LV("SystemStatus:%s MaxSockets:%d MaxUdpDg:%d",
wsaData.szSystemStatus,wsaData.iMaxSockets,wsaData.iMaxUdpDg);
if( wsaData.lpVendorInfo )
LV("VenderInfo:%s",wsaData.lpVendorInfo);
nh = nsh = nhi = nshi = 0;
for( hi = 0; hi < MAXHANDLE; hi++ ){
flags = 0;
if( GetHandleInformation((HANDLE)hi,&flags) == 0 )
continue; /* not available on Win95 */
nh++;
if( flags & HANDLE_FLAG_INHERIT )
nhi++;
if( hi < 128 ){
/* getsockopt() blocks for lower handle ??? */
continue;
}
len = sizeof(type);
if( getsockopt(hi,SOL_SOCKET,SO_TYPE,(char*)&type,&len) == 0 ){
nsh++;
if( flags & HANDLE_FLAG_INHERIT )
nshi++;
sprintf(sp," %d",hi);
sp += strlen(sp);
if( type != 1 ){
sprintf(sp,"/%d",type);
sp += strlen(sp);
}
if( (flags & HANDLE_FLAG_INHERIT) == 0 ){
sprintf(sp,"#");
sp += strlen(sp);
}
}
}
setVStrEnd(sp,0);
if( *sockets )
LV("Sockets(%d/%d/%d:%d/%d):%s",nshi,nsh,FD_SETSIZE,nhi,nh,sockets);
}
#else
static void dumpWSAstat(){
}
#endif
static void sockInfo()
{
if( getppid() == 0 ){
LT("WINSOCK INFO.");
LT("Desc: %s",wsaData.szDescription);
LT("Stat: %s",wsaData.szSystemStatus);
LT("Maxs: %d, Vend: %s",wsaData.iMaxSockets,wsaData.lpVendorInfo);
}
}
static int ISSOCK(int sock)
{ int len,type;
len = sizeof(type);
if( getsockopt(sock,SOL_SOCKET,SO_TYPE,(char*)&type,&len) == 0 )
return 1 <= type;
return 0;
}
struct hostent *gethostbyname2(const char *name,int af){
return 0;
}
static int NO_SOCKOPEN = 1;
/* bad if this value is zero in CHARCODE filter from FTP/HTTP on WindowsNT
* where the client SOCKET is inherited twice...
*/
int SocketOf_FL(const char *F,int L,int fd);
#define SocketOf(fd) SocketOf_FL(__FILE__,__LINE__,fd)
#define USE_SOSMAP 1
#if isWindowsCE() || USE_SOSMAP /* ---{ */
#define MAXOSF 256
typedef struct {
char x_act;
char x_typ;
int x_idx;
int x_val;
} IdxVal;
static struct {
int cs_init;
CRITICAL_SECTION cs;
int lock;
IdxVal openosfx[MAXOSF];
int cs_max;
} SockOsf;
#define SOS_GET 0
#define SOS_SET 1
#define SOS_INC 2
#define SOS_DEC 3
#define SOS_DEL 4
static const char *op_syms[] = {"GET", "SET", "INC", "DEC", "DEL"};
#define TY_OSF 1
#define TY_DUP 2
#define TY_CNT 3
static const char *ty_syms[] = { "?","OSF","DUP","CNT" };
#define SOS_GetOsfh(fd) idxval(TY_OSF,__LINE__,SOS_GET,fd,0)
#define SOS_SetOsfh(fd,f) idxval(TY_OSF,__LINE__,SOS_SET,fd,f)
#define SOS_DelOsfh(fd) idxval(TY_OSF,__LINE__,SOS_DEL,fd,0)
#define SOS_GetDuph(fd) idxval(TY_DUP,__LINE__,SOS_GET,fd,0)
#define SOS_SetDuph(fd,f) idxval(TY_DUP,__LINE__,SOS_SET,fd,f)
#define SOS_DelDuph(fd) idxval(TY_DUP,__LINE__,SOS_DEL,fd,0)
#define SOS_GetRcnt(sock) idxval(TY_CNT,__LINE__,SOS_GET,sock,0)
#define SOS_IncRcnt(sock) idxval(TY_CNT,__LINE__,SOS_INC,sock,1)
#define SOS_DecRcnt(sock) idxval(TY_CNT,__LINE__,SOS_DEC,sock,1)
#define SOS_DelRcnt(sock) idxval(TY_CNT,__LINE__,SOS_DEL,sock,0)
int numsocks(int *nmaxp){
int fi;
IdxVal *iv = SockOsf.openosfx;
IdxVal *iv1;
int nact = 0;
for( fi = 0; fi < MAXOSF; fi++ ){
iv1 = &iv[fi];
if( iv1->x_act ){
nact++;
}
}
if( nmaxp ) *nmaxp = SockOsf.cs_max;
return nact;
}
int getthreadid();
static const IdxVal NullIdxVal;
static int idxval(int typ,int L,int set,int idx,int val){
int fi;
IdxVal *iv = SockOsf.openosfx;
IdxVal *iv1;
int nact = 0;
int rval = 0;
IdxVal *firstfree = 0;
if( SockOsf.cs_init == 0 ){
InitializeCriticalSection(&SockOsf.cs);
SockOsf.cs_init++;
}
EnterCriticalSection(&SockOsf.cs);
if( 1 < SockOsf.lock++ ){
int li;
for( li = 0; li < 100; li++ ){
fprintf(stderr,"--idxval--locked %d\n",SockOsf.lock);
_sleep(100);
if( SockOsf.lock == 1 ){
break;
}
}
}
for( fi = 0; fi < MAXOSF; fi++ ){
iv1 = &iv[fi];
if( iv1->x_act ){
nact++;
if( SockOsf.cs_max < fi ){
SockOsf.cs_max = fi;
}
if( iv1->x_typ == typ && iv1->x_idx == idx ){
switch( set ){
case SOS_GET:
case SOS_SET:
case SOS_INC:
case SOS_DEC:
case SOS_DEL:
goto FOUND;
if( set != SOS_GET )
fprintf(stderr,"--HIT %s windows.c:%d (%d/%2d) %s[%d]=%d %d\n",
op_syms[set],L,nact,fi,ty_syms[typ],idx,iv1->x_val,val);
}
}
}else
if( set == SOS_GET || set == SOS_DEL ){
}else
if( set == SOS_SET || set == SOS_INC || set == SOS_DEC ){
if( firstfree == 0 ){
firstfree = iv1;
}
}
}
if( firstfree != 0 ){
iv1 = firstfree;
if( set == SOS_SET || set == SOS_INC ){
iv1->x_act = 99;
iv1->x_typ = typ;
iv1->x_idx = idx;
/*
fprintf(stderr,"--NEW %s windows.c:%d (%d/%2d) %s[%d] %d\n",
op_syms[set],L,nact,fi,ty_syms[typ],idx,val);
*/
goto FOUND;
}else
if( set == SOS_DEC ){
// dangling ?
}
}
if( set == SOS_INC ){
fprintf(stderr,"--MIS %s windows.c:%d (%d/%2d) %s[%d] ???\n",
op_syms[set],L,nact,fi,ty_syms[typ],idx);
{
int i;
for( i = 0; i < MAXOSF; i++){
iv1 = &iv[fi];
if( iv1->x_act )
fprintf(stderr,"sosf[%3d] act=%X %s %d %d\n",i,
iv1->x_act,ty_syms[iv1->x_typ],iv1->x_idx,iv1->x_val);
}
}
}
rval = 0;
goto EXIT;
FOUND:
switch( set ){
case SOS_GET: break;
case SOS_SET: iv1->x_val = val; break;
case SOS_INC: iv1->x_val += 1; break;
case SOS_DEC: iv1->x_val -= 1;
if( iv1->x_val == 0 ){
/*
fprintf(stderr,"--del %d windows.c:%d (%d/%2d) %s[%d] %d\n",
set,L,nact,fi,wh,idx,val);
*/
*iv1 = NullIdxVal;
}
break;
case SOS_DEL:
/*
fprintf(stderr,"--DEL %d windows.c:%d (%d/%2d) %s[%d] %d\n",
set,L,nact,fi,wh,idx,val);
*/
*iv1 = NullIdxVal;
break;
}
rval = iv1->x_val;
EXIT:
SockOsf.lock--;
LeaveCriticalSection(&SockOsf.cs);
if(0)
if( set != SOS_GET )
for( fi = 0; fi < MAXOSF; fi++ ){
iv1 = &iv[fi];
if( iv1->x_act )
fprintf(stderr,"++[%2d/%2d] (%s %s[%d]) act=%2d typ=%s[idx=%2d]=[val=%2d]\n",
fi,MAXOSF,op_syms[set],ty_syms[typ],idx,
iv1->x_act,ty_syms[iv1->x_typ],iv1->x_idx,iv1->x_val);
}
return rval;
}
static int SOS_Next(int *idx,int *val,int sock,int typ){
int ix;
for( ix = *idx + 1; ix < MAXOSF; ix++ ){
if( SockOsf.openosfx[ix].x_act
&& SockOsf.openosfx[ix].x_typ == typ
&& SockOsf.openosfx[ix].x_val == sock ){
*idx = ix;
*val = SockOsf.openosfx[ix].x_idx;
return 1;
}
}
return 0;
}
#define SOS_NextDuph(i,v,s) SOS_Next(i,v,s,TY_DUP)
#define SOS_NextOsfh(i,v,s) SOS_Next(i,v,s,TY_OSF)
#else /* ---}{--- */
static short open_osfhandle[MAXHANDLE]; /* get_osfhandle(fd) emulation */
static short isdup_handles[MAXHANDLE];
static short opened_sockcnt[MAXHANDLE];
#define MAXOSF MAXHANDLE
#define BADRANGE(f) ((f)<0||MAXHANDLE<=(f))?0
#define SOS_GetOsfh(fd) (BADRANGE(fd):open_osfhandle[fd])
#define SOS_SetOsfh(fd,f) (BADRANGE(fd):open_osfhandle[fd] = f)
#define SOS_DelOsfh(fd) (BADRANGE(fd):open_osfhandle[fd] = 0)
#define SOS_GetDuph(fd) (BADRANGE(fd):isdup_handles[fd])
#define SOS_SetDuph(fd,f) (BADRANGE(fd):isdup_handles[fd] = f)
#define SOS_DelDuph(fd) (BADRANGE(fd):isdup_handles[fd] = 0)
#define SOS_GetRcnt(sock) (BADRANGE(sock):opened_sockcnt[sock])
#define SOS_IncRcnt(sock) (BADRANGE(sock):opened_sockcnt[sock] += 1)
#define SOS_DecRcnt(sock) (BADRANGE(sock):opened_sockcnt[sock] -= 1)
#define SOS_DelRcnt(sock) (BADRANGE(sock):opened_sockcnt[sock] = 0)
static int SOS_Next(int *idx,int *val,int sock,short *iv){
int ix;
for( ix = *idx + 1; ix < MAXHANDLE; ix++ ){
if( iv[ix] == sock ){
*idx = ix;
*val = ix;
return 1;
}
}
return 0;
}