Make use of automatic ordinal allocation.
[wine] / dlls / icmp / icmp_main.c
1 /*
2  * ICMP
3  *
4  * Francois Gouget, 1999, based on the work of
5  *   RW Hall, 1999, based on public domain code PING.C by Mike Muus (1983) 
6  *   and later works (c) 1989 Regents of Univ. of California - see copyright 
7  *   notice at end of source-code.
8  */
9
10 /* Future work:
11  * - Systems like FreeBSD don't seem to support the IP_TTL option and maybe others.
12  *   But using IP_HDRINCL and building the IP header by hand might work.
13  * - Not all IP options are supported.
14  * - Are ICMP handles real handles, i.e. inheritable and all? There might be some 
15  *   more work to do here, including server side stuff with synchronization.
16  * - Is it correct to use malloc for the internal buffer, for allocating the 
17  *   handle's structure?
18  * - This API should probably be thread safe. Is it really?
19  * - Using the winsock functions has not been tested.
20  */
21
22 #include "config.h"
23
24 #include <sys/types.h>
25 #ifdef HAVE_SYS_SOCKET_H
26 # include <sys/socket.h>
27 #endif
28 #include <netdb.h>
29 #include <netinet/in_systm.h>
30 #ifdef HAVE_NETINET_IN_H
31 # include <netinet/in.h>
32 #endif
33
34 #include <sys/time.h>
35 #include <malloc.h>
36 #include <string.h>
37 #include <errno.h>
38 #include <unistd.h>
39 #ifdef HAVE_ARPA_INET_H
40 # include <arpa/inet.h>
41 #endif
42
43 #include "windef.h"
44 #include "winbase.h"
45 #ifdef ICMP_WIN
46 #include "winsock.h"
47 #endif
48
49 #include "winerror.h"
50 #include "wine/ipexport.h"
51 #include "wine/icmpapi.h"
52 #include "debugtools.h"
53
54 /* Set up endiannes macros for the ip and ip_icmp BSD headers */
55 #ifndef BIG_ENDIAN
56 #define BIG_ENDIAN       4321
57 #endif
58 #ifndef LITTLE_ENDIAN
59 #define LITTLE_ENDIAN    1234
60 #endif
61 #ifndef BYTE_ORDER
62 #ifdef WORDS_BIGENDIAN
63 #define BYTE_ORDER       BIG_ENDIAN
64 #else
65 #define BYTE_ORDER       LITTLE_ENDIAN
66 #endif
67 #endif /* BYTE_ORDER */
68
69 #define u_int16_t  WORD
70 #define u_int32_t  DWORD
71
72 /* These are BSD headers. We use these here because they are needed on 
73  * libc5 Linux systems. On other platforms they are usually simply more 
74  * complete than the native stuff, and cause less portability problems 
75  * so we use them anyway.
76  */
77 #include "ip.h"
78 #include "ip_icmp.h"
79
80
81 DEFAULT_DEBUG_CHANNEL(icmp)
82
83 /* Define the following macro to use the winsock functions */
84 /*#define ICMP_WIN*/
85
86 #ifdef ICMP_WIN
87 /* FIXME: should we include winsock.h ???*/
88 SOCKET WINAPI WINSOCK_socket(INT af, INT type, INT protocol);
89 INT WINAPI WINSOCK_sendto(SOCKET s, char *buf, INT len, INT flags, struct sockaddr *to, INT tolen);
90 INT WINAPI WINSOCK_recvfrom(SOCKET s, char *buf,INT len, INT flags, struct sockaddr *from, INT *fromlen32);
91 INT WINAPI WINSOCK_shutdown(SOCKET s, INT how);
92 #endif
93
94
95 #ifdef ICMP_WIN
96 #define ISOCK_SOCKET                SOCKET
97 #define ISOCK_ISVALID(a)            ((a)!=INVALID_SOCKET)
98 #define ISOCK_getsockopt(a,b,c,d,e) WINSOCK_getsockopt(a,b,c,d,e)
99 #define ISOCK_recvfrom(a,b,c,d,e,f) WINSOCK_recvfrom(a,b,c,d,e,f)
100 #define ISOCK_select(a,b,c,d,e)     WINSOCK_select(a,b,c,d,e)
101 #define ISOCK_sendto(a,b,c,d,e,f)   WINSOCK_sendto(a,b,c,d,e,f)
102 #define ISOCK_setsockopt(a,b,c,d,e) WINSOCK_setsockopt(a,b,c,d,e)
103 #define ISOCK_shutdown(a,b)         WINSOCK_shutdown(a,b)
104 #define ISOCK_socket(a,b,c)         WINSOCK_socket(a,b,c)
105 #else
106 #define ISOCK_SOCKET                int
107 #define ISOCK_ISVALID(a)            ((a)>=0)
108 #define ISOCK_getsockopt(a,b,c,d,e) getsockopt(a,b,c,d,e)
109 #define ISOCK_recvfrom(a,b,c,d,e,f) recvfrom(a,b,c,d,e,f)
110 #define ISOCK_select(a,b,c,d,e)     select(a,b,c,d,e)
111 #define ISOCK_setsockopt(a,b,c,d,e) setsockopt(a,b,c,d,e)
112 #define ISOCK_sendto(a,b,c,d,e,f)   sendto(a,b,c,d,e,f)
113 #define ISOCK_shutdown(a,b)         shutdown(a,b)
114 #define ISOCK_socket(a,b,c)         socket(a,b,c)
115 #endif
116
117 typedef struct {
118     ISOCK_SOCKET sid;
119     IP_OPTION_INFORMATION default_opts;
120 } icmp_t;
121
122 #define IP_OPTS_UNKNOWN     0
123 #define IP_OPTS_DEFAULT     1
124 #define IP_OPTS_CUSTOM      2
125
126 /* The sequence number is unique process wide, so that all threads 
127  * have a distinct sequence number.
128  */
129 static LONG icmp_sequence=0;
130
131 static int in_cksum(u_short *addr, int len)
132 {
133     int nleft=len;
134     u_short *w = addr;
135     int sum = 0;
136     u_short answer = 0;
137
138     while (nleft > 1) {
139         sum += *w++;
140         nleft -= 2;
141     }
142
143     if (nleft == 1) {
144         *(u_char *)(&answer) = *(u_char *)w;
145         sum += answer;
146     }
147
148     sum = (sum >> 16) + (sum & 0xffff);
149     sum  += (sum >> 16);
150     answer = ~sum;
151     return(answer);
152 }
153
154
155
156 /*
157  * Exported Routines.
158  */
159
160 HANDLE WINAPI IcmpCreateFile(VOID)
161 {
162     icmp_t* icp;
163
164     ISOCK_SOCKET sid=ISOCK_socket(AF_INET,SOCK_RAW,IPPROTO_ICMP);
165     if (!ISOCK_ISVALID(sid)) {
166         MESSAGE("WARNING: Trying to use ICMP will fail unless running as root\n");
167         SetLastError(ERROR_ACCESS_DENIED);
168         return INVALID_HANDLE_VALUE;
169     }
170
171     icp=malloc(sizeof(*icp));
172     if (icp==NULL) {
173         SetLastError(IP_NO_RESOURCES);
174         return INVALID_HANDLE_VALUE;
175     }
176     icp->sid=sid;
177     icp->default_opts.OptionsSize=IP_OPTS_UNKNOWN;
178     return (HANDLE)icp;
179 }
180
181
182 BOOL WINAPI IcmpCloseHandle(HANDLE  IcmpHandle)
183 {
184     icmp_t* icp=(icmp_t*)IcmpHandle;
185     if (IcmpHandle==INVALID_HANDLE_VALUE) {
186         /* FIXME: in fact win98 seems to ignore the handle value !!! */
187         SetLastError(ERROR_INVALID_HANDLE);
188         return FALSE;
189     }
190
191     ISOCK_shutdown(icp->sid,2);
192     free(icp);
193     return TRUE;
194 }
195
196
197 DWORD WINAPI IcmpSendEcho(
198     HANDLE                   IcmpHandle,
199     IPAddr                   DestinationAddress,
200     LPVOID                   RequestData,
201     WORD                     RequestSize,
202     PIP_OPTION_INFORMATION   RequestOptions,
203     LPVOID                   ReplyBuffer,
204     DWORD                    ReplySize,
205     DWORD                    Timeout
206     )
207 {
208     icmp_t* icp=(icmp_t*)IcmpHandle;
209     unsigned char* reqbuf;
210     int reqsize;
211
212     struct icmp_echo_reply* ier;
213     struct ip* ip_header;
214     struct icmp* icmp_header;
215     char* endbuf;
216     int ip_header_len;
217     int maxlen;
218     fd_set fdr;
219     struct timeval timeout,send_time,recv_time;
220     struct sockaddr_in addr;
221     int addrlen;
222     unsigned short id,seq,cksum;
223     int res;
224
225     if (IcmpHandle==INVALID_HANDLE_VALUE) {
226         /* FIXME: in fact win98 seems to ignore the handle value !!! */
227         SetLastError(ERROR_INVALID_HANDLE);
228         return 0;
229     }
230
231     if (ReplySize<sizeof(ICMP_ECHO_REPLY)+ICMP_MINLEN) {
232         SetLastError(IP_BUF_TOO_SMALL);
233         return 0;
234     }
235     /* check the request size against SO_MAX_MSG_SIZE using getsockopt */
236
237     /* Prepare the request */
238     id=getpid() & 0xFFFF;
239     seq=InterlockedIncrement(&icmp_sequence) & 0xFFFF;
240
241     reqsize=ICMP_MINLEN+RequestSize;
242     reqbuf=malloc(reqsize);
243     if (reqbuf==NULL) {
244         SetLastError(ERROR_OUTOFMEMORY);
245         return 0;
246     }
247
248     icmp_header=(struct icmp*)reqbuf;
249     icmp_header->icmp_type=ICMP_ECHO;
250     icmp_header->icmp_code=0;
251     icmp_header->icmp_cksum=0;
252     icmp_header->icmp_id=id;
253     icmp_header->icmp_seq=seq;
254     memcpy(reqbuf+ICMP_MINLEN, RequestData, RequestSize);
255     icmp_header->icmp_cksum=cksum=in_cksum((u_short*)reqbuf,reqsize);
256
257     addr.sin_family=AF_INET;
258     addr.sin_addr.s_addr=DestinationAddress;
259     addr.sin_port=0;
260
261     if (RequestOptions!=NULL) {
262         int val;
263         if (icp->default_opts.OptionsSize==IP_OPTS_UNKNOWN) {
264             int len;
265             /* Before we mess with the options, get the default values */
266             len=sizeof(val);
267             ISOCK_getsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,&len);
268             icp->default_opts.Ttl=val;
269
270             len=sizeof(val);
271             ISOCK_getsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,&len);
272             icp->default_opts.Tos=val;
273             /* FIXME: missing: handling of IP 'flags', and all the other options */
274         }
275
276         val=RequestOptions->Ttl;
277         ISOCK_setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
278         val=RequestOptions->Tos;
279         ISOCK_setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
280         /* FIXME:  missing: handling of IP 'flags', and all the other options */
281
282         icp->default_opts.OptionsSize=IP_OPTS_CUSTOM;
283     } else if (icp->default_opts.OptionsSize==IP_OPTS_CUSTOM) {
284         int val;
285
286         /* Restore the default options */
287         val=icp->default_opts.Ttl;
288         ISOCK_setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
289         val=icp->default_opts.Tos;
290         ISOCK_setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
291         /* FIXME: missing: handling of IP 'flags', and all the other options */
292
293         icp->default_opts.OptionsSize=IP_OPTS_DEFAULT;
294     }
295
296     /* Get ready for receiving the reply
297      * Do it before we send the request to minimize the risk of introducing delays
298      */
299     FD_ZERO(&fdr);
300     FD_SET(icp->sid,&fdr);
301     timeout.tv_sec=Timeout/1000;
302     timeout.tv_usec=(Timeout % 1000)*1000;
303     addrlen=sizeof(addr);
304     ier=ReplyBuffer;
305     ip_header=ReplyBuffer+sizeof(ICMP_ECHO_REPLY);
306     endbuf=ReplyBuffer+ReplySize;
307     maxlen=ReplySize-sizeof(ICMP_ECHO_REPLY);
308
309     /* Send the packet */
310     TRACE("Sending %d bytes (RequestSize=%d) to %s\n", reqsize, RequestSize, inet_ntoa(addr.sin_addr));
311 #if 0
312     if (TRACE_ON(icmp)){
313         unsigned char* buf=(unsigned char*)reqbuf;
314         int i;
315         printf("Output buffer:\n");
316         for (i=0;i<reqsize;i++)
317             printf("%2x,", buf[i]);
318         printf("\n");
319     }
320 #endif
321
322     gettimeofday(&send_time,NULL);
323     res=ISOCK_sendto(icp->sid, reqbuf, reqsize, 0, (struct sockaddr*)&addr, sizeof(addr));
324     free(reqbuf);
325     if (res<0) {
326         if (errno==EMSGSIZE)
327             SetLastError(IP_PACKET_TOO_BIG);
328         else {
329             switch (errno) {
330             case ENETUNREACH:
331                 SetLastError(IP_DEST_NET_UNREACHABLE);
332                 break;
333             case EHOSTUNREACH:
334                 SetLastError(IP_DEST_NET_UNREACHABLE);
335                 break;
336             default:
337                 TRACE("unknown error: errno=%d\n",errno);
338                 SetLastError(ERROR_UNKNOWN);
339             }
340         }
341         return 0;
342     }
343
344     /* Get the reply */
345     ip_header_len=0; /* because gcc was complaining */
346     while ((res=ISOCK_select(icp->sid+1,&fdr,NULL,NULL,&timeout))>0) {
347         gettimeofday(&recv_time,NULL);
348         res=ISOCK_recvfrom(icp->sid, (char*)ip_header, maxlen, 0, (struct sockaddr*)&addr,&addrlen);
349         TRACE("received %d bytes from %s\n",res, inet_ntoa(addr.sin_addr));
350         ier->Status=IP_REQ_TIMED_OUT;
351
352         /* Check whether we should ignore this packet */
353         if ((ip_header->ip_p==IPPROTO_ICMP) && (res>=sizeof(struct ip)+ICMP_MINLEN)) {
354             ip_header_len=ip_header->ip_hl << 2;
355             icmp_header=(struct icmp*)(((char*)ip_header)+ip_header_len);
356             TRACE("received an ICMP packet of type,code=%d,%d\n",icmp_header->icmp_type,icmp_header->icmp_code);
357             if (icmp_header->icmp_type==ICMP_ECHOREPLY) {
358                 if ((icmp_header->icmp_id==id) && (icmp_header->icmp_seq==seq))
359                     ier->Status=IP_SUCCESS;
360             } else {
361                 switch (icmp_header->icmp_type) {
362                 case ICMP_UNREACH:
363                     switch (icmp_header->icmp_code) {
364                     case ICMP_UNREACH_HOST:
365 #ifdef ICMP_UNREACH_HOST_UNKNOWN
366                     case ICMP_UNREACH_HOST_UNKNOWN:
367 #endif
368 #ifdef ICMP_UNREACH_ISOLATED
369                     case ICMP_UNREACH_ISOLATED:
370 #endif
371 #ifdef ICMP_UNREACH_HOST_PROHIB
372                     case ICMP_UNREACH_HOST_PROHIB:
373 #endif
374 #ifdef ICMP_UNREACH_TOSHOST
375                     case ICMP_UNREACH_TOSHOST:
376 #endif
377                         ier->Status=IP_DEST_HOST_UNREACHABLE;
378                         break;
379                     case ICMP_UNREACH_PORT:
380                         ier->Status=IP_DEST_PORT_UNREACHABLE;
381                         break;
382                     case ICMP_UNREACH_PROTOCOL:
383                         ier->Status=IP_DEST_PROT_UNREACHABLE;
384                         break;
385                     case ICMP_UNREACH_SRCFAIL:
386                         ier->Status=IP_BAD_ROUTE;
387                         break;
388                     default:
389                         ier->Status=IP_DEST_NET_UNREACHABLE;
390                     }
391                     break;
392                 case ICMP_TIMXCEED:
393                     if (icmp_header->icmp_code==ICMP_TIMXCEED_REASS)
394                         ier->Status=IP_TTL_EXPIRED_REASSEM;
395                     else
396                         ier->Status=IP_TTL_EXPIRED_TRANSIT;
397                     break;
398                 case ICMP_PARAMPROB:
399                     ier->Status=IP_PARAM_PROBLEM;
400                     break;
401                 case ICMP_SOURCEQUENCH:
402                     ier->Status=IP_SOURCE_QUENCH;
403                     break;
404                 }
405                 if (ier->Status!=IP_REQ_TIMED_OUT) {
406                     struct ip* rep_ip_header;
407                     struct icmp* rep_icmp_header;
408                     /* The ICMP header size of all the packets we accept is the same */
409                     rep_ip_header=(struct ip*)(((char*)icmp_header)+ICMP_MINLEN);
410                     rep_icmp_header=(struct icmp*)(((char*)rep_ip_header)+(rep_ip_header->ip_hl << 2));
411
412                     /* Make sure that this is really a reply to our packet */
413                     if (ip_header_len+ICMP_MINLEN+(rep_ip_header->ip_hl << 2)+ICMP_MINLEN>ip_header->ip_len) {
414                         ier->Status=IP_REQ_TIMED_OUT;
415                     } else if ((rep_icmp_header->icmp_type!=ICMP_ECHO) ||
416                         (rep_icmp_header->icmp_code!=0) ||
417                         (rep_icmp_header->icmp_id!=id) ||
418                         (rep_icmp_header->icmp_seq!=seq) ||
419                         (rep_icmp_header->icmp_cksum!=cksum)) {
420                         /* This was not a reply to one of our packets after all */
421                         TRACE("skipping type,code=%d,%d id,seq=%d,%d cksum=%d\n",
422                             rep_icmp_header->icmp_type,rep_icmp_header->icmp_code,
423                             rep_icmp_header->icmp_id,rep_icmp_header->icmp_seq,
424                             rep_icmp_header->icmp_cksum);
425                         TRACE("expected type,code=8,0 id,seq=%d,%d cksum=%d\n",
426                             id,seq,
427                             cksum);
428                         ier->Status=IP_REQ_TIMED_OUT;
429                     }
430                 }
431             }                
432         }
433
434         if (ier->Status==IP_REQ_TIMED_OUT) {
435             /* This packet was not for us.
436              * Decrease the timeout so that we don't enter an endless loop even
437              * if we get flooded with ICMP packets that are not for us.
438              */
439             timeout.tv_sec=Timeout/1000-(recv_time.tv_sec-send_time.tv_sec);
440             timeout.tv_usec=(Timeout % 1000)*1000+send_time.tv_usec-(recv_time.tv_usec-send_time.tv_usec);
441             if (timeout.tv_usec<0) {
442                 timeout.tv_usec+=1000000;
443                 timeout.tv_sec--;
444             }
445             continue;
446         } else {
447             /* This is a reply to our packet */
448             memcpy(&ier->Address,&ip_header->ip_src,sizeof(IPAddr));
449             /* Status is already set */
450             ier->RoundTripTime=(recv_time.tv_sec-send_time.tv_sec)*1000+(recv_time.tv_usec-send_time.tv_usec)/1000;
451             ier->DataSize=res-ip_header_len-ICMP_MINLEN;
452             ier->Reserved=0;
453             ier->Data=endbuf-ier->DataSize;
454             memmove(ier->Data,((char*)ip_header)+ip_header_len+ICMP_MINLEN,ier->DataSize);
455             ier->Options.Ttl=ip_header->ip_ttl;
456             ier->Options.Tos=ip_header->ip_tos;
457             ier->Options.Flags=ip_header->ip_off >> 13;
458             ier->Options.OptionsSize=ip_header_len-sizeof(struct ip);
459             if (ier->Options.OptionsSize!=0) {
460                 ier->Options.OptionsData=ier->Data-ier->Options.OptionsSize;
461                 /* FIXME: We are supposed to rearrange the option's 'source route' data */
462                 memmove(ier->Options.OptionsData,((char*)ip_header)+ip_header_len,ier->Options.OptionsSize);
463                 endbuf=ier->Options.OptionsData;
464             } else {
465                 ier->Options.OptionsData=NULL;
466                 endbuf=ier->Data;
467             }
468
469             /* Prepare for the next packet */
470             ier++;
471             ip_header=(struct ip*)(((char*)ip_header)+sizeof(ICMP_ECHO_REPLY));
472             maxlen=endbuf-(char*)ip_header;
473
474             /* Check out whether there is more but don't wait this time */
475             timeout.tv_sec=0;
476             timeout.tv_usec=0;
477         }
478         FD_ZERO(&fdr);
479         FD_SET(icp->sid,&fdr);
480     }
481     res=ier-(ICMP_ECHO_REPLY*)ReplyBuffer;
482     if (res==0)
483         SetLastError(IP_REQ_TIMED_OUT);
484     TRACE("received %d replies\n",res);
485     return res;
486 }
487
488 /*
489  * Copyright (c) 1989 The Regents of the University of California.
490  * All rights reserved.
491  *
492  * This code is derived from software contributed to Berkeley by
493  * Mike Muuss.
494  *
495  * Redistribution and use in source and binary forms, with or without
496  * modification, are permitted provided that the following conditions
497  * are met:
498  * 1. Redistributions of source code must retain the above copyright
499  *    notice, this list of conditions and the following disclaimer.
500  * 2. Redistributions in binary form must reproduce the above copyright
501  *    notice, this list of conditions and the following disclaimer in the
502  *    documentation and/or other materials provided with the distribution.
503  * 3. All advertising materials mentioning features or use of this software
504  *    must display the following acknowledgement:
505  *      This product includes software developed by the University of
506  *      California, Berkeley and its contributors.
507  * 4. Neither the name of the University nor the names of its contributors
508  *    may be used to endorse or promote products derived from this software
509  *    without specific prior written permission.
510  *
511  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
512  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
513  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
514  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
515  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
516  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
517  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
518  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
519  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
520  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
521  * SUCH DAMAGE.
522  *
523  */