Release 980809
[wine] / misc / winsock.c
1 /*
2  * based on Windows Sockets 1.1 specs
3  * (ftp.microsoft.com:/Advsys/winsock/spec11/WINSOCK.TXT)
4  * 
5  * (C) 1993,1994,1996,1997 John Brezak, Erik Bos, Alex Korobka.
6  *
7  * NOTE: If you make any changes to fix a particular app, make sure 
8  * they don't break something else like Netscape or telnet and ftp 
9  * clients and servers (www.winsite.com got a lot of those).
10  *
11  */
12  
13 #include "config.h"
14
15 #include <string.h>
16 #include <signal.h>
17 #include <sys/types.h>
18 #include <sys/ipc.h>
19 #include <sys/ioctl.h>
20 #ifdef HAVE_SYS_FILIO_H
21 # include <sys/filio.h>
22 #endif
23 #if defined(__svr4__)
24 #include <sys/ioccom.h>
25 #include <sys/sockio.h>
26 #endif
27
28 #if defined(__EMX__)
29 # include <sys/so_ioctl.h>
30 #endif
31
32 #ifdef HAVE_SYS_PARAM_H
33 # include <sys/param.h>
34 #endif
35
36 #include <sys/msg.h>
37 #include <sys/wait.h>
38 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
41 #include <ctype.h>
42 #include <fcntl.h>
43 #include <errno.h>
44 #include <netdb.h>
45 #include <unistd.h>
46
47 #include "winsock.h"
48 #include "windows.h"
49 #include "winnt.h"
50 #include "heap.h"
51 #include "ldt.h"
52 #include "task.h"
53 #include "message.h"
54 #include "miscemu.h"
55 #include "debug.h"
56
57 #define DEBUG_SOCKADDR 0
58 #define dump_sockaddr(a) \
59         DUMP("sockaddr_in: family %d, address %s, port %d\n", \
60                         ((struct sockaddr_in *)a)->sin_family, \
61                         inet_ntoa(((struct sockaddr_in *)a)->sin_addr), \
62                         ntohs(((struct sockaddr_in *)a)->sin_port))
63
64 #pragma pack(4)
65
66 /* ----------------------------------- internal data */
67
68 static HANDLE32         _WSHeap = 0;
69 static unsigned char*   _ws_stub = NULL;
70 static LPWSINFO         _wsi_list = NULL;
71
72 #define WS_ALLOC(size) \
73         HeapAlloc(_WSHeap, HEAP_ZERO_MEMORY, (size) )
74 #define WS_FREE(ptr) \
75         HeapFree(_WSHeap, 0, (ptr) )
76
77 #define WS_PTR2HANDLE(ptr) \
78         ((short)((int)(ptr) - (int)_ws_stub))
79 #define WS_HANDLE2PTR(handle) \
80         ((unsigned)((int)_ws_stub + (int)(handle)))
81
82 #define WSI_CHECK_RANGE(pwsi, pws) \
83         ( ((unsigned)(pws) > (unsigned)(pwsi)) && \
84           ((unsigned)(pws) < ((unsigned)(pwsi) + sizeof(WSINFO))) )
85
86 static INT32         _ws_sock_ops[] =
87        { WS_SO_DEBUG, WS_SO_REUSEADDR, WS_SO_KEEPALIVE, WS_SO_DONTROUTE,
88          WS_SO_BROADCAST, WS_SO_LINGER, WS_SO_OOBINLINE, WS_SO_SNDBUF,
89          WS_SO_RCVBUF, WS_SO_ERROR, WS_SO_TYPE, WS_SO_DONTLINGER, 0 };
90 static int           _px_sock_ops[] =
91        { SO_DEBUG, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, SO_BROADCAST,
92          SO_LINGER, SO_OOBINLINE, SO_SNDBUF, SO_RCVBUF, SO_ERROR, SO_TYPE,
93          SO_LINGER };
94
95 static int   _check_ws(LPWSINFO pwsi, ws_socket* pws);
96 static char* _check_buffer(LPWSINFO pwsi, int size);
97
98 /***********************************************************************
99  *          convert_sockopt()
100  *
101  * Converts socket flags from Windows format.
102  */
103 static void convert_sockopt(INT32 *level, INT32 *optname)
104 {
105   int i;
106   switch (*level)
107   {
108      case WS_SOL_SOCKET:
109         *level = SOL_SOCKET;
110         for(i=0; _ws_sock_ops[i]; i++)
111             if( _ws_sock_ops[i] == *optname ) break;
112         if( _ws_sock_ops[i] ) *optname = _px_sock_ops[i];
113         else WARN(winsock, "Unknown optname %d\n", *optname);
114         break;
115      case WS_IPPROTO_TCP:
116         *optname = IPPROTO_TCP;
117   }
118 }
119
120 /* ----------------------------------- Per-thread info (or per-process?) */
121
122 static LPWSINFO wsi_find(HTASK16 hTask)
123
124     TDB*           pTask = (TDB*)GlobalLock16(hTask);
125     if( pTask )
126     {
127         if( pTask->pwsi ) return pTask->pwsi;
128         else
129         {
130             LPWSINFO pwsi = _wsi_list;
131             while( pwsi && pwsi->tid != hTask ) pwsi = pwsi->next;
132             if( pwsi )
133                 WARN(winsock,"(pwsi=0x%08x,task=0x%04x):Loose wsi struct! \n", 
134                                         (unsigned)pwsi, hTask );
135             return pwsi; 
136         }
137     }
138     return NULL;
139 }
140
141 static ws_socket* wsi_alloc_socket(LPWSINFO pwsi, int fd)
142 {
143     /* Initialize a new entry in the socket table */
144
145     if( pwsi->last_free >= 0 )
146     {
147         int i = pwsi->last_free;
148
149         pwsi->last_free = pwsi->sock[i].flags;  /* free list */
150         pwsi->sock[i].fd = fd;
151         pwsi->sock[i].flags = 0;
152         return &pwsi->sock[i];
153     }
154     return NULL;
155 }
156
157 static int wsi_strtolo(LPWSINFO pwsi, const char* name, const char* opt)
158 {
159     /* Stuff a lowercase copy of the string into the local buffer */
160
161     int i = strlen(name) + 2;
162     char* p = _check_buffer(pwsi, i + ((opt)?strlen(opt):0));
163
164     if( p )
165     {
166         do *p++ = tolower(*name); while(*name++);
167         i = (p - (char*)(pwsi->buffer));
168         if( opt ) do *p++ = tolower(*opt); while(*opt++);
169         return i;
170     }
171     return 0;
172 }
173
174 static fd_set* fd_set_import( fd_set* fds, LPWSINFO pwsi, void* wsfds, int* highfd, BOOL32 b32 )
175 {
176     /* translate Winsock fd set into local fd set */
177
178     if( wsfds ) 
179     { 
180 #define wsfds16 ((ws_fd_set16*)wsfds)
181 #define wsfds32 ((ws_fd_set32*)wsfds)
182         ws_socket* pws;
183         int i, count;
184
185         FD_ZERO(fds);
186         count = b32 ? wsfds32->fd_count : wsfds16->fd_count;
187
188         for( i = 0; i < count; i++ )
189         {
190              pws = (b32) ? (ws_socket*)WS_HANDLE2PTR(wsfds32->fd_array[i])
191                          : (ws_socket*)WS_HANDLE2PTR(wsfds16->fd_array[i]);
192              if( _check_ws(pwsi, pws) )
193              {
194                     if( pws->fd > *highfd ) *highfd = pws->fd;
195                     FD_SET(pws->fd, fds);
196              }
197         }
198 #undef wsfds32
199 #undef wsfds16
200         return fds;
201     }
202     return NULL;
203 }
204
205 __inline__ static int sock_error_p(int s)
206 {
207     unsigned int optval, optlen;
208
209     optlen = sizeof(optval);
210     getsockopt(s, SOL_SOCKET, SO_ERROR, &optval, &optlen);
211     if (optval) WARN(winsock, "\t[%i] error: %d\n", s, optval);
212     return optval != 0;
213 }
214
215 static int fd_set_export( LPWSINFO pwsi, fd_set* fds, fd_set* exceptfds, void* wsfds, BOOL32 b32 )
216 {
217     int num_err = 0;
218
219     /* translate local fd set into Winsock fd set, adding
220      * errors to exceptfds (only if app requested it) */
221
222     if( wsfds )
223     {
224 #define wsfds16 ((ws_fd_set16*)wsfds)
225 #define wsfds32 ((ws_fd_set32*)wsfds)
226         int i, j, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
227
228         for( i = 0, j = 0; i < count; i++ )
229         {
230             ws_socket *pws = (b32) ? (ws_socket*)WS_HANDLE2PTR(wsfds32->fd_array[i])
231                                    : (ws_socket*)WS_HANDLE2PTR(wsfds16->fd_array[i]);
232             if( _check_ws(pwsi, pws) )
233             {
234                 int fd = pws->fd;
235
236                 if( FD_ISSET(fd, fds) )
237                 {
238                     if ( exceptfds && sock_error_p(fd) )
239                     {
240                         FD_SET(fd, exceptfds);
241                         num_err++;
242                     }
243                     else if( b32 )
244                              wsfds32->fd_array[j++] = wsfds32->fd_array[i];
245                          else
246                              wsfds16->fd_array[j++] = wsfds16->fd_array[i];
247                 }
248             }
249         }
250
251         if( b32 ) wsfds32->fd_count = j;
252         else wsfds16->fd_count = j;
253
254         TRACE(winsock, "\n");
255 #undef wsfds32
256 #undef wsfds16
257     }
258     return num_err;
259 }
260
261 HANDLE16 __ws_gethandle( void* ptr )
262 {
263     return (HANDLE16)WS_PTR2HANDLE(ptr);
264 }
265
266 void* __ws_memalloc( int size )
267 {
268     return WS_ALLOC(size);
269 }
270
271 void __ws_memfree(void* ptr)
272 {
273     WS_FREE(ptr);
274 }
275
276 /* ----------------------------------- API ----- 
277  *
278  * Init / cleanup / error checking.
279  */
280
281 /***********************************************************************
282  *      WSAStartup16()                  (WINSOCK.115)
283  *
284  * Create socket control struct, attach it to the global list and
285  * update a pointer in the task struct.
286  */
287 INT16 WINAPI WSAStartup16(UINT16 wVersionRequested, LPWSADATA lpWSAData)
288 {
289     WSADATA WINSOCK_data = { 0x0101, 0x0101,
290                           "WINE Sockets 1.1",
291                         #ifdef linux
292                                 "Linux/i386",
293                         #elif defined(__NetBSD__)
294                                 "NetBSD/i386",
295                         #elif defined(sunos)
296                                 "SunOS",
297                         #elif defined(__FreeBSD__)
298                                 "FreeBSD",
299                         #elif defined(__OpenBSD__)
300                                 "OpenBSD/i386",
301                         #else
302                                 "Unknown",
303                         #endif
304                            WS_MAX_SOCKETS_PER_PROCESS,
305                            WS_MAX_UDP_DATAGRAM, (SEGPTR)NULL };
306     HTASK16             tid = GetCurrentTask();
307     LPWSINFO            pwsi;
308
309     TRACE(winsock, "verReq=%x\n", wVersionRequested);
310
311     if (LOBYTE(wVersionRequested) < 1 || (LOBYTE(wVersionRequested) == 1 &&
312         HIBYTE(wVersionRequested) < 1)) return WSAVERNOTSUPPORTED;
313
314     if (!lpWSAData) return WSAEINVAL;
315
316     /* initialize socket heap */
317
318     if( !_ws_stub )
319     {
320         _WSHeap = HeapCreate(HEAP_ZERO_MEMORY, 8120, 32768);
321         if( !(_ws_stub = WS_ALLOC(0x10)) )
322         {
323             ERR(winsock,"Fatal: failed to create WinSock heap\n");
324             return 0;
325         }
326     }
327     if( _WSHeap == 0 ) return WSASYSNOTREADY;
328
329     /* create socket array for this task */
330   
331     pwsi = wsi_find(GetCurrentTask());
332     if( pwsi == NULL )
333     {
334         TDB* pTask = (TDB*)GlobalLock16( tid );
335
336         if( (pwsi = (LPWSINFO)WS_ALLOC( sizeof(WSINFO))) )
337         {
338             int i = 0;
339             pwsi->tid = tid;
340             for( i = 0; i < WS_MAX_SOCKETS_PER_PROCESS; i++ )
341             {
342                 pwsi->sock[i].fd = -1; 
343                 pwsi->sock[i].flags = i + 1; 
344             }
345             pwsi->sock[WS_MAX_SOCKETS_PER_PROCESS - 1].flags = -1;
346         }
347         else return WSASYSNOTREADY;
348
349         /* add this control struct to the global list */
350
351         pwsi->prev = NULL;
352         if( _wsi_list ) 
353             _wsi_list->prev = pwsi;
354         pwsi->next = _wsi_list; 
355         _wsi_list = pwsi;
356         pTask->pwsi = pwsi;
357     }
358     else pwsi->num_startup++;
359
360     /* return winsock information */
361
362     memcpy(lpWSAData, &WINSOCK_data, sizeof(WINSOCK_data));
363
364     TRACE(winsock, "succeeded\n");
365     return 0;
366 }
367
368 /***********************************************************************
369  *      WSAStartup32()                  (WSOCK32.115)
370  */
371 INT32 WINAPI WSAStartup32(UINT32 wVersionRequested, LPWSADATA lpWSAData)
372 {
373     return WSAStartup16( wVersionRequested, lpWSAData );
374 }
375
376 /***********************************************************************
377  *      WSACleanup()                    (WINSOCK.116)
378  *
379  * Cleanup functions of varying impact.
380  */
381 void WINSOCK_Shutdown()
382 {
383     /* Called on exit(), has to remove all outstanding async DNS processes.  */
384
385     WINSOCK_cancel_task_aops( 0, __ws_memfree );
386 }
387
388 INT32 WINSOCK_DeleteTaskWSI( TDB* pTask, LPWSINFO pwsi )
389 {
390     /* WSACleanup() backend, called on task termination as well.
391      * Real DLL would have registered its own signal handler with
392      * TaskSetSignalHandler() and waited until USIG_TERMINATION/USIG_GPF
393      * but this scheme is much more straightforward.
394      */
395
396     int i, j, n;
397
398     if( --pwsi->num_startup > 0 ) return 0;
399
400     SIGNAL_MaskAsyncEvents( TRUE );
401     WINSOCK_cancel_task_aops( pTask->hSelf, __ws_memfree );
402     SIGNAL_MaskAsyncEvents( FALSE );
403
404     /* unlink socket control struct */
405
406     if( pwsi == _wsi_list ) 
407         _wsi_list = pwsi->next;
408     else
409         pwsi->prev->next = pwsi->next;
410     if( pwsi->next ) pwsi->next->prev = pwsi->prev; 
411
412     if( _wsi_list == NULL ) 
413         WINSOCK_Shutdown();     /* just in case */
414
415     if( pwsi->flags & WSI_BLOCKINGCALL )
416         TRACE(winsock,"\tinside blocking call!\n");
417
418 /* FIXME: aop_control() doesn't decrement pwsi->num_async_rq
419  *
420  *    if( pwsi->num_async_rq )
421  *        WARN(winsock,"\thave %i outstanding async ops!\n", pwsi->num_async_rq );
422  */
423
424     for(i = 0, j = 0, n = 0; i < WS_MAX_SOCKETS_PER_PROCESS; i++)
425         if( pwsi->sock[i].fd != -1 )
426         {
427             if( pwsi->sock[i].psop )
428             {
429                 n++;
430                 WSAAsyncSelect32( (SOCKET16)WS_PTR2HANDLE(pwsi->sock + i), 0, 0, 0 );
431             }
432             close(pwsi->sock[i].fd); j++; 
433         }
434     if( j ) 
435           TRACE(winsock,"\tclosed %i sockets, killed %i async selects!\n", j, n);
436
437     /* delete scratch buffers */
438
439     if( pwsi->buffer ) SEGPTR_FREE(pwsi->buffer);
440     if( pwsi->dbuffer ) SEGPTR_FREE(pwsi->dbuffer);
441         
442     if( pTask )
443         pTask->pwsi = NULL;
444     memset( pwsi, 0, sizeof(WSINFO) );
445     WS_FREE(pwsi);
446     return 0;
447 }
448
449 INT32 WINAPI WSACleanup(void)
450 {
451     HTASK16     hTask = GetCurrentTask();
452
453     TRACE(winsock, "(%04x)\n", hTask );
454     if( hTask )
455     {
456         LPWSINFO pwsi = wsi_find(hTask);
457         if( pwsi )
458             return WINSOCK_DeleteTaskWSI( (TDB*)GlobalLock16(hTask), pwsi );
459         return SOCKET_ERROR;
460     }
461     else
462         WINSOCK_Shutdown(); /* remove all outstanding DNS requests */
463     return 0;
464 }
465
466
467 /***********************************************************************
468  *      WSAGetLastError()               (WSOCK32.111)(WINSOCK.111)
469  */
470 INT32 WINAPI WSAGetLastError(void)
471 {
472     LPWSINFO pwsi = wsi_find(GetCurrentTask());
473     INT16    ret = (pwsi) ? pwsi->err : WSANOTINITIALISED;
474
475     TRACE(winsock, "(%08x) = %i\n", 
476                     (unsigned)pwsi, (int)ret);
477     return ret;
478 }
479
480 /***********************************************************************
481  *      WSASetLastError32()             (WSOCK32.112)
482  */
483 void WINAPI WSASetLastError32(INT32 iError)
484 {
485     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
486
487     TRACE(winsock, "(%08x): %d\n", (unsigned)pwsi, (int)iError);
488     if( pwsi ) pwsi->err = iError;
489 }
490
491 /***********************************************************************
492  *      WSASetLastError16()             (WINSOCK.112)
493  */
494 void WINAPI WSASetLastError16(INT16 iError)
495 {
496     WSASetLastError32(iError);
497 }
498
499 int _check_ws(LPWSINFO pwsi, ws_socket* pws)
500 {
501     if( pwsi )
502         if( pwsi->flags & WSI_BLOCKINGCALL ) pwsi->err = WSAEINPROGRESS;
503         else if( WSI_CHECK_RANGE(pwsi, pws) ) return 1;
504                  else pwsi->err = WSAENOTSOCK;
505     return 0;
506 }
507
508 char* _check_buffer(LPWSINFO pwsi, int size)
509 {
510     if( pwsi->buffer && pwsi->buflen >= size ) return pwsi->buffer;
511     else SEGPTR_FREE(pwsi->buffer);
512
513     pwsi->buffer = (char*)SEGPTR_ALLOC((pwsi->buflen = size)); 
514     return pwsi->buffer;
515 }
516
517 struct ws_hostent* _check_buffer_he(LPWSINFO pwsi, int size)
518 {
519     if( pwsi->he && pwsi->helen >= size ) return pwsi->he;
520     else SEGPTR_FREE(pwsi->he);
521
522     pwsi->he = (struct ws_hostent*)SEGPTR_ALLOC((pwsi->helen = size)); 
523     return pwsi->he;
524 }
525
526 struct ws_servent* _check_buffer_se(LPWSINFO pwsi, int size)
527 {
528     if( pwsi->se && pwsi->selen >= size ) return pwsi->se;
529     else SEGPTR_FREE(pwsi->se);
530
531     pwsi->se = (struct ws_servent*)SEGPTR_ALLOC((pwsi->selen = size)); 
532     return pwsi->se;
533 }
534
535 struct ws_protoent* _check_buffer_pe(LPWSINFO pwsi, int size)
536 {
537     if( pwsi->pe && pwsi->pelen >= size ) return pwsi->pe;
538     else SEGPTR_FREE(pwsi->pe);
539
540     pwsi->pe = (struct ws_protoent*)SEGPTR_ALLOC((pwsi->pelen = size)); 
541     return pwsi->pe;
542 }
543
544 /* ----------------------------------- i/o APIs */
545
546 /***********************************************************************
547  *              accept()                (WSOCK32.1)
548  */
549 SOCKET32 WINAPI WINSOCK_accept32(SOCKET32 s, struct sockaddr *addr,
550                                  INT32 *addrlen32)
551 {
552     ws_socket*  pws  = (ws_socket*)WS_HANDLE2PTR((SOCKET16)s);
553     LPWSINFO    pwsi = wsi_find(GetCurrentTask());
554
555     TRACE(winsock, "(%08x): socket %04x\n", 
556                                   (unsigned)pwsi, (UINT16)s ); 
557     if( _check_ws(pwsi, pws) )
558     {
559         int     sock, fd_flags;
560
561         fd_flags = fcntl(pws->fd, F_GETFL, 0);
562
563         if( (sock = accept(pws->fd, addr, addrlen32)) >= 0 )
564         {
565             ws_socket*  pnew = wsi_alloc_socket(pwsi, sock); 
566             if( pnew )
567             {
568                 s = (SOCKET32)WS_PTR2HANDLE(pnew);
569                 if( pws->psop && pws->flags & WS_FD_ACCEPT )
570                 {
571                     EVENT_AddIO( pws->fd, EVENT_IO_READ );      /* reenabler */
572
573                     /* async select the accept()'ed socket */
574                     WSAAsyncSelect32( s, pws->psop->hWnd, pws->psop->uMsg,
575                                       pws->flags & ~WS_FD_ACCEPT );
576                 }
577                 return s;
578             } 
579             else pwsi->err = WSAENOBUFS;
580         } 
581         else pwsi->err = wsaErrno();
582     }
583     return INVALID_SOCKET32;
584 }
585
586 /***********************************************************************
587  *              accept()                (WINSOCK.1)
588  */
589 SOCKET16 WINAPI WINSOCK_accept16(SOCKET16 s, struct sockaddr* addr,
590                                  INT16* addrlen16 )
591 {
592     INT32 addrlen32 = addrlen16 ? *addrlen16 : 0;
593     SOCKET32 retSocket = WINSOCK_accept32( s, addr, &addrlen32 );
594     if( addrlen16 ) *addrlen16 = (INT16)addrlen32;
595     return (SOCKET16)retSocket;
596 }
597
598 /***********************************************************************
599  *              bind()                  (WSOCK32.2)
600  */
601 INT32 WINAPI WINSOCK_bind32(SOCKET32 s, struct sockaddr *name, INT32 namelen)
602 {
603     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
604     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
605
606     TRACE(winsock, "(%08x): socket %04x, ptr %8x, length %d\n", 
607                            (unsigned)pwsi, s, (int) name, namelen);
608 #if DEBUG_SOCKADDR
609     dump_sockaddr(name);
610 #endif
611
612     if ( _check_ws(pwsi, pws) )
613       if ( namelen >= sizeof(*name) ) 
614         if ( ((struct ws_sockaddr_in *)name)->sin_family == AF_INET )
615           if ( bind(pws->fd, name, namelen) < 0 ) 
616           {
617              int        loc_errno = errno;
618              WARN(winsock, "\tfailure - errno = %i\n", errno);
619              errno = loc_errno;
620              switch(errno)
621              {
622                 case EBADF: pwsi->err = WSAENOTSOCK; break;
623                 case EADDRNOTAVAIL: pwsi->err = WSAEINVAL; break;
624                 default: pwsi->err = wsaErrno();
625              }
626           }
627           else return 0; /* success */
628         else pwsi->err = WSAEAFNOSUPPORT;
629       else pwsi->err = WSAEFAULT;
630     return SOCKET_ERROR;
631 }
632
633 /***********************************************************************
634  *              bind()                  (WINSOCK.2)
635  */
636 INT16 WINAPI WINSOCK_bind16(SOCKET16 s, struct sockaddr *name, INT16 namelen)
637 {
638   return (INT16)WINSOCK_bind32( s, name, namelen );
639 }
640
641 /***********************************************************************
642  *              closesocket()           (WSOCK32.3)
643  */
644 INT32 WINAPI WINSOCK_closesocket32(SOCKET32 s)
645 {
646     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
647     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
648
649     TRACE(winsock, "(%08x): socket %08x\n", (unsigned)pwsi, s);
650
651     if( _check_ws(pwsi, pws) )
652     { 
653         int     fd = pws->fd;
654
655         if( pws->psop ) WSAAsyncSelect32( s, 0, 0, 0 );
656
657         pws->fd = -1;
658         pws->flags = (unsigned)pwsi->last_free;
659         pwsi->last_free = pws - &pwsi->sock[0]; /* add to free list */
660
661         if( close(fd) == 0 ) 
662             return 0;
663         pwsi->err = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
664     }
665     return SOCKET_ERROR;
666 }
667
668 /***********************************************************************
669  *              closesocket()           (WINSOCK.3)
670  */
671 INT16 WINAPI WINSOCK_closesocket16(SOCKET16 s)
672 {
673     return (INT16)WINSOCK_closesocket32(s);
674 }
675
676 /***********************************************************************
677  *              connect()               (WSOCK32.4)
678  */
679 INT32 WINAPI WINSOCK_connect32(SOCKET32 s, struct sockaddr *name, INT32 namelen)
680 {
681   ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
682   LPWSINFO      pwsi = wsi_find(GetCurrentTask());
683
684   TRACE(winsock, "(%08x): socket %04x, ptr %8x, length %d\n", 
685                            (unsigned)pwsi, s, (int) name, namelen);
686 #if DEBUG_SOCKADDR
687   dump_sockaddr(name);
688 #endif
689
690   if( _check_ws(pwsi, pws) )
691   {
692     if (connect(pws->fd, name, namelen) == 0) 
693     { 
694         if( pws->psop && (pws->flags & WS_FD_CONNECT) )
695         {
696             /* application did AsyncSelect() but then went
697              * ahead and called connect() without waiting for 
698              * notification.
699              *
700              * FIXME: Do we have to post a notification message 
701              *        in this case?
702              */
703
704             if( !(pws->flags & WS_FD_CONNECTED) )
705             {
706                 if( pws->flags & (WS_FD_READ | WS_FD_CLOSE) )
707                     EVENT_AddIO( pws->fd, EVENT_IO_READ );
708                 else
709                     EVENT_DeleteIO( pws->fd, EVENT_IO_READ );
710                 if( pws->flags & WS_FD_WRITE )
711                     EVENT_AddIO( pws->fd, EVENT_IO_WRITE );
712                 else
713                     EVENT_DeleteIO( pws->fd, EVENT_IO_WRITE );
714             }
715         }
716         pws->flags |= WS_FD_CONNECTED;
717         pws->flags &= ~(WS_FD_INACTIVE | WS_FD_CONNECT | WS_FD_LISTENING);
718         return 0; 
719     }
720     pwsi->err = (errno == EINPROGRESS) ? WSAEWOULDBLOCK : wsaErrno();
721   }
722   return SOCKET_ERROR;
723 }
724
725 /***********************************************************************
726  *              connect()               (WINSOCK.4)
727  */
728 INT16 WINAPI WINSOCK_connect16(SOCKET16 s, struct sockaddr *name, INT16 namelen)
729 {
730   return (INT16)WINSOCK_connect32( s, name, namelen );
731 }
732
733 /***********************************************************************
734  *              getpeername()           (WSOCK32.5)
735  */
736 INT32 WINAPI WINSOCK_getpeername32(SOCKET32 s, struct sockaddr *name,
737                                    INT32 *namelen)
738 {
739     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
740     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
741
742     TRACE(winsock, "(%08x): socket: %04x, ptr %8x, ptr %8x\n", 
743                            (unsigned)pwsi, s, (int) name, *namelen);
744     if( _check_ws(pwsi, pws) )
745     {
746         if (getpeername(pws->fd, name, namelen) == 0) 
747             return 0; 
748         pwsi->err = (h_errno < 0) ? wsaErrno() : wsaHerrno();
749     }
750     return SOCKET_ERROR;
751 }
752
753 /***********************************************************************
754  *              getpeername()           (WINSOCK.5)
755  */
756 INT16 WINAPI WINSOCK_getpeername16(SOCKET16 s, struct sockaddr *name,
757                                    INT16 *namelen16)
758 {
759     INT32 namelen32 = *namelen16;
760     INT32 retVal = WINSOCK_getpeername32( s, name, &namelen32 );
761
762 #if DEBUG_SOCKADDR
763     dump_sockaddr(name);
764 #endif
765
766    *namelen16 = namelen32;
767     return (INT16)retVal;
768 }
769
770 /***********************************************************************
771  *              getsockname()           (WSOCK32.6)
772  */
773 INT32 WINAPI WINSOCK_getsockname32(SOCKET32 s, struct sockaddr *name,
774                                    INT32 *namelen)
775 {
776     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
777     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
778
779     TRACE(winsock, "(%08x): socket: %04x, ptr %8x, ptr %8x\n", 
780                           (unsigned)pwsi, s, (int) name, (int) *namelen);
781     if( _check_ws(pwsi, pws) )
782     {
783         if (getsockname(pws->fd, name, namelen) == 0)
784             return 0; 
785         pwsi->err = (h_errno < 0) ? wsaErrno() : wsaHerrno();
786     }
787     return SOCKET_ERROR;
788 }
789
790 /***********************************************************************
791  *              getsockname()           (WINSOCK.6)
792  */
793 INT16 WINAPI WINSOCK_getsockname16(SOCKET16 s, struct sockaddr *name,
794                                    INT16 *namelen16)
795 {
796     INT32 retVal;
797
798     if( namelen16 )
799     {
800         INT32 namelen32 = *namelen16;
801         retVal = WINSOCK_getsockname32( s, name, &namelen32 );
802        *namelen16 = namelen32;
803
804 #if DEBUG_SOCKADDR
805     dump_sockaddr(name);
806 #endif
807
808     }
809     else retVal = SOCKET_ERROR;
810     return (INT16)retVal;
811 }
812
813
814 /***********************************************************************
815  *              getsockopt()            (WSOCK32.7)
816  */
817 INT32 WINAPI WINSOCK_getsockopt32(SOCKET32 s, INT32 level, 
818                                   INT32 optname, char *optval, INT32 *optlen)
819 {
820     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
821     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
822
823     TRACE(winsock, "(%08x): socket: %04x, opt %d, ptr %8x, ptr %8x\n", 
824                            (unsigned)pwsi, s, level, (int) optval, (int) *optlen);
825     if( _check_ws(pwsi, pws) )
826     {
827         convert_sockopt(&level, &optname);
828         if (getsockopt(pws->fd, (int) level, optname, optval, optlen) == 0 )
829             return 0;
830         pwsi->err = (errno == EBADF) ? WSAENOTSOCK : wsaErrno();
831     }
832     return SOCKET_ERROR;
833 }
834
835 /***********************************************************************
836  *              getsockopt()            (WINSOCK.7)
837  */
838 INT16 WINAPI WINSOCK_getsockopt16(SOCKET16 s, INT16 level,
839                                   INT16 optname, char *optval, INT16 *optlen)
840 {
841     INT32 optlen32;
842     INT32 *p = &optlen32;
843     INT32 retVal;
844     if( optlen ) optlen32 = *optlen; else p = NULL;
845     retVal = WINSOCK_getsockopt32( s, (UINT16)level, optname, optval, p );
846     if( optlen ) *optlen = optlen32;
847     return (INT16)retVal;
848 }
849
850 /***********************************************************************
851  *              htonl()                 (WINSOCK.8)(WSOCK32.8)
852  */
853 u_long WINAPI WINSOCK_htonl(u_long hostlong)   { return( htonl(hostlong) ); }
854 /***********************************************************************
855  *              htons()                 (WINSOCK.9)(WSOCK32.9)
856  */
857 u_short WINAPI WINSOCK_htons(u_short hostshort) { return( htons(hostshort) ); }
858 /***********************************************************************
859  *              inet_addr()             (WINSOCK.10)(WSOCK32.10)
860  */
861 u_long WINAPI WINSOCK_inet_addr(char *cp)      { return( inet_addr(cp) ); }
862 /***********************************************************************
863  *              htohl()                 (WINSOCK.14)(WSOCK32.14)
864  */
865 u_long WINAPI WINSOCK_ntohl(u_long netlong)    { return( ntohl(netlong) ); }
866 /***********************************************************************
867  *              ntohs()                 (WINSOCK.15)(WSOCK32.15)
868  */
869 u_short WINAPI WINSOCK_ntohs(u_short netshort)  { return( ntohs(netshort) ); }
870
871 /***********************************************************************
872  *              inet_ntoa()             (WINSOCK.11)(WSOCK32.11)
873  */
874 char* WINAPI WINSOCK_inet_ntoa32(struct in_addr in)
875 {
876   /* use "buffer for dummies" here because some applications have 
877    * propensity to decode addresses in ws_hostent structure without 
878    * saving them first...
879    */
880
881     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
882
883     if( pwsi )
884     {
885         char*   s = inet_ntoa(in);
886         if( s ) 
887         {
888             if( pwsi->dbuffer == NULL )
889                 if((pwsi->dbuffer = (char*) SEGPTR_ALLOC(32)) == NULL )
890                 {
891                     pwsi->err = WSAENOBUFS;
892                     return NULL;
893                 }
894             strncpy(pwsi->dbuffer, s, 32 );
895             return pwsi->dbuffer; 
896         }
897         pwsi->err = wsaErrno();
898     }
899     return NULL;
900 }
901
902 SEGPTR WINAPI WINSOCK_inet_ntoa16(struct in_addr in)
903 {
904   char* retVal = WINSOCK_inet_ntoa32(in);
905   return retVal ? SEGPTR_GET(retVal) : (SEGPTR)NULL;
906 }
907
908 /***********************************************************************
909  *              ioctlsocket()           (WSOCK32.12)
910  */
911 INT32 WINAPI WINSOCK_ioctlsocket32(SOCKET32 s, UINT32 cmd, UINT32 *argp)
912 {
913   ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
914   LPWSINFO      pwsi = wsi_find(GetCurrentTask());
915
916   TRACE(winsock, "(%08x): socket %04x, cmd %08x, ptr %8x\n", 
917                           (unsigned)pwsi, s, cmd, (unsigned) argp);
918   if( _check_ws(pwsi, pws) )
919   {
920     long        newcmd  = cmd;
921
922     switch( cmd )
923     {
924         case WS_FIONREAD:   
925                 newcmd=FIONREAD; 
926                 break;
927
928         case WS_FIONBIO:    
929                 newcmd=FIONBIO;  
930                 if( pws->psop && *argp == 0 ) 
931                 {
932                     /* AsyncSelect()'ed sockets are always nonblocking */
933                     pwsi->err = WSAEINVAL; 
934                     return SOCKET_ERROR; 
935                 }
936                 break;
937
938         case WS_SIOCATMARK: 
939                 newcmd=SIOCATMARK; 
940                 break;
941
942         case WS_IOW('f',125,u_long): 
943                 WARN(winsock,"Warning: WS1.1 shouldn't be using async I/O\n");
944                 pwsi->err = WSAEINVAL; 
945                 return SOCKET_ERROR;
946
947         default:          
948                 /* Netscape tries hard to use bogus ioctl 0x667e */
949                 WARN(winsock, "\tunknown WS_IOCTL cmd (%08x)\n", cmd);
950     }
951     if( ioctl(pws->fd, newcmd, (char*)argp ) == 0 ) return 0;
952     pwsi->err = (errno == EBADF) ? WSAENOTSOCK : wsaErrno(); 
953   }
954   return SOCKET_ERROR;
955 }
956
957 /***********************************************************************
958  *              ioctlsocket()           (WINSOCK.12)
959  */
960 INT16 WINAPI WINSOCK_ioctlsocket16(SOCKET16 s, UINT32 cmd, UINT32 *argp)
961 {
962     return (INT16)WINSOCK_ioctlsocket32( s, cmd, argp );
963 }
964
965
966 /***********************************************************************
967  *              listen()                (WSOCK32.13)
968  */
969 INT32 WINAPI WINSOCK_listen32(SOCKET32 s, INT32 backlog)
970 {
971     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
972     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
973
974     TRACE(winsock, "(%08x): socket %04x, backlog %d\n", 
975                             (unsigned)pwsi, s, backlog);
976     if( _check_ws(pwsi, pws) )
977     {
978         if (listen(pws->fd, backlog) == 0)
979         {
980             if( !pws->psop )
981             {
982                 int  fd_flags = fcntl(pws->fd, F_GETFL, 0);
983                 if( !(fd_flags & O_NONBLOCK) ) pws->flags |= WS_FD_ACCEPT;
984             }
985             pws->flags |= WS_FD_LISTENING;
986             pws->flags &= ~(WS_FD_INACTIVE | WS_FD_CONNECT | WS_FD_CONNECTED); /* just in case */
987             return 0;
988         }
989         pwsi->err = wsaErrno();
990     }
991     else if( pwsi ) pwsi->err = WSAENOTSOCK;
992     return SOCKET_ERROR;
993 }
994
995 /***********************************************************************
996  *              listen()                (WINSOCK.13)
997  */
998 INT16 WINAPI WINSOCK_listen16(SOCKET16 s, INT16 backlog)
999 {
1000     return (INT16)WINSOCK_listen32( s, backlog );
1001 }
1002
1003
1004 /***********************************************************************
1005  *              recv()                  (WSOCK32.16)
1006  */
1007 INT32 WINAPI WINSOCK_recv32(SOCKET32 s, char *buf, INT32 len, INT32 flags)
1008 {
1009     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
1010     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
1011
1012     TRACE(winsock, "(%08x): socket %04x, buf %8x, len %d, "
1013                     "flags %d\n", (unsigned)pwsi, s, (unsigned)buf, 
1014                     len, flags);
1015     if( _check_ws(pwsi, pws) )
1016     {
1017         INT32 length;
1018         if ((length = recv(pws->fd, buf, len, flags)) >= 0) 
1019         { 
1020             TRACE(winsock, " -> %i bytes\n", length);
1021
1022             if( pws->psop && (pws->flags & (WS_FD_READ | WS_FD_CLOSE)) )
1023                 EVENT_AddIO( pws->fd, EVENT_IO_READ );  /* reenabler */
1024
1025             return length;
1026         }
1027         pwsi->err = wsaErrno();
1028     }
1029     else if( pwsi ) pwsi->err = WSAENOTSOCK;
1030     WARN(winsock, " -> ERROR\n");
1031     return SOCKET_ERROR;
1032 }
1033
1034 /***********************************************************************
1035  *              recv()                  (WINSOCK.16)
1036  */
1037 INT16 WINAPI WINSOCK_recv16(SOCKET16 s, char *buf, INT16 len, INT16 flags)
1038 {
1039     return (INT16)WINSOCK_recv32( s, buf, len, flags );
1040 }
1041
1042
1043 /***********************************************************************
1044  *              recvfrom()              (WSOCK32.17)
1045  */
1046 INT32 WINAPI WINSOCK_recvfrom32(SOCKET32 s, char *buf, INT32 len, INT32 flags, 
1047                                 struct sockaddr *from, INT32 *fromlen32)
1048 {
1049     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
1050     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
1051
1052     TRACE(winsock, "(%08x): socket %04x, ptr %08x, "
1053                     "len %d, flags %d\n", (unsigned)pwsi, s, (unsigned)buf,
1054                     len, flags);
1055 #if DEBUG_SOCKADDR
1056     if( from ) dump_sockaddr(from);
1057     else DUMP("from = NULL\n");
1058 #endif
1059
1060     if( _check_ws(pwsi, pws) )
1061     {
1062         int length;
1063
1064         if ((length = recvfrom(pws->fd, buf, len, flags, from, fromlen32)) >= 0)
1065         {
1066             TRACE(winsock, " -> %i bytes\n", length);
1067
1068             if( pws->psop && (pws->flags & (WS_FD_READ | WS_FD_CLOSE)) )
1069                 EVENT_AddIO( pws->fd, EVENT_IO_READ );  /* reenabler */
1070
1071             return (INT16)length;
1072         }
1073         pwsi->err = wsaErrno();
1074     }
1075     else if( pwsi ) pwsi->err = WSAENOTSOCK;
1076     WARN(winsock, " -> ERROR\n");
1077     return SOCKET_ERROR;
1078 }
1079
1080 /***********************************************************************
1081  *              recvfrom()              (WINSOCK.17)
1082  */
1083 INT16 WINAPI WINSOCK_recvfrom16(SOCKET16 s, char *buf, INT16 len, INT16 flags,
1084                                 struct sockaddr *from, INT16 *fromlen16)
1085 {
1086     INT32 fromlen32;
1087     INT32 *p = &fromlen32;
1088     INT32 retVal;
1089
1090     if( fromlen16 ) fromlen32 = *fromlen16; else p = NULL;
1091     retVal = WINSOCK_recvfrom32( s, buf, len, flags, from, p );
1092     if( fromlen16 ) *fromlen16 = fromlen32;
1093     return (INT16)retVal;
1094 }
1095
1096 /***********************************************************************
1097  *              select()                (WINSOCK.18)(WSOCK32.18)
1098  */
1099 static INT32 __ws_select( BOOL32 b32, void *ws_readfds, void *ws_writefds, void *ws_exceptfds,
1100                           struct timeval *timeout )
1101 {
1102     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
1103         
1104     TRACE(winsock, "(%08x): read %8x, write %8x, excp %8x\n", 
1105     (unsigned) pwsi, (unsigned) ws_readfds, (unsigned) ws_writefds, (unsigned) ws_exceptfds);
1106
1107     if( pwsi )
1108     {
1109         int         highfd = 0;
1110         fd_set      readfds, writefds, exceptfds;
1111         fd_set     *p_read, *p_write, *p_except;
1112
1113         p_read = fd_set_import(&readfds, pwsi, ws_readfds, &highfd, b32);
1114         p_write = fd_set_import(&writefds, pwsi, ws_writefds, &highfd, b32);
1115         p_except = fd_set_import(&exceptfds, pwsi, ws_exceptfds, &highfd, b32);
1116
1117         if( (highfd = select(highfd + 1, p_read, p_write, p_except, timeout)) > 0 )
1118         {
1119             fd_set_export(pwsi, &readfds, p_except, ws_readfds, b32);
1120             fd_set_export(pwsi, &writefds, p_except, ws_writefds, b32);
1121
1122             if (p_except && ws_exceptfds)
1123             {
1124 #define wsfds16 ((ws_fd_set16*)ws_exceptfds)
1125 #define wsfds32 ((ws_fd_set32*)ws_exceptfds)
1126                 int i, j, count = (b32) ? wsfds32->fd_count : wsfds16->fd_count;
1127
1128                 for (i = j = 0; i < count; i++)
1129                 {
1130                     ws_socket *pws = (b32) ? (ws_socket *)WS_HANDLE2PTR(wsfds32->fd_array[i])
1131                                            : (ws_socket *)WS_HANDLE2PTR(wsfds16->fd_array[i]);
1132                     if( _check_ws(pwsi, pws) && FD_ISSET(pws->fd, &exceptfds) )
1133                     {
1134                         if( b32 )
1135                                 wsfds32->fd_array[j++] = wsfds32->fd_array[i];
1136                         else
1137                                 wsfds16->fd_array[j++] = wsfds16->fd_array[i];
1138                     }
1139                 }
1140                 if( b32 )
1141                     wsfds32->fd_count = j;
1142                 else
1143                     wsfds16->fd_count = j;
1144 #undef wsfds32
1145 #undef wsfds16
1146             }
1147             return highfd; 
1148         }
1149         if( ws_readfds ) ((ws_fd_set32*)ws_readfds)->fd_count = 0;
1150         if( ws_writefds ) ((ws_fd_set32*)ws_writefds)->fd_count = 0;
1151         if( ws_exceptfds ) ((ws_fd_set32*)ws_exceptfds)->fd_count = 0;
1152
1153         if( highfd == 0 ) return 0;
1154         pwsi->err = wsaErrno();
1155     } 
1156     return SOCKET_ERROR;
1157 }
1158
1159 INT16 WINAPI WINSOCK_select16(INT16 nfds, ws_fd_set16 *ws_readfds,
1160                               ws_fd_set16 *ws_writefds, ws_fd_set16 *ws_exceptfds,
1161                               struct timeval *timeout)
1162 {
1163     return (INT16)__ws_select( FALSE, ws_readfds, ws_writefds, ws_exceptfds, timeout );
1164 }
1165
1166 INT32 WINAPI WINSOCK_select32(INT32 nfds, ws_fd_set32 *ws_readfds,
1167                               ws_fd_set32 *ws_writefds, ws_fd_set32 *ws_exceptfds,
1168                               struct timeval *timeout)
1169 {
1170     /* struct timeval is the same for both 32- and 16-bit code */
1171     return (INT32)__ws_select( TRUE, ws_readfds, ws_writefds, ws_exceptfds, timeout );
1172 }
1173
1174
1175 /***********************************************************************
1176  *              send()                  (WSOCK32.19)
1177  */
1178 INT32 WINAPI WINSOCK_send32(SOCKET32 s, char *buf, INT32 len, INT32 flags)
1179 {
1180     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
1181     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
1182
1183     TRACE(winsock, "(%08x): socket %04x, ptr %08x, length %d, flags %d\n", 
1184                            (unsigned)pwsi, s, (unsigned) buf, len, flags);
1185     if( _check_ws(pwsi, pws) )
1186     {
1187         int     length;
1188
1189         if ((length = send(pws->fd, buf, len, flags)) < 0 ) 
1190         {
1191             pwsi->err = wsaErrno();
1192             if( pwsi->err == WSAEWOULDBLOCK && 
1193                 pws->psop && pws->flags & WS_FD_WRITE )
1194                 EVENT_AddIO( pws->fd, EVENT_IO_WRITE ); /* reenabler */
1195         }
1196         else return (INT16)length;
1197     }
1198     else if( pwsi ) pwsi->err = WSAENOTSOCK;
1199     return SOCKET_ERROR;
1200 }
1201
1202 /***********************************************************************
1203  *              send()                  (WINSOCK.19)
1204  */
1205 INT16 WINAPI WINSOCK_send16(SOCKET16 s, char *buf, INT16 len, INT16 flags)
1206 {
1207     return WINSOCK_send32( s, buf, len, flags );
1208 }
1209
1210 /***********************************************************************
1211  *              sendto()                (WSOCK32.20)
1212  */
1213 INT32 WINAPI WINSOCK_sendto32(SOCKET32 s, char *buf, INT32 len, INT32 flags,
1214                               struct sockaddr *to, INT32 tolen)
1215 {
1216     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
1217     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
1218
1219     TRACE(winsock, "(%08x): socket %04x, ptr %08x, length %d, flags %d\n",
1220                           (unsigned)pwsi, s, (unsigned) buf, len, flags);
1221     if( _check_ws(pwsi, pws) )
1222     {
1223         INT32   length;
1224
1225         if ((length = sendto(pws->fd, buf, len, flags, to, tolen)) < 0 )
1226         {
1227             pwsi->err = wsaErrno();
1228             if( pwsi->err == WSAEWOULDBLOCK &&
1229                 pws->psop && pws->flags & WS_FD_WRITE )
1230                 EVENT_AddIO( pws->fd, EVENT_IO_WRITE ); /* reenabler */
1231         } 
1232         else return length;
1233     }
1234     else if( pwsi ) pwsi->err = WSAENOTSOCK;
1235     return SOCKET_ERROR;
1236 }
1237
1238 /***********************************************************************
1239  *              sendto()                (WINSOCK.20)
1240  */
1241 INT16 WINAPI WINSOCK_sendto16(SOCKET16 s, char *buf, INT16 len, INT16 flags,
1242                               struct sockaddr *to, INT16 tolen)
1243 {
1244     return (INT16)WINSOCK_sendto32( s, buf, len, flags, to, tolen );
1245 }
1246
1247 /***********************************************************************
1248  *              setsockopt()            (WSOCK32.21)
1249  */
1250 INT32 WINAPI WINSOCK_setsockopt32(SOCKET16 s, INT32 level, INT32 optname, 
1251                                   char *optval, INT32 optlen)
1252 {
1253     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
1254     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
1255
1256     TRACE(winsock, "(%08x): socket %04x, lev %d, opt %d, ptr %08x, len %d\n",
1257                           (unsigned)pwsi, s, level, optname, (int) optval, optlen);
1258     if( _check_ws(pwsi, pws) )
1259     {
1260         struct  linger linger;
1261
1262         convert_sockopt(&level, &optname);
1263         if (optname == SO_LINGER) {
1264                 /* yes, uses unsigned short in both win16/win32 */
1265                 linger.l_onoff  = ((UINT16*)optval)[0];
1266                 linger.l_linger = ((UINT16*)optval)[1];
1267                 optval = (char*)&linger;
1268                 optlen = sizeof(struct linger);
1269         }
1270         if (setsockopt(pws->fd, level, optname, optval, optlen) == 0) return 0;
1271         pwsi->err = wsaErrno();
1272     }
1273     else if( pwsi ) pwsi->err = WSAENOTSOCK;
1274     return SOCKET_ERROR;
1275 }
1276
1277 /***********************************************************************
1278  *              setsockopt()            (WINSOCK.21)
1279  */
1280 INT16 WINAPI WINSOCK_setsockopt16(SOCKET16 s, INT16 level, INT16 optname,
1281                                   char *optval, INT16 optlen)
1282 {
1283     if( !optval ) return SOCKET_ERROR;
1284     return (INT16)WINSOCK_setsockopt32( s, (UINT16)level, optname, optval, optlen );
1285 }
1286
1287
1288 /***********************************************************************
1289  *              shutdown()              (WSOCK32.22)
1290  */
1291 INT32 WINAPI WINSOCK_shutdown32(SOCKET32 s, INT32 how)
1292 {
1293     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
1294     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
1295
1296     TRACE(winsock, "(%08x): socket %04x, how %i\n",
1297                             (unsigned)pwsi, s, how );
1298     if( _check_ws(pwsi, pws) )
1299     {
1300         if( pws->psop )
1301             switch( how )
1302             {
1303                 case 0: /* drop receives */
1304                         if( pws->flags & (WS_FD_READ | WS_FD_CLOSE) )
1305                             EVENT_DeleteIO( pws->fd, EVENT_IO_READ );
1306                         pws->flags &= ~(WS_FD_READ | WS_FD_CLOSE);
1307 #ifdef SHUT_RD
1308                         how = SHUT_RD;
1309 #endif
1310                         break;
1311
1312                 case 1: /* drop sends */
1313                         if( pws->flags & WS_FD_WRITE )
1314                             EVENT_DeleteIO( pws->fd, EVENT_IO_WRITE );
1315                         pws->flags &= ~WS_FD_WRITE;
1316 #ifdef SHUT_WR
1317                         how = SHUT_WR;
1318 #endif
1319                         break;
1320
1321                 case 2: /* drop all */
1322 #ifdef SHUT_RDWR
1323                         how = SHUT_RDWR;
1324 #endif
1325                 default:
1326                         WSAAsyncSelect32( s, 0, 0, 0 );
1327                         break;
1328             }
1329
1330         if (shutdown(pws->fd, how) == 0) 
1331         {
1332             if( how > 1 ) 
1333             {
1334                 pws->flags &= ~(WS_FD_CONNECTED | WS_FD_LISTENING);
1335                 pws->flags |= WS_FD_INACTIVE;
1336             }
1337             return 0;
1338         }
1339         pwsi->err = wsaErrno();
1340     } 
1341     else if( pwsi ) pwsi->err = WSAENOTSOCK;
1342     return SOCKET_ERROR;
1343 }
1344
1345 /***********************************************************************
1346  *              shutdown()              (WINSOCK.22)
1347  */
1348 INT16 WINAPI WINSOCK_shutdown16(SOCKET16 s, INT16 how)
1349 {
1350     return (INT16)WINSOCK_shutdown32( s, how );
1351 }
1352
1353
1354 /***********************************************************************
1355  *              socket()                (WSOCK32.23)
1356  */
1357 SOCKET32 WINAPI WINSOCK_socket32(INT32 af, INT32 type, INT32 protocol)
1358 {
1359   LPWSINFO      pwsi = wsi_find(GetCurrentTask());
1360
1361   TRACE(winsock, "(%08x): af=%d type=%d protocol=%d\n", 
1362                           (unsigned)pwsi, af, type, protocol);
1363
1364   if( pwsi )
1365   {
1366     int         sock;
1367
1368     /* check the socket family */
1369     switch(af) 
1370     {
1371         case AF_INET:
1372         case AF_UNSPEC: break;
1373         default:        pwsi->err = WSAEAFNOSUPPORT; 
1374                         return INVALID_SOCKET32;
1375     }
1376
1377     /* check the socket type */
1378     switch(type) 
1379     {
1380         case SOCK_STREAM:
1381         case SOCK_DGRAM:
1382         case SOCK_RAW:  break;
1383         default:        pwsi->err = WSAESOCKTNOSUPPORT; 
1384                         return INVALID_SOCKET32;
1385     }
1386
1387     /* check the protocol type */
1388     if ( protocol < 0 )  /* don't support negative values */
1389     { pwsi->err = WSAEPROTONOSUPPORT; return INVALID_SOCKET32; }
1390
1391     if ( af == AF_UNSPEC)  /* did they not specify the address family? */
1392         switch(protocol) 
1393         {
1394           case IPPROTO_TCP:
1395              if (type == SOCK_STREAM) { af = AF_INET; break; }
1396           case IPPROTO_UDP:
1397              if (type == SOCK_DGRAM)  { af = AF_INET; break; }
1398           default: pwsi->err = WSAEPROTOTYPE; return INVALID_SOCKET32;
1399         }
1400
1401     if ((sock = socket(af, type, protocol)) >= 0) 
1402     {
1403         ws_socket*      pnew = wsi_alloc_socket(pwsi, sock);
1404
1405         TRACE(winsock,"\tcreated %i (handle %04x)\n", sock, (UINT16)WS_PTR2HANDLE(pnew));
1406
1407         if( pnew ) 
1408         {
1409             pnew->flags |= WS_FD_INACTIVE;
1410             return (SOCKET16)WS_PTR2HANDLE(pnew);
1411         }
1412         
1413         close(sock);
1414         pwsi->err = WSAENOBUFS;
1415         return INVALID_SOCKET32;
1416     }
1417
1418     if (errno == EPERM) /* raw socket denied */
1419     {
1420         WARN(winsock, "WS_SOCKET: not enough privileges\n");
1421         pwsi->err = WSAESOCKTNOSUPPORT;
1422     } else pwsi->err = wsaErrno();
1423   }
1424  
1425   WARN(winsock, "\t\tfailed!\n");
1426   return INVALID_SOCKET32;
1427 }
1428
1429 /***********************************************************************
1430  *              socket()                (WINSOCK.23)
1431  */
1432 SOCKET16 WINAPI WINSOCK_socket16(INT16 af, INT16 type, INT16 protocol)
1433 {
1434     return (SOCKET16)WINSOCK_socket32( af, type, protocol );
1435 }
1436     
1437
1438 /* ----------------------------------- DNS services
1439  *
1440  * IMPORTANT: 16-bit API structures have SEGPTR pointers inside them.
1441  * Also, we have to use wsock32 stubs to convert structures and
1442  * error codes from Unix to WSA, hence there is no direct mapping in 
1443  * the relay32/wsock32.spec.
1444  */
1445
1446 static char*    NULL_STRING = "NULL";
1447
1448 /***********************************************************************
1449  *              gethostbyaddr()         (WINSOCK.51)(WSOCK32.51)
1450  */
1451 static struct WIN_hostent* __ws_gethostbyaddr(const char *addr, int len, int type, int dup_flag)
1452 {
1453     LPWSINFO            pwsi = wsi_find(GetCurrentTask());
1454
1455     if( pwsi )
1456     {
1457         struct hostent* host;
1458         if( (host = gethostbyaddr(addr, len, type)) != NULL )
1459             if( WS_dup_he(pwsi, host, dup_flag) )
1460                 return (struct WIN_hostent*)(pwsi->he);
1461             else 
1462                 pwsi->err = WSAENOBUFS;
1463         else 
1464             pwsi->err = (h_errno < 0) ? wsaErrno() : wsaHerrno();
1465     }
1466     return NULL;
1467 }
1468
1469 SEGPTR WINAPI WINSOCK_gethostbyaddr16(const char *addr, INT16 len, INT16 type)
1470 {
1471     struct WIN_hostent* retval;
1472     TRACE(winsock, "ptr %08x, len %d, type %d\n",
1473                             (unsigned) addr, len, type);
1474     retval = __ws_gethostbyaddr( addr, len, type, WS_DUP_SEGPTR );
1475     return retval ? SEGPTR_GET(retval) : ((SEGPTR)NULL);
1476 }
1477
1478 struct WIN_hostent* WINAPI WINSOCK_gethostbyaddr32(const char *addr, INT32 len,
1479                                                 INT32 type)
1480 {
1481     TRACE(winsock, "ptr %08x, len %d, type %d\n",
1482                              (unsigned) addr, len, type);
1483     return __ws_gethostbyaddr(addr, len, type, WS_DUP_LINEAR);
1484 }
1485
1486 /***********************************************************************
1487  *              gethostbyname()         (WINSOCK.52)(WSOCK32.52)
1488  */
1489 static struct WIN_hostent * __ws_gethostbyname(const char *name, int dup_flag)
1490 {
1491     LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1492
1493     if( pwsi )
1494     {
1495         struct hostent*     host;
1496         if( (host = gethostbyname(name)) != NULL )
1497              if( WS_dup_he(pwsi, host, dup_flag) )
1498                  return (struct WIN_hostent*)(pwsi->he);
1499              else pwsi->err = WSAENOBUFS;
1500         else pwsi->err = (h_errno < 0) ? wsaErrno() : wsaHerrno();
1501     }
1502     return NULL;
1503 }
1504
1505 SEGPTR WINAPI WINSOCK_gethostbyname16(const char *name)
1506 {
1507     struct WIN_hostent* retval;
1508     TRACE(winsock, "%s\n", (name)?name:NULL_STRING);
1509     retval = __ws_gethostbyname( name, WS_DUP_SEGPTR );
1510     return (retval)? SEGPTR_GET(retval) : ((SEGPTR)NULL) ;
1511 }
1512
1513 struct WIN_hostent* WINAPI WINSOCK_gethostbyname32(const char* name)
1514 {
1515     TRACE(winsock, "%s\n", (name)?name:NULL_STRING);
1516     return __ws_gethostbyname( name, WS_DUP_LINEAR );
1517 }
1518
1519
1520 /***********************************************************************
1521  *              getprotobyname()        (WINSOCK.53)(WSOCK32.53)
1522  */
1523 static struct WIN_protoent* __ws_getprotobyname(const char *name, int dup_flag)
1524 {
1525     LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1526
1527     if( pwsi )
1528     {
1529         struct protoent*     proto;
1530         if( (proto = getprotobyname(name)) != NULL )
1531             if( WS_dup_pe(pwsi, proto, dup_flag) )
1532                 return (struct WIN_protoent*)(pwsi->pe);
1533             else pwsi->err = WSAENOBUFS;
1534         else pwsi->err = (h_errno < 0) ? wsaErrno() : wsaHerrno();
1535     }
1536     return NULL;
1537 }
1538
1539 SEGPTR WINAPI WINSOCK_getprotobyname16(const char *name)
1540 {
1541     struct WIN_protoent* retval;
1542     TRACE(winsock, "%s\n", (name)?name:NULL_STRING);
1543     retval = __ws_getprotobyname(name, WS_DUP_SEGPTR);
1544     return retval ? SEGPTR_GET(retval) : ((SEGPTR)NULL);
1545 }
1546
1547 struct WIN_protoent* WINAPI WINSOCK_getprotobyname32(const char* name)
1548 {
1549     TRACE(winsock, "%s\n", (name)?name:NULL_STRING);
1550     return __ws_getprotobyname(name, WS_DUP_LINEAR);
1551 }
1552
1553
1554 /***********************************************************************
1555  *              getprotobynumber()      (WINSOCK.54)(WSOCK32.54)
1556  */
1557 static struct WIN_protoent* __ws_getprotobynumber(int number, int dup_flag)
1558 {
1559     LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1560
1561     if( pwsi )
1562     {
1563         struct protoent*     proto;
1564         if( (proto = getprotobynumber(number)) != NULL )
1565             if( WS_dup_pe(pwsi, proto, dup_flag) )
1566                 return (struct WIN_protoent*)(pwsi->pe);
1567             else pwsi->err = WSAENOBUFS;
1568         else pwsi->err = WSANO_DATA;
1569     }
1570     return NULL;
1571 }
1572
1573 SEGPTR WINAPI WINSOCK_getprotobynumber16(INT16 number)
1574 {
1575     struct WIN_protoent* retval;
1576     TRACE(winsock, "%i\n", number);
1577     retval = __ws_getprotobynumber(number, WS_DUP_SEGPTR);
1578     return retval ? SEGPTR_GET(retval) : ((SEGPTR)NULL);
1579 }
1580
1581 struct WIN_protoent* WINAPI WINSOCK_getprotobynumber32(INT32 number)
1582 {
1583     TRACE(winsock, "%i\n", number);
1584     return __ws_getprotobynumber(number, WS_DUP_LINEAR);
1585 }
1586
1587
1588 /***********************************************************************
1589  *              getservbyname()         (WINSOCK.55)(WSOCK32.55)
1590  */
1591 struct WIN_servent* __ws_getservbyname(const char *name, const char *proto, int dup_flag)
1592 {
1593     LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1594
1595     if( pwsi )
1596     {
1597         struct servent*     serv;
1598         int i = wsi_strtolo( pwsi, name, proto );
1599
1600         if( i )
1601             if( (serv = getservbyname(pwsi->buffer, pwsi->buffer + i)) != NULL )
1602                 if( WS_dup_se(pwsi, serv, dup_flag) )
1603                     return (struct WIN_servent*)(pwsi->se);
1604                 else pwsi->err = WSAENOBUFS;
1605             else pwsi->err = (h_errno < 0) ? wsaErrno() : wsaHerrno();
1606         else pwsi->err = WSAENOBUFS;
1607     }
1608     return NULL;
1609 }
1610
1611 SEGPTR WINAPI WINSOCK_getservbyname16(const char *name, const char *proto)
1612 {
1613     struct WIN_servent* retval;
1614     TRACE(winsock, "'%s', '%s'\n",
1615                             (name)?name:NULL_STRING, (proto)?proto:NULL_STRING);
1616     retval = __ws_getservbyname(name, proto, WS_DUP_SEGPTR);
1617     return retval ? SEGPTR_GET(retval) : ((SEGPTR)NULL);
1618 }
1619
1620 struct WIN_servent* WINAPI WINSOCK_getservbyname32(const char *name, const char *proto)
1621 {
1622     TRACE(winsock, "'%s', '%s'\n",
1623                             (name)?name:NULL_STRING, (proto)?proto:NULL_STRING);
1624     return __ws_getservbyname(name, proto, WS_DUP_LINEAR);
1625 }
1626
1627
1628 /***********************************************************************
1629  *              getservbyport()         (WINSOCK.56)(WSOCK32.56)
1630  */
1631 static struct WIN_servent* __ws_getservbyport(int port, const char* proto, int dup_flag)
1632 {
1633     LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1634
1635     if( pwsi )
1636     {
1637         struct servent*     serv;
1638         int i = wsi_strtolo( pwsi, proto, NULL );
1639
1640         if( i )
1641             if( (serv = getservbyport(port, pwsi->buffer)) != NULL )
1642                 if( WS_dup_se(pwsi, serv, dup_flag) )
1643                     return (struct WIN_servent*)(pwsi->se);
1644                 else pwsi->err = WSAENOBUFS;
1645             else pwsi->err = (h_errno < 0) ? wsaErrno() : wsaHerrno();
1646         else pwsi->err = WSAENOBUFS;
1647     }
1648     return NULL;
1649 }
1650
1651 SEGPTR WINAPI WINSOCK_getservbyport16(INT16 port, const char *proto)
1652 {
1653     struct WIN_servent* retval;
1654     TRACE(winsock, "%i, '%s'\n",
1655                             (int)port, (proto)?proto:NULL_STRING);
1656     retval = __ws_getservbyport(port, proto, WS_DUP_SEGPTR);
1657     return retval ? SEGPTR_GET(retval) : ((SEGPTR)NULL);
1658 }
1659
1660 struct WIN_servent* WINAPI WINSOCK_getservbyport32(INT32 port, const char *proto)
1661 {
1662     TRACE(winsock, "%i, '%s'\n",
1663                             (int)port, (proto)?proto:NULL_STRING);
1664     return __ws_getservbyport(port, proto, WS_DUP_LINEAR);
1665 }
1666
1667
1668 /***********************************************************************
1669  *              gethostname()           (WSOCK32.57)
1670  */
1671 INT32 WINAPI WINSOCK_gethostname32(char *name, INT32 namelen)
1672 {
1673     LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1674
1675     TRACE(winsock, "(%08x): name %s, len %d\n",
1676                           (unsigned)pwsi, (name)?name:NULL_STRING, namelen);
1677     if( pwsi )
1678     {
1679         if (gethostname(name, namelen) == 0) return 0;
1680         pwsi->err = (errno == EINVAL) ? WSAEFAULT : wsaErrno();
1681     }
1682     return SOCKET_ERROR;
1683 }
1684
1685 /***********************************************************************
1686  *              gethostname()           (WINSOCK.57)
1687  */
1688 INT16 WINAPI WINSOCK_gethostname16(char *name, INT16 namelen)
1689 {
1690     return (INT16)WINSOCK_gethostname32(name, namelen);
1691 }
1692
1693
1694 /* ------------------------------------- Windows sockets extensions -- *
1695  *                                                                     *
1696  * ------------------------------------------------------------------- */
1697
1698
1699 /***********************************************************************
1700  *       WSAAsyncGetHostByAddr()        (WINSOCK.102)
1701  */
1702 HANDLE16 WINAPI WSAAsyncGetHostByAddr16(HWND16 hWnd, UINT16 uMsg, LPCSTR addr,
1703                                INT16 len, INT16 type, SEGPTR sbuf, INT16 buflen)
1704 {
1705   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1706
1707   TRACE(winsock, "(%08x): hwnd %04x, msg %04x, addr %08x[%i]\n",
1708                (unsigned)pwsi, hWnd, uMsg, (unsigned)addr , len );
1709
1710   if( pwsi ) 
1711     return __WSAsyncDBQuery(pwsi, hWnd, uMsg, type, addr, len,
1712                             NULL, (void*)sbuf, buflen, WSMSG_ASYNC_HOSTBYADDR );
1713   return 0;
1714 }
1715
1716 /***********************************************************************
1717  *       WSAAsyncGetHostByAddr()        (WSOCK32.102)
1718  */
1719 HANDLE32 WINAPI WSAAsyncGetHostByAddr32(HWND32 hWnd, UINT32 uMsg, LPCSTR addr,
1720                                INT32 len, INT32 type, LPSTR sbuf, INT32 buflen)
1721 {
1722   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1723
1724   TRACE(winsock, "(%08x): hwnd %04x, msg %08x, addr %08x[%i]\n",
1725                (unsigned)pwsi, (HWND16)hWnd, uMsg, (unsigned)addr , len );
1726
1727   if( pwsi )
1728     return __WSAsyncDBQuery(pwsi, hWnd, uMsg, type, addr, len,
1729                             NULL, (void*)sbuf, buflen, WSMSG_ASYNC_HOSTBYADDR | WSMSG_WIN32_AOP);
1730   return 0;
1731 }
1732
1733
1734 /***********************************************************************
1735  *       WSAAsyncGetHostByName()        (WINSOCK.103)
1736  */
1737 HANDLE16 WINAPI WSAAsyncGetHostByName16(HWND16 hWnd, UINT16 uMsg, LPCSTR name, 
1738                                       SEGPTR sbuf, INT16 buflen)
1739 {
1740   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1741
1742   TRACE(winsock, "(%08x): hwnd %04x, msg %04x, host %s, 
1743 buffer %i\n", (unsigned)pwsi, hWnd, uMsg, (name)?name:NULL_STRING, (int)buflen );
1744
1745   if( pwsi )
1746     return __WSAsyncDBQuery(pwsi, hWnd, uMsg, 0, name, 0,
1747                             NULL, (void*)sbuf, buflen, WSMSG_ASYNC_HOSTBYNAME );
1748   return 0;
1749 }                     
1750
1751 /***********************************************************************
1752  *       WSAAsyncGetHostByName32()      (WSOCK32.103)
1753  */
1754 HANDLE32 WINAPI WSAAsyncGetHostByName32(HWND32 hWnd, UINT32 uMsg, LPCSTR name, 
1755                                         LPSTR sbuf, INT32 buflen)
1756 {
1757   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1758   TRACE(winsock, "(%08x): hwnd %04x, msg %08x, host %s, buffer %i\n", 
1759                (unsigned)pwsi, (HWND16)hWnd, uMsg, 
1760                (name)?name:NULL_STRING, (int)buflen );
1761   if( pwsi )
1762     return __WSAsyncDBQuery(pwsi, hWnd, uMsg, 0, name, 0,
1763                             NULL, (void*)sbuf, buflen, WSMSG_ASYNC_HOSTBYNAME | WSMSG_WIN32_AOP);
1764   return 0;
1765 }                     
1766
1767
1768 /***********************************************************************
1769  *       WSAAsyncGetProtoByName()       (WINSOCK.105)
1770  */
1771 HANDLE16 WINAPI WSAAsyncGetProtoByName16(HWND16 hWnd, UINT16 uMsg, LPCSTR name, 
1772                                          SEGPTR sbuf, INT16 buflen)
1773 {
1774   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1775
1776   TRACE(winsock, "(%08x): hwnd %04x, msg %08x, protocol %s\n",
1777                (unsigned)pwsi, (HWND16)hWnd, uMsg, (name)?name:NULL_STRING );
1778
1779   if( pwsi )
1780     return __WSAsyncDBQuery(pwsi, hWnd, uMsg, 0, name, 0,
1781                             NULL, (void*)sbuf, buflen, WSMSG_ASYNC_PROTOBYNAME );
1782   return 0;
1783 }
1784
1785 /***********************************************************************
1786  *       WSAAsyncGetProtoByName()       (WSOCK32.105)
1787  */
1788 HANDLE32 WINAPI WSAAsyncGetProtoByName32(HWND32 hWnd, UINT32 uMsg, LPCSTR name,
1789                                          LPSTR sbuf, INT32 buflen)
1790 {
1791   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1792
1793   TRACE(winsock, "(%08x): hwnd %04x, msg %08x, protocol %s\n",
1794                (unsigned)pwsi, (HWND16)hWnd, uMsg, (name)?name:NULL_STRING );
1795
1796   if( pwsi )
1797     return __WSAsyncDBQuery(pwsi, hWnd, uMsg, 0, name, 0,
1798                             NULL, (void*)sbuf, buflen, WSMSG_ASYNC_PROTOBYNAME | WSMSG_WIN32_AOP);
1799   return 0;
1800 }
1801
1802
1803 /***********************************************************************
1804  *       WSAAsyncGetProtoByNumber()     (WINSOCK.104)
1805  */
1806 HANDLE16 WINAPI WSAAsyncGetProtoByNumber16(HWND16 hWnd, UINT16 uMsg, INT16 number, 
1807                                            SEGPTR sbuf, INT16 buflen)
1808 {
1809   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1810
1811   TRACE(winsock, "(%08x): hwnd %04x, msg %04x, num %i\n",
1812                (unsigned)pwsi, hWnd, uMsg, number );
1813
1814   if( pwsi )
1815     return __WSAsyncDBQuery(pwsi, hWnd, uMsg, number, NULL, 0,
1816                             NULL, (void*)sbuf, buflen, WSMSG_ASYNC_PROTOBYNUM );
1817   return 0;
1818 }
1819
1820 /***********************************************************************
1821  *       WSAAsyncGetProtoByNumber()     (WSOCK32.104)
1822  */
1823 HANDLE32 WINAPI WSAAsyncGetProtoByNumber32(HWND32 hWnd, UINT32 uMsg, INT32 number,
1824                                            LPSTR sbuf, INT32 buflen)
1825 {
1826   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1827
1828   TRACE(winsock, "(%08x): hwnd %04x, msg %08x, num %i\n",
1829                (unsigned)pwsi, (HWND16)hWnd, uMsg, number );
1830
1831   if( pwsi )
1832     return __WSAsyncDBQuery(pwsi, hWnd, uMsg, number, NULL, 0,
1833                             NULL, (void*)sbuf, buflen, WSMSG_ASYNC_PROTOBYNUM | WSMSG_WIN32_AOP);
1834   return 0;
1835 }
1836
1837
1838 /***********************************************************************
1839  *       WSAAsyncGetServByName()        (WINSOCK.107)
1840  */
1841 HANDLE16 WINAPI WSAAsyncGetServByName16(HWND16 hWnd, UINT16 uMsg, LPCSTR name, 
1842                                         LPCSTR proto, SEGPTR sbuf, INT16 buflen)
1843 {
1844   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1845
1846   TRACE(winsock, "(%08x): hwnd %04x, msg %04x, name %s, proto %s\n",
1847                (unsigned)pwsi, hWnd, uMsg, 
1848                (name)?name:NULL_STRING, (proto)?proto:NULL_STRING );
1849
1850   if( pwsi )
1851   {
1852       int i = wsi_strtolo( pwsi, name, proto );
1853
1854       if( i )
1855           return __WSAsyncDBQuery(pwsi, hWnd, uMsg, 0, pwsi->buffer, 0,
1856                     pwsi->buffer + i, (void*)sbuf, buflen, WSMSG_ASYNC_SERVBYNAME );
1857   }
1858   return 0;
1859 }
1860
1861 /***********************************************************************
1862  *       WSAAsyncGetServByName()        (WSOCK32.107)
1863  */
1864 HANDLE32 WINAPI WSAAsyncGetServByName32(HWND32 hWnd, UINT32 uMsg, LPCSTR name,
1865                                         LPCSTR proto, LPSTR sbuf, INT32 buflen)
1866 {
1867   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1868
1869   TRACE(winsock, "(%08x): hwnd %04x, msg %08x, name %s, proto %s\n",
1870                (unsigned)pwsi, (HWND16)hWnd, uMsg, 
1871                (name)?name:NULL_STRING, (proto)?proto:NULL_STRING );
1872   if( pwsi )
1873   {
1874       int i = wsi_strtolo( pwsi, name, proto );
1875
1876       if( i )
1877           return __WSAsyncDBQuery(pwsi, hWnd, uMsg, 0, pwsi->buffer, 0,
1878                  pwsi->buffer + i, (void*)sbuf, buflen, WSMSG_ASYNC_SERVBYNAME | WSMSG_WIN32_AOP);
1879   }
1880   return 0;
1881 }
1882
1883
1884 /***********************************************************************
1885  *       WSAAsyncGetServByPort()        (WINSOCK.106)
1886  */
1887 HANDLE16 WINAPI WSAAsyncGetServByPort16(HWND16 hWnd, UINT16 uMsg, INT16 port, 
1888                                         LPCSTR proto, SEGPTR sbuf, INT16 buflen)
1889 {
1890   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1891
1892   TRACE(winsock, "(%08x): hwnd %04x, msg %04x, port %i, proto %s\n",
1893                (unsigned)pwsi, hWnd, uMsg, port, (proto)?proto:NULL_STRING );
1894
1895   if( pwsi )
1896   {
1897       int i = wsi_strtolo( pwsi, proto, NULL );
1898
1899       if( i )
1900           return __WSAsyncDBQuery(pwsi, hWnd, uMsg, port, pwsi->buffer, 0,
1901                 NULL, (void*)sbuf, buflen, WSMSG_ASYNC_SERVBYPORT );
1902   }
1903   return 0;
1904 }
1905
1906 /***********************************************************************
1907  *       WSAAsyncGetServByPort()        (WSOCK32.106)
1908  */
1909 HANDLE32 WINAPI WSAAsyncGetServByPort32(HWND32 hWnd, UINT32 uMsg, INT32 port,
1910                                         LPCSTR proto, LPSTR sbuf, INT32 buflen)
1911 {
1912   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
1913
1914   TRACE(winsock, "(%08x): hwnd %04x, msg %08x, port %i, proto %s\n",
1915                (unsigned)pwsi, (HWND16)hWnd, uMsg, port, (proto)?proto:NULL_STRING );
1916
1917   if( pwsi )
1918   {
1919       int i = wsi_strtolo( pwsi, proto, NULL );
1920
1921       if( i )
1922           return __WSAsyncDBQuery(pwsi, hWnd, uMsg, port, pwsi->buffer, 0,
1923                  NULL, (void*)sbuf, buflen, WSMSG_ASYNC_SERVBYPORT | WSMSG_WIN32_AOP);
1924   }
1925   return 0;
1926 }
1927
1928
1929 /***********************************************************************
1930  *       WSACancelAsyncRequest()        (WINSOCK.108)(WSOCK32.109)
1931  */
1932 INT32 WINAPI WSACancelAsyncRequest32(HANDLE32 hAsyncTaskHandle)
1933 {
1934     INT32               retVal = SOCKET_ERROR;
1935     LPWSINFO            pwsi = wsi_find(GetCurrentTask());
1936     ws_async_op*        p_aop = (ws_async_op*)WS_HANDLE2PTR(hAsyncTaskHandle);
1937
1938     TRACE(winsock, "(%08x): handle %08x\n", 
1939                            (unsigned)pwsi, hAsyncTaskHandle);
1940     if( pwsi )
1941     {
1942         SIGNAL_MaskAsyncEvents( TRUE ); /* block SIGIO */
1943         if( WINSOCK_cancel_async_op(p_aop) )
1944         {
1945             WS_FREE(p_aop);
1946             pwsi->num_async_rq--;
1947             retVal = 0;
1948         }
1949         else pwsi->err = WSAEINVAL;
1950         SIGNAL_MaskAsyncEvents( FALSE );
1951     }
1952     return retVal;
1953 }
1954
1955 INT16 WINAPI WSACancelAsyncRequest16(HANDLE16 hAsyncTaskHandle)
1956 {
1957     return (HANDLE16)WSACancelAsyncRequest32((HANDLE32)hAsyncTaskHandle);
1958 }
1959
1960 /***********************************************************************
1961  *      WSAAsyncSelect()                (WINSOCK.101)(WSOCK32.101)
1962  */
1963
1964 static ws_select_op* __ws_select_list = NULL;
1965
1966 BOOL32 WINSOCK_HandleIO( int* max_fd, int num_pending, 
1967                          fd_set pending_set[3], fd_set event_set[3] )
1968 {
1969     /* This function is called by the event dispatcher
1970      * with the pending_set[] containing the result of select() and
1971      * the event_set[] containing all fd that are being watched */
1972
1973     ws_select_op*       psop = __ws_select_list;
1974     BOOL32              bPost = FALSE;
1975     DWORD               dwEvent, dwErrBytes;
1976     int                 num_posted;
1977
1978     TRACE(winsock,"%i pending descriptors\n", num_pending );
1979
1980     for( num_posted = dwEvent = 0 ; psop; psop = psop->next )
1981     {
1982         unsigned        flags = psop->pws->flags;
1983         int             fd = psop->pws->fd;
1984         int             r, w, e;
1985
1986         w = 0;
1987         if( (r = FD_ISSET( fd, &pending_set[EVENT_IO_READ] )) ||
1988             (w = FD_ISSET( fd, &pending_set[EVENT_IO_WRITE] )) ||
1989             (e = FD_ISSET( fd, &pending_set[EVENT_IO_EXCEPT] )) )
1990         {
1991             /* This code removes WS_FD flags on one-shot events (WS_FD_CLOSE, 
1992              * WS_FD_CONNECT), otherwise it clears descriptors in the io_set.
1993              * Reenabling calls turn them back on.
1994              */
1995
1996             TRACE(winsock,"\tchecking psop = 0x%08x\n", (unsigned) psop );
1997
1998             num_pending--;
1999
2000             /* Now figure out what kind of event we've got. The worst problem
2001              * we have to contend with is that some out of control applications 
2002              * really want to use mutually exclusive AsyncSelect() flags all at
2003              * the same time.
2004              */
2005
2006             if((flags & WS_FD_ACCEPT) && (flags & WS_FD_LISTENING))
2007             {
2008                 /* WS_FD_ACCEPT is valid only if the socket is in the
2009                  * listening state */
2010
2011                 FD_CLR( fd, &event_set[EVENT_IO_WRITE] );
2012                 if( r )
2013                 {
2014                     FD_CLR( fd, &event_set[EVENT_IO_READ] ); /* reenabled by the next accept() */
2015                     dwEvent = WSAMAKESELECTREPLY( WS_FD_ACCEPT, 0 );
2016                     bPost = TRUE;
2017                 } 
2018                 else continue;
2019             }
2020             else if( flags & WS_FD_CONNECT )
2021             {
2022                 /* connecting socket */
2023
2024                 if( w || (w = FD_ISSET( fd, &pending_set[EVENT_IO_WRITE] )) )
2025                 {
2026                     /* ready to write means that socket is connected 
2027                      *
2028                      * FIXME: Netscape calls AsyncSelect( s, ... WS_FD_CONNECT .. )
2029                      * right after s = socket() and somehow "s" becomes writeable 
2030                      * before it goes through connect()!?!?
2031                      */
2032
2033                     psop->pws->flags |= WS_FD_CONNECTED;
2034                     psop->pws->flags &= ~(WS_FD_CONNECT | WS_FD_INACTIVE);
2035                     dwEvent = WSAMAKESELECTREPLY( WS_FD_CONNECT, 0 );
2036
2037                     if( flags & (WS_FD_READ | WS_FD_CLOSE))
2038                         FD_SET( fd, &event_set[EVENT_IO_READ] );
2039                     else 
2040                         FD_CLR( fd, &event_set[EVENT_IO_READ] );
2041                     if( flags & WS_FD_WRITE ) 
2042                         FD_SET( fd, &event_set[EVENT_IO_WRITE] );
2043                     else 
2044                         FD_CLR( fd, &event_set[EVENT_IO_WRITE] );
2045                     bPost = TRUE;
2046                 }
2047                 else if( r )
2048                 {
2049                     /* failure - do read() to get correct errno */
2050
2051                     if( read( fd, &dwErrBytes, sizeof(dwErrBytes) ) == -1 )
2052                     {
2053                         dwEvent = WSAMAKESELECTREPLY( WS_FD_CONNECT, wsaErrno() );
2054                         bPost = TRUE;
2055                     }
2056                 }
2057                 /* otherwise bPost stays FALSE, should probably clear event_set  */
2058             }
2059             else 
2060             {
2061                 /* connected socket, no WS_FD_OOB code for now. */
2062
2063                 if( flags & WS_FD_WRITE &&
2064                    (w || (w = FD_ISSET( fd, &pending_set[EVENT_IO_WRITE] ))) )
2065                 {
2066                     /* this will be reenabled when send() or sendto() fail with
2067                      * WSAEWOULDBLOCK */
2068
2069                     if( PostMessage32A( psop->hWnd, psop->uMsg, (WPARAM32)WS_PTR2HANDLE(psop->pws), 
2070                                       (LPARAM)WSAMAKESELECTREPLY( WS_FD_WRITE, 0 ) ) )
2071                     {
2072                         TRACE(winsock, "\t    hwnd %04x - %04x, %08x\n",
2073                                 psop->hWnd, psop->uMsg, (unsigned)MAKELONG(WS_FD_WRITE, 0) );
2074                         FD_CLR( fd, &event_set[EVENT_IO_WRITE] );
2075                         num_posted++;
2076                     }
2077                 }
2078
2079                 if( r && (flags & (WS_FD_READ | WS_FD_CLOSE)) )
2080                 {
2081                     int val = (flags & WS_FD_RAW);
2082
2083                      /* WS_FD_RAW is set by the WSAAsyncSelect() init */
2084
2085                     bPost = TRUE;
2086                     if( !val && ioctl( fd, FIONREAD, (char*)&dwErrBytes) == -1 )
2087                     {
2088                         /* weirdness */
2089
2090                         dwEvent = WSAMAKESELECTREPLY( WS_FD_READ, wsaErrno() );
2091                     }
2092                     else if( val || dwErrBytes )
2093                     {
2094                         /* got pending data, will be reenabled by recv() or recvfrom() */
2095
2096                         FD_CLR( fd, &event_set[EVENT_IO_READ] );
2097                         dwEvent = WSAMAKESELECTREPLY( WS_FD_READ, 0 );
2098                     }
2099                     else
2100                     {
2101                         /* 0 bytes to read - connection reset by peer? */
2102
2103                         do
2104                             val = read( fd, (char*)&dwErrBytes, sizeof(dwErrBytes));
2105                         while( errno == EINTR );
2106                         if( errno != EWOULDBLOCK )
2107                         {
2108                             switch( val )
2109                             {
2110                                 case  0: errno = ENETDOWN;      /* soft reset, fall through */
2111                                 case -1:                        /* hard reset */
2112                                          dwEvent = WSAMAKESELECTREPLY( WS_FD_CLOSE, wsaErrno() );
2113                                          break;
2114
2115                                 default: bPost = FALSE;
2116                                          continue;              /* FIXME: this is real bad */
2117                             }
2118                         }
2119                         else { bPost = FALSE; continue; }       /* more weirdness */
2120
2121                         /* this is it, this socket is closed */
2122
2123                         psop->pws->flags &= ~(WS_FD_READ | WS_FD_CLOSE | WS_FD_WRITE);
2124                         FD_CLR( fd, &event_set[EVENT_IO_READ] );
2125                         FD_CLR( fd, &event_set[EVENT_IO_WRITE] );
2126
2127                         if( *max_fd == (fd + 1) ) (*max_fd)--;
2128                     }
2129                 }
2130             }
2131
2132             if( bPost )
2133             {
2134                 TRACE(winsock, "\t    hwnd %04x - %04x, %08x\n", 
2135                                 psop->hWnd, psop->uMsg, (unsigned)dwEvent );
2136                 PostMessage32A( psop->hWnd, psop->uMsg, 
2137                               (WPARAM32)WS_PTR2HANDLE(psop->pws), (LPARAM)dwEvent );
2138                 bPost = FALSE;
2139                 num_posted++;
2140             }
2141         }
2142         if( num_pending <= 0 ) break;
2143     }
2144
2145     TRACE(winsock, "\tdone, %i posted events\n", num_posted );
2146     return ( num_posted ) ? TRUE : FALSE;
2147 }
2148
2149 INT32 WINAPI WSAAsyncSelect32(SOCKET32 s, HWND32 hWnd, UINT32 uMsg, UINT32 lEvent)
2150 {
2151     ws_socket*    pws  = (ws_socket*)WS_HANDLE2PTR(s);
2152     LPWSINFO      pwsi = wsi_find(GetCurrentTask());
2153
2154     TRACE(winsock, "(%08x): %04x, hWnd %04x, uMsg %08x, event %08x\n",
2155                           (unsigned)pwsi, (SOCKET16)s, (HWND16)hWnd, uMsg, (unsigned)lEvent );
2156     if( _check_ws(pwsi, pws) )
2157     {
2158         ws_select_op* psop;
2159
2160         if( (psop = pws->psop) )
2161         {
2162             /* delete previous control struct */
2163
2164             if( psop == __ws_select_list )
2165                 __ws_select_list = psop->next;
2166             else
2167                 psop->prev->next = psop->next; 
2168             if( psop->next ) psop->next->prev = psop->prev;
2169
2170             if( pws->flags & (WS_FD_ACCEPT | WS_FD_CONNECT | WS_FD_READ | WS_FD_CLOSE) )
2171                 EVENT_DeleteIO( pws->fd, EVENT_IO_READ );
2172             if( pws->flags & (WS_FD_CONNECT | WS_FD_WRITE) )
2173                 EVENT_DeleteIO( pws->fd, EVENT_IO_WRITE );
2174
2175             TRACE(winsock,"\tremoving psop = 0x%08x\n", (unsigned) psop );
2176
2177             WS_FREE( pws->psop );
2178             pws->flags &= ~(WS_FD_RAW | WS_FD_ACCEPT | WS_FD_CONNECT | 
2179                             WS_FD_READ | WS_FD_WRITE | WS_FD_CLOSE);
2180             pws->psop = NULL;
2181         }
2182
2183         if( lEvent )
2184         {
2185             psop = (ws_select_op*)WS_ALLOC(sizeof(ws_select_op));
2186             if( psop )
2187             {
2188                 int sock_type, bytes = sizeof(int);
2189
2190                 WINSOCK_unblock_io( pws->fd, TRUE );
2191
2192                 psop->prev = NULL;
2193                 psop->next = __ws_select_list;
2194                 if( __ws_select_list )
2195                     __ws_select_list->prev = psop;
2196                 __ws_select_list = psop;
2197                 
2198                 psop->pws = pws;
2199                 psop->hWnd = hWnd;
2200                 psop->uMsg = uMsg;
2201
2202                 pws->psop = psop;
2203                 pws->flags |= (0x0000FFFF & lEvent);
2204                 getsockopt(pws->fd, SOL_SOCKET, SO_TYPE, &sock_type, &bytes);
2205                 if( sock_type == SOCK_RAW ) pws->flags |= WS_FD_RAW;
2206
2207                 if( lEvent & (WS_FD_ACCEPT | WS_FD_CONNECT | WS_FD_READ | WS_FD_CLOSE) )
2208                     EVENT_AddIO( pws->fd, EVENT_IO_READ );
2209                 if( lEvent & (WS_FD_CONNECT | WS_FD_WRITE) )
2210                     EVENT_AddIO( pws->fd, EVENT_IO_WRITE );
2211
2212                 /* TODO: handle WS_FD_ACCEPT right away if the socket is readable */
2213
2214                 TRACE(winsock,"\tcreating psop = 0x%08x\n", (unsigned)psop );
2215
2216                 return 0; /* success */
2217             }
2218             else pwsi->err = WSAENOBUFS;
2219         } 
2220         else return 0;
2221     } 
2222     else if( pwsi ) pwsi->err = WSAEINVAL;
2223     return SOCKET_ERROR; 
2224 }
2225
2226 INT16 WINAPI WSAAsyncSelect16(SOCKET16 s, HWND16 hWnd, UINT16 wMsg, UINT32 lEvent)
2227 {
2228     return (INT16)WSAAsyncSelect32( s, hWnd, wMsg, lEvent );
2229 }
2230
2231
2232 /***********************************************************************
2233  *      __WSAFDIsSet()                  (WINSOCK.151)
2234  */
2235 INT16 WINAPI __WSAFDIsSet16(SOCKET16 s, ws_fd_set16 *set)
2236 {
2237   int i = set->fd_count;
2238   
2239   TRACE(winsock, "(%d,%8lx(%i))\n", s,(unsigned long)set, i);
2240     
2241   while (i--)
2242       if (set->fd_array[i] == s) return 1;
2243   return 0;
2244 }                                                            
2245
2246 /***********************************************************************
2247  *      __WSAFDIsSet()                  (WSOCK32.151)
2248  */
2249 INT32 WINAPI __WSAFDIsSet32(SOCKET32 s, ws_fd_set32 *set)
2250 {
2251   int i = set->fd_count;
2252
2253   TRACE(winsock, "(%d,%8lx(%i))\n", s,(unsigned long)set, i);
2254
2255   while (i--)
2256       if (set->fd_array[i] == s) return 1;
2257   return 0;
2258 }
2259
2260 /***********************************************************************
2261  *      WSAIsBlocking()                 (WINSOCK.114)(WSOCK32.114)
2262  */
2263 BOOL32 WINAPI WSAIsBlocking(void)
2264 {
2265   /* By default WinSock should set all its sockets to non-blocking mode
2266    * and poll in PeekMessage loop when processing "blocking" ones. This 
2267    * function is supposed to tell if the program is in this loop. Our 
2268    * blocking calls are truly blocking so we always return FALSE.
2269    *
2270    * Note: It is allowed to call this function without prior WSAStartup().
2271    */
2272
2273   TRACE(winsock, "\n");
2274   return FALSE;
2275 }
2276
2277 /***********************************************************************
2278  *      WSACancelBlockingCall()         (WINSOCK.113)(WSOCK32.113)
2279  */
2280 INT32 WINAPI WSACancelBlockingCall(void)
2281 {
2282   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
2283
2284   TRACE(winsock, "(%08x)\n", (unsigned)pwsi);
2285
2286   if( pwsi ) return 0;
2287   return SOCKET_ERROR;
2288 }
2289
2290
2291 /***********************************************************************
2292  *      WSASetBlockingHook16()          (WINSOCK.109)
2293  */
2294 FARPROC16 WINAPI WSASetBlockingHook16(FARPROC16 lpBlockFunc)
2295 {
2296   FARPROC16             prev;
2297   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
2298
2299   TRACE(winsock, "(%08x): hook %08x\n", 
2300                (unsigned)pwsi, (unsigned) lpBlockFunc);
2301   if( pwsi ) 
2302   { 
2303       prev = (FARPROC16)pwsi->blocking_hook; 
2304       pwsi->blocking_hook = (DWORD)lpBlockFunc; 
2305       pwsi->flags &= ~WSI_BLOCKINGHOOK32;
2306       return prev; 
2307   }
2308   return 0;
2309 }
2310
2311
2312 /***********************************************************************
2313  *      WSASetBlockingHook32()
2314  */
2315 FARPROC32 WINAPI WSASetBlockingHook32(FARPROC32 lpBlockFunc)
2316 {
2317   FARPROC32             prev;
2318   LPWSINFO              pwsi = wsi_find(GetCurrentTask());
2319
2320   TRACE(winsock, "(%08x): hook %08x\n",
2321                (unsigned)pwsi, (unsigned) lpBlockFunc);
2322   if( pwsi ) {
2323       prev = (FARPROC32)pwsi->blocking_hook;
2324       pwsi->blocking_hook = (DWORD)lpBlockFunc;
2325       pwsi->flags |= WSI_BLOCKINGHOOK32;
2326       return prev;
2327   }
2328   return NULL;
2329 }
2330
2331
2332 /***********************************************************************
2333  *      WSAUnhookBlockingHook16()       (WINSOCK.110)
2334  */
2335 INT16 WINAPI WSAUnhookBlockingHook16(void)
2336 {
2337     LPWSINFO              pwsi = wsi_find(GetCurrentTask());
2338
2339     TRACE(winsock, "(%08x)\n", (unsigned)pwsi);
2340     if( pwsi ) return (INT16)(pwsi->blocking_hook = 0);
2341     return SOCKET_ERROR;
2342 }
2343
2344
2345 /***********************************************************************
2346  *      WSAUnhookBlockingHook32()
2347  */
2348 INT32 WINAPI WSAUnhookBlockingHook32(void)
2349 {
2350     LPWSINFO              pwsi = wsi_find(GetCurrentTask());
2351
2352     TRACE(winsock, "(%08x)\n", (unsigned)pwsi);
2353     if( pwsi )
2354     {
2355         pwsi->blocking_hook = 0;
2356         pwsi->flags &= ~WSI_BLOCKINGHOOK32;
2357         return 0;
2358     }
2359     return SOCKET_ERROR;
2360 }
2361
2362 /*
2363  *      TCP/IP action codes.
2364  */
2365
2366
2367 #define WSCNTL_TCPIP_QUERY_INFO             0x00000000
2368 #define WSCNTL_TCPIP_SET_INFO               0x00000001
2369 #define WSCNTL_TCPIP_ICMP_ECHO              0x00000002
2370 #define WSCNTL_TCPIP_TEST                   0x00000003
2371
2372
2373 /***********************************************************************
2374  *      WsControl()
2375  *
2376  * WsControl seems to be an undocumented Win95 function. A lot of 
2377  * discussion about WsControl can be found on the net, e.g.
2378  * Subject:      Re: WSOCK32.DLL WsControl Exported Function
2379  * From:         "Peter Rindfuss" <rindfuss-s@medea.wz-berlin.de>
2380  * Date:         1997/08/17
2381  */
2382
2383 DWORD WINAPI WsControl(DWORD protocoll,DWORD action,
2384                       LPVOID inbuf,LPDWORD inbuflen,
2385                       LPVOID outbuf,LPDWORD outbuflen) 
2386 {
2387
2388   switch (action) {
2389   case WSCNTL_TCPIP_ICMP_ECHO:
2390     {
2391       unsigned int addr = *(unsigned int*)inbuf;
2392 #if 0
2393       int timeout= *(unsigned int*)(inbuf+4);
2394       short x1 = *(unsigned short*)(inbuf+8);
2395       short sendbufsize = *(unsigned short*)(inbuf+10);
2396       char x2 = *(unsigned char*)(inbuf+12);
2397       char ttl = *(unsigned char*)(inbuf+13);
2398       char service = *(unsigned char*)(inbuf+14);
2399       char type= *(unsigned char*)(inbuf+15); /* 0x2: don't fragment*/
2400 #endif      
2401       
2402       FIXME(winsock,"(ICMP_ECHO) to 0x%08x stub \n", addr);
2403       break;
2404     }
2405   default:
2406     FIXME(winsock,"(%lx,%lx,%p,%p,%p,%p) stub\n",
2407           protocoll,action,inbuf,inbuflen,outbuf,outbuflen);
2408   }
2409   return FALSE;
2410 }
2411 /*********************************************************
2412  *       WS_s_perror         WSOCK32.1108 
2413  */
2414 void WINAPI WS_s_perror(LPCSTR message)
2415 {
2416     FIXME(winsock,"(%s): stub\n",message);
2417     return;
2418 }
2419
2420
2421 /* ----------------------------------- end of API stuff */
2422
2423 /* ----------------------------------- helper functions -
2424  *
2425  * TODO: Merge WS_dup_..() stuff into one function that
2426  * would operate with a generic structure containing internal
2427  * pointers (via a template of some kind).
2428  */
2429
2430 static int list_size(char** l, int item_size)
2431 {
2432   int i,j = 0;
2433   if(l)
2434   { for(i=0;l[i];i++) 
2435         j += (item_size) ? item_size : strlen(l[i]) + 1;
2436     j += (i + 1) * sizeof(char*); }
2437   return j;
2438 }
2439
2440 static int list_dup(char** l_src, char* ref, char* base, int item_size)
2441
2442    /* base is either either equal to ref or 0 or SEGPTR */
2443
2444    char*                p = ref;
2445    char**               l_to = (char**)ref;
2446    int                  i,j,k;
2447
2448    for(j=0;l_src[j];j++) ;
2449    p += (j + 1) * sizeof(char*);
2450    for(i=0;i<j;i++)
2451    { l_to[i] = base + (p - ref);
2452      k = ( item_size ) ? item_size : strlen(l_src[i]) + 1;
2453      memcpy(p, l_src[i], k); p += k; }
2454    l_to[i] = NULL;
2455    return (p - ref);
2456 }
2457
2458 /* ----- hostent */
2459
2460 static int hostent_size(struct hostent* p_he)
2461 {
2462   int size = 0;
2463   if( p_he )
2464   { size  = sizeof(struct hostent); 
2465     size += strlen(p_he->h_name) + 1;
2466     size += list_size(p_he->h_aliases, 0);  
2467     size += list_size(p_he->h_addr_list, p_he->h_length ); }
2468   return size;
2469 }
2470
2471 int WS_dup_he(LPWSINFO pwsi, struct hostent* p_he, int flag)
2472 {
2473    /* Convert hostent structure into ws_hostent so that the data fits 
2474     * into pwsi->buffer. Internal pointers can be linear, SEGPTR, or 
2475     * relative to pwsi->buffer depending on "flag" value. Returns size
2476     * of the data copied (also in the pwsi->buflen).
2477     */
2478
2479    int size = hostent_size(p_he);
2480
2481    if( size )
2482    {
2483      struct ws_hostent* p_to;
2484      char* p_name,*p_aliases,*p_addr,*p_base,*p;
2485
2486      _check_buffer_he(pwsi, size);
2487      p_to = (struct ws_hostent*)pwsi->he;
2488      p = (char*)pwsi->he;
2489      p_base = (flag & WS_DUP_OFFSET) ? NULL
2490                                      : ((flag & WS_DUP_SEGPTR) ? (char*)SEGPTR_GET(p) : p);
2491      p += sizeof(struct ws_hostent);
2492      p_name = p;
2493      strcpy(p, p_he->h_name); p += strlen(p) + 1;
2494      p_aliases = p;
2495      p += list_dup(p_he->h_aliases, p, p_base + (p - (char*)pwsi->he), 0);
2496      p_addr = p;
2497      list_dup(p_he->h_addr_list, p, p_base + (p - (char*)pwsi->he), p_he->h_length);
2498
2499      p_to->h_addrtype = (INT16)p_he->h_addrtype; 
2500      p_to->h_length = (INT16)p_he->h_length;
2501      p_to->h_name = (SEGPTR)(p_base + (p_name - (char*)pwsi->he));
2502      p_to->h_aliases = (SEGPTR)(p_base + (p_aliases - (char*)pwsi->he));
2503      p_to->h_addr_list = (SEGPTR)(p_base + (p_addr - (char*)pwsi->he));
2504
2505      size += (sizeof(struct ws_hostent) - sizeof(struct hostent));
2506    }
2507    return size;
2508 }
2509
2510 /* ----- protoent */
2511
2512 static int protoent_size(struct protoent* p_pe)
2513 {
2514   int size = 0;
2515   if( p_pe )
2516   { size  = sizeof(struct protoent);
2517     size += strlen(p_pe->p_name) + 1;
2518     size += list_size(p_pe->p_aliases, 0); }
2519   return size;
2520 }
2521
2522 int WS_dup_pe(LPWSINFO pwsi, struct protoent* p_pe, int flag)
2523 {
2524    int size = protoent_size(p_pe);
2525    if( size )
2526    {
2527      struct ws_protoent* p_to;
2528      char* p_name,*p_aliases,*p_base,*p;
2529
2530      _check_buffer_pe(pwsi, size);
2531      p_to = (struct ws_protoent*)pwsi->pe;
2532      p = (char*)pwsi->pe; 
2533      p_base = (flag & WS_DUP_OFFSET) ? NULL
2534                                      : ((flag & WS_DUP_SEGPTR) ? (char*)SEGPTR_GET(p) : p);
2535      p += sizeof(struct ws_protoent);
2536      p_name = p;
2537      strcpy(p, p_pe->p_name); p += strlen(p) + 1;
2538      p_aliases = p;
2539      list_dup(p_pe->p_aliases, p, p_base + (p - (char*)pwsi->pe), 0);
2540
2541      p_to->p_proto = (INT16)p_pe->p_proto;
2542      p_to->p_name = (SEGPTR)(p_base) + (p_name - (char*)pwsi->pe);
2543      p_to->p_aliases = (SEGPTR)((p_base) + (p_aliases - (char*)pwsi->pe)); 
2544
2545      size += (sizeof(struct ws_protoent) - sizeof(struct protoent));
2546    }
2547    return size;
2548 }
2549
2550 /* ----- servent */
2551
2552 static int servent_size(struct servent* p_se)
2553 {
2554   int size = 0;
2555   if( p_se )
2556   { size += sizeof(struct servent);
2557     size += strlen(p_se->s_proto) + strlen(p_se->s_name) + 2;
2558     size += list_size(p_se->s_aliases, 0); }
2559   return size;
2560 }
2561
2562 int WS_dup_se(LPWSINFO pwsi, struct servent* p_se, int flag)
2563 {
2564    int size = servent_size(p_se);
2565    if( size )
2566    {
2567      struct ws_servent* p_to;
2568      char* p_name,*p_aliases,*p_proto,*p_base,*p;
2569
2570      _check_buffer_se(pwsi, size);
2571      p_to = (struct ws_servent*)pwsi->se;
2572      p = (char*)pwsi->se;
2573      p_base = (flag & WS_DUP_OFFSET) ? NULL 
2574                                      : ((flag & WS_DUP_SEGPTR) ? (char*)SEGPTR_GET(p) : p);
2575      p += sizeof(struct ws_servent);
2576      p_name = p;
2577      strcpy(p, p_se->s_name); p += strlen(p) + 1;
2578      p_proto = p;
2579      strcpy(p, p_se->s_proto); p += strlen(p) + 1;
2580      p_aliases = p;
2581      list_dup(p_se->s_aliases, p, p_base + (p - (char*)pwsi->se), 0);
2582
2583      p_to->s_port = (INT16)p_se->s_port;
2584      p_to->s_name = (SEGPTR)(p_base + (p_name - (char*)pwsi->se));
2585      p_to->s_proto = (SEGPTR)(p_base + (p_proto - (char*)pwsi->se));
2586      p_to->s_aliases = (SEGPTR)(p_base + (p_aliases - (char*)pwsi->se)); 
2587
2588      size += (sizeof(struct ws_servent) - sizeof(struct servent));
2589    }
2590    return size;
2591 }
2592
2593 /* ----------------------------------- error handling */
2594
2595 UINT16 wsaErrno(void)
2596 {
2597     int loc_errno = errno; 
2598 #ifdef HAVE_STRERROR
2599     WARN(winsock, "errno %d, (%s).\n", loc_errno, strerror(loc_errno));
2600 #else
2601     WARN(winsock, "errno %d\n", loc_errno);
2602 #endif
2603
2604     switch(loc_errno)
2605     {
2606         case EINTR:             return WSAEINTR;
2607         case EBADF:             return WSAEBADF;
2608         case EACCES:            return WSAEACCES;
2609         case EFAULT:            return WSAEFAULT;
2610         case EINVAL:            return WSAEINVAL;
2611         case EMFILE:            return WSAEMFILE;
2612         case EWOULDBLOCK:       return WSAEWOULDBLOCK;
2613         case EINPROGRESS:       return WSAEINPROGRESS;
2614         case EALREADY:          return WSAEALREADY;
2615         case ENOTSOCK:          return WSAENOTSOCK;
2616         case EDESTADDRREQ:      return WSAEDESTADDRREQ;
2617         case EMSGSIZE:          return WSAEMSGSIZE;
2618         case EPROTOTYPE:        return WSAEPROTOTYPE;
2619         case ENOPROTOOPT:       return WSAENOPROTOOPT;
2620         case EPROTONOSUPPORT:   return WSAEPROTONOSUPPORT;
2621         case ESOCKTNOSUPPORT:   return WSAESOCKTNOSUPPORT;
2622         case EOPNOTSUPP:        return WSAEOPNOTSUPP;
2623         case EPFNOSUPPORT:      return WSAEPFNOSUPPORT;
2624         case EAFNOSUPPORT:      return WSAEAFNOSUPPORT;
2625         case EADDRINUSE:        return WSAEADDRINUSE;
2626         case EADDRNOTAVAIL:     return WSAEADDRNOTAVAIL;
2627         case ENETDOWN:          return WSAENETDOWN;
2628         case ENETUNREACH:       return WSAENETUNREACH;
2629         case ENETRESET:         return WSAENETRESET;
2630         case ECONNABORTED:      return WSAECONNABORTED;
2631         case EPIPE:
2632         case ECONNRESET:        return WSAECONNRESET;
2633         case ENOBUFS:           return WSAENOBUFS;
2634         case EISCONN:           return WSAEISCONN;
2635         case ENOTCONN:          return WSAENOTCONN;
2636         case ESHUTDOWN:         return WSAESHUTDOWN;
2637         case ETOOMANYREFS:      return WSAETOOMANYREFS;
2638         case ETIMEDOUT:         return WSAETIMEDOUT;
2639         case ECONNREFUSED:      return WSAECONNREFUSED;
2640         case ELOOP:             return WSAELOOP;
2641         case ENAMETOOLONG:      return WSAENAMETOOLONG;
2642         case EHOSTDOWN:         return WSAEHOSTDOWN;
2643         case EHOSTUNREACH:      return WSAEHOSTUNREACH;
2644         case ENOTEMPTY:         return WSAENOTEMPTY;
2645 #ifdef EPROCLIM
2646         case EPROCLIM:          return WSAEPROCLIM;
2647 #endif
2648 #ifdef EUSERS
2649         case EUSERS:            return WSAEUSERS;
2650 #endif
2651 #ifdef EDQUOT
2652         case EDQUOT:            return WSAEDQUOT;
2653 #endif
2654 #ifdef ESTALE
2655         case ESTALE:            return WSAESTALE;
2656 #endif
2657 #ifdef EREMOTE
2658         case EREMOTE:           return WSAEREMOTE;
2659 #endif
2660
2661        /* just in case we ever get here and there are no problems */
2662         case 0:                 return 0;
2663         default:
2664                 WARN(winsock, "Unknown errno %d!\n", loc_errno);
2665                 return WSAEOPNOTSUPP;
2666     }
2667 }
2668
2669 UINT16 wsaHerrno(void)
2670 {
2671     int         loc_errno = h_errno;
2672
2673     WARN(winsock, "h_errno %d.\n", loc_errno);
2674
2675     switch(loc_errno)
2676     {
2677         case HOST_NOT_FOUND:    return WSAHOST_NOT_FOUND;
2678         case TRY_AGAIN:         return WSATRY_AGAIN;
2679         case NO_RECOVERY:       return WSANO_RECOVERY;
2680         case NO_DATA:           return WSANO_DATA; 
2681
2682         case 0:                 return 0;
2683         default:
2684                 WARN(winsock,"Unknown h_errno %d!\n", loc_errno);
2685                 return WSAEOPNOTSUPP;
2686     }
2687 }