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