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