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