This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Mark the common case with LIKELY branch predictor hint
[perl5.git] / win32 / win32sck.c
1 /* win32sck.c
2  *
3  * (c) 1995 Microsoft Corporation. All rights reserved. 
4  *              Developed by hip communications inc.
5  * Portions (c) 1993 Intergraph Corporation. All rights reserved.
6  *
7  *    You may distribute under the terms of either the GNU General Public
8  *    License or the Artistic License, as specified in the README file.
9  */
10
11 #define WIN32IO_IS_STDIO
12 #define WIN32SCK_IS_STDSCK
13 #define WIN32_LEAN_AND_MEAN
14 #define PERLIO_NOT_STDIO 0
15 #ifdef __GNUC__
16 #define Win32_Winsock
17 #endif
18 #include <windows.h>
19 #include <ws2spi.h>
20
21 #include "EXTERN.h"
22 #include "perl.h"
23
24 #include "Win32iop.h"
25 #include <sys/socket.h>
26 #include <fcntl.h>
27 #include <sys/stat.h>
28 #include <assert.h>
29 #include <io.h>
30
31 /* thanks to Beverly Brown      (beverly@datacube.com) */
32 #define OPEN_SOCKET(x)  win32_open_osfhandle(x,O_RDWR|O_BINARY)
33 #define TO_SOCKET(x)    _get_osfhandle(x)
34
35 #define StartSockets() \
36     STMT_START {                                        \
37         if (!wsock_started)                             \
38             start_sockets();                            \
39     } STMT_END
40
41 #define SOCKET_TEST(x, y) \
42     STMT_START {                                        \
43         StartSockets();                                 \
44         if((x) == (y))                                  \
45             errno = WSAGetLastError();                  \
46     } STMT_END
47
48 #define SOCKET_TEST_ERROR(x) SOCKET_TEST(x, SOCKET_ERROR)
49
50 static struct servent* win32_savecopyservent(struct servent*d,
51                                              struct servent*s,
52                                              const char *proto);
53
54 static int wsock_started = 0;
55
56 EXTERN_C void
57 EndSockets(void)
58 {
59     if (wsock_started)
60         WSACleanup();
61 }
62
63 void
64 start_sockets(void) 
65 {
66     unsigned short version;
67     WSADATA retdata;
68     int ret;
69
70     /*
71      * initalize the winsock interface and insure that it is
72      * cleaned up at exit.
73      */
74     version = 0x2;
75     if(ret = WSAStartup(version, &retdata))
76         Perl_croak_nocontext("Unable to locate winsock library!\n");
77     if(retdata.wVersion != version)
78         Perl_croak_nocontext("Could not find version 2.0 of winsock dll\n");
79
80     /* atexit((void (*)(void)) EndSockets); */
81     wsock_started = 1;
82 }
83
84 /* in no sockets Win32 builds, these use the inline functions defined in
85  * perl.h
86  */
87 u_long
88 win32_htonl(u_long hostlong)
89 {
90 #ifndef WIN32_NO_SOCKETS
91     StartSockets();
92 #endif
93     return htonl(hostlong);
94 }
95
96 u_short
97 win32_htons(u_short hostshort)
98 {
99 #ifndef WIN32_NO_SOCKETS
100     StartSockets();
101 #endif
102     return htons(hostshort);
103 }
104
105 u_long
106 win32_ntohl(u_long netlong)
107 {
108 #ifndef WIN32_NO_SOCKETS
109     StartSockets();
110 #endif
111     return ntohl(netlong);
112 }
113
114 u_short
115 win32_ntohs(u_short netshort)
116 {
117 #ifndef WIN32_NO_SOCKETS
118     StartSockets();
119 #endif
120     return ntohs(netshort);
121 }
122
123
124
125 SOCKET
126 win32_accept(SOCKET s, struct sockaddr *addr, int *addrlen)
127 {
128     SOCKET r;
129
130     SOCKET_TEST((r = accept(TO_SOCKET(s), addr, addrlen)), INVALID_SOCKET);
131     return OPEN_SOCKET(r);
132 }
133
134 int
135 win32_bind(SOCKET s, const struct sockaddr *addr, int addrlen)
136 {
137     int r;
138
139     SOCKET_TEST_ERROR(r = bind(TO_SOCKET(s), addr, addrlen));
140     return r;
141 }
142
143 int
144 win32_connect(SOCKET s, const struct sockaddr *addr, int addrlen)
145 {
146     int r;
147
148     SOCKET_TEST_ERROR(r = connect(TO_SOCKET(s), addr, addrlen));
149     return r;
150 }
151
152
153 int
154 win32_getpeername(SOCKET s, struct sockaddr *addr, int *addrlen)
155 {
156     int r;
157
158     SOCKET_TEST_ERROR(r = getpeername(TO_SOCKET(s), addr, addrlen));
159     return r;
160 }
161
162 int
163 win32_getsockname(SOCKET s, struct sockaddr *addr, int *addrlen)
164 {
165     int r;
166
167     SOCKET_TEST_ERROR(r = getsockname(TO_SOCKET(s), addr, addrlen));
168     return r;
169 }
170
171 int
172 win32_getsockopt(SOCKET s, int level, int optname, char *optval, int *optlen)
173 {
174     int r;
175
176     SOCKET_TEST_ERROR(r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen));
177     return r;
178 }
179
180 int
181 win32_ioctlsocket(SOCKET s, long cmd, u_long *argp)
182 {
183     int r;
184
185     SOCKET_TEST_ERROR(r = ioctlsocket(TO_SOCKET(s), cmd, argp));
186     return r;
187 }
188
189 int
190 win32_listen(SOCKET s, int backlog)
191 {
192     int r;
193
194     SOCKET_TEST_ERROR(r = listen(TO_SOCKET(s), backlog));
195     return r;
196 }
197
198 int
199 win32_recv(SOCKET s, char *buf, int len, int flags)
200 {
201     int r;
202
203     SOCKET_TEST_ERROR(r = recv(TO_SOCKET(s), buf, len, flags));
204     return r;
205 }
206
207 int
208 win32_recvfrom(SOCKET s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen)
209 {
210     int r;
211     int frombufsize = *fromlen;
212
213     SOCKET_TEST_ERROR(r = recvfrom(TO_SOCKET(s), buf, len, flags, from, fromlen));
214     /* Winsock's recvfrom() only returns a valid 'from' when the socket
215      * is connectionless.  Perl expects a valid 'from' for all types
216      * of sockets, so go the extra mile.
217      */
218     if (r != SOCKET_ERROR && frombufsize == *fromlen)
219         (void)win32_getpeername(s, from, fromlen);
220     return r;
221 }
222
223 /* select contributed by Vincent R. Slyngstad (vrs@ibeam.intel.com) */
224 int
225 win32_select(int nfds, Perl_fd_set* rd, Perl_fd_set* wr, Perl_fd_set* ex, const struct timeval* timeout)
226 {
227     int r;
228     int i, fd, save_errno = errno;
229     FD_SET nrd, nwr, nex;
230     bool just_sleep = TRUE;
231
232     StartSockets();
233
234     FD_ZERO(&nrd);
235     FD_ZERO(&nwr);
236     FD_ZERO(&nex);
237     for (i = 0; i < nfds; i++) {
238         if (rd && PERL_FD_ISSET(i,rd)) {
239             fd = TO_SOCKET(i);
240             FD_SET((unsigned)fd, &nrd);
241             just_sleep = FALSE;
242         }
243         if (wr && PERL_FD_ISSET(i,wr)) {
244             fd = TO_SOCKET(i);
245             FD_SET((unsigned)fd, &nwr);
246             just_sleep = FALSE;
247         }
248         if (ex && PERL_FD_ISSET(i,ex)) {
249             fd = TO_SOCKET(i);
250             FD_SET((unsigned)fd, &nex);
251             just_sleep = FALSE;
252         }
253     }
254
255     /* winsock seems incapable of dealing with all three fd_sets being empty,
256      * so do the (millisecond) sleep as a special case
257      */
258     if (just_sleep) {
259         if (timeout)
260             Sleep(timeout->tv_sec  * 1000 +
261                   timeout->tv_usec / 1000);     /* do the best we can */
262         else
263             Sleep(UINT_MAX);
264         return 0;
265     }
266
267     errno = save_errno;
268     SOCKET_TEST_ERROR(r = select(nfds, &nrd, &nwr, &nex, timeout));
269     save_errno = errno;
270
271     for (i = 0; i < nfds; i++) {
272         if (rd && PERL_FD_ISSET(i,rd)) {
273             fd = TO_SOCKET(i);
274             if (!FD_ISSET(fd, &nrd))
275                 PERL_FD_CLR(i,rd);
276         }
277         if (wr && PERL_FD_ISSET(i,wr)) {
278             fd = TO_SOCKET(i);
279             if (!FD_ISSET(fd, &nwr))
280                 PERL_FD_CLR(i,wr);
281         }
282         if (ex && PERL_FD_ISSET(i,ex)) {
283             fd = TO_SOCKET(i);
284             if (!FD_ISSET(fd, &nex))
285                 PERL_FD_CLR(i,ex);
286         }
287     }
288     errno = save_errno;
289     return r;
290 }
291
292 int
293 win32_send(SOCKET s, const char *buf, int len, int flags)
294 {
295     int r;
296
297     SOCKET_TEST_ERROR(r = send(TO_SOCKET(s), buf, len, flags));
298     return r;
299 }
300
301 int
302 win32_sendto(SOCKET s, const char *buf, int len, int flags,
303              const struct sockaddr *to, int tolen)
304 {
305     int r;
306
307     SOCKET_TEST_ERROR(r = sendto(TO_SOCKET(s), buf, len, flags, to, tolen));
308     return r;
309 }
310
311 int
312 win32_setsockopt(SOCKET s, int level, int optname, const char *optval, int optlen)
313 {
314     int r;
315
316     SOCKET_TEST_ERROR(r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen));
317     return r;
318 }
319     
320 int
321 win32_shutdown(SOCKET s, int how)
322 {
323     int r;
324
325     SOCKET_TEST_ERROR(r = shutdown(TO_SOCKET(s), how));
326     return r;
327 }
328
329 int
330 win32_closesocket(SOCKET s)
331 {
332     int r;
333
334     SOCKET_TEST_ERROR(r = closesocket(TO_SOCKET(s)));
335     return r;
336 }
337
338 void
339 convert_proto_info_w2a(WSAPROTOCOL_INFOW *in, WSAPROTOCOL_INFOA *out)
340 {
341     Copy(in, out, 1, WSAPROTOCOL_INFOA);
342     wcstombs(out->szProtocol, in->szProtocol, sizeof(out->szProtocol));
343 }
344
345 SOCKET
346 open_ifs_socket(int af, int type, int protocol)
347 {
348     dTHX;
349     char *s;
350     unsigned long proto_buffers_len = 0;
351     int error_code;
352     SOCKET out = INVALID_SOCKET;
353
354     if ((s = PerlEnv_getenv("PERL_ALLOW_NON_IFS_LSP")) && atoi(s))
355         return WSASocket(af, type, protocol, NULL, 0, 0);
356
357     if (WSCEnumProtocols(NULL, NULL, &proto_buffers_len, &error_code) == SOCKET_ERROR
358         && error_code == WSAENOBUFS)
359     {
360         WSAPROTOCOL_INFOW *proto_buffers;
361         int protocols_available = 0;       
362  
363         Newx(proto_buffers, proto_buffers_len / sizeof(WSAPROTOCOL_INFOW),
364             WSAPROTOCOL_INFOW);
365
366         if ((protocols_available = WSCEnumProtocols(NULL, proto_buffers, 
367             &proto_buffers_len, &error_code)) != SOCKET_ERROR)
368         {
369             int i;
370             for (i = 0; i < protocols_available; i++)
371             {
372                 WSAPROTOCOL_INFOA proto_info;
373
374                 if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily)
375                     || (type != proto_buffers[i].iSocketType)
376                     || (protocol != 0 && proto_buffers[i].iProtocol != 0 &&
377                         protocol != proto_buffers[i].iProtocol))
378                     continue;
379
380                 if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0)
381                     continue;
382
383                 convert_proto_info_w2a(&(proto_buffers[i]), &proto_info);
384
385                 out = WSASocket(af, type, protocol, &proto_info, 0, 0);
386                 break;
387             }
388         }
389
390         Safefree(proto_buffers);
391     }
392
393     return out;
394 }
395
396 SOCKET
397 win32_socket(int af, int type, int protocol)
398 {
399     SOCKET s;
400
401     StartSockets();
402
403     if((s = open_ifs_socket(af, type, protocol)) == INVALID_SOCKET)
404         errno = WSAGetLastError();
405     else
406         s = OPEN_SOCKET(s);
407
408     return s;
409 }
410
411 /*
412  * close RTL fd while respecting sockets
413  * added as temporary measure until PerlIO has real
414  * Win32 native layer
415  *   -- BKS, 11-11-2000
416 */
417
418 int my_close(int fd)
419 {
420     int osf;
421     if (!wsock_started)         /* No WinSock? */
422         return(close(fd));      /* Then not a socket. */
423     osf = TO_SOCKET(fd);/* Get it now before it's gone! */
424     if (osf != -1) {
425         int err;
426         err = closesocket(osf);
427         if (err == 0) {
428             (void)close(fd);    /* handle already closed, ignore error */
429             return 0;
430         }
431         else if (err == SOCKET_ERROR) {
432             err = WSAGetLastError();
433             if (err != WSAENOTSOCK) {
434                 (void)close(fd);
435                 errno = err;
436                 return EOF;
437             }
438         }
439     }
440     return close(fd);
441 }
442
443 #undef fclose
444 int
445 my_fclose (FILE *pf)
446 {
447     int osf;
448     if (!wsock_started)         /* No WinSock? */
449         return(fclose(pf));     /* Then not a socket. */
450     osf = TO_SOCKET(win32_fileno(pf));/* Get it now before it's gone! */
451     if (osf != -1) {
452         int err;
453         win32_fflush(pf);
454         err = closesocket(osf);
455         if (err == 0) {
456             (void)fclose(pf);   /* handle already closed, ignore error */
457             return 0;
458         }
459         else if (err == SOCKET_ERROR) {
460             err = WSAGetLastError();
461             if (err != WSAENOTSOCK) {
462                 (void)fclose(pf);
463                 errno = err;
464                 return EOF;
465             }
466         }
467     }
468     return fclose(pf);
469 }
470
471 struct hostent *
472 win32_gethostbyaddr(const char *addr, int len, int type)
473 {
474     struct hostent *r;
475
476     SOCKET_TEST(r = gethostbyaddr(addr, len, type), NULL);
477     return r;
478 }
479
480 struct hostent *
481 win32_gethostbyname(const char *name)
482 {
483     struct hostent *r;
484
485     SOCKET_TEST(r = gethostbyname(name), NULL);
486     return r;
487 }
488
489 int
490 win32_gethostname(char *name, int len)
491 {
492     int r;
493
494     SOCKET_TEST_ERROR(r = gethostname(name, len));
495     return r;
496 }
497
498 struct protoent *
499 win32_getprotobyname(const char *name)
500 {
501     struct protoent *r;
502
503     SOCKET_TEST(r = getprotobyname(name), NULL);
504     return r;
505 }
506
507 struct protoent *
508 win32_getprotobynumber(int num)
509 {
510     struct protoent *r;
511
512     SOCKET_TEST(r = getprotobynumber(num), NULL);
513     return r;
514 }
515
516 struct servent *
517 win32_getservbyname(const char *name, const char *proto)
518 {
519     dTHXa(NULL);    
520     struct servent *r;
521
522     SOCKET_TEST(r = getservbyname(name, proto), NULL);
523     if (r) {
524         aTHXa(PERL_GET_THX);
525         r = win32_savecopyservent(&w32_servent, r, proto);
526     }
527     return r;
528 }
529
530 struct servent *
531 win32_getservbyport(int port, const char *proto)
532 {
533     dTHXa(NULL); 
534     struct servent *r;
535
536     SOCKET_TEST(r = getservbyport(port, proto), NULL);
537     if (r) {
538         aTHXa(PERL_GET_THX);
539         r = win32_savecopyservent(&w32_servent, r, proto);
540     }
541     return r;
542 }
543
544 int
545 win32_ioctl(int i, unsigned int u, char *data)
546 {
547     u_long u_long_arg; 
548     int retval;
549     
550     if (!wsock_started) {
551         Perl_croak_nocontext("ioctl implemented only on sockets");
552         /* NOTREACHED */
553     }
554
555     /* mauke says using memcpy avoids alignment issues */
556     memcpy(&u_long_arg, data, sizeof u_long_arg); 
557     retval = ioctlsocket(TO_SOCKET(i), (long)u, &u_long_arg);
558     memcpy(data, &u_long_arg, sizeof u_long_arg);
559     
560     if (retval == SOCKET_ERROR) {
561         if (WSAGetLastError() == WSAENOTSOCK) {
562             Perl_croak_nocontext("ioctl implemented only on sockets");
563             /* NOTREACHED */
564         }
565         errno = WSAGetLastError();
566     }
567     return retval;
568 }
569
570 char FAR *
571 win32_inet_ntoa(struct in_addr in)
572 {
573     StartSockets();
574     return inet_ntoa(in);
575 }
576
577 unsigned long
578 win32_inet_addr(const char FAR *cp)
579 {
580     StartSockets();
581     return inet_addr(cp);
582 }
583
584 /*
585  * Networking stubs
586  */
587
588 void
589 win32_endhostent() 
590 {
591     win32_croak_not_implemented("endhostent");
592 }
593
594 void
595 win32_endnetent()
596 {
597     win32_croak_not_implemented("endnetent");
598 }
599
600 void
601 win32_endprotoent()
602 {
603     win32_croak_not_implemented("endprotoent");
604 }
605
606 void
607 win32_endservent()
608 {
609     win32_croak_not_implemented("endservent");
610 }
611
612
613 struct netent *
614 win32_getnetent(void) 
615 {
616     win32_croak_not_implemented("getnetent");
617     return (struct netent *) NULL;
618 }
619
620 struct netent *
621 win32_getnetbyname(char *name) 
622 {
623     win32_croak_not_implemented("getnetbyname");
624     return (struct netent *)NULL;
625 }
626
627 struct netent *
628 win32_getnetbyaddr(long net, int type) 
629 {
630     win32_croak_not_implemented("getnetbyaddr");
631     return (struct netent *)NULL;
632 }
633
634 struct protoent *
635 win32_getprotoent(void) 
636 {
637     win32_croak_not_implemented("getprotoent");
638     return (struct protoent *) NULL;
639 }
640
641 struct servent *
642 win32_getservent(void) 
643 {
644     win32_croak_not_implemented("getservent");
645     return (struct servent *) NULL;
646 }
647
648 void
649 win32_sethostent(int stayopen)
650 {
651     win32_croak_not_implemented("sethostent");
652 }
653
654
655 void
656 win32_setnetent(int stayopen)
657 {
658     win32_croak_not_implemented("setnetent");
659 }
660
661
662 void
663 win32_setprotoent(int stayopen)
664 {
665     win32_croak_not_implemented("setprotoent");
666 }
667
668
669 void
670 win32_setservent(int stayopen)
671 {
672     win32_croak_not_implemented("setservent");
673 }
674
675 static struct servent*
676 win32_savecopyservent(struct servent*d, struct servent*s, const char *proto)
677 {
678     d->s_name = s->s_name;
679     d->s_aliases = s->s_aliases;
680     d->s_port = s->s_port;
681     if (s->s_proto && strlen(s->s_proto))
682         d->s_proto = s->s_proto;
683     else
684     if (proto && strlen(proto))
685         d->s_proto = (char *)proto;
686     else
687         d->s_proto = "tcp";
688    
689     return d;
690 }
691
692