Release 20030408.
[wine/gsoc-2012-control.git] / dlls / icmp / icmp_main.c
blobe77d55490d50aea79e1bcaf760366e4f66784d5b
1 /*
2 * ICMP
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.
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.
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.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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.
36 #include "config.h"
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
52 #ifdef HAVE_SYS_TIME_H
53 # include <sys/time.h>
54 #endif
55 #include <string.h>
56 #include <errno.h>
57 #ifdef HAVE_UNISTD_H
58 # include <unistd.h>
59 #endif
60 #ifdef HAVE_ARPA_INET_H
61 # include <arpa/inet.h>
62 #endif
64 #include "windef.h"
65 #include "winbase.h"
66 #include "winerror.h"
67 #include "ipexport.h"
68 #include "icmpapi.h"
69 #include "wine/debug.h"
71 /* Set up endiannes macros for the ip and ip_icmp BSD headers */
72 #ifndef BIG_ENDIAN
73 #define BIG_ENDIAN 4321
74 #endif
75 #ifndef LITTLE_ENDIAN
76 #define LITTLE_ENDIAN 1234
77 #endif
78 #ifndef BYTE_ORDER
79 #ifdef WORDS_BIGENDIAN
80 #define BYTE_ORDER BIG_ENDIAN
81 #else
82 #define BYTE_ORDER LITTLE_ENDIAN
83 #endif
84 #endif /* BYTE_ORDER */
86 #define u_int16_t WORD
87 #define u_int32_t DWORD
89 /* These are BSD headers. We use these here because they are needed on
90 * libc5 Linux systems. On other platforms they are usually simply more
91 * complete than the native stuff, and cause less portability problems
92 * so we use them anyway.
94 #include "ip.h"
95 #include "ip_icmp.h"
98 WINE_DEFAULT_DEBUG_CHANNEL(icmp);
101 typedef struct {
102 int sid;
103 IP_OPTION_INFORMATION default_opts;
104 } icmp_t;
106 #define IP_OPTS_UNKNOWN 0
107 #define IP_OPTS_DEFAULT 1
108 #define IP_OPTS_CUSTOM 2
110 /* The sequence number is unique process wide, so that all threads
111 * have a distinct sequence number.
113 static LONG icmp_sequence=0;
115 static int in_cksum(u_short *addr, int len)
117 int nleft=len;
118 u_short *w = addr;
119 int sum = 0;
120 u_short answer = 0;
122 while (nleft > 1) {
123 sum += *w++;
124 nleft -= 2;
127 if (nleft == 1) {
128 *(u_char *)(&answer) = *(u_char *)w;
129 sum += answer;
132 sum = (sum >> 16) + (sum & 0xffff);
133 sum += (sum >> 16);
134 answer = ~sum;
135 return(answer);
141 * Exported Routines.
144 /***********************************************************************
145 * IcmpCreateFile (ICMP.@)
147 HANDLE WINAPI IcmpCreateFile(VOID)
149 icmp_t* icp;
151 int sid=socket(AF_INET,SOCK_RAW,IPPROTO_ICMP);
152 if (sid < 0) {
153 MESSAGE("WARNING: Trying to use ICMP (network ping) will fail unless running as root\n");
154 SetLastError(ERROR_ACCESS_DENIED);
155 return INVALID_HANDLE_VALUE;
158 icp=HeapAlloc(GetProcessHeap(), 0, sizeof(*icp));
159 if (icp==NULL) {
160 SetLastError(IP_NO_RESOURCES);
161 return INVALID_HANDLE_VALUE;
163 icp->sid=sid;
164 icp->default_opts.OptionsSize=IP_OPTS_UNKNOWN;
165 return (HANDLE)icp;
169 /***********************************************************************
170 * IcmpCloseHandle (ICMP.@)
172 BOOL WINAPI IcmpCloseHandle(HANDLE IcmpHandle)
174 icmp_t* icp=(icmp_t*)IcmpHandle;
175 if (IcmpHandle==INVALID_HANDLE_VALUE) {
176 /* FIXME: in fact win98 seems to ignore the handle value !!! */
177 SetLastError(ERROR_INVALID_HANDLE);
178 return FALSE;
181 shutdown(icp->sid,2);
182 HeapFree(GetProcessHeap (), 0, icp);
183 return TRUE;
187 /***********************************************************************
188 * IcmpSendEcho (ICMP.@)
190 DWORD WINAPI IcmpSendEcho(
191 HANDLE IcmpHandle,
192 IPAddr DestinationAddress,
193 LPVOID RequestData,
194 WORD RequestSize,
195 PIP_OPTION_INFORMATION RequestOptions,
196 LPVOID ReplyBuffer,
197 DWORD ReplySize,
198 DWORD Timeout
201 icmp_t* icp=(icmp_t*)IcmpHandle;
202 unsigned char* reqbuf;
203 int reqsize;
205 struct icmp_echo_reply* ier;
206 struct ip* ip_header;
207 struct icmp* icmp_header;
208 char* endbuf;
209 int ip_header_len;
210 int maxlen;
211 fd_set fdr;
212 struct timeval timeout,send_time,recv_time;
213 struct sockaddr_in addr;
214 int addrlen;
215 unsigned short id,seq,cksum;
216 int res;
218 if (IcmpHandle==INVALID_HANDLE_VALUE) {
219 /* FIXME: in fact win98 seems to ignore the handle value !!! */
220 SetLastError(ERROR_INVALID_HANDLE);
221 return 0;
224 if (ReplySize<sizeof(ICMP_ECHO_REPLY)+ICMP_MINLEN) {
225 SetLastError(IP_BUF_TOO_SMALL);
226 return 0;
228 /* check the request size against SO_MAX_MSG_SIZE using getsockopt */
230 /* Prepare the request */
231 id=getpid() & 0xFFFF;
232 seq=InterlockedIncrement(&icmp_sequence) & 0xFFFF;
234 reqsize=ICMP_MINLEN+RequestSize;
235 reqbuf=HeapAlloc(GetProcessHeap(), 0, reqsize);
236 if (reqbuf==NULL) {
237 SetLastError(ERROR_OUTOFMEMORY);
238 return 0;
241 icmp_header=(struct icmp*)reqbuf;
242 icmp_header->icmp_type=ICMP_ECHO;
243 icmp_header->icmp_code=0;
244 icmp_header->icmp_cksum=0;
245 icmp_header->icmp_id=id;
246 icmp_header->icmp_seq=seq;
247 memcpy(reqbuf+ICMP_MINLEN, RequestData, RequestSize);
248 icmp_header->icmp_cksum=cksum=in_cksum((u_short*)reqbuf,reqsize);
250 addr.sin_family=AF_INET;
251 addr.sin_addr.s_addr=DestinationAddress;
252 addr.sin_port=0;
254 if (RequestOptions!=NULL) {
255 int val;
256 if (icp->default_opts.OptionsSize==IP_OPTS_UNKNOWN) {
257 int len;
258 /* Before we mess with the options, get the default values */
259 len=sizeof(val);
260 getsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,&len);
261 icp->default_opts.Ttl=val;
263 len=sizeof(val);
264 getsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,&len);
265 icp->default_opts.Tos=val;
266 /* FIXME: missing: handling of IP 'flags', and all the other options */
269 val=RequestOptions->Ttl;
270 setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
271 val=RequestOptions->Tos;
272 setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
273 /* FIXME: missing: handling of IP 'flags', and all the other options */
275 icp->default_opts.OptionsSize=IP_OPTS_CUSTOM;
276 } else if (icp->default_opts.OptionsSize==IP_OPTS_CUSTOM) {
277 int val;
279 /* Restore the default options */
280 val=icp->default_opts.Ttl;
281 setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
282 val=icp->default_opts.Tos;
283 setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
284 /* FIXME: missing: handling of IP 'flags', and all the other options */
286 icp->default_opts.OptionsSize=IP_OPTS_DEFAULT;
289 /* Get ready for receiving the reply
290 * Do it before we send the request to minimize the risk of introducing delays
292 FD_ZERO(&fdr);
293 FD_SET(icp->sid,&fdr);
294 timeout.tv_sec=Timeout/1000;
295 timeout.tv_usec=(Timeout % 1000)*1000;
296 addrlen=sizeof(addr);
297 ier=ReplyBuffer;
298 ip_header=(struct ip *) ((char *) ReplyBuffer+sizeof(ICMP_ECHO_REPLY));
299 endbuf=(char *) ReplyBuffer+ReplySize;
300 maxlen=ReplySize-sizeof(ICMP_ECHO_REPLY);
302 /* Send the packet */
303 TRACE("Sending %d bytes (RequestSize=%d) to %s\n", reqsize, RequestSize, inet_ntoa(addr.sin_addr));
304 #if 0
305 if (TRACE_ON(icmp)){
306 unsigned char* buf=(unsigned char*)reqbuf;
307 int i;
308 printf("Output buffer:\n");
309 for (i=0;i<reqsize;i++)
310 printf("%2x,", buf[i]);
311 printf("\n");
313 #endif
315 gettimeofday(&send_time,NULL);
316 res=sendto(icp->sid, reqbuf, reqsize, 0, (struct sockaddr*)&addr, sizeof(addr));
317 HeapFree(GetProcessHeap (), 0, reqbuf);
318 if (res<0) {
319 if (errno==EMSGSIZE)
320 SetLastError(IP_PACKET_TOO_BIG);
321 else {
322 switch (errno) {
323 case ENETUNREACH:
324 SetLastError(IP_DEST_NET_UNREACHABLE);
325 break;
326 case EHOSTUNREACH:
327 SetLastError(IP_DEST_NET_UNREACHABLE);
328 break;
329 default:
330 TRACE("unknown error: errno=%d\n",errno);
331 SetLastError(ERROR_UNKNOWN);
334 return 0;
337 /* Get the reply */
338 ip_header_len=0; /* because gcc was complaining */
339 while ((res=select(icp->sid+1,&fdr,NULL,NULL,&timeout))>0) {
340 gettimeofday(&recv_time,NULL);
341 res=recvfrom(icp->sid, (char*)ip_header, maxlen, 0, (struct sockaddr*)&addr,&addrlen);
342 TRACE("received %d bytes from %s\n",res, inet_ntoa(addr.sin_addr));
343 ier->Status=IP_REQ_TIMED_OUT;
345 /* Check whether we should ignore this packet */
346 if ((ip_header->ip_p==IPPROTO_ICMP) && (res>=sizeof(struct ip)+ICMP_MINLEN)) {
347 ip_header_len=ip_header->ip_hl << 2;
348 icmp_header=(struct icmp*)(((char*)ip_header)+ip_header_len);
349 TRACE("received an ICMP packet of type,code=%d,%d\n",icmp_header->icmp_type,icmp_header->icmp_code);
350 if (icmp_header->icmp_type==ICMP_ECHOREPLY) {
351 if ((icmp_header->icmp_id==id) && (icmp_header->icmp_seq==seq))
352 ier->Status=IP_SUCCESS;
353 } else {
354 switch (icmp_header->icmp_type) {
355 case ICMP_UNREACH:
356 switch (icmp_header->icmp_code) {
357 case ICMP_UNREACH_HOST:
358 #ifdef ICMP_UNREACH_HOST_UNKNOWN
359 case ICMP_UNREACH_HOST_UNKNOWN:
360 #endif
361 #ifdef ICMP_UNREACH_ISOLATED
362 case ICMP_UNREACH_ISOLATED:
363 #endif
364 #ifdef ICMP_UNREACH_HOST_PROHIB
365 case ICMP_UNREACH_HOST_PROHIB:
366 #endif
367 #ifdef ICMP_UNREACH_TOSHOST
368 case ICMP_UNREACH_TOSHOST:
369 #endif
370 ier->Status=IP_DEST_HOST_UNREACHABLE;
371 break;
372 case ICMP_UNREACH_PORT:
373 ier->Status=IP_DEST_PORT_UNREACHABLE;
374 break;
375 case ICMP_UNREACH_PROTOCOL:
376 ier->Status=IP_DEST_PROT_UNREACHABLE;
377 break;
378 case ICMP_UNREACH_SRCFAIL:
379 ier->Status=IP_BAD_ROUTE;
380 break;
381 default:
382 ier->Status=IP_DEST_NET_UNREACHABLE;
384 break;
385 case ICMP_TIMXCEED:
386 if (icmp_header->icmp_code==ICMP_TIMXCEED_REASS)
387 ier->Status=IP_TTL_EXPIRED_REASSEM;
388 else
389 ier->Status=IP_TTL_EXPIRED_TRANSIT;
390 break;
391 case ICMP_PARAMPROB:
392 ier->Status=IP_PARAM_PROBLEM;
393 break;
394 case ICMP_SOURCEQUENCH:
395 ier->Status=IP_SOURCE_QUENCH;
396 break;
398 if (ier->Status!=IP_REQ_TIMED_OUT) {
399 struct ip* rep_ip_header;
400 struct icmp* rep_icmp_header;
401 /* The ICMP header size of all the packets we accept is the same */
402 rep_ip_header=(struct ip*)(((char*)icmp_header)+ICMP_MINLEN);
403 rep_icmp_header=(struct icmp*)(((char*)rep_ip_header)+(rep_ip_header->ip_hl << 2));
405 /* Make sure that this is really a reply to our packet */
406 if (ip_header_len+ICMP_MINLEN+(rep_ip_header->ip_hl << 2)+ICMP_MINLEN>ip_header->ip_len) {
407 ier->Status=IP_REQ_TIMED_OUT;
408 } else if ((rep_icmp_header->icmp_type!=ICMP_ECHO) ||
409 (rep_icmp_header->icmp_code!=0) ||
410 (rep_icmp_header->icmp_id!=id) ||
411 /* windows doesn't check this checksum, else tracert */
412 /* behind a Linux 2.2 masquerading firewall would fail*/
413 /* (rep_icmp_header->icmp_cksum!=cksum) || */
414 (rep_icmp_header->icmp_seq!=seq)) {
415 /* This was not a reply to one of our packets after all */
416 TRACE("skipping type,code=%d,%d id,seq=%d,%d cksum=%d\n",
417 rep_icmp_header->icmp_type,rep_icmp_header->icmp_code,
418 rep_icmp_header->icmp_id,rep_icmp_header->icmp_seq,
419 rep_icmp_header->icmp_cksum);
420 TRACE("expected type,code=8,0 id,seq=%d,%d cksum=%d\n",
421 id,seq,
422 cksum);
423 ier->Status=IP_REQ_TIMED_OUT;
429 if (ier->Status==IP_REQ_TIMED_OUT) {
430 /* This packet was not for us.
431 * Decrease the timeout so that we don't enter an endless loop even
432 * if we get flooded with ICMP packets that are not for us.
434 timeout.tv_sec=Timeout/1000-(recv_time.tv_sec-send_time.tv_sec);
435 timeout.tv_usec=(Timeout % 1000)*1000+send_time.tv_usec-(recv_time.tv_usec-send_time.tv_usec);
436 if (timeout.tv_usec<0) {
437 timeout.tv_usec+=1000000;
438 timeout.tv_sec--;
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.tv_sec-send_time.tv_sec)*1000+(recv_time.tv_usec-send_time.tv_usec)/1000;
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=ier->Options.OptionsData;
459 } else {
460 ier->Options.OptionsData=NULL;
461 endbuf=ier->Data;
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;
469 /* Check out whether there is more but don't wait this time */
470 timeout.tv_sec=0;
471 timeout.tv_usec=0;
473 FD_ZERO(&fdr);
474 FD_SET(icp->sid,&fdr);
476 res=ier-(ICMP_ECHO_REPLY*)ReplyBuffer;
477 if (res==0)
478 SetLastError(IP_REQ_TIMED_OUT);
479 TRACE("received %d replies\n",res);
480 return res;
484 * Copyright (c) 1989 The Regents of the University of California.
485 * All rights reserved.
487 * This code is derived from software contributed to Berkeley by
488 * Mike Muuss.
490 * Redistribution and use in source and binary forms, with or without
491 * modification, are permitted provided that the following conditions
492 * are met:
493 * 1. Redistributions of source code must retain the above copyright
494 * notice, this list of conditions and the following disclaimer.
495 * 2. Redistributions in binary form must reproduce the above copyright
496 * notice, this list of conditions and the following disclaimer in the
497 * documentation and/or other materials provided with the distribution.
498 * 3. Neither the name of the University nor the names of its contributors
499 * may be used to endorse or promote products derived from this software
500 * without specific prior written permission.
502 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
503 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
504 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
505 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
506 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
507 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
508 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
509 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
510 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
511 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
512 * SUCH DAMAGE.