3edeefd6898d8b16467b230eee5d85c45a8053d4
[p5sagit/p5-mst-13.2.git] / win32 / win32sck.c
1 /* win32sck.c
2  *
3  * (c) 1995 Microsoft Corporation. All rights reserved. 
4  *              Developed by hip communications inc., http://info.hip.com/info/
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 "EXTERN.h"
20 #include "perl.h"
21
22 #if defined(PERL_OBJECT)
23 #define NO_XSLOCKS
24 #include "XSUB.h"
25 #endif
26
27 #include "Win32iop.h"
28 #include <sys/socket.h>
29 #include <fcntl.h>
30 #include <sys/stat.h>
31 #include <assert.h>
32 #include <io.h>
33
34 /* thanks to Beverly Brown      (beverly@datacube.com) */
35 #ifdef USE_SOCKETS_AS_HANDLES
36 #       define OPEN_SOCKET(x)   win32_open_osfhandle(x,O_RDWR|O_BINARY)
37 #       define TO_SOCKET(x)     _get_osfhandle(x)
38 #else
39 #       define OPEN_SOCKET(x)   (x)
40 #       define TO_SOCKET(x)     (x)
41 #endif  /* USE_SOCKETS_AS_HANDLES */
42
43 #if defined(USE_THREADS) || defined(USE_ITHREADS)
44 #define StartSockets() \
45     STMT_START {                                        \
46         if (!wsock_started)                             \
47             start_sockets();                            \
48         set_socktype();                                 \
49     } STMT_END
50 #else
51 #define StartSockets() \
52     STMT_START {                                        \
53         if (!wsock_started) {                           \
54             start_sockets();                            \
55             set_socktype();                             \
56         }                                               \
57     } STMT_END
58 #endif
59
60 #define SOCKET_TEST(x, y) \
61     STMT_START {                                        \
62         StartSockets();                                 \
63         if((x) == (y))                                  \
64             errno = WSAGetLastError();                  \
65     } STMT_END
66
67 #define SOCKET_TEST_ERROR(x) SOCKET_TEST(x, SOCKET_ERROR)
68
69 static struct servent* win32_savecopyservent(struct servent*d,
70                                              struct servent*s,
71                                              const char *proto);
72
73 static int wsock_started = 0;
74
75 EXTERN_C void
76 EndSockets(void)
77 {
78     if (wsock_started)
79         WSACleanup();
80 }
81
82 void
83 start_sockets(void) 
84 {
85     dTHXo;
86     unsigned short version;
87     WSADATA retdata;
88     int ret;
89
90     /*
91      * initalize the winsock interface and insure that it is
92      * cleaned up at exit.
93      */
94     version = 0x101;
95     if(ret = WSAStartup(version, &retdata))
96         Perl_croak_nocontext("Unable to locate winsock library!\n");
97     if(retdata.wVersion != version)
98         Perl_croak_nocontext("Could not find version 1.1 of winsock dll\n");
99
100     /* atexit((void (*)(void)) EndSockets); */
101     wsock_started = 1;
102 }
103
104 void
105 set_socktype(void)
106 {
107 #ifdef USE_SOCKETS_AS_HANDLES
108 #if defined(USE_THREADS) || defined(USE_ITHREADS)
109     dTHXo;
110     if (!w32_init_socktype) {
111 #endif
112         int iSockOpt = SO_SYNCHRONOUS_NONALERT;
113         /*
114          * Enable the use of sockets as filehandles
115          */
116         setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
117                     (char *)&iSockOpt, sizeof(iSockOpt));
118 #if defined(USE_THREADS) || defined(USE_ITHREADS)
119         w32_init_socktype = 1;
120     }
121 #endif
122 #endif  /* USE_SOCKETS_AS_HANDLES */
123 }
124
125
126 #ifndef USE_SOCKETS_AS_HANDLES
127 #undef fdopen
128 FILE *
129 my_fdopen(int fd, char *mode)
130 {
131     FILE *fp;
132     char sockbuf[256];
133     int optlen = sizeof(sockbuf);
134     int retval;
135
136     if (!wsock_started)
137         return(fdopen(fd, mode));
138
139     retval = getsockopt((SOCKET)fd, SOL_SOCKET, SO_TYPE, sockbuf, &optlen);
140     if(retval == SOCKET_ERROR && WSAGetLastError() == WSAENOTSOCK) {
141         return(fdopen(fd, mode));
142     }
143
144     /*
145      * If we get here, then fd is actually a socket.
146      */
147     Newz(1310, fp, 1, FILE);    /* XXX leak, good thing this code isn't used */
148     if(fp == NULL) {
149         errno = ENOMEM;
150         return NULL;
151     }
152
153     fp->_file = fd;
154     if(*mode == 'r')
155         fp->_flag = _IOREAD;
156     else
157         fp->_flag = _IOWRT;
158    
159     return fp;
160 }
161 #endif  /* USE_SOCKETS_AS_HANDLES */
162
163
164 u_long
165 win32_htonl(u_long hostlong)
166 {
167     StartSockets();
168     return htonl(hostlong);
169 }
170
171 u_short
172 win32_htons(u_short hostshort)
173 {
174     StartSockets();
175     return htons(hostshort);
176 }
177
178 u_long
179 win32_ntohl(u_long netlong)
180 {
181     StartSockets();
182     return ntohl(netlong);
183 }
184
185 u_short
186 win32_ntohs(u_short netshort)
187 {
188     StartSockets();
189     return ntohs(netshort);
190 }
191
192
193
194 SOCKET
195 win32_accept(SOCKET s, struct sockaddr *addr, int *addrlen)
196 {
197     SOCKET r;
198
199     SOCKET_TEST((r = accept(TO_SOCKET(s), addr, addrlen)), INVALID_SOCKET);
200     return OPEN_SOCKET(r);
201 }
202
203 int
204 win32_bind(SOCKET s, const struct sockaddr *addr, int addrlen)
205 {
206     int r;
207
208     SOCKET_TEST_ERROR(r = bind(TO_SOCKET(s), addr, addrlen));
209     return r;
210 }
211
212 int
213 win32_connect(SOCKET s, const struct sockaddr *addr, int addrlen)
214 {
215     int r;
216
217     SOCKET_TEST_ERROR(r = connect(TO_SOCKET(s), addr, addrlen));
218     return r;
219 }
220
221
222 int
223 win32_getpeername(SOCKET s, struct sockaddr *addr, int *addrlen)
224 {
225     int r;
226
227     SOCKET_TEST_ERROR(r = getpeername(TO_SOCKET(s), addr, addrlen));
228     return r;
229 }
230
231 int
232 win32_getsockname(SOCKET s, struct sockaddr *addr, int *addrlen)
233 {
234     int r;
235
236     SOCKET_TEST_ERROR(r = getsockname(TO_SOCKET(s), addr, addrlen));
237     return r;
238 }
239
240 int
241 win32_getsockopt(SOCKET s, int level, int optname, char *optval, int *optlen)
242 {
243     int r;
244
245     SOCKET_TEST_ERROR(r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen));
246     return r;
247 }
248
249 int
250 win32_ioctlsocket(SOCKET s, long cmd, u_long *argp)
251 {
252     int r;
253
254     SOCKET_TEST_ERROR(r = ioctlsocket(TO_SOCKET(s), cmd, argp));
255     return r;
256 }
257
258 int
259 win32_listen(SOCKET s, int backlog)
260 {
261     int r;
262
263     SOCKET_TEST_ERROR(r = listen(TO_SOCKET(s), backlog));
264     return r;
265 }
266
267 int
268 win32_recv(SOCKET s, char *buf, int len, int flags)
269 {
270     int r;
271
272     SOCKET_TEST_ERROR(r = recv(TO_SOCKET(s), buf, len, flags));
273     return r;
274 }
275
276 int
277 win32_recvfrom(SOCKET s, char *buf, int len, int flags, struct sockaddr *from, int *fromlen)
278 {
279     int r;
280     int frombufsize = *fromlen;
281
282     SOCKET_TEST_ERROR(r = recvfrom(TO_SOCKET(s), buf, len, flags, from, fromlen));
283     /* Winsock's recvfrom() only returns a valid 'from' when the socket
284      * is connectionless.  Perl expects a valid 'from' for all types
285      * of sockets, so go the extra mile.
286      */
287     if (r != SOCKET_ERROR && frombufsize == *fromlen)
288         (void)win32_getpeername(s, from, fromlen);
289     return r;
290 }
291
292 /* select contributed by Vincent R. Slyngstad (vrs@ibeam.intel.com) */
293 int
294 win32_select(int nfds, Perl_fd_set* rd, Perl_fd_set* wr, Perl_fd_set* ex, const struct timeval* timeout)
295 {
296     int r;
297 #ifdef USE_SOCKETS_AS_HANDLES
298     Perl_fd_set dummy;
299     int i, fd, bit, offset;
300     FD_SET nrd, nwr, nex, *prd, *pwr, *pex;
301
302     /* winsock seems incapable of dealing with all three null fd_sets,
303      * so do the (millisecond) sleep as a special case
304      */
305     if (!(rd || wr || ex)) {
306         if (timeout)
307             Sleep(timeout->tv_sec  * 1000 +
308                   timeout->tv_usec / 1000);     /* do the best we can */
309         else
310             Sleep(UINT_MAX);
311         return 0;
312     }
313     StartSockets();
314     PERL_FD_ZERO(&dummy);
315     if (!rd)
316         rd = &dummy, prd = NULL;
317     else
318         prd = &nrd;
319     if (!wr)
320         wr = &dummy, pwr = NULL;
321     else
322         pwr = &nwr;
323     if (!ex)
324         ex = &dummy, pex = NULL;
325     else
326         pex = &nex;
327
328     FD_ZERO(&nrd);
329     FD_ZERO(&nwr);
330     FD_ZERO(&nex);
331     for (i = 0; i < nfds; i++) {
332         fd = TO_SOCKET(i);
333         if (PERL_FD_ISSET(i,rd))
334             FD_SET(fd, &nrd);
335         if (PERL_FD_ISSET(i,wr))
336             FD_SET(fd, &nwr);
337         if (PERL_FD_ISSET(i,ex))
338             FD_SET(fd, &nex);
339     }
340
341     SOCKET_TEST_ERROR(r = select(nfds, prd, pwr, pex, timeout));
342
343     for (i = 0; i < nfds; i++) {
344         fd = TO_SOCKET(i);
345         if (PERL_FD_ISSET(i,rd) && !FD_ISSET(fd, &nrd))
346             PERL_FD_CLR(i,rd);
347         if (PERL_FD_ISSET(i,wr) && !FD_ISSET(fd, &nwr))
348             PERL_FD_CLR(i,wr);
349         if (PERL_FD_ISSET(i,ex) && !FD_ISSET(fd, &nex))
350             PERL_FD_CLR(i,ex);
351     }
352 #else
353     SOCKET_TEST_ERROR(r = select(nfds, rd, wr, ex, timeout));
354 #endif
355     return r;
356 }
357
358 int
359 win32_send(SOCKET s, const char *buf, int len, int flags)
360 {
361     int r;
362
363     SOCKET_TEST_ERROR(r = send(TO_SOCKET(s), buf, len, flags));
364     return r;
365 }
366
367 int
368 win32_sendto(SOCKET s, const char *buf, int len, int flags,
369              const struct sockaddr *to, int tolen)
370 {
371     int r;
372
373     SOCKET_TEST_ERROR(r = sendto(TO_SOCKET(s), buf, len, flags, to, tolen));
374     return r;
375 }
376
377 int
378 win32_setsockopt(SOCKET s, int level, int optname, const char *optval, int optlen)
379 {
380     int r;
381
382     SOCKET_TEST_ERROR(r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen));
383     return r;
384 }
385     
386 int
387 win32_shutdown(SOCKET s, int how)
388 {
389     int r;
390
391     SOCKET_TEST_ERROR(r = shutdown(TO_SOCKET(s), how));
392     return r;
393 }
394
395 int
396 win32_closesocket(SOCKET s)
397 {
398     int r;
399
400     SOCKET_TEST_ERROR(r = closesocket(TO_SOCKET(s)));
401     return r;
402 }
403
404 SOCKET
405 win32_socket(int af, int type, int protocol)
406 {
407     SOCKET s;
408
409 #ifndef USE_SOCKETS_AS_HANDLES
410     SOCKET_TEST(s = socket(af, type, protocol), INVALID_SOCKET);
411 #else
412     StartSockets();
413     if((s = socket(af, type, protocol)) == INVALID_SOCKET)
414         errno = WSAGetLastError();
415     else
416         s = OPEN_SOCKET(s);
417 #endif  /* USE_SOCKETS_AS_HANDLES */
418
419     return s;
420 }
421
422 /*
423  * close RTL fd while respecting sockets
424  * added as temporary measure until PerlIO has real
425  * Win32 native layer
426  *   -- BKS, 11-11-2000
427 */
428
429 int my_close(int fd)
430 {
431     int osf;
432     if (!wsock_started)         /* No WinSock? */
433         return(close(fd));      /* Then not a socket. */
434     osf = TO_SOCKET(fd);/* Get it now before it's gone! */
435     if (osf != -1) {
436         int err;
437         err = closesocket(osf);
438         if (err == 0) {
439 #if defined(USE_FIXED_OSFHANDLE) || defined(PERL_MSVCRT_READFIX)
440             _set_osfhnd(fd, INVALID_HANDLE_VALUE);
441 #endif
442             (void)close(fd);    /* handle already closed, ignore error */
443             return 0;
444         }
445         else if (err == SOCKET_ERROR) {
446             err = WSAGetLastError();
447             if (err != WSAENOTSOCK) {
448                 (void)close(fd);
449                 errno = err;
450                 return EOF;
451             }
452         }
453     }
454     return close(fd);
455 }
456
457 #undef fclose
458 int
459 my_fclose (FILE *pf)
460 {
461     int osf;
462     if (!wsock_started)         /* No WinSock? */
463         return(fclose(pf));     /* Then not a socket. */
464     osf = TO_SOCKET(win32_fileno(pf));/* Get it now before it's gone! */
465     if (osf != -1) {
466         int err;
467         win32_fflush(pf);
468         err = closesocket(osf);
469         if (err == 0) {
470 #if defined(USE_FIXED_OSFHANDLE) || defined(PERL_MSVCRT_READFIX)
471             _set_osfhnd(win32_fileno(pf), INVALID_HANDLE_VALUE);
472 #endif
473             (void)fclose(pf);   /* handle already closed, ignore error */
474             return 0;
475         }
476         else if (err == SOCKET_ERROR) {
477             err = WSAGetLastError();
478             if (err != WSAENOTSOCK) {
479                 (void)fclose(pf);
480                 errno = err;
481                 return EOF;
482             }
483         }
484     }
485     return fclose(pf);
486 }
487
488 #undef fstat
489 int
490 my_fstat(int fd, struct stat *sbufptr)
491 {
492     /* This fixes a bug in fstat() on Windows 9x.  fstat() uses the
493      * GetFileType() win32 syscall, which will fail on Windows 9x.
494      * So if we recognize a socket on Windows 9x, we return the
495      * same results as on Windows NT/2000.
496      * XXX this should be extended further to set S_IFSOCK on
497      * sbufptr->st_mode.
498      */
499     int osf;
500     if (!wsock_started || IsWinNT())
501         return fstat(fd, sbufptr);
502
503     osf = TO_SOCKET(fd);
504     if (osf != -1) {
505         char sockbuf[256];
506         int optlen = sizeof(sockbuf);
507         int retval;
508
509         retval = getsockopt((SOCKET)osf, SOL_SOCKET, SO_TYPE, sockbuf, &optlen);
510         if (retval != SOCKET_ERROR || WSAGetLastError() != WSAENOTSOCK) {
511 #if defined(__BORLANDC__)&&(__BORLANDC__<=0x520)
512             sbufptr->st_mode = S_IFIFO;
513 #else
514             sbufptr->st_mode = _S_IFIFO;
515 #endif
516             sbufptr->st_rdev = sbufptr->st_dev = (dev_t)fd;
517             sbufptr->st_nlink = 1;
518             sbufptr->st_uid = sbufptr->st_gid = sbufptr->st_ino = 0;
519             sbufptr->st_atime = sbufptr->st_mtime = sbufptr->st_ctime = 0;
520             sbufptr->st_size = (off_t)0;
521             return 0;
522         }
523     }
524     return fstat(fd, sbufptr);
525 }
526
527 struct hostent *
528 win32_gethostbyaddr(const char *addr, int len, int type)
529 {
530     struct hostent *r;
531
532     SOCKET_TEST(r = gethostbyaddr(addr, len, type), NULL);
533     return r;
534 }
535
536 struct hostent *
537 win32_gethostbyname(const char *name)
538 {
539     struct hostent *r;
540
541     SOCKET_TEST(r = gethostbyname(name), NULL);
542     return r;
543 }
544
545 int
546 win32_gethostname(char *name, int len)
547 {
548     int r;
549
550     SOCKET_TEST_ERROR(r = gethostname(name, len));
551     return r;
552 }
553
554 struct protoent *
555 win32_getprotobyname(const char *name)
556 {
557     struct protoent *r;
558
559     SOCKET_TEST(r = getprotobyname(name), NULL);
560     return r;
561 }
562
563 struct protoent *
564 win32_getprotobynumber(int num)
565 {
566     struct protoent *r;
567
568     SOCKET_TEST(r = getprotobynumber(num), NULL);
569     return r;
570 }
571
572 struct servent *
573 win32_getservbyname(const char *name, const char *proto)
574 {
575     dTHXo;    
576     struct servent *r;
577
578     SOCKET_TEST(r = getservbyname(name, proto), NULL);
579     if (r) {
580         r = win32_savecopyservent(&w32_servent, r, proto);
581     }
582     return r;
583 }
584
585 struct servent *
586 win32_getservbyport(int port, const char *proto)
587 {
588     dTHXo; 
589     struct servent *r;
590
591     SOCKET_TEST(r = getservbyport(port, proto), NULL);
592     if (r) {
593         r = win32_savecopyservent(&w32_servent, r, proto);
594     }
595     return r;
596 }
597
598 int
599 win32_ioctl(int i, unsigned int u, char *data)
600 {
601     dTHXo;
602     u_long argp = (u_long)data;
603     int retval;
604
605     if (!wsock_started) {
606         Perl_croak_nocontext("ioctl implemented only on sockets");
607         /* NOTREACHED */
608     }
609
610     retval = ioctlsocket(TO_SOCKET(i), (long)u, &argp);
611     if (retval == SOCKET_ERROR) {
612         if (WSAGetLastError() == WSAENOTSOCK) {
613             Perl_croak_nocontext("ioctl implemented only on sockets");
614             /* NOTREACHED */
615         }
616         errno = WSAGetLastError();
617     }
618     return retval;
619 }
620
621 char FAR *
622 win32_inet_ntoa(struct in_addr in)
623 {
624     StartSockets();
625     return inet_ntoa(in);
626 }
627
628 unsigned long
629 win32_inet_addr(const char FAR *cp)
630 {
631     StartSockets();
632     return inet_addr(cp);
633 }
634
635 /*
636  * Networking stubs
637  */
638
639 void
640 win32_endhostent() 
641 {
642     dTHXo;
643     Perl_croak_nocontext("endhostent not implemented!\n");
644 }
645
646 void
647 win32_endnetent()
648 {
649     dTHXo;
650     Perl_croak_nocontext("endnetent not implemented!\n");
651 }
652
653 void
654 win32_endprotoent()
655 {
656     dTHXo;
657     Perl_croak_nocontext("endprotoent not implemented!\n");
658 }
659
660 void
661 win32_endservent()
662 {
663     dTHXo;
664     Perl_croak_nocontext("endservent not implemented!\n");
665 }
666
667
668 struct netent *
669 win32_getnetent(void) 
670 {
671     dTHXo;
672     Perl_croak_nocontext("getnetent not implemented!\n");
673     return (struct netent *) NULL;
674 }
675
676 struct netent *
677 win32_getnetbyname(char *name) 
678 {
679     dTHXo;
680     Perl_croak_nocontext("getnetbyname not implemented!\n");
681     return (struct netent *)NULL;
682 }
683
684 struct netent *
685 win32_getnetbyaddr(long net, int type) 
686 {
687     dTHXo;
688     Perl_croak_nocontext("getnetbyaddr not implemented!\n");
689     return (struct netent *)NULL;
690 }
691
692 struct protoent *
693 win32_getprotoent(void) 
694 {
695     dTHXo;
696     Perl_croak_nocontext("getprotoent not implemented!\n");
697     return (struct protoent *) NULL;
698 }
699
700 struct servent *
701 win32_getservent(void) 
702 {
703     dTHXo;
704     Perl_croak_nocontext("getservent not implemented!\n");
705     return (struct servent *) NULL;
706 }
707
708 void
709 win32_sethostent(int stayopen)
710 {
711     dTHXo;
712     Perl_croak_nocontext("sethostent not implemented!\n");
713 }
714
715
716 void
717 win32_setnetent(int stayopen)
718 {
719     dTHXo;
720     Perl_croak_nocontext("setnetent not implemented!\n");
721 }
722
723
724 void
725 win32_setprotoent(int stayopen)
726 {
727     dTHXo;
728     Perl_croak_nocontext("setprotoent not implemented!\n");
729 }
730
731
732 void
733 win32_setservent(int stayopen)
734 {
735     dTHXo;
736     Perl_croak_nocontext("setservent not implemented!\n");
737 }
738
739 static struct servent*
740 win32_savecopyservent(struct servent*d, struct servent*s, const char *proto)
741 {
742     d->s_name = s->s_name;
743     d->s_aliases = s->s_aliases;
744     d->s_port = s->s_port;
745 #ifndef __BORLANDC__    /* Buggy on Win95 and WinNT-with-Borland-WSOCK */
746     if (!IsWin95() && s->s_proto && strlen(s->s_proto))
747         d->s_proto = s->s_proto;
748     else
749 #endif
750     if (proto && strlen(proto))
751         d->s_proto = (char *)proto;
752     else
753         d->s_proto = "tcp";
754    
755     return d;
756 }
757
758