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