u_int[16|32]_t might not be defined.
[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 #include "config.h"
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 HANDLE WINAPI IcmpCreateFile(VOID)
162 {
163     icmp_t* icp;
164
165     ISOCK_SOCKET sid=ISOCK_socket(AF_INET,SOCK_RAW,IPPROTO_ICMP);
166     if (!ISOCK_ISVALID(sid)) {
167         MESSAGE("WARNING: Trying to use ICMP will fail unless running as root\n");
168         SetLastError(ERROR_ACCESS_DENIED);
169         return INVALID_HANDLE_VALUE;
170     }
171
172     icp=malloc(sizeof(*icp));
173     if (icp==NULL) {
174         SetLastError(IP_NO_RESOURCES);
175         return INVALID_HANDLE_VALUE;
176     }
177     icp->sid=sid;
178     icp->default_opts.OptionsSize=IP_OPTS_UNKNOWN;
179     return (HANDLE)icp;
180 }
181
182
183 BOOL WINAPI IcmpCloseHandle(HANDLE  IcmpHandle)
184 {
185     icmp_t* icp=(icmp_t*)IcmpHandle;
186
187     ISOCK_shutdown(icp->sid,2);
188     free(icp);
189     return TRUE;
190 }
191
192
193 DWORD WINAPI IcmpSendEcho(
194     HANDLE                   IcmpHandle,
195     IPAddr                   DestinationAddress,
196     LPVOID                   RequestData,
197     WORD                     RequestSize,
198     PIP_OPTION_INFORMATION   RequestOptions,
199     LPVOID                   ReplyBuffer,
200     DWORD                    ReplySize,
201     DWORD                    Timeout
202     )
203 {
204     icmp_t* icp=(icmp_t*)IcmpHandle;
205     unsigned char* reqbuf;
206     int reqsize;
207
208     struct icmp_echo_reply* ier;
209     struct ip* ip_header;
210     struct icmp* icmp_header;
211     char* endbuf;
212     int ip_header_len;
213     int maxlen;
214     fd_set fdr;
215     struct timeval timeout,send_time,recv_time;
216     struct sockaddr_in addr;
217     int addrlen;
218     unsigned short id,seq,cksum;
219     int res;
220
221     if (ReplySize<sizeof(ICMP_ECHO_REPLY)+ICMP_MINLEN) {
222         SetLastError(IP_BUF_TOO_SMALL);
223         return 0;
224     }
225     /* check the request size against SO_MAX_MSG_SIZE using getsockopt */
226
227     /* Prepare the request */
228     id=getpid() & 0xFFFF;
229     seq=InterlockedIncrement(&icmp_sequence) & 0xFFFF;
230
231     reqsize=ICMP_MINLEN+RequestSize;
232     reqbuf=malloc(reqsize);
233     if (reqbuf==NULL) {
234         SetLastError(ERROR_OUTOFMEMORY);
235         return 0;
236     }
237
238     icmp_header=(struct icmp*)reqbuf;
239     icmp_header->icmp_type=ICMP_ECHO;
240     icmp_header->icmp_code=0;
241     icmp_header->icmp_cksum=0;
242     icmp_header->icmp_id=id;
243     icmp_header->icmp_seq=seq;
244     memcpy(reqbuf+ICMP_MINLEN, RequestData, RequestSize);
245     icmp_header->icmp_cksum=cksum=in_cksum((u_short*)reqbuf,reqsize);
246
247     addr.sin_family=AF_INET;
248     addr.sin_addr.s_addr=DestinationAddress;
249     addr.sin_port=0;
250
251     if (RequestOptions!=NULL) {
252         int val;
253         if (icp->default_opts.OptionsSize==IP_OPTS_UNKNOWN) {
254             int len;
255             /* Before we mess with the options, get the default values */
256             len=sizeof(val);
257             ISOCK_getsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,&len);
258             icp->default_opts.Ttl=val;
259
260             len=sizeof(val);
261             ISOCK_getsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,&len);
262             icp->default_opts.Tos=val;
263             /* FIXME: missing: handling of IP 'flags', and all the other options */
264         }
265
266         val=RequestOptions->Ttl;
267         ISOCK_setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
268         val=RequestOptions->Tos;
269         ISOCK_setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
270         /* FIXME:  missing: handling of IP 'flags', and all the other options */
271
272         icp->default_opts.OptionsSize=IP_OPTS_CUSTOM;
273     } else if (icp->default_opts.OptionsSize==IP_OPTS_CUSTOM) {
274         int val;
275
276         /* Restore the default options */
277         val=icp->default_opts.Ttl;
278         ISOCK_setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
279         val=icp->default_opts.Tos;
280         ISOCK_setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
281         /* FIXME: missing: handling of IP 'flags', and all the other options */
282
283         icp->default_opts.OptionsSize=IP_OPTS_DEFAULT;
284     }
285
286     /* Get ready for receiving the reply
287      * Do it before we send the request to minimize the risk of introducing delays
288      */
289     FD_ZERO(&fdr);
290     FD_SET(icp->sid,&fdr);
291     timeout.tv_sec=Timeout/1000;
292     timeout.tv_usec=(Timeout % 1000)*1000;
293     addrlen=sizeof(addr);
294     ier=ReplyBuffer;
295     ip_header=ReplyBuffer+sizeof(ICMP_ECHO_REPLY);
296     endbuf=ReplyBuffer+ReplySize;
297     maxlen=ReplySize-sizeof(ICMP_ECHO_REPLY);
298
299     /* Send the packet */
300     TRACE("Sending %d bytes (RequestSize=%d) to %s\n", reqsize, RequestSize, inet_ntoa(addr.sin_addr));
301 #if 0
302     if (TRACE_ON(icmp)){
303         unsigned char* buf=(unsigned char*)reqbuf;
304         int i;
305         printf("Output buffer:\n");
306         for (i=0;i<reqsize;i++)
307             printf("%2x,", buf[i]);
308         printf("\n");
309     }
310 #endif
311
312     gettimeofday(&send_time,NULL);
313     res=ISOCK_sendto(icp->sid, reqbuf, reqsize, 0, (struct sockaddr*)&addr, sizeof(addr));
314     free(reqbuf);
315     if (res<0) {
316         if (errno==EMSGSIZE)
317             SetLastError(IP_PACKET_TOO_BIG);
318         else {
319             switch (errno) {
320             case ENETUNREACH:
321                 SetLastError(IP_DEST_NET_UNREACHABLE);
322                 break;
323             case EHOSTUNREACH:
324                 SetLastError(IP_DEST_NET_UNREACHABLE);
325                 break;
326             default:
327                 TRACE("unknown error: errno=%d\n",errno);
328                 SetLastError(ERROR_UNKNOWN);
329             }
330         }
331         return 0;
332     }
333
334     /* Get the reply */
335     ip_header_len=0; /* because gcc was complaining */
336     while ((res=ISOCK_select(icp->sid+1,&fdr,NULL,NULL,&timeout))>0) {
337         gettimeofday(&recv_time,NULL);
338         res=ISOCK_recvfrom(icp->sid, (char*)ip_header, maxlen, 0, (struct sockaddr*)&addr,&addrlen);
339         TRACE("received %d bytes from %s\n",res, inet_ntoa(addr.sin_addr));
340         ier->Status=IP_REQ_TIMED_OUT;
341
342         /* Check whether we should ignore this packet */
343         if ((ip_header->ip_p==IPPROTO_ICMP) && (res>=sizeof(struct ip)+ICMP_MINLEN)) {
344             ip_header_len=ip_header->ip_hl << 2;
345             icmp_header=(struct icmp*)(((char*)ip_header)+ip_header_len);
346             TRACE("received an ICMP packet of type,code=%d,%d\n",icmp_header->icmp_type,icmp_header->icmp_code);
347             if (icmp_header->icmp_type==ICMP_ECHOREPLY) {
348                 if ((icmp_header->icmp_id==id) && (icmp_header->icmp_seq==seq))
349                     ier->Status=IP_SUCCESS;
350             } else {
351                 switch (icmp_header->icmp_type) {
352                 case ICMP_UNREACH:
353                     switch (icmp_header->icmp_code) {
354                     case ICMP_UNREACH_HOST:
355 #ifdef ICMP_UNREACH_HOST_UNKNOWN
356                     case ICMP_UNREACH_HOST_UNKNOWN:
357 #endif
358 #ifdef ICMP_UNREACH_ISOLATED
359                     case ICMP_UNREACH_ISOLATED:
360 #endif
361 #ifdef ICMP_UNREACH_HOST_PROHIB
362                     case ICMP_UNREACH_HOST_PROHIB:
363 #endif
364 #ifdef ICMP_UNREACH_TOSHOST
365                     case ICMP_UNREACH_TOSHOST:
366 #endif
367                         ier->Status=IP_DEST_HOST_UNREACHABLE;
368                         break;
369                     case ICMP_UNREACH_PORT:
370                         ier->Status=IP_DEST_PORT_UNREACHABLE;
371                         break;
372                     case ICMP_UNREACH_PROTOCOL:
373                         ier->Status=IP_DEST_PROT_UNREACHABLE;
374                         break;
375                     case ICMP_UNREACH_SRCFAIL:
376                         ier->Status=IP_BAD_ROUTE;
377                         break;
378                     default:
379                         ier->Status=IP_DEST_NET_UNREACHABLE;
380                     }
381                     break;
382                 case ICMP_TIMXCEED:
383                     if (icmp_header->icmp_code==ICMP_TIMXCEED_REASS)
384                         ier->Status=IP_TTL_EXPIRED_REASSEM;
385                     else
386                         ier->Status=IP_TTL_EXPIRED_TRANSIT;
387                     break;
388                 case ICMP_PARAMPROB:
389                     ier->Status=IP_PARAM_PROBLEM;
390                     break;
391                 case ICMP_SOURCEQUENCH:
392                     ier->Status=IP_SOURCE_QUENCH;
393                     break;
394                 }
395                 if (ier->Status!=IP_REQ_TIMED_OUT) {
396                     struct ip* rep_ip_header;
397                     struct icmp* rep_icmp_header;
398                     /* The ICMP header size of all the packets we accept is the same */
399                     rep_ip_header=(struct ip*)(((char*)icmp_header)+ICMP_MINLEN);
400                     rep_icmp_header=(struct icmp*)(((char*)rep_ip_header)+(rep_ip_header->ip_hl << 2));
401
402                     /* Make sure that this is really a reply to our packet */
403                     if (ip_header_len+ICMP_MINLEN+(rep_ip_header->ip_hl << 2)+ICMP_MINLEN>ip_header->ip_len) {
404                         ier->Status=IP_REQ_TIMED_OUT;
405                     } else if ((rep_icmp_header->icmp_type!=ICMP_ECHO) ||
406                         (rep_icmp_header->icmp_code!=0) ||
407                         (rep_icmp_header->icmp_id!=id) ||
408                         (rep_icmp_header->icmp_seq!=seq) ||
409                         (rep_icmp_header->icmp_cksum!=cksum)) {
410                         /* This was not a reply to one of our packets after all */
411                         TRACE("skipping type,code=%d,%d id,seq=%d,%d cksum=%d\n",
412                             rep_icmp_header->icmp_type,rep_icmp_header->icmp_code,
413                             rep_icmp_header->icmp_id,rep_icmp_header->icmp_seq,
414                             rep_icmp_header->icmp_cksum);
415                         TRACE("expected type,code=8,0 id,seq=%d,%d cksum=%d\n",
416                             id,seq,
417                             cksum);
418                         ier->Status=IP_REQ_TIMED_OUT;
419                     }
420                 }
421             }                
422         }
423
424         if (ier->Status==IP_REQ_TIMED_OUT) {
425             /* This packet was not for us.
426              * Decrease the timeout so that we don't enter an endless loop even
427              * if we get flooded with ICMP packets that are not for us.
428              */
429             timeout.tv_sec=Timeout/1000-(recv_time.tv_sec-send_time.tv_sec);
430             timeout.tv_usec=(Timeout % 1000)*1000+send_time.tv_usec-(recv_time.tv_usec-send_time.tv_usec);
431             if (timeout.tv_usec<0) {
432                 timeout.tv_usec+=1000000;
433                 timeout.tv_sec--;
434             }
435             continue;
436         } else {
437             /* This is a reply to our packet */
438             memcpy(&ier->Address,&ip_header->ip_src,sizeof(IPAddr));
439             /* Status is already set */
440             ier->RoundTripTime=(recv_time.tv_sec-send_time.tv_sec)*1000+(recv_time.tv_usec-send_time.tv_usec)/1000;
441             ier->DataSize=res-ip_header_len-ICMP_MINLEN;
442             ier->Reserved=0;
443             ier->Data=endbuf-ier->DataSize;
444             memmove(ier->Data,((char*)ip_header)+ip_header_len+ICMP_MINLEN,ier->DataSize);
445             ier->Options.Ttl=ip_header->ip_ttl;
446             ier->Options.Tos=ip_header->ip_tos;
447             ier->Options.Flags=ip_header->ip_off >> 13;
448             ier->Options.OptionsSize=ip_header_len-sizeof(struct ip);
449             if (ier->Options.OptionsSize!=0) {
450                 ier->Options.OptionsData=ier->Data-ier->Options.OptionsSize;
451                 /* FIXME: We are supposed to rearrange the option's 'source route' data */
452                 memmove(ier->Options.OptionsData,((char*)ip_header)+ip_header_len,ier->Options.OptionsSize);
453                 endbuf=ier->Options.OptionsData;
454             } else {
455                 ier->Options.OptionsData=NULL;
456                 endbuf=ier->Data;
457             }
458
459             /* Prepare for the next packet */
460             ier++;
461             ip_header=(struct ip*)(((char*)ip_header)+sizeof(ICMP_ECHO_REPLY));
462             maxlen=endbuf-(char*)ip_header;
463
464             /* Check out whether there is more but don't wait this time */
465             timeout.tv_sec=0;
466             timeout.tv_usec=0;
467         }
468         FD_ZERO(&fdr);
469         FD_SET(icp->sid,&fdr);
470     }
471     res=ier-(ICMP_ECHO_REPLY*)ReplyBuffer;
472     if (res==0)
473         SetLastError(IP_REQ_TIMED_OUT);
474     TRACE("received %d replies\n",res);
475     return res;
476 }
477
478 /*
479  * Copyright (c) 1989 The Regents of the University of California.
480  * All rights reserved.
481  *
482  * This code is derived from software contributed to Berkeley by
483  * Mike Muuss.
484  *
485  * Redistribution and use in source and binary forms, with or without
486  * modification, are permitted provided that the following conditions
487  * are met:
488  * 1. Redistributions of source code must retain the above copyright
489  *    notice, this list of conditions and the following disclaimer.
490  * 2. Redistributions in binary form must reproduce the above copyright
491  *    notice, this list of conditions and the following disclaimer in the
492  *    documentation and/or other materials provided with the distribution.
493  * 3. All advertising materials mentioning features or use of this software
494  *    must display the following acknowledgement:
495  *      This product includes software developed by the University of
496  *      California, Berkeley and its contributors.
497  * 4. Neither the name of the University nor the names of its contributors
498  *    may be used to endorse or promote products derived from this software
499  *    without specific prior written permission.
500  *
501  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
502  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
503  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
504  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
505  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
506  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
507  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
508  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
509  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
510  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
511  * SUCH DAMAGE.
512  *
513  */