forked from Alexpux/Cygwin
-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathsocket_local.cc
1691 lines (1546 loc) · 45.5 KB
/
socket_local.cc
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
/* fhandler_socket_local.cc.
See fhandler.h for a description of the fhandler classes.
This file is part of Cygwin.
This software is a copyrighted work licensed under the terms of the
Cygwin license. Please consult the file "CYGWIN_LICENSE" for
details. */
#define __INSIDE_CYGWIN_NET__
#define USE_SYS_TYPES_FD_SET
#include "winsup.h"
/* 2014-04-24: Current Mingw headers define sockaddr_in6 using u_long (8 byte)
because a redefinition for LP64 systems is missing. This leads to a wrong
definition and size of sockaddr_in6 when building with winsock headers.
This definition is also required to use the right u_long type in subsequent
function calls. */
#undef u_long
#define u_long __ms_u_long
#include "ntsecapi.h"
#include <w32api/ws2tcpip.h>
#include <w32api/mswsock.h>
#include <unistd.h>
#include <asm/byteorder.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/param.h>
#include <sys/statvfs.h>
#include <cygwin/acl.h>
#include "cygerrno.h"
#include "path.h"
#include "fhandler.h"
#include "dtable.h"
#include "cygheap.h"
#include "wininfo.h"
#include "ntdll.h"
extern "C" {
int sscanf (const char *, const char *, ...);
} /* End of "C" section */
#define ASYNC_MASK (FD_READ|FD_WRITE|FD_OOB|FD_ACCEPT|FD_CONNECT)
#define EVENT_MASK (FD_READ|FD_WRITE|FD_OOB|FD_ACCEPT|FD_CONNECT|FD_CLOSE)
#define LOCK_EVENTS \
if (wsock_mtx && \
WaitForSingleObject (wsock_mtx, INFINITE) != WAIT_FAILED) \
{
#define UNLOCK_EVENTS \
ReleaseMutex (wsock_mtx); \
}
static inline mode_t
adjust_socket_file_mode (mode_t mode)
{
/* Kludge: Don't allow to remove read bit on socket files for
user/group/other, if the accompanying write bit is set. It would
be nice to have exact permissions on a socket file, but it's
necessary that somebody able to access the socket can always read
the contents of the socket file to avoid spurious "permission
denied" messages. */
return mode | ((mode & (S_IWUSR | S_IWGRP | S_IWOTH)) << 1);
}
/* cygwin internal: map sockaddr into internet domain address */
int
get_inet_addr_local (const struct sockaddr *in, int inlen,
struct sockaddr_storage *out, int *outlen,
int *type = NULL, int *secret = NULL)
{
int secret_buf [4];
int* secret_ptr = (secret ? : secret_buf);
/* Check for abstract socket. These are generated for AF_LOCAL datagram
sockets in recv_internal, to allow a datagram server to use sendto
after recvfrom. */
if (inlen >= (int) sizeof (in->sa_family) + 7
&& in->sa_data[0] == '\0' && in->sa_data[1] == 'd'
&& in->sa_data[6] == '\0')
{
struct sockaddr_in addr;
addr.sin_family = AF_INET;
sscanf (in->sa_data + 2, "%04hx", &addr.sin_port);
addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
*outlen = sizeof addr;
memcpy (out, &addr, *outlen);
return 0;
}
path_conv pc (in->sa_data, PC_SYM_FOLLOW);
if (pc.error)
{
set_errno (pc.error);
return SOCKET_ERROR;
}
if (!pc.exists ())
{
set_errno (ENOENT);
return SOCKET_ERROR;
}
/* Do NOT test for the file being a socket file here. The socket file
creation is not an atomic operation, so there is a chance that socket
files which are just in the process of being created are recognized
as non-socket files. To work around this problem we now create the
file with all sharing disabled. If the below NtOpenFile fails
with STATUS_SHARING_VIOLATION we know that the file already exists,
but the creating process isn't finished yet. So we yield and try
again, until we can either open the file successfully, or some error
other than STATUS_SHARING_VIOLATION occurs.
Since we now don't know if the file is actually a socket file, we
perform this check here explicitely. */
NTSTATUS status;
HANDLE fh;
OBJECT_ATTRIBUTES attr;
IO_STATUS_BLOCK io;
pc.get_object_attr (attr, sec_none_nih);
do
{
status = NtOpenFile (&fh, GENERIC_READ | SYNCHRONIZE, &attr, &io,
FILE_SHARE_VALID_FLAGS,
FILE_SYNCHRONOUS_IO_NONALERT
| FILE_OPEN_FOR_BACKUP_INTENT
| FILE_NON_DIRECTORY_FILE);
if (status == STATUS_SHARING_VIOLATION)
{
/* While we hope that the sharing violation is only temporary, we
also could easily get stuck here, waiting for a file in use by
some greedy Win32 application. Therefore we should never wait
endlessly without checking for signals and thread cancel event. */
pthread_testcancel ();
if (cygwait (NULL, cw_nowait, cw_sig_eintr) == WAIT_SIGNALED
&& !_my_tls.call_signal_handler ())
{
set_errno (EINTR);
return SOCKET_ERROR;
}
yield ();
}
else if (!NT_SUCCESS (status))
{
__seterrno_from_nt_status (status);
return SOCKET_ERROR;
}
}
while (status == STATUS_SHARING_VIOLATION);
/* Now test for the SYSTEM bit. */
FILE_BASIC_INFORMATION fbi;
status = NtQueryInformationFile (fh, &io, &fbi, sizeof fbi,
FileBasicInformation);
if (!NT_SUCCESS (status))
{
__seterrno_from_nt_status (status);
return SOCKET_ERROR;
}
if (!(fbi.FileAttributes & FILE_ATTRIBUTE_SYSTEM))
{
NtClose (fh);
set_errno (EBADF);
return SOCKET_ERROR;
}
/* Eventually check the content and fetch the required information. */
char buf[128];
memset (buf, 0, sizeof buf);
status = NtReadFile (fh, NULL, NULL, NULL, &io, buf, 128, NULL, NULL);
NtClose (fh);
if (NT_SUCCESS (status))
{
struct sockaddr_in sin;
char ctype;
sin.sin_family = AF_INET;
if (strncmp (buf, SOCKET_COOKIE, strlen (SOCKET_COOKIE)))
{
set_errno (EBADF);
return SOCKET_ERROR;
}
sscanf (buf + strlen (SOCKET_COOKIE), "%hu %c %08x-%08x-%08x-%08x",
&sin.sin_port,
&ctype,
secret_ptr, secret_ptr + 1, secret_ptr + 2, secret_ptr + 3);
sin.sin_port = htons (sin.sin_port);
sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
memcpy (out, &sin, sizeof sin);
*outlen = sizeof sin;
if (type)
*type = (ctype == 's' ? SOCK_STREAM :
ctype == 'd' ? SOCK_DGRAM
: 0);
return 0;
}
__seterrno_from_nt_status (status);
return SOCKET_ERROR;
}
/* There's no DLL which exports the symbol WSARecvMsg. One has to call
WSAIoctl as below to fetch the function pointer. Why on earth did the
MS developers decide not to export a normal symbol for these extension
functions? */
inline int
get_ext_funcptr (SOCKET sock, void *funcptr)
{
DWORD bret;
const GUID guid = WSAID_WSARECVMSG;
return WSAIoctl (sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
(void *) &guid, sizeof (GUID), funcptr, sizeof (void *),
&bret, NULL, NULL);
}
fhandler_socket_local::fhandler_socket_local () :
fhandler_socket_wsock (),
sun_path (NULL),
peer_sun_path (NULL),
status ()
{
}
fhandler_socket_local::~fhandler_socket_local ()
{
if (sun_path)
cfree (sun_path);
if (peer_sun_path)
cfree (peer_sun_path);
}
int
fhandler_socket_local::socket (int af, int type, int protocol, int flags)
{
SOCKET sock;
int ret;
if (type != SOCK_STREAM && type != SOCK_DGRAM)
{
set_errno (EINVAL);
return -1;
}
if (protocol != 0)
{
set_errno (EPROTONOSUPPORT);
return -1;
}
sock = ::socket (AF_INET, type, protocol);
if (sock == INVALID_SOCKET)
{
set_winsock_errno ();
return -1;
}
ret = set_socket_handle (sock, af, type, flags);
if (ret < 0)
::closesocket (sock);
return ret;
}
int
fhandler_socket_local::socketpair (int af, int type, int protocol, int flags,
fhandler_socket *_fh_out)
{
SOCKET insock = INVALID_SOCKET;
SOCKET outsock = INVALID_SOCKET;
SOCKET sock = INVALID_SOCKET;
struct sockaddr_in sock_in, sock_out;
int len;
fhandler_socket_local *fh_out = reinterpret_cast<fhandler_socket_local *>
(_fh_out);
if (type != SOCK_STREAM && type != SOCK_DGRAM)
{
set_errno (EINVAL);
return -1;
}
if (protocol != 0)
{
set_errno (EPROTONOSUPPORT);
return -1;
}
/* create listening socket */
sock = ::socket (AF_INET, type, 0);
if (sock == INVALID_SOCKET)
{
set_winsock_errno ();
goto err;
}
/* bind to unused port */
sock_in.sin_family = AF_INET;
sock_in.sin_port = 0;
sock_in.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
if (::bind (sock, (struct sockaddr *) &sock_in, sizeof (sock_in)) < 0)
{
set_winsock_errno ();
goto err;
}
/* fetch socket name */
len = sizeof (sock_in);
if (::getsockname (sock, (struct sockaddr *) &sock_in, &len) < 0)
{
set_winsock_errno ();
goto err;
}
/* on stream sockets, create listener */
if (type == SOCK_STREAM && ::listen (sock, 2) < 0)
{
set_winsock_errno ();
goto err;
}
/* create connecting socket */
outsock = ::socket (AF_INET, type, 0);
if (outsock == INVALID_SOCKET)
{
set_winsock_errno ();
goto err;
}
/* on datagram sockets, bind connecting socket */
if (type == SOCK_DGRAM)
{
sock_out.sin_family = AF_INET;
sock_out.sin_port = 0;
sock_out.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
if (::bind (outsock, (struct sockaddr *) &sock_out,
sizeof (sock_out)) < 0)
{
set_winsock_errno ();
goto err;
}
/* ...and fetch name */
len = sizeof (sock_out);
if (::getsockname (outsock, (struct sockaddr *) &sock_out, &len) < 0)
{
set_winsock_errno ();
goto err;
}
}
sock_in.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
if (type == SOCK_DGRAM)
sock_out.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
/* connect */
if (::connect (outsock, (struct sockaddr *) &sock_in, sizeof (sock_in)) < 0)
{
set_winsock_errno ();
goto err;
}
if (type == SOCK_STREAM)
{
/* on stream sockets, accept connection and close listener */
len = sizeof (sock_in);
insock = ::accept (sock, (struct sockaddr *) &sock_in, &len);
if (insock == INVALID_SOCKET)
{
set_winsock_errno ();
goto err;
}
::closesocket (sock);
}
else
{
/* on datagram sockets, connect vice versa */
if (::connect (sock, (struct sockaddr *) &sock_out,
sizeof (sock_out)) < 0)
{
set_winsock_errno ();
goto err;
}
insock = sock;
}
sock = INVALID_SOCKET;
/* postprocessing */
connect_state (connected);
fh_out->connect_state (connected);
if (af == AF_LOCAL && type == SOCK_STREAM)
{
af_local_set_sockpair_cred ();
fh_out->af_local_set_sockpair_cred ();
}
if (set_socket_handle (insock, af, type, flags) < 0
|| fh_out->set_socket_handle (outsock, af, type, flags) < 0)
goto err;
return 0;
err:
if (sock != INVALID_SOCKET)
::closesocket (sock);
if (insock != INVALID_SOCKET)
::closesocket (insock);
if (outsock != INVALID_SOCKET)
::closesocket (outsock);
return -1;
}
void
fhandler_socket_local::af_local_set_sockpair_cred ()
{
sec_pid = sec_peer_pid = getpid ();
sec_uid = sec_peer_uid = geteuid ();
sec_gid = sec_peer_gid = getegid ();
}
void
fhandler_socket_local::af_local_setblocking (bool &async, bool &nonblocking)
{
async = async_io ();
nonblocking = is_nonblocking ();
if (async)
{
WSAAsyncSelect (get_socket (), winmsg, 0, 0);
WSAEventSelect (get_socket (), wsock_evt, EVENT_MASK);
}
set_nonblocking (false);
async_io (false);
}
void
fhandler_socket_local::af_local_unsetblocking (bool async, bool nonblocking)
{
if (nonblocking)
set_nonblocking (true);
if (async)
{
WSAAsyncSelect (get_socket (), winmsg, WM_ASYNCIO, ASYNC_MASK);
async_io (true);
}
}
bool
fhandler_socket_local::af_local_recv_secret ()
{
int out[4] = { 0, 0, 0, 0 };
int rest = sizeof out;
char *ptr = (char *) out;
while (rest > 0)
{
int ret = recvfrom (ptr, rest, 0, NULL, NULL);
if (ret <= 0)
break;
rest -= ret;
ptr += ret;
}
if (rest == 0)
{
debug_printf ("Received af_local secret: %08x-%08x-%08x-%08x",
out[0], out[1], out[2], out[3]);
if (out[0] != connect_secret[0] || out[1] != connect_secret[1]
|| out[2] != connect_secret[2] || out[3] != connect_secret[3])
{
debug_printf ("Receiving af_local secret mismatch");
return false;
}
}
else
debug_printf ("Receiving af_local secret failed");
return rest == 0;
}
bool
fhandler_socket_local::af_local_send_secret ()
{
int rest = sizeof connect_secret;
char *ptr = (char *) connect_secret;
while (rest > 0)
{
int ret = sendto (ptr, rest, 0, NULL, 0);
if (ret <= 0)
break;
rest -= ret;
ptr += ret;
}
debug_printf ("Sending af_local secret %s", rest == 0 ? "succeeded"
: "failed");
return rest == 0;
}
bool
fhandler_socket_local::af_local_recv_cred ()
{
struct ucred out = { (pid_t) 0, (uid_t) -1, (gid_t) -1 };
int rest = sizeof out;
char *ptr = (char *) &out;
while (rest > 0)
{
int ret = recvfrom (ptr, rest, 0, NULL, NULL);
if (ret <= 0)
break;
rest -= ret;
ptr += ret;
}
if (rest == 0)
{
debug_printf ("Received eid credentials: pid: %d, uid: %d, gid: %d",
out.pid, out.uid, out.gid);
sec_peer_pid = out.pid;
sec_peer_uid = out.uid;
sec_peer_gid = out.gid;
}
else
debug_printf ("Receiving eid credentials failed");
return rest == 0;
}
bool
fhandler_socket_local::af_local_send_cred ()
{
struct ucred in = { sec_pid, sec_uid, sec_gid };
int rest = sizeof in;
char *ptr = (char *) ∈
while (rest > 0)
{
int ret = sendto (ptr, rest, 0, NULL, 0);
if (ret <= 0)
break;
rest -= ret;
ptr += ret;
}
if (rest == 0)
debug_printf ("Sending eid credentials succeeded");
else
debug_printf ("Sending eid credentials failed");
return rest == 0;
}
int
fhandler_socket_local::af_local_connect ()
{
bool orig_async_io, orig_is_nonblocking;
if (get_socket_type () != SOCK_STREAM)
return 0;
debug_printf ("af_local_connect called, no_getpeereid=%d", no_getpeereid ());
if (no_getpeereid ())
return 0;
af_local_setblocking (orig_async_io, orig_is_nonblocking);
if (!af_local_send_secret () || !af_local_recv_secret ()
|| !af_local_send_cred () || !af_local_recv_cred ())
{
debug_printf ("accept from unauthorized server");
::shutdown (get_socket (), SD_BOTH);
WSASetLastError (WSAECONNREFUSED);
return -1;
}
af_local_unsetblocking (orig_async_io, orig_is_nonblocking);
return 0;
}
int
fhandler_socket_local::af_local_accept ()
{
bool orig_async_io, orig_is_nonblocking;
debug_printf ("af_local_accept called, no_getpeereid=%d", no_getpeereid ());
if (no_getpeereid ())
return 0;
af_local_setblocking (orig_async_io, orig_is_nonblocking);
if (!af_local_recv_secret () || !af_local_send_secret ()
|| !af_local_recv_cred () || !af_local_send_cred ())
{
debug_printf ("connect from unauthorized client");
::shutdown (get_socket (), SD_BOTH);
::closesocket (get_socket ());
WSASetLastError (WSAECONNABORTED);
return -1;
}
af_local_unsetblocking (orig_async_io, orig_is_nonblocking);
return 0;
}
int
fhandler_socket_local::af_local_set_no_getpeereid ()
{
if (get_addr_family () != AF_LOCAL || get_socket_type () != SOCK_STREAM)
{
set_errno (EINVAL);
return -1;
}
if (connect_state () != unconnected)
{
set_errno (EALREADY);
return -1;
}
debug_printf ("no_getpeereid set");
no_getpeereid (true);
return 0;
}
void
fhandler_socket_local::af_local_set_cred ()
{
sec_pid = getpid ();
sec_uid = geteuid ();
sec_gid = getegid ();
sec_peer_pid = (pid_t) 0;
sec_peer_uid = (uid_t) -1;
sec_peer_gid = (gid_t) -1;
}
void
fhandler_socket_local::af_local_copy (fhandler_socket_local *sock)
{
sock->connect_secret[0] = connect_secret[0];
sock->connect_secret[1] = connect_secret[1];
sock->connect_secret[2] = connect_secret[2];
sock->connect_secret[3] = connect_secret[3];
sock->sec_pid = sec_pid;
sock->sec_uid = sec_uid;
sock->sec_gid = sec_gid;
sock->sec_peer_pid = sec_peer_pid;
sock->sec_peer_uid = sec_peer_uid;
sock->sec_peer_gid = sec_peer_gid;
sock->no_getpeereid (no_getpeereid ());
}
void
fhandler_socket_local::af_local_set_secret (char *buf)
{
if (!RtlGenRandom (connect_secret, sizeof (connect_secret)))
bzero ((char*) connect_secret, sizeof (connect_secret));
__small_sprintf (buf, "%08x-%08x-%08x-%08x",
connect_secret [0], connect_secret [1],
connect_secret [2], connect_secret [3]);
}
int
fhandler_socket_local::dup (fhandler_base *child, int flags)
{
if (get_flags () & O_PATH)
/* We're viewing the socket as a disk file, but fhandler_base::dup
suffices here. */
return fhandler_base::dup (child, flags);
fhandler_socket_local *fhs = (fhandler_socket_local *) child;
fhs->set_sun_path (get_sun_path ());
fhs->set_peer_sun_path (get_peer_sun_path ());
return fhandler_socket_wsock::dup (child, flags);
}
int
fhandler_socket_local::open (int flags, mode_t mode)
{
/* We don't support opening sockets unless O_PATH is specified. */
if (flags & O_PATH)
return open_fs (flags, mode);
set_errno (EOPNOTSUPP);
return 0;
}
int
fhandler_socket_local::close ()
{
if (get_flags () & O_PATH)
return fhandler_base::close ();
else
return fhandler_socket_wsock::close ();
}
int
fhandler_socket_local::fcntl (int cmd, intptr_t arg)
{
if (get_flags () & O_PATH)
/* We're viewing the socket as a disk file, but
fhandler_base::fcntl suffices here. */
return fhandler_base::fcntl (cmd, arg);
else
return fhandler_socket_wsock::fcntl (cmd, arg);
}
int
fhandler_socket_local::fstat (struct stat *buf)
{
if (!dev ().isfs ())
/* fstat called on a socket. */
return fhandler_socket_wsock::fstat (buf);
/* stat/lstat on a socket file or fstat on a socket opened w/ O_PATH. */
int res = fhandler_base::fstat_fs (buf);
if (!res)
{
buf->st_mode = (buf->st_mode & ~S_IFMT) | S_IFSOCK;
buf->st_size = 0;
}
return res;
}
int
fhandler_socket_local::fstatvfs (struct statvfs *sfs)
{
if (!dev ().isfs ())
/* fstatvfs called on a socket. */
return fhandler_socket_wsock::fstatvfs (sfs);
/* statvfs on a socket file or fstatvfs on a socket opened w/ O_PATH. */
if (get_flags () & O_PATH)
/* We already have a handle. */
{
HANDLE h = get_handle ();
if (h)
return fstatvfs_by_handle (h, sfs);
}
fhandler_disk_file fh (pc);
fh.get_device () = FH_FS;
return fh.fstatvfs (sfs);
}
int
fhandler_socket_local::fchmod (mode_t newmode)
{
if (!dev ().isfs ())
/* fchmod called on a socket. */
return fhandler_socket_wsock::fchmod (newmode);
/* chmod on a socket file. [We won't get here if fchmod is called
on a socket opened w/ O_PATH.] */
fhandler_disk_file fh (pc);
fh.get_device () = FH_FS;
return fh.fchmod (S_IFSOCK | adjust_socket_file_mode (newmode));
}
int
fhandler_socket_local::fchown (uid_t uid, gid_t gid)
{
if (!dev ().isfs ())
/* fchown called on a socket. */
return fhandler_socket_wsock::fchown (uid, gid);
/* chown/lchown on a socket file. [We won't get here if fchown is
called on a socket opened w/ O_PATH.] */
fhandler_disk_file fh (pc);
return fh.fchown (uid, gid);
}
int
fhandler_socket_local::facl (int cmd, int nentries, aclent_t *aclbufp)
{
if (!dev ().isfs ())
/* facl called on a socket. */
return fhandler_socket_wsock::facl (cmd, nentries, aclbufp);
/* facl on a socket file. [We won't get here if facl is called on a
socket opened w/ O_PATH.] */
fhandler_disk_file fh (pc);
return fh.facl (cmd, nentries, aclbufp);
}
int
fhandler_socket_local::link (const char *newpath)
{
if (!dev ().isfs ())
/* linkat w/ AT_EMPTY_PATH called on a socket not opened w/ O_PATH. */
return fhandler_socket_wsock::link (newpath);
/* link on a socket file or linkat w/ AT_EMPTY_PATH called on a
socket opened w/ O_PATH. */
fhandler_disk_file fh (pc);
if (get_flags () & O_PATH)
fh.set_handle (get_handle ());
return fh.link (newpath);
}
int
fhandler_socket_local::bind (const struct sockaddr *name, int namelen)
{
int res = -1;
#define un_addr ((struct sockaddr_un *) name)
struct sockaddr_in sin;
int len = namelen - offsetof (struct sockaddr_un, sun_path);
/* Check that name is within bounds. Don't check if the string is
NUL-terminated, because there are projects out there which set
namelen to a value which doesn't cover the trailing NUL. */
if (len <= 1 || (len = strnlen (un_addr->sun_path, len)) > UNIX_PATH_MAX)
{
set_errno (len <= 1 ? (len == 1 ? ENOENT : EINVAL) : ENAMETOOLONG);
return -1;
}
/* Copy over the sun_path string into a buffer big enough to add a
trailing NUL. */
char sun_path[len + 1];
strncpy (sun_path, un_addr->sun_path, len);
sun_path[len] = '\0';
/* This isn't entirely foolproof, but we check first if the file exists
so we can return with EADDRINUSE before having bound the socket.
This allows an application to call bind again on the same socket using
another filename. If we bind first, the application will not be able
to call bind successfully ever again. */
path_conv pc (sun_path, PC_SYM_FOLLOW);
if (pc.error)
{
set_errno (pc.error);
return -1;
}
if (pc.exists ())
{
set_errno (EADDRINUSE);
return -1;
}
sin.sin_family = AF_INET;
sin.sin_port = 0;
sin.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
if (::bind (get_socket (), (sockaddr *) &sin, len = sizeof sin))
{
syscall_printf ("AF_LOCAL: bind failed");
set_winsock_errno ();
return -1;
}
if (::getsockname (get_socket (), (sockaddr *) &sin, &len))
{
syscall_printf ("AF_LOCAL: getsockname failed");
set_winsock_errno ();
return -1;
}
sin.sin_port = ntohs (sin.sin_port);
debug_printf ("AF_LOCAL: socket bound to port %u", sin.sin_port);
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
DWORD fattr = FILE_ATTRIBUTE_SYSTEM;
if (!pc.has_acls ()
&& !(mode & ~cygheap->umask & (S_IWUSR | S_IWGRP | S_IWOTH)))
fattr |= FILE_ATTRIBUTE_READONLY;
SECURITY_ATTRIBUTES sa = sec_none_nih;
NTSTATUS status;
HANDLE fh;
OBJECT_ATTRIBUTES attr;
IO_STATUS_BLOCK io;
ULONG access = DELETE | FILE_GENERIC_WRITE;
/* If the filesystem supports ACLs, we will overwrite the DACL after the
call to NtCreateFile. This requires a handle with READ_CONTROL and
WRITE_DAC access, otherwise get_file_sd and set_file_sd both have to
open the file again.
FIXME: On remote NTFS shares open sometimes fails because even the
creator of the file doesn't have the right to change the DACL.
I don't know what setting that is or how to recognize such a share,
so for now we don't request WRITE_DAC on remote drives. */
if (pc.has_acls () && !pc.isremote ())
access |= READ_CONTROL | WRITE_DAC | WRITE_OWNER;
status = NtCreateFile (&fh, access, pc.get_object_attr (attr, sa), &io,
NULL, fattr, 0, FILE_CREATE,
FILE_NON_DIRECTORY_FILE
| FILE_SYNCHRONOUS_IO_NONALERT
| FILE_OPEN_FOR_BACKUP_INTENT,
NULL, 0);
if (!NT_SUCCESS (status))
{
if (io.Information == FILE_EXISTS)
set_errno (EADDRINUSE);
else
__seterrno_from_nt_status (status);
}
else
{
if (pc.has_acls ())
set_created_file_access (fh, pc, mode);
char buf[sizeof (SOCKET_COOKIE) + 80];
__small_sprintf (buf, "%s%u %c ", SOCKET_COOKIE, sin.sin_port,
get_socket_type () == SOCK_STREAM ? 's'
: get_socket_type () == SOCK_DGRAM ? 'd' : '-');
af_local_set_secret (strchr (buf, '\0'));
DWORD blen = strlen (buf) + 1;
status = NtWriteFile (fh, NULL, NULL, NULL, &io, buf, blen, NULL, 0);
if (!NT_SUCCESS (status))
{
__seterrno_from_nt_status (status);
FILE_DISPOSITION_INFORMATION fdi = { TRUE };
status = NtSetInformationFile (fh, &io, &fdi, sizeof fdi,
FileDispositionInformation);
if (!NT_SUCCESS (status))
debug_printf ("Setting delete dispostion failed, status = %y",
status);
}
else
{
set_sun_path (sun_path);
res = 0;
}
NtClose (fh);
}
#undef un_addr
return res;
}
int
fhandler_socket_local::connect (const struct sockaddr *name, int namelen)
{
struct sockaddr_storage sst;
int type = 0;
bool reset = (name->sa_family == AF_UNSPEC
&& get_socket_type () == SOCK_DGRAM);
if (reset)
{
if (connect_state () == unconnected)
return 0;
/* To reset a connected DGRAM socket, call Winsock's connect
function with the address member of the sockaddr structure
filled with zeroes. */
memset (&sst, 0, sizeof sst);
sst.ss_family = get_addr_family ();
}
else if (get_inet_addr_local (name, namelen, &sst, &namelen, &type,
connect_secret) == SOCKET_ERROR)
return SOCKET_ERROR;
if (get_socket_type () != type && !reset)
{
WSASetLastError (WSAEPROTOTYPE);
set_winsock_errno ();
return SOCKET_ERROR;
}
if (reset)
set_peer_sun_path (NULL);
else
set_peer_sun_path (name->sa_data);
/* Don't move af_local_set_cred into af_local_connect which may be called
via select, possibly running under another identity. Call early here,
because af_local_connect is called in wait_for_events. */
if (get_socket_type () == SOCK_STREAM)
af_local_set_cred ();
/* Initialize connect state to "connect_pending". In the SOCK_STREAM
case, the state is ultimately set to "connected" or "connect_failed" in
wait_for_events when the FD_CONNECT event occurs. Note that the
underlying OS sockets are always non-blocking in this case and a
successfully initiated non-blocking Winsock connect always returns
WSAEWOULDBLOCK. Thus it's safe to rely on event handling. For DGRAM
sockets, however, connect can return immediately.
Check for either unconnected or connect_failed since in both cases it's
allowed to retry connecting the socket. It's also ok (albeit ugly) to
call connect to check if a previous non-blocking connect finished.
Set connect_state before calling connect, otherwise a race condition with
an already running select or poll might occur. */
if (connect_state () == unconnected || connect_state () == connect_failed)
connect_state (connect_pending);
int res = ::connect (get_socket (), (struct sockaddr *) &sst, namelen);
if (!res)
{
if (reset)
connect_state (unconnected);
else
connect_state (connected);
}
else if (!is_nonblocking ()
&& res == SOCKET_ERROR
&& WSAGetLastError () == WSAEWOULDBLOCK)
res = wait_for_events (FD_CONNECT | FD_CLOSE, 0);
if (res)
{
DWORD err = WSAGetLastError ();
/* Some applications use the ugly technique to check if a non-blocking
connect succeeded by calling connect again, until it returns EISCONN.
This circumvents the event handling and connect_state is never set.
Thus we check for this situation here. */
if (err == WSAEISCONN)
connect_state (connected);
/* Winsock returns WSAEWOULDBLOCK if the non-blocking socket cannot be
conected immediately. Convert to POSIX/Linux compliant EINPROGRESS. */
else if (is_nonblocking () && err == WSAEWOULDBLOCK)
WSASetLastError (WSAEINPROGRESS);
/* Winsock returns WSAEINVAL if the socket is already a listener.
Convert to POSIX/Linux compliant EISCONN. */
else if (err == WSAEINVAL && connect_state () == listener)
WSASetLastError (WSAEISCONN);
/* Any other error except WSAEALREADY means the connect failed. */
else if (connect_state () == connect_pending && err != WSAEALREADY)
connect_state (connect_failed);
set_winsock_errno ();
}
return res;
}
int
fhandler_socket_local::listen (int backlog)
{
int res = ::listen (get_socket (), backlog);
if (res && WSAGetLastError () == WSAEINVAL)
{
/* It's perfectly valid to call listen on an unbound INET socket.
In this case the socket is automatically bound to an unused
port number, listening on all interfaces. On WinSock, listen
fails with WSAEINVAL when it's called on an unbound socket.
So we have to bind manually here to have POSIX semantics. */
if (get_addr_family () == AF_INET)
{
struct sockaddr_in sin;