Use wine_get_dos_file_name rather than relying on GetFullPathNameW
[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  * 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 "icmpapi.h"
70 #include "wine/debug.h"
71
72 /* Set up endiannes macros for the ip and ip_icmp BSD headers */
73 #ifndef BIG_ENDIAN
74 #define BIG_ENDIAN       4321
75 #endif
76 #ifndef LITTLE_ENDIAN
77 #define LITTLE_ENDIAN    1234
78 #endif
79 #ifndef BYTE_ORDER
80 #ifdef WORDS_BIGENDIAN
81 #define BYTE_ORDER       BIG_ENDIAN
82 #else
83 #define BYTE_ORDER       LITTLE_ENDIAN
84 #endif
85 #endif /* BYTE_ORDER */
86
87 #define u_int16_t  WORD
88 #define u_int32_t  DWORD
89
90 /* These are BSD headers. We use these here because they are needed on
91  * libc5 Linux systems. On other platforms they are usually simply more
92  * complete than the native stuff, and cause less portability problems
93  * so we use them anyway.
94  */
95 #include "ip.h"
96 #include "ip_icmp.h"
97
98
99 WINE_DEFAULT_DEBUG_CHANNEL(icmp);
100
101
102 typedef struct {
103     int sid;
104     IP_OPTION_INFORMATION default_opts;
105 } icmp_t;
106
107 #define IP_OPTS_UNKNOWN     0
108 #define IP_OPTS_DEFAULT     1
109 #define IP_OPTS_CUSTOM      2
110
111 /* The sequence number is unique process wide, so that all threads
112  * have a distinct sequence number.
113  */
114 static LONG icmp_sequence=0;
115
116 static int in_cksum(u_short *addr, int len)
117 {
118     int nleft=len;
119     u_short *w = addr;
120     int sum = 0;
121     u_short answer = 0;
122
123     while (nleft > 1) {
124         sum += *w++;
125         nleft -= 2;
126     }
127
128     if (nleft == 1) {
129         *(u_char *)(&answer) = *(u_char *)w;
130         sum += answer;
131     }
132
133     sum = (sum >> 16) + (sum & 0xffff);
134     sum  += (sum >> 16);
135     answer = ~sum;
136     return(answer);
137 }
138
139
140
141 /*
142  * Exported Routines.
143  */
144
145 /***********************************************************************
146  *              IcmpCreateFile (ICMP.@)
147  */
148 HANDLE WINAPI IcmpCreateFile(VOID)
149 {
150     icmp_t* icp;
151
152     int sid=socket(AF_INET,SOCK_RAW,IPPROTO_ICMP);
153     if (sid < 0) {
154         MESSAGE("WARNING: Trying to use ICMP (network ping) will fail unless running as root\n");
155         SetLastError(ERROR_ACCESS_DENIED);
156         return INVALID_HANDLE_VALUE;
157     }
158
159     icp=HeapAlloc(GetProcessHeap(), 0, sizeof(*icp));
160     if (icp==NULL) {
161         SetLastError(IP_NO_RESOURCES);
162         return INVALID_HANDLE_VALUE;
163     }
164     icp->sid=sid;
165     icp->default_opts.OptionsSize=IP_OPTS_UNKNOWN;
166     return (HANDLE)icp;
167 }
168
169
170 /***********************************************************************
171  *              IcmpCloseHandle (ICMP.@)
172  */
173 BOOL WINAPI IcmpCloseHandle(HANDLE  IcmpHandle)
174 {
175     icmp_t* icp=(icmp_t*)IcmpHandle;
176     if (IcmpHandle==INVALID_HANDLE_VALUE) {
177         /* FIXME: in fact win98 seems to ignore the handle value !!! */
178         SetLastError(ERROR_INVALID_HANDLE);
179         return FALSE;
180     }
181
182     shutdown(icp->sid,2);
183     HeapFree(GetProcessHeap (), 0, icp);
184     return TRUE;
185 }
186
187
188 /***********************************************************************
189  *              IcmpSendEcho (ICMP.@)
190  */
191 DWORD WINAPI IcmpSendEcho(
192     HANDLE                   IcmpHandle,
193     IPAddr                   DestinationAddress,
194     LPVOID                   RequestData,
195     WORD                     RequestSize,
196     PIP_OPTION_INFORMATION   RequestOptions,
197     LPVOID                   ReplyBuffer,
198     DWORD                    ReplySize,
199     DWORD                    Timeout
200     )
201 {
202     icmp_t* icp=(icmp_t*)IcmpHandle;
203     unsigned char* reqbuf;
204     int reqsize;
205
206     struct icmp_echo_reply* ier;
207     struct ip* ip_header;
208     struct icmp* icmp_header;
209     char* endbuf;
210     int ip_header_len;
211     int maxlen;
212     fd_set fdr;
213     struct timeval timeout;
214     DWORD send_time,recv_time;
215     struct sockaddr_in addr;
216     unsigned int addrlen;
217     unsigned short id,seq,cksum;
218     int res;
219
220     if (IcmpHandle==INVALID_HANDLE_VALUE) {
221         /* FIXME: in fact win98 seems to ignore the handle value !!! */
222         SetLastError(ERROR_INVALID_HANDLE);
223         return 0;
224     }
225
226     if (ReplySize<sizeof(ICMP_ECHO_REPLY)+ICMP_MINLEN) {
227         SetLastError(IP_BUF_TOO_SMALL);
228         return 0;
229     }
230     /* check the request size against SO_MAX_MSG_SIZE using getsockopt */
231
232     /* Prepare the request */
233     id=getpid() & 0xFFFF;
234     seq=InterlockedIncrement(&icmp_sequence) & 0xFFFF;
235
236     reqsize=ICMP_MINLEN+RequestSize;
237     reqbuf=HeapAlloc(GetProcessHeap(), 0, reqsize);
238     if (reqbuf==NULL) {
239         SetLastError(ERROR_OUTOFMEMORY);
240         return 0;
241     }
242
243     icmp_header=(struct icmp*)reqbuf;
244     icmp_header->icmp_type=ICMP_ECHO;
245     icmp_header->icmp_code=0;
246     icmp_header->icmp_cksum=0;
247     icmp_header->icmp_id=id;
248     icmp_header->icmp_seq=seq;
249     memcpy(reqbuf+ICMP_MINLEN, RequestData, RequestSize);
250     icmp_header->icmp_cksum=cksum=in_cksum((u_short*)reqbuf,reqsize);
251
252     addr.sin_family=AF_INET;
253     addr.sin_addr.s_addr=DestinationAddress;
254     addr.sin_port=0;
255
256     if (RequestOptions!=NULL) {
257         int val;
258         if (icp->default_opts.OptionsSize==IP_OPTS_UNKNOWN) {
259             unsigned int len;
260             /* Before we mess with the options, get the default values */
261             len=sizeof(val);
262             getsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,&len);
263             icp->default_opts.Ttl=val;
264
265             len=sizeof(val);
266             getsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,&len);
267             icp->default_opts.Tos=val;
268             /* FIXME: missing: handling of IP 'flags', and all the other options */
269         }
270
271         val=RequestOptions->Ttl;
272         setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
273         val=RequestOptions->Tos;
274         setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
275         /* FIXME:  missing: handling of IP 'flags', and all the other options */
276
277         icp->default_opts.OptionsSize=IP_OPTS_CUSTOM;
278     } else if (icp->default_opts.OptionsSize==IP_OPTS_CUSTOM) {
279         int val;
280
281         /* Restore the default options */
282         val=icp->default_opts.Ttl;
283         setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
284         val=icp->default_opts.Tos;
285         setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
286         /* FIXME: missing: handling of IP 'flags', and all the other options */
287
288         icp->default_opts.OptionsSize=IP_OPTS_DEFAULT;
289     }
290
291     /* Get ready for receiving the reply
292      * Do it before we send the request to minimize the risk of introducing delays
293      */
294     FD_ZERO(&fdr);
295     FD_SET(icp->sid,&fdr);
296     timeout.tv_sec=Timeout/1000;
297     timeout.tv_usec=(Timeout % 1000)*1000;
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);
303
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");
314     }
315 #endif
316
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);
334             }
335         }
336         return 0;
337     }
338
339     /* Get the reply */
340     ip_header_len=0; /* because gcc was complaining */
341     while ((res=select(icp->sid+1,&fdr,NULL,NULL,&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;
346
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;
385                     }
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;
399                 }
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));
406
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;
426                     }
427                 }
428             }
429         }
430
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.
435              */
436             int t = Timeout - (recv_time - send_time);
437             if (t < 0) t = 0;
438             timeout.tv_sec = t / 1000;
439             timeout.tv_usec = (t % 1000) * 1000;
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.tv_sec=0;
471             timeout.tv_usec=0;
472         }
473         FD_ZERO(&fdr);
474         FD_SET(icp->sid,&fdr);
475     }
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;
481 }
482
483 /*
484  * Copyright (c) 1989 The Regents of the University of California.
485  * All rights reserved.
486  *
487  * This code is derived from software contributed to Berkeley by
488  * Mike Muuss.
489  *
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.
501  *
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.
513  *
514  */