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