ntoskrnl.exe/tests: Fix path buffer allocation size.
[wine.git] / dlls / iphlpapi / ipstats.c
blobc36f42a378a2e6b26bf6d09c69ae5c76acffd55b
1 /*
2 * Copyright (C) 2003,2006 Juan Lang
3 * Copyright (C) 2007 TransGaming Technologies Inc.
4 * Copyright (C) 2009 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #ifdef HAVE_DIRENT_H
31 #include <dirent.h>
32 #endif
33 #ifdef HAVE_ALIAS_H
34 #include <alias.h>
35 #endif
36 #ifdef HAVE_SYS_SOCKET_H
37 #include <sys/socket.h>
38 #endif
39 #ifdef HAVE_SYS_SOCKETVAR_H
40 #include <sys/socketvar.h>
41 #endif
42 #ifdef HAVE_SYS_TIMEOUT_H
43 #include <sys/timeout.h>
44 #endif
45 #ifdef HAVE_NETINET_IN_H
46 #include <netinet/in.h>
47 #endif
48 #ifdef HAVE_NETINET_IN_SYSTM_H
49 #include <netinet/in_systm.h>
50 #endif
51 #ifdef HAVE_ARPA_INET_H
52 #include <arpa/inet.h>
53 #endif
54 #ifdef HAVE_NET_IF_H
55 #include <net/if.h>
56 #endif
57 #ifdef HAVE_NET_IF_DL_H
58 #include <net/if_dl.h>
59 #endif
60 #ifdef HAVE_NET_IF_TYPES_H
61 #include <net/if_types.h>
62 #endif
63 #ifdef HAVE_NET_ROUTE_H
64 #include <net/route.h>
65 #endif
66 #ifdef HAVE_NET_IF_ARP_H
67 #include <net/if_arp.h>
68 #endif
69 #ifdef HAVE_NETINET_IF_ETHER_H
70 #include <netinet/if_ether.h>
71 #endif
72 #ifdef HAVE_NETINET_IF_INARP_H
73 #include <netinet/if_inarp.h>
74 #endif
75 #ifdef HAVE_NETINET_IP_H
76 #include <netinet/ip.h>
77 #endif
78 #ifdef HAVE_NETINET_TCP_H
79 #include <netinet/tcp.h>
80 #endif
81 #ifdef HAVE_NETINET_IP_VAR_H
82 #include <netinet/ip_var.h>
83 #endif
84 #ifdef HAVE_NETINET_TCP_FSM_H
85 #include <netinet/tcp_fsm.h>
86 #endif
87 #ifdef HAVE_NETINET_IN_PCB_H
88 #include <netinet/in_pcb.h>
89 #endif
90 #ifdef HAVE_NETINET_TCP_TIMER_H
91 #include <netinet/tcp_timer.h>
92 #endif
93 #ifdef HAVE_NETINET_TCP_VAR_H
94 #include <netinet/tcp_var.h>
95 #endif
96 #ifdef HAVE_NETINET_IP_ICMP_H
97 #include <netinet/ip_icmp.h>
98 #endif
99 #ifdef HAVE_NETINET_ICMP_VAR_H
100 #include <netinet/icmp_var.h>
101 #endif
102 #ifdef HAVE_NETINET_UDP_H
103 #include <netinet/udp.h>
104 #endif
105 #ifdef HAVE_NETINET_UDP_VAR_H
106 #include <netinet/udp_var.h>
107 #endif
108 #ifdef HAVE_SYS_PROTOSW_H
109 #include <sys/protosw.h>
110 #endif
111 #ifdef HAVE_SYS_SYSCTL_H
112 #include <sys/sysctl.h>
113 #endif
114 #ifdef HAVE_KSTAT_H
115 #include <kstat.h>
116 #endif
117 #ifdef HAVE_INET_MIB2_H
118 #include <inet/mib2.h>
119 #endif
120 #ifdef HAVE_STROPTS_H
121 #include <stropts.h>
122 #endif
123 #ifdef HAVE_SYS_TIHDR_H
124 #include <sys/tihdr.h>
125 #endif
126 #ifdef HAVE_SYS_PARAM_H
127 #include <sys/param.h>
128 #endif
129 #ifdef HAVE_SYS_QUEUE_H
130 #include <sys/queue.h>
131 #endif
132 #ifdef HAVE_SYS_USER_H
133 /* Make sure the definitions of struct kinfo_proc are the same. */
134 #include <sys/user.h>
135 #endif
136 #ifdef HAVE_LIBPROCSTAT_H
137 #include <libprocstat.h>
138 #endif
139 #ifdef HAVE_LIBPROC_H
140 #include <libproc.h>
141 #endif
143 #ifndef ROUNDUP
144 #define ROUNDUP(a) \
145 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
146 #endif
147 #ifndef ADVANCE
148 #define ADVANCE(x, n) (x += ROUNDUP(((struct sockaddr *)n)->sa_len))
149 #endif
151 #include "ntstatus.h"
152 #define WIN32_NO_STATUS
153 #define NONAMELESSUNION
154 #define USE_WS_PREFIX
155 #include "winsock2.h"
156 #include "ws2ipdef.h"
157 #include "ifenum.h"
158 #include "ipstats.h"
159 #include "iphlpapi.h"
161 #include "wine/debug.h"
162 #include "wine/server.h"
163 #include "wine/unicode.h"
165 #ifndef HAVE_NETINET_TCP_FSM_H
166 #define TCPS_ESTABLISHED 1
167 #define TCPS_SYN_SENT 2
168 #define TCPS_SYN_RECEIVED 3
169 #define TCPS_FIN_WAIT_1 4
170 #define TCPS_FIN_WAIT_2 5
171 #define TCPS_TIME_WAIT 6
172 #define TCPS_CLOSED 7
173 #define TCPS_CLOSE_WAIT 8
174 #define TCPS_LAST_ACK 9
175 #define TCPS_LISTEN 10
176 #define TCPS_CLOSING 11
177 #endif
179 #ifndef RTF_MULTICAST
180 #define RTF_MULTICAST 0 /* Not available on NetBSD/OpenBSD */
181 #endif
183 #ifndef RTF_LLINFO
184 #define RTF_LLINFO 0 /* Not available on FreeBSD 8 and above */
185 #endif
187 WINE_DEFAULT_DEBUG_CHANNEL(iphlpapi);
189 #ifdef HAVE_LIBKSTAT
190 static DWORD kstat_get_ui32( kstat_t *ksp, const char *name )
192 unsigned int i;
193 kstat_named_t *data = ksp->ks_data;
195 for (i = 0; i < ksp->ks_ndata; i++)
196 if (!strcmp( data[i].name, name )) return data[i].value.ui32;
197 return 0;
200 static ULONGLONG kstat_get_ui64( kstat_t *ksp, const char *name )
202 unsigned int i;
203 kstat_named_t *data = ksp->ks_data;
205 for (i = 0; i < ksp->ks_ndata; i++)
206 if (!strcmp( data[i].name, name )) return data[i].value.ui64;
207 return 0;
209 #endif
211 #if defined(HAVE_SYS_TIHDR_H) && defined(T_OPTMGMT_ACK)
212 static int open_streams_mib( const char *proto )
214 int fd;
215 struct strbuf buf;
216 struct request
218 struct T_optmgmt_req req_header;
219 struct opthdr opt_header;
220 } request;
222 if ((fd = open( "/dev/arp", O_RDWR )) == -1)
224 WARN( "could not open /dev/arp: %s\n", strerror(errno) );
225 return -1;
227 if (proto) ioctl( fd, I_PUSH, proto );
229 request.req_header.PRIM_type = T_SVR4_OPTMGMT_REQ;
230 request.req_header.OPT_length = sizeof(request.opt_header);
231 request.req_header.OPT_offset = FIELD_OFFSET( struct request, opt_header );
232 request.req_header.MGMT_flags = T_CURRENT;
233 request.opt_header.level = MIB2_IP;
234 request.opt_header.name = 0;
235 request.opt_header.len = 0;
237 buf.len = sizeof(request);
238 buf.buf = (caddr_t)&request;
239 if (putmsg( fd, &buf, NULL, 0 ) == -1)
241 WARN( "putmsg: %s\n", strerror(errno) );
242 close( fd );
243 fd = -1;
245 return fd;
248 static void *read_mib_entry( int fd, int level, int name, int *len )
250 struct strbuf buf;
251 void *data;
252 int ret, flags = 0;
254 struct reply
256 struct T_optmgmt_ack ack_header;
257 struct opthdr opt_header;
258 } reply;
260 for (;;)
262 buf.maxlen = sizeof(reply);
263 buf.buf = (caddr_t)&reply;
264 if ((ret = getmsg( fd, &buf, NULL, &flags )) < 0) return NULL;
265 if (!(ret & MOREDATA)) return NULL;
266 if (reply.ack_header.PRIM_type != T_OPTMGMT_ACK) return NULL;
267 if (buf.len < sizeof(reply.ack_header)) return NULL;
268 if (reply.ack_header.OPT_length < sizeof(reply.opt_header)) return NULL;
270 if (!(data = HeapAlloc( GetProcessHeap(), 0, reply.opt_header.len ))) return NULL;
271 buf.maxlen = reply.opt_header.len;
272 buf.buf = (caddr_t)data;
273 flags = 0;
274 if (getmsg( fd, NULL, &buf, &flags ) >= 0 &&
275 reply.opt_header.level == level &&
276 reply.opt_header.name == name)
278 *len = buf.len;
279 return data;
281 HeapFree( GetProcessHeap(), 0, data );
284 #endif /* HAVE_SYS_TIHDR_H && T_OPTMGMT_ACK */
286 DWORD getInterfaceStatsByName(const char *name, PMIB_IFROW entry)
288 DWORD ret = ERROR_NOT_SUPPORTED;
290 if (!name || !entry) return ERROR_INVALID_PARAMETER;
292 #ifdef __linux__
294 FILE *fp;
296 if ((fp = fopen("/proc/net/dev", "r")))
298 DWORD skip;
299 char buf[512], *ptr;
300 int nameLen = strlen(name);
302 while ((ptr = fgets(buf, sizeof(buf), fp)))
304 while (*ptr && isspace(*ptr)) ptr++;
305 if (strncasecmp(ptr, name, nameLen) == 0 && *(ptr + nameLen) == ':')
307 ptr += nameLen + 1;
308 sscanf( ptr, "%u %u %u %u %u %u %u %u %u %u %u %u",
309 &entry->dwInOctets, &entry->dwInUcastPkts,
310 &entry->dwInErrors, &entry->dwInDiscards,
311 &skip, &skip, &skip,
312 &entry->dwInNUcastPkts, &entry->dwOutOctets,
313 &entry->dwOutUcastPkts, &entry->dwOutErrors,
314 &entry->dwOutDiscards );
315 break;
318 fclose(fp);
319 ret = NO_ERROR;
322 #elif defined(HAVE_LIBKSTAT)
324 kstat_ctl_t *kc;
325 kstat_t *ksp;
327 if ((kc = kstat_open()) &&
328 (ksp = kstat_lookup( kc, NULL, -1, (char *)name )) &&
329 kstat_read( kc, ksp, NULL ) != -1 &&
330 ksp->ks_type == KSTAT_TYPE_NAMED)
332 entry->dwMtu = 1500; /* FIXME */
333 entry->dwSpeed = min( kstat_get_ui64( ksp, "ifspeed" ), ~0u );
334 entry->dwInOctets = kstat_get_ui32( ksp, "rbytes" );
335 entry->dwInNUcastPkts = kstat_get_ui32( ksp, "multircv" );
336 entry->dwInNUcastPkts += kstat_get_ui32( ksp, "brdcstrcv" );
337 entry->dwInUcastPkts = kstat_get_ui32( ksp, "ipackets" ) - entry->dwInNUcastPkts;
338 entry->dwInDiscards = kstat_get_ui32( ksp, "norcvbuf" );
339 entry->dwInErrors = kstat_get_ui32( ksp, "ierrors" );
340 entry->dwInUnknownProtos = kstat_get_ui32( ksp, "unknowns" );
341 entry->dwOutOctets = kstat_get_ui32( ksp, "obytes" );
342 entry->dwOutNUcastPkts = kstat_get_ui32( ksp, "multixmt" );
343 entry->dwOutNUcastPkts += kstat_get_ui32( ksp, "brdcstxmt" );
344 entry->dwOutUcastPkts = kstat_get_ui32( ksp, "opackets" ) - entry->dwOutNUcastPkts;
345 entry->dwOutDiscards = 0; /* FIXME */
346 entry->dwOutErrors = kstat_get_ui32( ksp, "oerrors" );
347 entry->dwOutQLen = kstat_get_ui32( ksp, "noxmtbuf" );
348 ret = NO_ERROR;
350 if (kc) kstat_close( kc );
352 #elif defined(HAVE_SYS_SYSCTL_H) && defined(NET_RT_IFLIST)
354 int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_IFLIST, if_nametoindex(name)};
355 size_t needed;
356 char *buf = NULL, *end;
357 struct if_msghdr *ifm;
358 struct if_data ifdata;
360 if(sysctl(mib, ARRAY_SIZE(mib), NULL, &needed, NULL, 0) == -1)
362 ERR ("failed to get size of iflist\n");
363 goto done;
365 buf = HeapAlloc (GetProcessHeap (), 0, needed);
366 if (!buf)
368 ret = ERROR_OUTOFMEMORY;
369 goto done;
371 if(sysctl(mib, ARRAY_SIZE(mib), buf, &needed, NULL, 0) == -1)
373 ERR ("failed to get iflist\n");
374 goto done;
376 for ( end = buf + needed; buf < end; buf += ifm->ifm_msglen)
378 ifm = (struct if_msghdr *) buf;
379 if(ifm->ifm_type == RTM_IFINFO)
381 ifdata = ifm->ifm_data;
382 entry->dwMtu = ifdata.ifi_mtu;
383 entry->dwSpeed = ifdata.ifi_baudrate;
384 entry->dwInOctets = ifdata.ifi_ibytes;
385 entry->dwInErrors = ifdata.ifi_ierrors;
386 entry->dwInDiscards = ifdata.ifi_iqdrops;
387 entry->dwInUcastPkts = ifdata.ifi_ipackets;
388 entry->dwInNUcastPkts = ifdata.ifi_imcasts;
389 entry->dwOutOctets = ifdata.ifi_obytes;
390 entry->dwOutUcastPkts = ifdata.ifi_opackets;
391 entry->dwOutErrors = ifdata.ifi_oerrors;
392 ret = NO_ERROR;
393 break;
396 done:
397 HeapFree (GetProcessHeap (), 0, buf);
399 #else
400 FIXME( "unimplemented\n" );
401 #endif
402 return ret;
406 /******************************************************************
407 * GetIcmpStatistics (IPHLPAPI.@)
409 * Get the ICMP statistics for the local computer.
411 * PARAMS
412 * stats [Out] buffer for ICMP statistics
414 * RETURNS
415 * Success: NO_ERROR
416 * Failure: error code from winerror.h
418 DWORD WINAPI GetIcmpStatistics(PMIB_ICMP stats)
420 DWORD ret = ERROR_NOT_SUPPORTED;
422 if (!stats) return ERROR_INVALID_PARAMETER;
423 memset( stats, 0, sizeof(MIB_ICMP) );
425 #ifdef __linux__
427 FILE *fp;
429 if ((fp = fopen("/proc/net/snmp", "r")))
431 static const char hdr[] = "Icmp:";
432 char buf[512], *ptr;
434 while ((ptr = fgets(buf, sizeof(buf), fp)))
436 if (strncasecmp(buf, hdr, sizeof(hdr) - 1)) continue;
437 /* last line was a header, get another */
438 if (!(ptr = fgets(buf, sizeof(buf), fp))) break;
439 if (!strncasecmp(buf, hdr, sizeof(hdr) - 1))
441 ptr += sizeof(hdr);
442 sscanf( ptr, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
443 &stats->stats.icmpInStats.dwMsgs,
444 &stats->stats.icmpInStats.dwErrors,
445 &stats->stats.icmpInStats.dwDestUnreachs,
446 &stats->stats.icmpInStats.dwTimeExcds,
447 &stats->stats.icmpInStats.dwParmProbs,
448 &stats->stats.icmpInStats.dwSrcQuenchs,
449 &stats->stats.icmpInStats.dwRedirects,
450 &stats->stats.icmpInStats.dwEchoReps,
451 &stats->stats.icmpInStats.dwTimestamps,
452 &stats->stats.icmpInStats.dwTimestampReps,
453 &stats->stats.icmpInStats.dwAddrMasks,
454 &stats->stats.icmpInStats.dwAddrMaskReps,
455 &stats->stats.icmpOutStats.dwMsgs,
456 &stats->stats.icmpOutStats.dwErrors,
457 &stats->stats.icmpOutStats.dwDestUnreachs,
458 &stats->stats.icmpOutStats.dwTimeExcds,
459 &stats->stats.icmpOutStats.dwParmProbs,
460 &stats->stats.icmpOutStats.dwSrcQuenchs,
461 &stats->stats.icmpOutStats.dwRedirects,
462 &stats->stats.icmpOutStats.dwEchoReps,
463 &stats->stats.icmpOutStats.dwTimestamps,
464 &stats->stats.icmpOutStats.dwTimestampReps,
465 &stats->stats.icmpOutStats.dwAddrMasks,
466 &stats->stats.icmpOutStats.dwAddrMaskReps );
467 break;
470 fclose(fp);
471 ret = NO_ERROR;
474 #elif defined(HAVE_LIBKSTAT)
476 static char ip[] = "ip", icmp[] = "icmp";
477 kstat_ctl_t *kc;
478 kstat_t *ksp;
480 if ((kc = kstat_open()) &&
481 (ksp = kstat_lookup( kc, ip, 0, icmp )) &&
482 kstat_read( kc, ksp, NULL ) != -1 &&
483 ksp->ks_type == KSTAT_TYPE_NAMED)
485 stats->stats.icmpInStats.dwMsgs = kstat_get_ui32( ksp, "inMsgs" );
486 stats->stats.icmpInStats.dwErrors = kstat_get_ui32( ksp, "inErrors" );
487 stats->stats.icmpInStats.dwDestUnreachs = kstat_get_ui32( ksp, "inDestUnreachs" );
488 stats->stats.icmpInStats.dwTimeExcds = kstat_get_ui32( ksp, "inTimeExcds" );
489 stats->stats.icmpInStats.dwParmProbs = kstat_get_ui32( ksp, "inParmProbs" );
490 stats->stats.icmpInStats.dwSrcQuenchs = kstat_get_ui32( ksp, "inSrcQuenchs" );
491 stats->stats.icmpInStats.dwRedirects = kstat_get_ui32( ksp, "inRedirects" );
492 stats->stats.icmpInStats.dwEchos = kstat_get_ui32( ksp, "inEchos" );
493 stats->stats.icmpInStats.dwEchoReps = kstat_get_ui32( ksp, "inEchoReps" );
494 stats->stats.icmpInStats.dwTimestamps = kstat_get_ui32( ksp, "inTimestamps" );
495 stats->stats.icmpInStats.dwTimestampReps = kstat_get_ui32( ksp, "inTimestampReps" );
496 stats->stats.icmpInStats.dwAddrMasks = kstat_get_ui32( ksp, "inAddrMasks" );
497 stats->stats.icmpInStats.dwAddrMaskReps = kstat_get_ui32( ksp, "inAddrMaskReps" );
498 stats->stats.icmpOutStats.dwMsgs = kstat_get_ui32( ksp, "outMsgs" );
499 stats->stats.icmpOutStats.dwErrors = kstat_get_ui32( ksp, "outErrors" );
500 stats->stats.icmpOutStats.dwDestUnreachs = kstat_get_ui32( ksp, "outDestUnreachs" );
501 stats->stats.icmpOutStats.dwTimeExcds = kstat_get_ui32( ksp, "outTimeExcds" );
502 stats->stats.icmpOutStats.dwParmProbs = kstat_get_ui32( ksp, "outParmProbs" );
503 stats->stats.icmpOutStats.dwSrcQuenchs = kstat_get_ui32( ksp, "outSrcQuenchs" );
504 stats->stats.icmpOutStats.dwRedirects = kstat_get_ui32( ksp, "outRedirects" );
505 stats->stats.icmpOutStats.dwEchos = kstat_get_ui32( ksp, "outEchos" );
506 stats->stats.icmpOutStats.dwEchoReps = kstat_get_ui32( ksp, "outEchoReps" );
507 stats->stats.icmpOutStats.dwTimestamps = kstat_get_ui32( ksp, "outTimestamps" );
508 stats->stats.icmpOutStats.dwTimestampReps = kstat_get_ui32( ksp, "outTimestampReps" );
509 stats->stats.icmpOutStats.dwAddrMasks = kstat_get_ui32( ksp, "outAddrMasks" );
510 stats->stats.icmpOutStats.dwAddrMaskReps = kstat_get_ui32( ksp, "outAddrMaskReps" );
511 ret = NO_ERROR;
513 if (kc) kstat_close( kc );
515 #elif defined(HAVE_SYS_SYSCTL_H) && defined(ICMPCTL_STATS) && (defined(HAVE_STRUCT_ICMPSTAT_ICPS_INHIST) || defined(HAVE_STRUCT_ICMPSTAT_ICPS_OUTHIST))
517 int mib[] = {CTL_NET, PF_INET, IPPROTO_ICMP, ICMPCTL_STATS};
518 struct icmpstat icmp_stat;
519 size_t needed = sizeof(icmp_stat);
520 int i;
522 if(sysctl(mib, ARRAY_SIZE(mib), &icmp_stat, &needed, NULL, 0) != -1)
524 #ifdef HAVE_STRUCT_ICMPSTAT_ICPS_INHIST
525 /*in stats */
526 stats->stats.icmpInStats.dwMsgs = icmp_stat.icps_badcode + icmp_stat.icps_checksum + icmp_stat.icps_tooshort + icmp_stat.icps_badlen;
527 for(i = 0; i <= ICMP_MAXTYPE; i++)
528 stats->stats.icmpInStats.dwMsgs += icmp_stat.icps_inhist[i];
530 stats->stats.icmpInStats.dwErrors = icmp_stat.icps_badcode + icmp_stat.icps_tooshort + icmp_stat.icps_checksum + icmp_stat.icps_badlen;
532 stats->stats.icmpInStats.dwDestUnreachs = icmp_stat.icps_inhist[ICMP_UNREACH];
533 stats->stats.icmpInStats.dwTimeExcds = icmp_stat.icps_inhist[ICMP_TIMXCEED];
534 stats->stats.icmpInStats.dwParmProbs = icmp_stat.icps_inhist[ICMP_PARAMPROB];
535 stats->stats.icmpInStats.dwSrcQuenchs = icmp_stat.icps_inhist[ICMP_SOURCEQUENCH];
536 stats->stats.icmpInStats.dwRedirects = icmp_stat.icps_inhist[ICMP_REDIRECT];
537 stats->stats.icmpInStats.dwEchos = icmp_stat.icps_inhist[ICMP_ECHO];
538 stats->stats.icmpInStats.dwEchoReps = icmp_stat.icps_inhist[ICMP_ECHOREPLY];
539 stats->stats.icmpInStats.dwTimestamps = icmp_stat.icps_inhist[ICMP_TSTAMP];
540 stats->stats.icmpInStats.dwTimestampReps = icmp_stat.icps_inhist[ICMP_TSTAMPREPLY];
541 stats->stats.icmpInStats.dwAddrMasks = icmp_stat.icps_inhist[ICMP_MASKREQ];
542 stats->stats.icmpInStats.dwAddrMaskReps = icmp_stat.icps_inhist[ICMP_MASKREPLY];
543 #endif
545 #ifdef HAVE_STRUCT_ICMPSTAT_ICPS_OUTHIST
546 /* out stats */
547 stats->stats.icmpOutStats.dwMsgs = icmp_stat.icps_oldshort + icmp_stat.icps_oldicmp;
548 for(i = 0; i <= ICMP_MAXTYPE; i++)
549 stats->stats.icmpOutStats.dwMsgs += icmp_stat.icps_outhist[i];
551 stats->stats.icmpOutStats.dwErrors = icmp_stat.icps_oldshort + icmp_stat.icps_oldicmp;
553 stats->stats.icmpOutStats.dwDestUnreachs = icmp_stat.icps_outhist[ICMP_UNREACH];
554 stats->stats.icmpOutStats.dwTimeExcds = icmp_stat.icps_outhist[ICMP_TIMXCEED];
555 stats->stats.icmpOutStats.dwParmProbs = icmp_stat.icps_outhist[ICMP_PARAMPROB];
556 stats->stats.icmpOutStats.dwSrcQuenchs = icmp_stat.icps_outhist[ICMP_SOURCEQUENCH];
557 stats->stats.icmpOutStats.dwRedirects = icmp_stat.icps_outhist[ICMP_REDIRECT];
558 stats->stats.icmpOutStats.dwEchos = icmp_stat.icps_outhist[ICMP_ECHO];
559 stats->stats.icmpOutStats.dwEchoReps = icmp_stat.icps_outhist[ICMP_ECHOREPLY];
560 stats->stats.icmpOutStats.dwTimestamps = icmp_stat.icps_outhist[ICMP_TSTAMP];
561 stats->stats.icmpOutStats.dwTimestampReps = icmp_stat.icps_outhist[ICMP_TSTAMPREPLY];
562 stats->stats.icmpOutStats.dwAddrMasks = icmp_stat.icps_outhist[ICMP_MASKREQ];
563 stats->stats.icmpOutStats.dwAddrMaskReps = icmp_stat.icps_outhist[ICMP_MASKREPLY];
564 #endif /* HAVE_STRUCT_ICMPSTAT_ICPS_OUTHIST */
565 ret = NO_ERROR;
568 #else /* ICMPCTL_STATS */
569 FIXME( "unimplemented\n" );
570 #endif
571 return ret;
574 /******************************************************************
575 * GetIcmpStatisticsEx (IPHLPAPI.@)
577 * Get the IPv4 and IPv6 ICMP statistics for the local computer.
579 * PARAMS
580 * stats [Out] buffer for ICMP statistics
581 * family [In] specifies whether IPv4 or IPv6 statistics are returned
583 * RETURNS
584 * Success: NO_ERROR
585 * Failure: error code from winerror.h
587 DWORD WINAPI GetIcmpStatisticsEx(PMIB_ICMP_EX stats, DWORD family)
589 DWORD ret = ERROR_NOT_SUPPORTED;
590 MIB_ICMP ipv4stats;
592 if (!stats) return ERROR_INVALID_PARAMETER;
593 if (family != WS_AF_INET && family != WS_AF_INET6) return ERROR_INVALID_PARAMETER;
594 memset( stats, 0, sizeof(MIB_ICMP_EX) );
596 if (family == WS_AF_INET6)
598 #ifdef __linux__
600 FILE *fp;
602 if ((fp = fopen("/proc/net/snmp6", "r")))
604 struct icmpstatstruct{
605 const char *name;
606 DWORD pos;
608 static const struct icmpstatstruct icmpinstatlist[] = {
609 { "Icmp6InDestUnreachs", ICMP6_DST_UNREACH },
610 { "Icmp6InPktTooBigs", ICMP6_PACKET_TOO_BIG },
611 { "Icmp6InTimeExcds", ICMP6_TIME_EXCEEDED },
612 { "Icmp6InParmProblems", ICMP6_PARAM_PROB },
613 { "Icmp6InEchos", ICMP6_ECHO_REQUEST },
614 { "Icmp6InEchoReplies", ICMP6_ECHO_REPLY },
615 { "Icmp6InGroupMembQueries", ICMP6_MEMBERSHIP_QUERY },
616 { "Icmp6InGroupMembResponses", ICMP6_MEMBERSHIP_REPORT },
617 { "Icmp6InGroupMembReductions", ICMP6_MEMBERSHIP_REDUCTION },
618 { "Icmp6InRouterSolicits", ND_ROUTER_SOLICIT },
619 { "Icmp6InRouterAdvertisements", ND_ROUTER_ADVERT },
620 { "Icmp6InNeighborSolicits", ND_NEIGHBOR_SOLICIT },
621 { "Icmp6InNeighborAdvertisements", ND_NEIGHBOR_ADVERT },
622 { "Icmp6InRedirects", ND_REDIRECT },
623 { "Icmp6InMLDv2Reports", ICMP6_V2_MEMBERSHIP_REPORT },
625 static const struct icmpstatstruct icmpoutstatlist[] = {
626 { "Icmp6OutDestUnreachs", ICMP6_DST_UNREACH },
627 { "Icmp6OutPktTooBigs", ICMP6_PACKET_TOO_BIG },
628 { "Icmp6OutTimeExcds", ICMP6_TIME_EXCEEDED },
629 { "Icmp6OutParmProblems", ICMP6_PARAM_PROB },
630 { "Icmp6OutEchos", ICMP6_ECHO_REQUEST },
631 { "Icmp6OutEchoReplies", ICMP6_ECHO_REPLY },
632 { "Icmp6OutGroupMembQueries", ICMP6_MEMBERSHIP_QUERY },
633 { "Icmp6OutGroupMembResponses", ICMP6_MEMBERSHIP_REPORT },
634 { "Icmp6OutGroupMembReductions", ICMP6_MEMBERSHIP_REDUCTION },
635 { "Icmp6OutRouterSolicits", ND_ROUTER_SOLICIT },
636 { "Icmp6OutRouterAdvertisements", ND_ROUTER_ADVERT },
637 { "Icmp6OutNeighborSolicits", ND_NEIGHBOR_SOLICIT },
638 { "Icmp6OutNeighborAdvertisements", ND_NEIGHBOR_ADVERT },
639 { "Icmp6OutRedirects", ND_REDIRECT },
640 { "Icmp6OutMLDv2Reports", ICMP6_V2_MEMBERSHIP_REPORT },
642 char buf[512], *ptr, *value;
643 DWORD res, i;
645 while ((ptr = fgets(buf, sizeof(buf), fp)))
647 if (!(value = strchr(buf, ' ')))
648 continue;
650 /* terminate the valuename */
651 ptr = value - 1;
652 *(ptr + 1) = '\0';
654 /* and strip leading spaces from value */
655 value += 1;
656 while (*value==' ') value++;
657 if ((ptr = strchr(value, '\n')))
658 *ptr='\0';
660 if (!strcasecmp(buf, "Icmp6InMsgs"))
662 if (sscanf(value, "%d", &res)) stats->icmpInStats.dwMsgs = res;
663 continue;
666 if (!strcasecmp(buf, "Icmp6InErrors"))
668 if (sscanf(value, "%d", &res)) stats->icmpInStats.dwErrors = res;
669 continue;
672 for (i = 0; i < ARRAY_SIZE(icmpinstatlist); i++)
674 if (!strcasecmp(buf, icmpinstatlist[i].name))
676 if (sscanf(value, "%d", &res))
677 stats->icmpInStats.rgdwTypeCount[icmpinstatlist[i].pos] = res;
678 break;
682 if (!strcasecmp(buf, "Icmp6OutMsgs"))
684 if (sscanf(value, "%d", &res)) stats->icmpOutStats.dwMsgs = res;
685 continue;
688 if (!strcasecmp(buf, "Icmp6OutErrors"))
690 if (sscanf(value, "%d", &res)) stats->icmpOutStats.dwErrors = res;
691 continue;
694 for (i = 0; i < ARRAY_SIZE(icmpoutstatlist); i++)
696 if (!strcasecmp(buf, icmpoutstatlist[i].name))
698 if (sscanf(value, "%d", &res))
699 stats->icmpOutStats.rgdwTypeCount[icmpoutstatlist[i].pos] = res;
700 break;
705 fclose(fp);
706 ret = NO_ERROR;
709 #else
710 FIXME( "unimplemented for IPv6\n" );
711 #endif
712 return ret;
715 ret = GetIcmpStatistics(&ipv4stats);
716 if (!ret)
718 stats->icmpInStats.dwMsgs = ipv4stats.stats.icmpInStats.dwMsgs;
719 stats->icmpInStats.dwErrors = ipv4stats.stats.icmpInStats.dwErrors;
720 stats->icmpInStats.rgdwTypeCount[ICMP4_DST_UNREACH] = ipv4stats.stats.icmpInStats.dwDestUnreachs;
721 stats->icmpInStats.rgdwTypeCount[ICMP4_SOURCE_QUENCH] = ipv4stats.stats.icmpInStats.dwSrcQuenchs;
722 stats->icmpInStats.rgdwTypeCount[ICMP4_REDIRECT] = ipv4stats.stats.icmpInStats.dwRedirects;
723 stats->icmpInStats.rgdwTypeCount[ICMP4_ECHO_REQUEST] = ipv4stats.stats.icmpInStats.dwEchos;
724 stats->icmpInStats.rgdwTypeCount[ICMP4_TIME_EXCEEDED] = ipv4stats.stats.icmpInStats.dwTimeExcds;
725 stats->icmpInStats.rgdwTypeCount[ICMP4_PARAM_PROB] = ipv4stats.stats.icmpInStats.dwParmProbs;
726 stats->icmpInStats.rgdwTypeCount[ICMP4_TIMESTAMP_REQUEST] = ipv4stats.stats.icmpInStats.dwTimestamps;
727 stats->icmpInStats.rgdwTypeCount[ICMP4_TIMESTAMP_REPLY] = ipv4stats.stats.icmpInStats.dwTimestampReps;
728 stats->icmpInStats.rgdwTypeCount[ICMP4_MASK_REQUEST] = ipv4stats.stats.icmpInStats.dwAddrMasks;
729 stats->icmpInStats.rgdwTypeCount[ICMP4_MASK_REPLY] = ipv4stats.stats.icmpInStats.dwAddrMaskReps;
731 stats->icmpOutStats.dwMsgs = ipv4stats.stats.icmpOutStats.dwMsgs;
732 stats->icmpOutStats.dwErrors = ipv4stats.stats.icmpOutStats.dwErrors;
733 stats->icmpOutStats.rgdwTypeCount[ICMP4_DST_UNREACH] = ipv4stats.stats.icmpOutStats.dwDestUnreachs;
734 stats->icmpOutStats.rgdwTypeCount[ICMP4_SOURCE_QUENCH] = ipv4stats.stats.icmpOutStats.dwSrcQuenchs;
735 stats->icmpOutStats.rgdwTypeCount[ICMP4_REDIRECT] = ipv4stats.stats.icmpOutStats.dwRedirects;
736 stats->icmpOutStats.rgdwTypeCount[ICMP4_ECHO_REQUEST] = ipv4stats.stats.icmpOutStats.dwEchos;
737 stats->icmpOutStats.rgdwTypeCount[ICMP4_TIME_EXCEEDED] = ipv4stats.stats.icmpOutStats.dwTimeExcds;
738 stats->icmpOutStats.rgdwTypeCount[ICMP4_PARAM_PROB] = ipv4stats.stats.icmpOutStats.dwParmProbs;
739 stats->icmpOutStats.rgdwTypeCount[ICMP4_TIMESTAMP_REQUEST] = ipv4stats.stats.icmpOutStats.dwTimestamps;
740 stats->icmpOutStats.rgdwTypeCount[ICMP4_TIMESTAMP_REPLY] = ipv4stats.stats.icmpOutStats.dwTimestampReps;
741 stats->icmpOutStats.rgdwTypeCount[ICMP4_MASK_REQUEST] = ipv4stats.stats.icmpOutStats.dwAddrMasks;
742 stats->icmpOutStats.rgdwTypeCount[ICMP4_MASK_REPLY] = ipv4stats.stats.icmpOutStats.dwAddrMaskReps;
744 return ret;
747 /******************************************************************
748 * GetIpStatisticsEx (IPHLPAPI.@)
750 * Get the IPv4 and IPv6 statistics for the local computer.
752 * PARAMS
753 * stats [Out] buffer for IP statistics
754 * family [In] specifies whether IPv4 or IPv6 statistics are returned
756 * RETURNS
757 * Success: NO_ERROR
758 * Failure: error code from winerror.h
760 DWORD WINAPI GetIpStatisticsEx(PMIB_IPSTATS stats, DWORD family)
762 DWORD ret = ERROR_NOT_SUPPORTED;
763 MIB_IPFORWARDTABLE *fwd_table;
765 if (!stats) return ERROR_INVALID_PARAMETER;
766 if (family != WS_AF_INET && family != WS_AF_INET6) return ERROR_INVALID_PARAMETER;
767 memset( stats, 0, sizeof(*stats) );
769 stats->dwNumIf = stats->dwNumAddr = get_interface_indices( FALSE, NULL );
770 if (!AllocateAndGetIpForwardTableFromStack( &fwd_table, FALSE, GetProcessHeap(), 0 ))
772 stats->dwNumRoutes = fwd_table->dwNumEntries;
773 HeapFree( GetProcessHeap(), 0, fwd_table );
776 if (family == WS_AF_INET6)
778 #ifdef __linux__
780 FILE *fp;
782 if ((fp = fopen("/proc/net/snmp6", "r")))
784 struct {
785 const char *name;
786 DWORD *elem;
787 } ipstatlist[] = {
788 { "Ip6InReceives", &stats->dwInReceives },
789 { "Ip6InHdrErrors", &stats->dwInHdrErrors },
790 { "Ip6InAddrErrors", &stats->dwInAddrErrors },
791 { "Ip6OutForwDatagrams", &stats->dwForwDatagrams },
792 { "Ip6InUnknownProtos", &stats->dwInUnknownProtos },
793 { "Ip6InDiscards", &stats->dwInDiscards },
794 { "Ip6InDelivers", &stats->dwInDelivers },
795 { "Ip6OutRequests", &stats->dwOutRequests },
796 { "Ip6OutDiscards", &stats->dwOutDiscards },
797 { "Ip6OutNoRoutes", &stats->dwOutNoRoutes },
798 { "Ip6ReasmTimeout", &stats->dwReasmTimeout },
799 { "Ip6ReasmReqds", &stats->dwReasmReqds },
800 { "Ip6ReasmOKs", &stats->dwReasmOks },
801 { "Ip6ReasmFails", &stats->dwReasmFails },
802 { "Ip6FragOKs", &stats->dwFragOks },
803 { "Ip6FragFails", &stats->dwFragFails },
804 { "Ip6FragCreates", &stats->dwFragCreates },
805 /* hmm, no routingDiscards, defaultTTL and forwarding? */
807 char buf[512], *ptr, *value;
808 DWORD res, i;
810 while ((ptr = fgets(buf, sizeof(buf), fp)))
812 if (!(value = strchr(buf, ' ')))
813 continue;
815 /* terminate the valuename */
816 ptr = value - 1;
817 *(ptr + 1) = '\0';
819 /* and strip leading spaces from value */
820 value += 1;
821 while (*value==' ') value++;
822 if ((ptr = strchr(value, '\n')))
823 *ptr='\0';
825 for (i = 0; i < ARRAY_SIZE(ipstatlist); i++)
826 if (!strcasecmp(buf, ipstatlist[i].name))
828 if (sscanf(value, "%d", &res)) *ipstatlist[i].elem = res;
829 continue;
832 fclose(fp);
833 ret = NO_ERROR;
836 #else
837 FIXME( "unimplemented for IPv6\n" );
838 #endif
839 return ret;
842 #ifdef __linux__
844 FILE *fp;
846 if ((fp = fopen("/proc/net/snmp", "r")))
848 static const char hdr[] = "Ip:";
849 char buf[512], *ptr;
851 while ((ptr = fgets(buf, sizeof(buf), fp)))
853 if (strncasecmp(buf, hdr, sizeof(hdr) - 1)) continue;
854 /* last line was a header, get another */
855 if (!(ptr = fgets(buf, sizeof(buf), fp))) break;
856 if (!strncasecmp(buf, hdr, sizeof(hdr) - 1))
858 ptr += sizeof(hdr);
859 sscanf( ptr, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
860 &stats->u.dwForwarding,
861 &stats->dwDefaultTTL,
862 &stats->dwInReceives,
863 &stats->dwInHdrErrors,
864 &stats->dwInAddrErrors,
865 &stats->dwForwDatagrams,
866 &stats->dwInUnknownProtos,
867 &stats->dwInDiscards,
868 &stats->dwInDelivers,
869 &stats->dwOutRequests,
870 &stats->dwOutDiscards,
871 &stats->dwOutNoRoutes,
872 &stats->dwReasmTimeout,
873 &stats->dwReasmReqds,
874 &stats->dwReasmOks,
875 &stats->dwReasmFails,
876 &stats->dwFragOks,
877 &stats->dwFragFails,
878 &stats->dwFragCreates );
879 /* hmm, no routingDiscards */
880 break;
883 fclose(fp);
884 ret = NO_ERROR;
887 #elif defined(HAVE_LIBKSTAT)
889 static char ip[] = "ip";
890 kstat_ctl_t *kc;
891 kstat_t *ksp;
893 if ((kc = kstat_open()) &&
894 (ksp = kstat_lookup( kc, ip, 0, ip )) &&
895 kstat_read( kc, ksp, NULL ) != -1 &&
896 ksp->ks_type == KSTAT_TYPE_NAMED)
898 stats->u.dwForwarding = kstat_get_ui32( ksp, "forwarding" );
899 stats->dwDefaultTTL = kstat_get_ui32( ksp, "defaultTTL" );
900 stats->dwInReceives = kstat_get_ui32( ksp, "inReceives" );
901 stats->dwInHdrErrors = kstat_get_ui32( ksp, "inHdrErrors" );
902 stats->dwInAddrErrors = kstat_get_ui32( ksp, "inAddrErrors" );
903 stats->dwForwDatagrams = kstat_get_ui32( ksp, "forwDatagrams" );
904 stats->dwInUnknownProtos = kstat_get_ui32( ksp, "inUnknownProtos" );
905 stats->dwInDiscards = kstat_get_ui32( ksp, "inDiscards" );
906 stats->dwInDelivers = kstat_get_ui32( ksp, "inDelivers" );
907 stats->dwOutRequests = kstat_get_ui32( ksp, "outRequests" );
908 stats->dwRoutingDiscards = kstat_get_ui32( ksp, "routingDiscards" );
909 stats->dwOutDiscards = kstat_get_ui32( ksp, "outDiscards" );
910 stats->dwOutNoRoutes = kstat_get_ui32( ksp, "outNoRoutes" );
911 stats->dwReasmTimeout = kstat_get_ui32( ksp, "reasmTimeout" );
912 stats->dwReasmReqds = kstat_get_ui32( ksp, "reasmReqds" );
913 stats->dwReasmOks = kstat_get_ui32( ksp, "reasmOKs" );
914 stats->dwReasmFails = kstat_get_ui32( ksp, "reasmFails" );
915 stats->dwFragOks = kstat_get_ui32( ksp, "fragOKs" );
916 stats->dwFragFails = kstat_get_ui32( ksp, "fragFails" );
917 stats->dwFragCreates = kstat_get_ui32( ksp, "fragCreates" );
918 ret = NO_ERROR;
920 if (kc) kstat_close( kc );
922 #elif defined(HAVE_SYS_SYSCTL_H) && defined(IPCTL_STATS) && (defined(HAVE_STRUCT_IPSTAT_IPS_TOTAL) || defined(HAVE_STRUCT_IP_STATS_IPS_TOTAL))
924 int mib[] = {CTL_NET, PF_INET, IPPROTO_IP, IPCTL_STATS};
925 int ip_ttl, ip_forwarding;
926 #if defined(HAVE_STRUCT_IPSTAT_IPS_TOTAL)
927 struct ipstat ip_stat;
928 #elif defined(HAVE_STRUCT_IP_STATS_IPS_TOTAL)
929 struct ip_stats ip_stat;
930 #endif
931 size_t needed;
933 needed = sizeof(ip_stat);
934 if(sysctl(mib, ARRAY_SIZE(mib), &ip_stat, &needed, NULL, 0) == -1)
936 ERR ("failed to get ipstat\n");
937 return ERROR_NOT_SUPPORTED;
940 needed = sizeof(ip_ttl);
941 if (sysctlbyname ("net.inet.ip.ttl", &ip_ttl, &needed, NULL, 0) == -1)
943 ERR ("failed to get ip Default TTL\n");
944 return ERROR_NOT_SUPPORTED;
947 needed = sizeof(ip_forwarding);
948 if (sysctlbyname ("net.inet.ip.forwarding", &ip_forwarding, &needed, NULL, 0) == -1)
950 ERR ("failed to get ip forwarding\n");
951 return ERROR_NOT_SUPPORTED;
954 stats->u.dwForwarding = ip_forwarding;
955 stats->dwDefaultTTL = ip_ttl;
956 stats->dwInDelivers = ip_stat.ips_delivered;
957 stats->dwInHdrErrors = ip_stat.ips_badhlen + ip_stat.ips_badsum + ip_stat.ips_tooshort + ip_stat.ips_badlen;
958 stats->dwInAddrErrors = ip_stat.ips_cantforward;
959 stats->dwInReceives = ip_stat.ips_total;
960 stats->dwForwDatagrams = ip_stat.ips_forward;
961 stats->dwInUnknownProtos = ip_stat.ips_noproto;
962 stats->dwInDiscards = ip_stat.ips_fragdropped;
963 stats->dwOutDiscards = ip_stat.ips_odropped;
964 stats->dwReasmOks = ip_stat.ips_reassembled;
965 stats->dwFragOks = ip_stat.ips_fragmented;
966 stats->dwFragFails = ip_stat.ips_cantfrag;
967 stats->dwReasmTimeout = ip_stat.ips_fragtimeout;
968 stats->dwOutNoRoutes = ip_stat.ips_noroute;
969 stats->dwOutRequests = ip_stat.ips_localout;
970 stats->dwReasmReqds = ip_stat.ips_fragments;
971 ret = NO_ERROR;
973 #else
974 FIXME( "unimplemented for IPv4\n" );
975 #endif
976 return ret;
979 /******************************************************************
980 * GetIpStatistics (IPHLPAPI.@)
982 * Get the IP statistics for the local computer.
984 * PARAMS
985 * stats [Out] buffer for IP statistics
987 * RETURNS
988 * Success: NO_ERROR
989 * Failure: error code from winerror.h
991 DWORD WINAPI GetIpStatistics(PMIB_IPSTATS stats)
993 return GetIpStatisticsEx(stats, WS_AF_INET);
996 /******************************************************************
997 * GetTcpStatisticsEx (IPHLPAPI.@)
999 * Get the IPv4 and IPv6 TCP statistics for the local computer.
1001 * PARAMS
1002 * stats [Out] buffer for TCP statistics
1003 * family [In] specifies whether IPv4 or IPv6 statistics are returned
1005 * RETURNS
1006 * Success: NO_ERROR
1007 * Failure: error code from winerror.h
1009 DWORD WINAPI GetTcpStatisticsEx(PMIB_TCPSTATS stats, DWORD family)
1011 DWORD ret = ERROR_NOT_SUPPORTED;
1013 if (!stats) return ERROR_INVALID_PARAMETER;
1014 if (family != WS_AF_INET && family != WS_AF_INET6) return ERROR_INVALID_PARAMETER;
1015 memset( stats, 0, sizeof(*stats) );
1017 if (family == WS_AF_INET6)
1019 FIXME( "unimplemented for IPv6\n" );
1020 return ret;
1023 #ifdef __linux__
1025 FILE *fp;
1027 if ((fp = fopen("/proc/net/snmp", "r")))
1029 static const char hdr[] = "Tcp:";
1030 MIB_TCPTABLE *tcp_table;
1031 char buf[512], *ptr;
1033 while ((ptr = fgets(buf, sizeof(buf), fp)))
1035 if (strncasecmp(buf, hdr, sizeof(hdr) - 1)) continue;
1036 /* last line was a header, get another */
1037 if (!(ptr = fgets(buf, sizeof(buf), fp))) break;
1038 if (!strncasecmp(buf, hdr, sizeof(hdr) - 1))
1040 ptr += sizeof(hdr);
1041 sscanf( ptr, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u",
1042 &stats->u.dwRtoAlgorithm,
1043 &stats->dwRtoMin,
1044 &stats->dwRtoMax,
1045 &stats->dwMaxConn,
1046 &stats->dwActiveOpens,
1047 &stats->dwPassiveOpens,
1048 &stats->dwAttemptFails,
1049 &stats->dwEstabResets,
1050 &stats->dwCurrEstab,
1051 &stats->dwInSegs,
1052 &stats->dwOutSegs,
1053 &stats->dwRetransSegs,
1054 &stats->dwInErrs,
1055 &stats->dwOutRsts );
1056 break;
1059 if (!AllocateAndGetTcpTableFromStack( &tcp_table, FALSE, GetProcessHeap(), 0 ))
1061 stats->dwNumConns = tcp_table->dwNumEntries;
1062 HeapFree( GetProcessHeap(), 0, tcp_table );
1064 fclose(fp);
1065 ret = NO_ERROR;
1068 #elif defined(HAVE_LIBKSTAT)
1070 static char tcp[] = "tcp";
1071 kstat_ctl_t *kc;
1072 kstat_t *ksp;
1074 if ((kc = kstat_open()) &&
1075 (ksp = kstat_lookup( kc, tcp, 0, tcp )) &&
1076 kstat_read( kc, ksp, NULL ) != -1 &&
1077 ksp->ks_type == KSTAT_TYPE_NAMED)
1079 stats->u.dwRtoAlgorithm = kstat_get_ui32( ksp, "rtoAlgorithm" );
1080 stats->dwRtoMin = kstat_get_ui32( ksp, "rtoMin" );
1081 stats->dwRtoMax = kstat_get_ui32( ksp, "rtoMax" );
1082 stats->dwMaxConn = kstat_get_ui32( ksp, "maxConn" );
1083 stats->dwActiveOpens = kstat_get_ui32( ksp, "activeOpens" );
1084 stats->dwPassiveOpens = kstat_get_ui32( ksp, "passiveOpens" );
1085 stats->dwAttemptFails = kstat_get_ui32( ksp, "attemptFails" );
1086 stats->dwEstabResets = kstat_get_ui32( ksp, "estabResets" );
1087 stats->dwCurrEstab = kstat_get_ui32( ksp, "currEstab" );
1088 stats->dwInSegs = kstat_get_ui32( ksp, "inSegs" );
1089 stats->dwOutSegs = kstat_get_ui32( ksp, "outSegs" );
1090 stats->dwRetransSegs = kstat_get_ui32( ksp, "retransSegs" );
1091 stats->dwInErrs = kstat_get_ui32( ksp, "inErrs" );
1092 stats->dwOutRsts = kstat_get_ui32( ksp, "outRsts" );
1093 stats->dwNumConns = kstat_get_ui32( ksp, "connTableSize" );
1094 ret = NO_ERROR;
1096 if (kc) kstat_close( kc );
1098 #elif defined(HAVE_SYS_SYSCTL_H) && defined(TCPCTL_STATS) && (defined(HAVE_STRUCT_TCPSTAT_TCPS_CONNATTEMPT) || defined(HAVE_STRUCT_TCP_STATS_TCPS_CONNATTEMPT))
1100 #ifndef TCPTV_MIN /* got removed in Mac OS X for some reason */
1101 #define TCPTV_MIN 2
1102 #define TCPTV_REXMTMAX 128
1103 #endif
1104 int mib[] = {CTL_NET, PF_INET, IPPROTO_TCP, TCPCTL_STATS};
1105 #define hz 1000
1106 #if defined(HAVE_STRUCT_TCPSTAT_TCPS_CONNATTEMPT)
1107 struct tcpstat tcp_stat;
1108 #elif defined(HAVE_STRUCT_TCP_STATS_TCPS_CONNATTEMPT)
1109 struct tcp_stats tcp_stat;
1110 #endif
1111 size_t needed = sizeof(tcp_stat);
1113 if(sysctl(mib, ARRAY_SIZE(mib), &tcp_stat, &needed, NULL, 0) != -1)
1115 stats->u.RtoAlgorithm = MIB_TCP_RTO_VANJ;
1116 stats->dwRtoMin = TCPTV_MIN;
1117 stats->dwRtoMax = TCPTV_REXMTMAX;
1118 stats->dwMaxConn = -1;
1119 stats->dwActiveOpens = tcp_stat.tcps_connattempt;
1120 stats->dwPassiveOpens = tcp_stat.tcps_accepts;
1121 stats->dwAttemptFails = tcp_stat.tcps_conndrops;
1122 stats->dwEstabResets = tcp_stat.tcps_drops;
1123 stats->dwCurrEstab = 0;
1124 stats->dwInSegs = tcp_stat.tcps_rcvtotal;
1125 stats->dwOutSegs = tcp_stat.tcps_sndtotal - tcp_stat.tcps_sndrexmitpack;
1126 stats->dwRetransSegs = tcp_stat.tcps_sndrexmitpack;
1127 stats->dwInErrs = tcp_stat.tcps_rcvbadsum + tcp_stat.tcps_rcvbadoff + tcp_stat.tcps_rcvmemdrop + tcp_stat.tcps_rcvshort;
1128 stats->dwOutRsts = tcp_stat.tcps_sndctrl - tcp_stat.tcps_closed;
1129 stats->dwNumConns = tcp_stat.tcps_connects;
1130 ret = NO_ERROR;
1132 else ERR ("failed to get tcpstat\n");
1134 #else
1135 FIXME( "unimplemented\n" );
1136 #endif
1137 return ret;
1140 /******************************************************************
1141 * GetTcpStatistics (IPHLPAPI.@)
1143 * Get the TCP statistics for the local computer.
1145 * PARAMS
1146 * stats [Out] buffer for TCP statistics
1148 * RETURNS
1149 * Success: NO_ERROR
1150 * Failure: error code from winerror.h
1152 DWORD WINAPI GetTcpStatistics(PMIB_TCPSTATS stats)
1154 return GetTcpStatisticsEx(stats, WS_AF_INET);
1157 /******************************************************************
1158 * GetUdpStatistics (IPHLPAPI.@)
1160 * Get the IPv4 and IPv6 UDP statistics for the local computer.
1162 * PARAMS
1163 * stats [Out] buffer for UDP statistics
1164 * family [In] specifies whether IPv4 or IPv6 statistics are returned
1166 * RETURNS
1167 * Success: NO_ERROR
1168 * Failure: error code from winerror.h
1170 DWORD WINAPI GetUdpStatisticsEx(PMIB_UDPSTATS stats, DWORD family)
1172 DWORD ret = ERROR_NOT_SUPPORTED;
1174 if (!stats) return ERROR_INVALID_PARAMETER;
1175 if (family != WS_AF_INET && family != WS_AF_INET6) return ERROR_INVALID_PARAMETER;
1176 memset( stats, 0, sizeof(*stats) );
1178 stats->dwNumAddrs = get_interface_indices( FALSE, NULL );
1180 if (family == WS_AF_INET6)
1182 #ifdef __linux__
1184 FILE *fp;
1186 if ((fp = fopen("/proc/net/snmp6", "r")))
1188 struct {
1189 const char *name;
1190 DWORD *elem;
1191 } udpstatlist[] = {
1192 { "Udp6InDatagrams", &stats->dwInDatagrams },
1193 { "Udp6NoPorts", &stats->dwNoPorts },
1194 { "Udp6InErrors", &stats->dwInErrors },
1195 { "Udp6OutDatagrams", &stats->dwOutDatagrams },
1197 char buf[512], *ptr, *value;
1198 DWORD res, i;
1200 while ((ptr = fgets(buf, sizeof(buf), fp)))
1202 if (!(value = strchr(buf, ' ')))
1203 continue;
1205 /* terminate the valuename */
1206 ptr = value - 1;
1207 *(ptr + 1) = '\0';
1209 /* and strip leading spaces from value */
1210 value += 1;
1211 while (*value==' ') value++;
1212 if ((ptr = strchr(value, '\n')))
1213 *ptr='\0';
1215 for (i = 0; i < ARRAY_SIZE(udpstatlist); i++)
1216 if (!strcasecmp(buf, udpstatlist[i].name))
1218 if (sscanf(value, "%d", &res)) *udpstatlist[i].elem = res;
1219 continue;
1222 fclose(fp);
1223 ret = NO_ERROR;
1226 #else
1227 FIXME( "unimplemented for IPv6\n" );
1228 #endif
1229 return ret;
1232 #ifdef __linux__
1234 FILE *fp;
1236 if ((fp = fopen("/proc/net/snmp", "r")))
1238 static const char hdr[] = "Udp:";
1239 char buf[512], *ptr;
1241 while ((ptr = fgets(buf, sizeof(buf), fp)))
1243 if (strncasecmp(buf, hdr, sizeof(hdr) - 1)) continue;
1244 /* last line was a header, get another */
1245 if (!(ptr = fgets(buf, sizeof(buf), fp))) break;
1246 if (!strncasecmp(buf, hdr, sizeof(hdr) - 1))
1248 ptr += sizeof(hdr);
1249 sscanf( ptr, "%u %u %u %u %u",
1250 &stats->dwInDatagrams, &stats->dwNoPorts,
1251 &stats->dwInErrors, &stats->dwOutDatagrams, &stats->dwNumAddrs );
1252 break;
1255 fclose(fp);
1256 ret = NO_ERROR;
1259 #elif defined(HAVE_LIBKSTAT)
1261 static char udp[] = "udp";
1262 kstat_ctl_t *kc;
1263 kstat_t *ksp;
1264 MIB_UDPTABLE *udp_table;
1266 if ((kc = kstat_open()) &&
1267 (ksp = kstat_lookup( kc, udp, 0, udp )) &&
1268 kstat_read( kc, ksp, NULL ) != -1 &&
1269 ksp->ks_type == KSTAT_TYPE_NAMED)
1271 stats->dwInDatagrams = kstat_get_ui32( ksp, "inDatagrams" );
1272 stats->dwNoPorts = 0; /* FIXME */
1273 stats->dwInErrors = kstat_get_ui32( ksp, "inErrors" );
1274 stats->dwOutDatagrams = kstat_get_ui32( ksp, "outDatagrams" );
1275 if (!AllocateAndGetUdpTableFromStack( &udp_table, FALSE, GetProcessHeap(), 0 ))
1277 stats->dwNumAddrs = udp_table->dwNumEntries;
1278 HeapFree( GetProcessHeap(), 0, udp_table );
1280 ret = NO_ERROR;
1282 if (kc) kstat_close( kc );
1284 #elif defined(HAVE_SYS_SYSCTL_H) && defined(UDPCTL_STATS) && defined(HAVE_STRUCT_UDPSTAT_UDPS_IPACKETS)
1286 int mib[] = {CTL_NET, PF_INET, IPPROTO_UDP, UDPCTL_STATS};
1287 struct udpstat udp_stat;
1288 MIB_UDPTABLE *udp_table;
1289 size_t needed = sizeof(udp_stat);
1291 if(sysctl(mib, ARRAY_SIZE(mib), &udp_stat, &needed, NULL, 0) != -1)
1293 stats->dwInDatagrams = udp_stat.udps_ipackets;
1294 stats->dwOutDatagrams = udp_stat.udps_opackets;
1295 stats->dwNoPorts = udp_stat.udps_noport;
1296 stats->dwInErrors = udp_stat.udps_hdrops + udp_stat.udps_badsum + udp_stat.udps_fullsock + udp_stat.udps_badlen;
1297 if (!AllocateAndGetUdpTableFromStack( &udp_table, FALSE, GetProcessHeap(), 0 ))
1299 stats->dwNumAddrs = udp_table->dwNumEntries;
1300 HeapFree( GetProcessHeap(), 0, udp_table );
1302 ret = NO_ERROR;
1304 else ERR ("failed to get udpstat\n");
1306 #else
1307 FIXME( "unimplemented for IPv4\n" );
1308 #endif
1309 return ret;
1312 /******************************************************************
1313 * GetUdpStatistics (IPHLPAPI.@)
1315 * Get the UDP statistics for the local computer.
1317 * PARAMS
1318 * stats [Out] buffer for UDP statistics
1320 * RETURNS
1321 * Success: NO_ERROR
1322 * Failure: error code from winerror.h
1324 DWORD WINAPI GetUdpStatistics(PMIB_UDPSTATS stats)
1326 return GetUdpStatisticsEx(stats, WS_AF_INET);
1329 static MIB_IPFORWARDTABLE *append_ipforward_row( HANDLE heap, DWORD flags, MIB_IPFORWARDTABLE *table,
1330 DWORD *count, const MIB_IPFORWARDROW *row )
1332 if (table->dwNumEntries >= *count)
1334 MIB_IPFORWARDTABLE *new_table;
1335 DWORD new_count = table->dwNumEntries * 2;
1337 if (!(new_table = HeapReAlloc( heap, flags, table,
1338 FIELD_OFFSET(MIB_IPFORWARDTABLE, table[new_count] ))))
1340 HeapFree( heap, 0, table );
1341 return NULL;
1343 *count = new_count;
1344 table = new_table;
1346 memcpy( &table->table[table->dwNumEntries++], row, sizeof(*row) );
1347 return table;
1350 static int compare_ipforward_rows(const void *a, const void *b)
1352 const MIB_IPFORWARDROW *rowA = a;
1353 const MIB_IPFORWARDROW *rowB = b;
1354 int ret;
1356 if ((ret = rowA->dwForwardDest - rowB->dwForwardDest) != 0) return ret;
1357 if ((ret = rowA->u2.dwForwardProto - rowB->u2.dwForwardProto) != 0) return ret;
1358 if ((ret = rowA->dwForwardPolicy - rowB->dwForwardPolicy) != 0) return ret;
1359 return rowA->dwForwardNextHop - rowB->dwForwardNextHop;
1362 /******************************************************************
1363 * AllocateAndGetIpForwardTableFromStack (IPHLPAPI.@)
1365 * Get the route table.
1366 * Like GetIpForwardTable(), but allocate the returned table from heap.
1368 * PARAMS
1369 * ppIpForwardTable [Out] pointer into which the MIB_IPFORWARDTABLE is
1370 * allocated and returned.
1371 * bOrder [In] whether to sort the table
1372 * heap [In] heap from which the table is allocated
1373 * flags [In] flags to HeapAlloc
1375 * RETURNS
1376 * ERROR_INVALID_PARAMETER if ppIfTable is NULL, other error codes
1377 * on failure, NO_ERROR on success.
1379 DWORD WINAPI AllocateAndGetIpForwardTableFromStack(PMIB_IPFORWARDTABLE *ppIpForwardTable, BOOL bOrder,
1380 HANDLE heap, DWORD flags)
1382 MIB_IPFORWARDTABLE *table;
1383 MIB_IPFORWARDROW row;
1384 DWORD ret = NO_ERROR, count = 16;
1386 TRACE("table %p, bOrder %d, heap %p, flags 0x%08x\n", ppIpForwardTable, bOrder, heap, flags);
1388 if (!ppIpForwardTable) return ERROR_INVALID_PARAMETER;
1390 if (!(table = HeapAlloc( heap, flags, FIELD_OFFSET(MIB_IPFORWARDTABLE, table[count] ))))
1391 return ERROR_OUTOFMEMORY;
1393 table->dwNumEntries = 0;
1395 #ifdef __linux__
1397 FILE *fp;
1399 if ((fp = fopen("/proc/net/route", "r")))
1401 char buf[512], *ptr;
1402 DWORD flags;
1404 /* skip header line */
1405 ptr = fgets(buf, sizeof(buf), fp);
1406 while ((ptr = fgets(buf, sizeof(buf), fp)))
1408 memset( &row, 0, sizeof(row) );
1410 while (!isspace(*ptr)) ptr++;
1411 *ptr++ = 0;
1412 if (getInterfaceIndexByName(buf, &row.dwForwardIfIndex) != NO_ERROR)
1413 continue;
1415 row.dwForwardDest = strtoul(ptr, &ptr, 16);
1416 row.dwForwardNextHop = strtoul(ptr + 1, &ptr, 16);
1417 flags = strtoul(ptr + 1, &ptr, 16);
1419 if (!(flags & RTF_UP)) row.u1.ForwardType = MIB_IPROUTE_TYPE_INVALID;
1420 else if (flags & RTF_GATEWAY) row.u1.ForwardType = MIB_IPROUTE_TYPE_INDIRECT;
1421 else row.u1.ForwardType = MIB_IPROUTE_TYPE_DIRECT;
1423 strtoul(ptr + 1, &ptr, 16); /* refcount, skip */
1424 strtoul(ptr + 1, &ptr, 16); /* use, skip */
1425 row.dwForwardMetric1 = strtoul(ptr + 1, &ptr, 16);
1426 row.dwForwardMask = strtoul(ptr + 1, &ptr, 16);
1427 /* FIXME: other protos might be appropriate, e.g. the default
1428 * route is typically set with MIB_IPPROTO_NETMGMT instead */
1429 row.u2.ForwardProto = MIB_IPPROTO_LOCAL;
1431 if (!(table = append_ipforward_row( heap, flags, table, &count, &row )))
1432 break;
1434 fclose(fp);
1436 else ret = ERROR_NOT_SUPPORTED;
1438 #elif defined(HAVE_SYS_TIHDR_H) && defined(T_OPTMGMT_ACK)
1440 void *data;
1441 int fd, len, namelen;
1442 mib2_ipRouteEntry_t *entry;
1443 char name[64];
1445 if ((fd = open_streams_mib( NULL )) != -1)
1447 if ((data = read_mib_entry( fd, MIB2_IP, MIB2_IP_ROUTE, &len )))
1449 for (entry = data; (char *)(entry + 1) <= (char *)data + len; entry++)
1451 row.dwForwardDest = entry->ipRouteDest;
1452 row.dwForwardMask = entry->ipRouteMask;
1453 row.dwForwardPolicy = 0;
1454 row.dwForwardNextHop = entry->ipRouteNextHop;
1455 row.u1.dwForwardType = entry->ipRouteType;
1456 row.u2.dwForwardProto = entry->ipRouteProto;
1457 row.dwForwardAge = entry->ipRouteAge;
1458 row.dwForwardNextHopAS = 0;
1459 row.dwForwardMetric1 = entry->ipRouteMetric1;
1460 row.dwForwardMetric2 = entry->ipRouteMetric2;
1461 row.dwForwardMetric3 = entry->ipRouteMetric3;
1462 row.dwForwardMetric4 = entry->ipRouteMetric4;
1463 row.dwForwardMetric5 = entry->ipRouteMetric5;
1464 namelen = min( sizeof(name) - 1, entry->ipRouteIfIndex.o_length );
1465 memcpy( name, entry->ipRouteIfIndex.o_bytes, namelen );
1466 name[namelen] = 0;
1467 getInterfaceIndexByName( name, &row.dwForwardIfIndex );
1468 if (!(table = append_ipforward_row( heap, flags, table, &count, &row ))) break;
1470 HeapFree( GetProcessHeap(), 0, data );
1472 close( fd );
1474 else ret = ERROR_NOT_SUPPORTED;
1476 #elif defined(HAVE_SYS_SYSCTL_H) && defined(NET_RT_DUMP)
1478 int mib[6] = {CTL_NET, PF_ROUTE, 0, PF_INET, NET_RT_DUMP, 0};
1479 size_t needed;
1480 char *buf = NULL, *lim, *next, *addrPtr;
1481 struct rt_msghdr *rtm;
1483 if (sysctl (mib, 6, NULL, &needed, NULL, 0) < 0)
1485 ERR ("sysctl 1 failed!\n");
1486 ret = ERROR_NOT_SUPPORTED;
1487 goto done;
1490 buf = HeapAlloc (GetProcessHeap (), 0, needed);
1491 if (!buf)
1493 ret = ERROR_OUTOFMEMORY;
1494 goto done;
1497 if (sysctl (mib, 6, buf, &needed, NULL, 0) < 0)
1499 ret = ERROR_NOT_SUPPORTED;
1500 goto done;
1503 lim = buf + needed;
1504 for (next = buf; next < lim; next += rtm->rtm_msglen)
1506 int i;
1508 rtm = (struct rt_msghdr *)next;
1510 if (rtm->rtm_type != RTM_GET)
1512 WARN ("Got unexpected message type 0x%x!\n",
1513 rtm->rtm_type);
1514 continue;
1517 /* Ignore gateway routes which are multicast */
1518 if ((rtm->rtm_flags & RTF_GATEWAY) && (rtm->rtm_flags & RTF_MULTICAST))
1519 continue;
1521 memset( &row, 0, sizeof(row) );
1522 row.dwForwardIfIndex = rtm->rtm_index;
1523 row.u1.ForwardType = (rtm->rtm_flags & RTF_GATEWAY) ? MIB_IPROUTE_TYPE_INDIRECT : MIB_IPROUTE_TYPE_DIRECT;
1524 row.dwForwardMetric1 = rtm->rtm_rmx.rmx_hopcount;
1525 row.u2.ForwardProto = MIB_IPPROTO_LOCAL;
1527 addrPtr = (char *)(rtm + 1);
1529 for (i = 1; i; i <<= 1)
1531 struct sockaddr *sa;
1532 DWORD addr;
1534 if (!(i & rtm->rtm_addrs))
1535 continue;
1537 sa = (struct sockaddr *)addrPtr;
1538 ADVANCE (addrPtr, sa);
1540 /* default routes are encoded by length-zero sockaddr */
1541 if (sa->sa_len == 0) {
1542 addr = 0;
1543 }else {
1544 switch(sa->sa_family) {
1545 case AF_INET: {
1546 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
1547 addr = sin->sin_addr.s_addr;
1548 break;
1550 #ifdef AF_LINK
1551 case AF_LINK:
1552 if(i == RTA_GATEWAY && row.u1.ForwardType == MIB_IPROUTE_TYPE_DIRECT) {
1553 /* For direct route we may simply use dest addr as next hop */
1554 C_ASSERT(RTA_DST < RTA_GATEWAY);
1555 addr = row.dwForwardDest;
1556 break;
1558 /* fallthrough */
1559 #endif
1560 default:
1561 WARN ("Received unsupported sockaddr family 0x%x\n", sa->sa_family);
1562 addr = 0;
1566 switch (i)
1568 case RTA_DST: row.dwForwardDest = addr; break;
1569 case RTA_GATEWAY: row.dwForwardNextHop = addr; break;
1570 case RTA_NETMASK: row.dwForwardMask = addr; break;
1571 default:
1572 WARN ("Unexpected address type 0x%x\n", i);
1576 if (!(table = append_ipforward_row( heap, flags, table, &count, &row )))
1577 break;
1579 done:
1580 HeapFree( GetProcessHeap (), 0, buf );
1582 #else
1583 FIXME( "not implemented\n" );
1584 ret = ERROR_NOT_SUPPORTED;
1585 #endif
1587 if (!table) return ERROR_OUTOFMEMORY;
1588 if (!ret)
1590 if (bOrder && table->dwNumEntries)
1591 qsort( table->table, table->dwNumEntries, sizeof(row), compare_ipforward_rows );
1592 *ppIpForwardTable = table;
1594 else HeapFree( heap, flags, table );
1595 TRACE( "returning ret %u table %p\n", ret, table );
1596 return ret;
1599 static MIB_IPNETTABLE *append_ipnet_row( HANDLE heap, DWORD flags, MIB_IPNETTABLE *table,
1600 DWORD *count, const MIB_IPNETROW *row )
1602 if (table->dwNumEntries >= *count)
1604 MIB_IPNETTABLE *new_table;
1605 DWORD new_count = table->dwNumEntries * 2;
1607 if (!(new_table = HeapReAlloc( heap, flags, table,
1608 FIELD_OFFSET(MIB_IPNETTABLE, table[new_count] ))))
1610 HeapFree( heap, 0, table );
1611 return NULL;
1613 *count = new_count;
1614 table = new_table;
1616 memcpy( &table->table[table->dwNumEntries++], row, sizeof(*row) );
1617 return table;
1620 static int compare_ipnet_rows(const void *a, const void *b)
1622 const MIB_IPNETROW *rowA = a;
1623 const MIB_IPNETROW *rowB = b;
1625 return ntohl(rowA->dwAddr) - ntohl(rowB->dwAddr);
1629 /******************************************************************
1630 * AllocateAndGetIpNetTableFromStack (IPHLPAPI.@)
1632 * Get the IP-to-physical address mapping table.
1633 * Like GetIpNetTable(), but allocate the returned table from heap.
1635 * PARAMS
1636 * ppIpNetTable [Out] pointer into which the MIB_IPNETTABLE is
1637 * allocated and returned.
1638 * bOrder [In] whether to sort the table
1639 * heap [In] heap from which the table is allocated
1640 * flags [In] flags to HeapAlloc
1642 * RETURNS
1643 * ERROR_INVALID_PARAMETER if ppIpNetTable is NULL, other error codes
1644 * on failure, NO_ERROR on success.
1646 DWORD WINAPI AllocateAndGetIpNetTableFromStack(PMIB_IPNETTABLE *ppIpNetTable, BOOL bOrder,
1647 HANDLE heap, DWORD flags)
1649 MIB_IPNETTABLE *table;
1650 MIB_IPNETROW row;
1651 DWORD ret = NO_ERROR, count = 16;
1653 TRACE("table %p, bOrder %d, heap %p, flags 0x%08x\n", ppIpNetTable, bOrder, heap, flags);
1655 if (!ppIpNetTable) return ERROR_INVALID_PARAMETER;
1657 if (!(table = HeapAlloc( heap, flags, FIELD_OFFSET(MIB_IPNETTABLE, table[count] ))))
1658 return ERROR_OUTOFMEMORY;
1660 table->dwNumEntries = 0;
1662 #ifdef __linux__
1664 FILE *fp;
1666 if ((fp = fopen("/proc/net/arp", "r")))
1668 char buf[512], *ptr;
1669 DWORD flags;
1671 /* skip header line */
1672 ptr = fgets(buf, sizeof(buf), fp);
1673 while ((ptr = fgets(buf, sizeof(buf), fp)))
1675 memset( &row, 0, sizeof(row) );
1677 row.dwAddr = inet_addr(ptr);
1678 while (*ptr && !isspace(*ptr)) ptr++;
1679 strtoul(ptr + 1, &ptr, 16); /* hw type (skip) */
1680 flags = strtoul(ptr + 1, &ptr, 16);
1682 #ifdef ATF_COM
1683 if (flags & ATF_COM) row.u.Type = MIB_IPNET_TYPE_DYNAMIC;
1684 else
1685 #endif
1686 #ifdef ATF_PERM
1687 if (flags & ATF_PERM) row.u.Type = MIB_IPNET_TYPE_STATIC;
1688 else
1689 #endif
1690 row.u.Type = MIB_IPNET_TYPE_OTHER;
1692 while (*ptr && isspace(*ptr)) ptr++;
1693 while (*ptr && !isspace(*ptr))
1695 row.bPhysAddr[row.dwPhysAddrLen++] = strtoul(ptr, &ptr, 16);
1696 if (*ptr) ptr++;
1698 while (*ptr && isspace(*ptr)) ptr++;
1699 while (*ptr && !isspace(*ptr)) ptr++; /* mask (skip) */
1700 while (*ptr && isspace(*ptr)) ptr++;
1701 getInterfaceIndexByName(ptr, &row.dwIndex);
1703 if (!(table = append_ipnet_row( heap, flags, table, &count, &row )))
1704 break;
1706 fclose(fp);
1708 else ret = ERROR_NOT_SUPPORTED;
1710 #elif defined(HAVE_SYS_TIHDR_H) && defined(T_OPTMGMT_ACK)
1712 void *data;
1713 int fd, len, namelen;
1714 mib2_ipNetToMediaEntry_t *entry;
1715 char name[64];
1717 if ((fd = open_streams_mib( NULL )) != -1)
1719 if ((data = read_mib_entry( fd, MIB2_IP, MIB2_IP_MEDIA, &len )))
1721 for (entry = data; (char *)(entry + 1) <= (char *)data + len; entry++)
1723 row.dwPhysAddrLen = min( entry->ipNetToMediaPhysAddress.o_length, MAXLEN_PHYSADDR );
1724 memcpy( row.bPhysAddr, entry->ipNetToMediaPhysAddress.o_bytes, row.dwPhysAddrLen );
1725 row.dwAddr = entry->ipNetToMediaNetAddress;
1726 row.u.Type = entry->ipNetToMediaType;
1727 namelen = min( sizeof(name) - 1, entry->ipNetToMediaIfIndex.o_length );
1728 memcpy( name, entry->ipNetToMediaIfIndex.o_bytes, namelen );
1729 name[namelen] = 0;
1730 getInterfaceIndexByName( name, &row.dwIndex );
1731 if (!(table = append_ipnet_row( heap, flags, table, &count, &row ))) break;
1733 HeapFree( GetProcessHeap(), 0, data );
1735 close( fd );
1737 else ret = ERROR_NOT_SUPPORTED;
1739 #elif defined(HAVE_SYS_SYSCTL_H) && defined(NET_RT_DUMP)
1741 int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_LLINFO};
1742 size_t needed;
1743 char *buf = NULL, *lim, *next;
1744 struct rt_msghdr *rtm;
1745 struct sockaddr_inarp *sinarp;
1746 struct sockaddr_dl *sdl;
1748 if (sysctl (mib, ARRAY_SIZE(mib), NULL, &needed, NULL, 0) == -1)
1750 ERR ("failed to get arp table\n");
1751 ret = ERROR_NOT_SUPPORTED;
1752 goto done;
1755 buf = HeapAlloc (GetProcessHeap (), 0, needed);
1756 if (!buf)
1758 ret = ERROR_OUTOFMEMORY;
1759 goto done;
1762 if (sysctl (mib, ARRAY_SIZE(mib), buf, &needed, NULL, 0) == -1)
1764 ret = ERROR_NOT_SUPPORTED;
1765 goto done;
1768 lim = buf + needed;
1769 next = buf;
1770 while(next < lim)
1772 rtm = (struct rt_msghdr *)next;
1773 sinarp=(struct sockaddr_inarp *)(rtm + 1);
1774 sdl = (struct sockaddr_dl *)((char *)sinarp + ROUNDUP(sinarp->sin_len));
1775 if(sdl->sdl_alen) /* arp entry */
1777 memset( &row, 0, sizeof(row) );
1778 row.dwAddr = sinarp->sin_addr.s_addr;
1779 row.dwIndex = sdl->sdl_index;
1780 row.dwPhysAddrLen = min( 8, sdl->sdl_alen );
1781 memcpy( row.bPhysAddr, &sdl->sdl_data[sdl->sdl_nlen], row.dwPhysAddrLen );
1782 if(rtm->rtm_rmx.rmx_expire == 0) row.u.Type = MIB_IPNET_TYPE_STATIC;
1783 else if(sinarp->sin_other & SIN_PROXY) row.u.Type = MIB_IPNET_TYPE_OTHER;
1784 else if(rtm->rtm_rmx.rmx_expire != 0) row.u.Type = MIB_IPNET_TYPE_DYNAMIC;
1785 else row.u.Type = MIB_IPNET_TYPE_INVALID;
1787 if (!(table = append_ipnet_row( heap, flags, table, &count, &row )))
1788 break;
1790 next += rtm->rtm_msglen;
1792 done:
1793 HeapFree( GetProcessHeap (), 0, buf );
1795 #else
1796 FIXME( "not implemented\n" );
1797 ret = ERROR_NOT_SUPPORTED;
1798 #endif
1800 if (!table) return ERROR_OUTOFMEMORY;
1801 if (!ret)
1803 if (bOrder && table->dwNumEntries)
1804 qsort( table->table, table->dwNumEntries, sizeof(row), compare_ipnet_rows );
1805 *ppIpNetTable = table;
1807 else HeapFree( heap, flags, table );
1808 TRACE( "returning ret %u table %p\n", ret, table );
1809 return ret;
1812 static DWORD get_tcp_table_sizes( TCP_TABLE_CLASS class, DWORD row_count, DWORD *row_size )
1814 DWORD table_size;
1816 switch (class)
1818 case TCP_TABLE_BASIC_LISTENER:
1819 case TCP_TABLE_BASIC_CONNECTIONS:
1820 case TCP_TABLE_BASIC_ALL:
1822 table_size = FIELD_OFFSET(MIB_TCPTABLE, table[row_count]);
1823 if (row_size) *row_size = sizeof(MIB_TCPROW);
1824 break;
1826 case TCP_TABLE_OWNER_PID_LISTENER:
1827 case TCP_TABLE_OWNER_PID_CONNECTIONS:
1828 case TCP_TABLE_OWNER_PID_ALL:
1830 table_size = FIELD_OFFSET(MIB_TCPTABLE_OWNER_PID, table[row_count]);
1831 if (row_size) *row_size = sizeof(MIB_TCPROW_OWNER_PID);
1832 break;
1834 case TCP_TABLE_OWNER_MODULE_LISTENER:
1835 case TCP_TABLE_OWNER_MODULE_CONNECTIONS:
1836 case TCP_TABLE_OWNER_MODULE_ALL:
1838 table_size = FIELD_OFFSET(MIB_TCPTABLE_OWNER_MODULE, table[row_count]);
1839 if (row_size) *row_size = sizeof(MIB_TCPROW_OWNER_MODULE);
1840 break;
1842 default:
1843 ERR("unhandled class %u\n", class);
1844 return 0;
1846 return table_size;
1849 static MIB_TCPTABLE *append_tcp_row( TCP_TABLE_CLASS class, HANDLE heap, DWORD flags,
1850 MIB_TCPTABLE *table, DWORD *count,
1851 const MIB_TCPROW_OWNER_MODULE *row, DWORD row_size )
1853 if (table->dwNumEntries >= *count)
1855 MIB_TCPTABLE *new_table;
1856 DWORD new_count = table->dwNumEntries * 2, new_table_size;
1858 new_table_size = get_tcp_table_sizes( class, new_count, NULL );
1859 if (!(new_table = HeapReAlloc( heap, flags, table, new_table_size )))
1861 HeapFree( heap, 0, table );
1862 return NULL;
1864 *count = new_count;
1865 table = new_table;
1867 memcpy( (char *)table->table + (table->dwNumEntries * row_size), row, row_size );
1868 table->dwNumEntries++;
1869 return table;
1873 /* Why not a lookup table? Because the TCPS_* constants are different
1874 on different platforms */
1875 static inline MIB_TCP_STATE TCPStateToMIBState (int state)
1877 switch (state)
1879 case TCPS_ESTABLISHED: return MIB_TCP_STATE_ESTAB;
1880 case TCPS_SYN_SENT: return MIB_TCP_STATE_SYN_SENT;
1881 case TCPS_SYN_RECEIVED: return MIB_TCP_STATE_SYN_RCVD;
1882 case TCPS_FIN_WAIT_1: return MIB_TCP_STATE_FIN_WAIT1;
1883 case TCPS_FIN_WAIT_2: return MIB_TCP_STATE_FIN_WAIT2;
1884 case TCPS_TIME_WAIT: return MIB_TCP_STATE_TIME_WAIT;
1885 case TCPS_CLOSE_WAIT: return MIB_TCP_STATE_CLOSE_WAIT;
1886 case TCPS_LAST_ACK: return MIB_TCP_STATE_LAST_ACK;
1887 case TCPS_LISTEN: return MIB_TCP_STATE_LISTEN;
1888 case TCPS_CLOSING: return MIB_TCP_STATE_CLOSING;
1889 default:
1890 case TCPS_CLOSED: return MIB_TCP_STATE_CLOSED;
1894 static int compare_tcp_rows(const void *a, const void *b)
1896 const MIB_TCPROW *rowA = a;
1897 const MIB_TCPROW *rowB = b;
1898 int ret;
1900 if ((ret = ntohl (rowA->dwLocalAddr) - ntohl (rowB->dwLocalAddr)) != 0) return ret;
1901 if ((ret = ntohs ((unsigned short)rowA->dwLocalPort) -
1902 ntohs ((unsigned short)rowB->dwLocalPort)) != 0) return ret;
1903 if ((ret = ntohl (rowA->dwRemoteAddr) - ntohl (rowB->dwRemoteAddr)) != 0) return ret;
1904 return ntohs ((unsigned short)rowA->dwRemotePort) - ntohs ((unsigned short)rowB->dwRemotePort);
1907 struct pid_map
1909 unsigned int pid;
1910 unsigned int unix_pid;
1913 static struct pid_map *get_pid_map( unsigned int *num_entries )
1915 HANDLE snapshot = NULL;
1916 struct pid_map *map;
1917 unsigned int i = 0, count = 16, size = count * sizeof(*map);
1918 NTSTATUS ret;
1920 if (!(map = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
1922 SERVER_START_REQ( create_snapshot )
1924 req->flags = SNAP_PROCESS;
1925 req->attributes = 0;
1926 if (!(ret = wine_server_call( req )))
1927 snapshot = wine_server_ptr_handle( reply->handle );
1929 SERVER_END_REQ;
1931 *num_entries = 0;
1932 while (ret == STATUS_SUCCESS)
1934 SERVER_START_REQ( next_process )
1936 req->handle = wine_server_obj_handle( snapshot );
1937 req->reset = (i == 0);
1938 if (!(ret = wine_server_call( req )))
1940 if (i >= count)
1942 struct pid_map *new_map;
1943 count *= 2;
1944 size = count * sizeof(*new_map);
1946 if (!(new_map = HeapReAlloc( GetProcessHeap(), 0, map, size )))
1948 HeapFree( GetProcessHeap(), 0, map );
1949 map = NULL;
1950 goto done;
1952 map = new_map;
1954 map[i].pid = reply->pid;
1955 map[i].unix_pid = reply->unix_pid;
1956 (*num_entries)++;
1957 i++;
1960 SERVER_END_REQ;
1963 done:
1964 NtClose( snapshot );
1965 return map;
1968 static unsigned int find_owning_pid( struct pid_map *map, unsigned int num_entries, UINT_PTR inode )
1970 #ifdef __linux__
1971 unsigned int i, len_socket;
1972 char socket[32];
1974 sprintf( socket, "socket:[%lu]", inode );
1975 len_socket = strlen( socket );
1976 for (i = 0; i < num_entries; i++)
1978 char dir[32];
1979 struct dirent *dirent;
1980 DIR *dirfd;
1982 sprintf( dir, "/proc/%u/fd", map[i].unix_pid );
1983 if ((dirfd = opendir( dir )))
1985 while ((dirent = readdir( dirfd )))
1987 char link[sizeof(dirent->d_name) + 32], name[32];
1988 int len;
1990 sprintf( link, "/proc/%u/fd/%s", map[i].unix_pid, dirent->d_name );
1991 if ((len = readlink( link, name, sizeof(name) - 1 )) > 0) name[len] = 0;
1992 if (len == len_socket && !strcmp( socket, name ))
1994 closedir( dirfd );
1995 return map[i].pid;
1998 closedir( dirfd );
2001 return 0;
2002 #elif defined(HAVE_LIBPROCSTAT)
2003 struct procstat *pstat;
2004 struct kinfo_proc *proc;
2005 struct filestat_list *fds;
2006 struct filestat *fd;
2007 struct sockstat sock;
2008 unsigned int i, proc_count;
2010 pstat = procstat_open_sysctl();
2011 if (!pstat) return 0;
2013 for (i = 0; i < num_entries; i++)
2015 proc = procstat_getprocs( pstat, KERN_PROC_PID, map[i].unix_pid, &proc_count );
2016 if (!proc || proc_count < 1) continue;
2018 fds = procstat_getfiles( pstat, proc, 0 );
2019 if (!fds)
2021 procstat_freeprocs( pstat, proc );
2022 continue;
2025 STAILQ_FOREACH( fd, fds, next )
2027 char errbuf[_POSIX2_LINE_MAX];
2029 if (fd->fs_type != PS_FST_TYPE_SOCKET) continue;
2031 procstat_get_socket_info( pstat, fd, &sock, errbuf );
2033 if (sock.so_pcb == inode)
2035 procstat_freefiles( pstat, fds );
2036 procstat_freeprocs( pstat, proc );
2037 procstat_close( pstat );
2038 return map[i].pid;
2042 procstat_freefiles( pstat, fds );
2043 procstat_freeprocs( pstat, proc );
2046 procstat_close( pstat );
2047 return 0;
2048 #elif defined(HAVE_PROC_PIDINFO)
2049 struct proc_fdinfo *fds;
2050 struct socket_fdinfo sock;
2051 unsigned int i, j, n;
2053 for (i = 0; i < num_entries; i++)
2055 int fd_len = proc_pidinfo( map[i].unix_pid, PROC_PIDLISTFDS, 0, NULL, 0 );
2056 if (fd_len <= 0) continue;
2058 fds = HeapAlloc( GetProcessHeap(), 0, fd_len );
2059 if (!fds) continue;
2061 proc_pidinfo( map[i].unix_pid, PROC_PIDLISTFDS, 0, fds, fd_len );
2062 n = fd_len / sizeof(struct proc_fdinfo);
2063 for (j = 0; j < n; j++)
2065 if (fds[j].proc_fdtype != PROX_FDTYPE_SOCKET) continue;
2067 proc_pidfdinfo( map[i].unix_pid, fds[j].proc_fd, PROC_PIDFDSOCKETINFO, &sock, sizeof(sock) );
2068 if (sock.psi.soi_pcb == inode)
2070 HeapFree( GetProcessHeap(), 0, fds );
2071 return map[i].pid;
2075 HeapFree( GetProcessHeap(), 0, fds );
2077 return 0;
2078 #else
2079 FIXME( "not implemented\n" );
2080 return 0;
2081 #endif
2084 static BOOL match_class( TCP_TABLE_CLASS class, MIB_TCP_STATE state )
2086 switch (class)
2088 case TCP_TABLE_BASIC_ALL:
2089 case TCP_TABLE_OWNER_PID_ALL:
2090 case TCP_TABLE_OWNER_MODULE_ALL:
2091 return TRUE;
2093 case TCP_TABLE_BASIC_LISTENER:
2094 case TCP_TABLE_OWNER_PID_LISTENER:
2095 case TCP_TABLE_OWNER_MODULE_LISTENER:
2096 if (state == MIB_TCP_STATE_LISTEN) return TRUE;
2097 return FALSE;
2099 case TCP_TABLE_BASIC_CONNECTIONS:
2100 case TCP_TABLE_OWNER_PID_CONNECTIONS:
2101 case TCP_TABLE_OWNER_MODULE_CONNECTIONS:
2102 if (state == MIB_TCP_STATE_ESTAB) return TRUE;
2103 return FALSE;
2105 default:
2106 ERR( "unhandled class %u\n", class );
2107 return FALSE;
2111 DWORD build_tcp_table( TCP_TABLE_CLASS class, void **tablep, BOOL order, HANDLE heap, DWORD flags,
2112 DWORD *size )
2114 MIB_TCPTABLE *table;
2115 MIB_TCPROW_OWNER_MODULE row;
2116 DWORD ret = NO_ERROR, count = 16, table_size, row_size;
2118 if (!(table_size = get_tcp_table_sizes( class, count, &row_size )))
2119 return ERROR_INVALID_PARAMETER;
2121 if (!(table = HeapAlloc( heap, flags, table_size )))
2122 return ERROR_OUTOFMEMORY;
2124 table->dwNumEntries = 0;
2126 #ifdef __linux__
2128 FILE *fp;
2130 if ((fp = fopen("/proc/net/tcp", "r")))
2132 char buf[512], *ptr;
2133 struct pid_map *map = NULL;
2134 unsigned int dummy, num_entries = 0;
2135 int inode;
2137 if (class >= TCP_TABLE_OWNER_PID_LISTENER) map = get_pid_map( &num_entries );
2139 /* skip header line */
2140 ptr = fgets(buf, sizeof(buf), fp);
2141 while ((ptr = fgets(buf, sizeof(buf), fp)))
2143 if (sscanf( ptr, "%x: %x:%x %x:%x %x %*s %*s %*s %*s %*s %d", &dummy,
2144 &row.dwLocalAddr, &row.dwLocalPort, &row.dwRemoteAddr,
2145 &row.dwRemotePort, &row.dwState, &inode ) != 7)
2146 continue;
2147 row.dwLocalPort = htons( row.dwLocalPort );
2148 row.dwRemotePort = htons( row.dwRemotePort );
2149 row.dwState = TCPStateToMIBState( row.dwState );
2150 if (!match_class( class, row.dwState )) continue;
2152 if (class >= TCP_TABLE_OWNER_PID_LISTENER)
2153 row.dwOwningPid = find_owning_pid( map, num_entries, inode );
2154 if (class >= TCP_TABLE_OWNER_MODULE_LISTENER)
2156 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
2157 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
2159 if (!(table = append_tcp_row( class, heap, flags, table, &count, &row, row_size )))
2160 break;
2162 HeapFree( GetProcessHeap(), 0, map );
2163 fclose( fp );
2165 else ret = ERROR_NOT_SUPPORTED;
2167 #elif defined(HAVE_SYS_TIHDR_H) && defined(T_OPTMGMT_ACK)
2169 void *data;
2170 int fd, len;
2171 mib2_tcpConnEntry_t *entry;
2173 if ((fd = open_streams_mib( "tcp" )) != -1)
2175 if ((data = read_mib_entry( fd, MIB2_TCP, MIB2_TCP_CONN, &len )))
2177 for (entry = data; (char *)(entry + 1) <= (char *)data + len; entry++)
2179 row.dwLocalAddr = entry->tcpConnLocalAddress;
2180 row.dwLocalPort = htons( entry->tcpConnLocalPort );
2181 row.dwRemoteAddr = entry->tcpConnRemAddress;
2182 row.dwRemotePort = htons( entry->tcpConnRemPort );
2183 row.dwState = entry->tcpConnState;
2184 if (!match_class( class, row.dwState )) continue;
2185 if (!(table = append_tcp_row( class, heap, flags, table, &count, &row, row_size )))
2186 break;
2188 HeapFree( GetProcessHeap(), 0, data );
2190 close( fd );
2192 else ret = ERROR_NOT_SUPPORTED;
2194 #elif defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_STRUCT_XINPGEN)
2196 size_t Len = 0;
2197 char *Buf = NULL;
2198 struct xinpgen *pXIG, *pOrigXIG;
2199 struct pid_map *pMap = NULL;
2200 unsigned NumEntries;
2202 if (sysctlbyname ("net.inet.tcp.pcblist", NULL, &Len, NULL, 0) < 0)
2204 ERR ("Failure to read net.inet.tcp.pcblist via sysctlbyname!\n");
2205 ret = ERROR_NOT_SUPPORTED;
2206 goto done;
2209 Buf = HeapAlloc (GetProcessHeap (), 0, Len);
2210 if (!Buf)
2212 ret = ERROR_OUTOFMEMORY;
2213 goto done;
2216 if (sysctlbyname ("net.inet.tcp.pcblist", Buf, &Len, NULL, 0) < 0)
2218 ERR ("Failure to read net.inet.tcp.pcblist via sysctlbyname!\n");
2219 ret = ERROR_NOT_SUPPORTED;
2220 goto done;
2223 if (class >= TCP_TABLE_OWNER_PID_LISTENER) pMap = get_pid_map( &NumEntries );
2225 /* Might be nothing here; first entry is just a header it seems */
2226 if (Len <= sizeof (struct xinpgen)) goto done;
2228 pOrigXIG = (struct xinpgen *)Buf;
2229 pXIG = pOrigXIG;
2231 for (pXIG = (struct xinpgen *)((char *)pXIG + pXIG->xig_len);
2232 pXIG->xig_len > sizeof (struct xinpgen);
2233 pXIG = (struct xinpgen *)((char *)pXIG + pXIG->xig_len))
2235 struct tcpcb *pTCPData = NULL;
2236 struct inpcb *pINData;
2237 struct xsocket *pSockData;
2239 pTCPData = &((struct xtcpcb *)pXIG)->xt_tp;
2240 pINData = &((struct xtcpcb *)pXIG)->xt_inp;
2241 pSockData = &((struct xtcpcb *)pXIG)->xt_socket;
2243 /* Ignore sockets for other protocols */
2244 if (pSockData->xso_protocol != IPPROTO_TCP)
2245 continue;
2247 /* Ignore PCBs that were freed while generating the data */
2248 if (pINData->inp_gencnt > pOrigXIG->xig_gen)
2249 continue;
2251 /* we're only interested in IPv4 addresses */
2252 if (!(pINData->inp_vflag & INP_IPV4) ||
2253 (pINData->inp_vflag & INP_IPV6))
2254 continue;
2256 /* If all 0's, skip it */
2257 if (!pINData->inp_laddr.s_addr &&
2258 !pINData->inp_lport &&
2259 !pINData->inp_faddr.s_addr &&
2260 !pINData->inp_fport)
2261 continue;
2263 /* Fill in structure details */
2264 row.dwLocalAddr = pINData->inp_laddr.s_addr;
2265 row.dwLocalPort = pINData->inp_lport;
2266 row.dwRemoteAddr = pINData->inp_faddr.s_addr;
2267 row.dwRemotePort = pINData->inp_fport;
2268 row.dwState = TCPStateToMIBState (pTCPData->t_state);
2269 if (!match_class( class, row.dwState )) continue;
2270 if (class >= TCP_TABLE_OWNER_PID_LISTENER)
2271 row.dwOwningPid = find_owning_pid( pMap, NumEntries, (UINT_PTR)pSockData->so_pcb );
2272 if (class >= TCP_TABLE_OWNER_MODULE_LISTENER)
2274 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
2275 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
2277 if (!(table = append_tcp_row( class, heap, flags, table, &count, &row, row_size )))
2278 break;
2281 done:
2282 HeapFree( GetProcessHeap(), 0, pMap );
2283 HeapFree (GetProcessHeap (), 0, Buf);
2285 #else
2286 FIXME( "not implemented\n" );
2287 ret = ERROR_NOT_SUPPORTED;
2288 #endif
2290 if (!table) return ERROR_OUTOFMEMORY;
2291 if (!ret)
2293 if (order && table->dwNumEntries)
2294 qsort( table->table, table->dwNumEntries, row_size, compare_tcp_rows );
2295 *tablep = table;
2297 else HeapFree( heap, flags, table );
2298 if (size) *size = get_tcp_table_sizes( class, count, NULL );
2299 TRACE( "returning ret %u table %p\n", ret, table );
2300 return ret;
2303 /******************************************************************
2304 * AllocateAndGetTcpTableFromStack (IPHLPAPI.@)
2306 * Get the TCP connection table.
2307 * Like GetTcpTable(), but allocate the returned table from heap.
2309 * PARAMS
2310 * ppTcpTable [Out] pointer into which the MIB_TCPTABLE is
2311 * allocated and returned.
2312 * bOrder [In] whether to sort the table
2313 * heap [In] heap from which the table is allocated
2314 * flags [In] flags to HeapAlloc
2316 * RETURNS
2317 * ERROR_INVALID_PARAMETER if ppTcpTable is NULL, whatever GetTcpTable()
2318 * returns otherwise.
2320 DWORD WINAPI AllocateAndGetTcpTableFromStack( PMIB_TCPTABLE *ppTcpTable, BOOL bOrder,
2321 HANDLE heap, DWORD flags )
2323 TRACE("table %p, bOrder %d, heap %p, flags 0x%08x\n", ppTcpTable, bOrder, heap, flags);
2325 if (!ppTcpTable) return ERROR_INVALID_PARAMETER;
2326 return build_tcp_table( TCP_TABLE_BASIC_ALL, (void **)ppTcpTable, bOrder, heap, flags, NULL );
2329 static DWORD get_udp_table_sizes( UDP_TABLE_CLASS class, DWORD row_count, DWORD *row_size )
2331 DWORD table_size;
2333 switch (class)
2335 case UDP_TABLE_BASIC:
2337 table_size = FIELD_OFFSET(MIB_UDPTABLE, table[row_count]);
2338 if (row_size) *row_size = sizeof(MIB_UDPROW);
2339 break;
2341 case UDP_TABLE_OWNER_PID:
2343 table_size = FIELD_OFFSET(MIB_UDPTABLE_OWNER_PID, table[row_count]);
2344 if (row_size) *row_size = sizeof(MIB_UDPROW_OWNER_PID);
2345 break;
2347 case UDP_TABLE_OWNER_MODULE:
2349 table_size = FIELD_OFFSET(MIB_UDPTABLE_OWNER_MODULE, table[row_count]);
2350 if (row_size) *row_size = sizeof(MIB_UDPROW_OWNER_MODULE);
2351 break;
2353 default:
2354 ERR("unhandled class %u\n", class);
2355 return 0;
2357 return table_size;
2360 static MIB_UDPTABLE *append_udp_row( UDP_TABLE_CLASS class, HANDLE heap, DWORD flags,
2361 MIB_UDPTABLE *table, DWORD *count,
2362 const MIB_UDPROW_OWNER_MODULE *row, DWORD row_size )
2364 if (table->dwNumEntries >= *count)
2366 MIB_UDPTABLE *new_table;
2367 DWORD new_count = table->dwNumEntries * 2, new_table_size;
2369 new_table_size = get_udp_table_sizes( class, new_count, NULL );
2370 if (!(new_table = HeapReAlloc( heap, flags, table, new_table_size )))
2372 HeapFree( heap, 0, table );
2373 return NULL;
2375 *count = new_count;
2376 table = new_table;
2378 memcpy( (char *)table->table + (table->dwNumEntries * row_size), row, row_size );
2379 table->dwNumEntries++;
2380 return table;
2383 static int compare_udp_rows(const void *a, const void *b)
2385 const MIB_UDPROW *rowA = a;
2386 const MIB_UDPROW *rowB = b;
2387 int ret;
2389 if ((ret = rowA->dwLocalAddr - rowB->dwLocalAddr) != 0) return ret;
2390 return rowA->dwLocalPort - rowB->dwLocalPort;
2393 DWORD build_udp_table( UDP_TABLE_CLASS class, void **tablep, BOOL order, HANDLE heap, DWORD flags,
2394 DWORD *size )
2396 MIB_UDPTABLE *table;
2397 MIB_UDPROW_OWNER_MODULE row;
2398 DWORD ret = NO_ERROR, count = 16, table_size, row_size;
2400 if (!(table_size = get_udp_table_sizes( class, count, &row_size )))
2401 return ERROR_INVALID_PARAMETER;
2403 if (!(table = HeapAlloc( heap, flags, table_size )))
2404 return ERROR_OUTOFMEMORY;
2406 table->dwNumEntries = 0;
2407 memset( &row, 0, sizeof(row) );
2409 #ifdef __linux__
2411 FILE *fp;
2413 if ((fp = fopen( "/proc/net/udp", "r" )))
2415 char buf[512], *ptr;
2416 struct pid_map *map = NULL;
2417 unsigned int dummy, num_entries = 0;
2418 int inode;
2420 if (class >= UDP_TABLE_OWNER_PID) map = get_pid_map( &num_entries );
2422 /* skip header line */
2423 ptr = fgets( buf, sizeof(buf), fp );
2424 while ((ptr = fgets( buf, sizeof(buf), fp )))
2426 if (sscanf( ptr, "%u: %x:%x %*s %*s %*s %*s %*s %*s %*s %d", &dummy,
2427 &row.dwLocalAddr, &row.dwLocalPort, &inode ) != 4)
2428 continue;
2429 row.dwLocalPort = htons( row.dwLocalPort );
2431 if (class >= UDP_TABLE_OWNER_PID)
2432 row.dwOwningPid = find_owning_pid( map, num_entries, inode );
2433 if (class >= UDP_TABLE_OWNER_MODULE)
2435 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
2436 row.u.dwFlags = 0;
2437 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
2439 if (!(table = append_udp_row( class, heap, flags, table, &count, &row, row_size )))
2440 break;
2442 HeapFree( GetProcessHeap(), 0, map );
2443 fclose( fp );
2445 else ret = ERROR_NOT_SUPPORTED;
2447 #elif defined(HAVE_SYS_TIHDR_H) && defined(T_OPTMGMT_ACK)
2449 void *data;
2450 int fd, len;
2451 mib2_udpEntry_t *entry;
2453 if ((fd = open_streams_mib( "udp" )) != -1)
2455 if ((data = read_mib_entry( fd, MIB2_UDP, MIB2_UDP_ENTRY, &len )))
2457 for (entry = data; (char *)(entry + 1) <= (char *)data + len; entry++)
2459 row.dwLocalAddr = entry->udpLocalAddress;
2460 row.dwLocalPort = htons( entry->udpLocalPort );
2461 if (!(table = append_udp_row( class, heap, flags, table, &count, &row, row_size ))) break;
2463 HeapFree( GetProcessHeap(), 0, data );
2465 close( fd );
2467 else ret = ERROR_NOT_SUPPORTED;
2469 #elif defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_STRUCT_XINPGEN)
2471 size_t Len = 0;
2472 char *Buf = NULL;
2473 struct xinpgen *pXIG, *pOrigXIG;
2474 struct pid_map *pMap = NULL;
2475 unsigned NumEntries;
2477 if (sysctlbyname ("net.inet.udp.pcblist", NULL, &Len, NULL, 0) < 0)
2479 ERR ("Failure to read net.inet.udp.pcblist via sysctlbyname!\n");
2480 ret = ERROR_NOT_SUPPORTED;
2481 goto done;
2484 Buf = HeapAlloc (GetProcessHeap (), 0, Len);
2485 if (!Buf)
2487 ret = ERROR_OUTOFMEMORY;
2488 goto done;
2491 if (sysctlbyname ("net.inet.udp.pcblist", Buf, &Len, NULL, 0) < 0)
2493 ERR ("Failure to read net.inet.udp.pcblist via sysctlbyname!\n");
2494 ret = ERROR_NOT_SUPPORTED;
2495 goto done;
2498 if (class >= UDP_TABLE_OWNER_PID)
2499 pMap = get_pid_map( &NumEntries );
2501 /* Might be nothing here; first entry is just a header it seems */
2502 if (Len <= sizeof (struct xinpgen)) goto done;
2504 pOrigXIG = (struct xinpgen *)Buf;
2505 pXIG = pOrigXIG;
2507 for (pXIG = (struct xinpgen *)((char *)pXIG + pXIG->xig_len);
2508 pXIG->xig_len > sizeof (struct xinpgen);
2509 pXIG = (struct xinpgen *)((char *)pXIG + pXIG->xig_len))
2511 struct inpcb *pINData;
2512 struct xsocket *pSockData;
2514 pINData = &((struct xinpcb *)pXIG)->xi_inp;
2515 pSockData = &((struct xinpcb *)pXIG)->xi_socket;
2517 /* Ignore sockets for other protocols */
2518 if (pSockData->xso_protocol != IPPROTO_UDP)
2519 continue;
2521 /* Ignore PCBs that were freed while generating the data */
2522 if (pINData->inp_gencnt > pOrigXIG->xig_gen)
2523 continue;
2525 /* we're only interested in IPv4 addresses */
2526 if (!(pINData->inp_vflag & INP_IPV4) ||
2527 (pINData->inp_vflag & INP_IPV6))
2528 continue;
2530 /* If all 0's, skip it */
2531 if (!pINData->inp_laddr.s_addr &&
2532 !pINData->inp_lport)
2533 continue;
2535 /* Fill in structure details */
2536 row.dwLocalAddr = pINData->inp_laddr.s_addr;
2537 row.dwLocalPort = pINData->inp_lport;
2538 if (class >= UDP_TABLE_OWNER_PID)
2539 row.dwOwningPid = find_owning_pid( pMap, NumEntries, (UINT_PTR)pSockData->so_pcb );
2540 if (class >= UDP_TABLE_OWNER_MODULE)
2542 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
2543 row.u.dwFlags = 0;
2544 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
2546 if (!(table = append_udp_row( class, heap, flags, table, &count, &row, row_size ))) break;
2549 done:
2550 HeapFree( GetProcessHeap(), 0, pMap );
2551 HeapFree (GetProcessHeap (), 0, Buf);
2553 #else
2554 FIXME( "not implemented\n" );
2555 ret = ERROR_NOT_SUPPORTED;
2556 #endif
2558 if (!table) return ERROR_OUTOFMEMORY;
2559 if (!ret)
2561 if (order && table->dwNumEntries)
2562 qsort( table->table, table->dwNumEntries, row_size, compare_udp_rows );
2563 *tablep = table;
2565 else HeapFree( heap, flags, table );
2566 if (size) *size = get_udp_table_sizes( class, count, NULL );
2567 TRACE( "returning ret %u table %p\n", ret, table );
2568 return ret;
2571 static DWORD get_udp6_table_sizes( UDP_TABLE_CLASS class, DWORD row_count, DWORD *row_size )
2573 DWORD table_size;
2575 switch (class)
2577 case UDP_TABLE_BASIC:
2579 table_size = FIELD_OFFSET(MIB_UDP6TABLE, table[row_count]);
2580 if (row_size) *row_size = sizeof(MIB_UDP6ROW);
2581 break;
2583 case UDP_TABLE_OWNER_PID:
2585 table_size = FIELD_OFFSET(MIB_UDP6TABLE_OWNER_PID, table[row_count]);
2586 if (row_size) *row_size = sizeof(MIB_UDP6ROW_OWNER_PID);
2587 break;
2589 case UDP_TABLE_OWNER_MODULE:
2591 table_size = FIELD_OFFSET(MIB_UDP6TABLE_OWNER_MODULE, table[row_count]);
2592 if (row_size) *row_size = sizeof(MIB_UDP6ROW_OWNER_MODULE);
2593 break;
2595 default:
2596 ERR("unhandled class %u\n", class);
2597 return 0;
2599 return table_size;
2602 static MIB_UDP6TABLE *append_udp6_row( UDP_TABLE_CLASS class, HANDLE heap, DWORD flags,
2603 MIB_UDP6TABLE *table, DWORD *count,
2604 const MIB_UDP6ROW_OWNER_MODULE *row, DWORD row_size )
2606 if (table->dwNumEntries >= *count)
2608 MIB_UDP6TABLE *new_table;
2609 DWORD new_count = table->dwNumEntries * 2, new_table_size;
2611 new_table_size = get_udp6_table_sizes( class, new_count, NULL );
2612 if (!(new_table = HeapReAlloc( heap, flags, table, new_table_size )))
2614 HeapFree( heap, 0, table );
2615 return NULL;
2617 *count = new_count;
2618 table = new_table;
2620 memcpy( (char *)table->table + (table->dwNumEntries * row_size), row, row_size );
2621 table->dwNumEntries++;
2622 return table;
2625 static int compare_udp6_rows(const void *a, const void *b)
2627 const MIB_UDP6ROW *rowA = a;
2628 const MIB_UDP6ROW *rowB = b;
2629 int ret;
2631 if ((ret = memcmp(&rowA->dwLocalAddr, &rowB->dwLocalAddr, sizeof(rowA->dwLocalAddr)) != 0)) return ret;
2632 if ((ret = rowA->dwLocalScopeId - rowB->dwLocalScopeId) != 0) return ret;
2633 return rowA->dwLocalPort - rowB->dwLocalPort;
2636 struct ipv6_addr_scope
2638 IN6_ADDR addr;
2639 DWORD scope;
2642 static struct ipv6_addr_scope *get_ipv6_addr_scope_table(unsigned int *size)
2644 struct ipv6_addr_scope *table = NULL;
2645 unsigned int table_size = 0;
2647 if (!(table = HeapAlloc( GetProcessHeap(), 0, sizeof(table[0]) )))
2648 return NULL;
2650 #ifdef __linux__
2652 FILE *fp;
2653 char buf[512], *ptr;
2655 if (!(fp = fopen( "/proc/net/if_inet6", "r" )))
2656 goto failed;
2658 while ((ptr = fgets( buf, sizeof(buf), fp )))
2660 WORD a[8];
2661 DWORD scope;
2662 struct ipv6_addr_scope *new_table;
2663 struct ipv6_addr_scope *entry;
2664 unsigned int i;
2666 if (sscanf( ptr, "%4hx%4hx%4hx%4hx%4hx%4hx%4hx%4hx %*s %*s %x",
2667 &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7], &scope ) != 9)
2668 continue;
2670 table_size++;
2671 if (!(new_table = HeapReAlloc( GetProcessHeap(), 0, table, table_size * sizeof(table[0]) )))
2673 fclose(fp);
2674 goto failed;
2677 table = new_table;
2678 entry = &table[table_size - 1];
2680 i = 0;
2681 while (i < 8)
2683 entry->addr.u.Word[i] = htons(a[i]);
2684 i++;
2687 entry->scope = htons(scope);
2690 fclose(fp);
2692 #else
2693 FIXME( "not implemented\n" );
2694 goto failed;
2695 #endif
2697 *size = table_size;
2698 return table;
2700 failed:
2701 HeapFree( GetProcessHeap(), 0, table );
2702 return NULL;
2705 static DWORD find_ipv6_addr_scope(const IN6_ADDR *addr, const struct ipv6_addr_scope *table, unsigned int size)
2707 const BYTE multicast_scope_mask = 0x0F;
2708 const BYTE multicast_scope_shift = 0;
2709 unsigned int i = 0;
2711 if (WS_IN6_IS_ADDR_UNSPECIFIED(addr))
2712 return 0;
2714 if (WS_IN6_IS_ADDR_MULTICAST(addr))
2715 return htons((addr->u.Byte[1] & multicast_scope_mask) >> multicast_scope_shift);
2717 if (!table)
2718 return -1;
2720 while (i < size)
2722 if (memcmp(&table[i].addr, addr, sizeof(table[i].addr)) == 0)
2723 return table[i].scope;
2724 i++;
2727 return -1;
2730 DWORD build_udp6_table( UDP_TABLE_CLASS class, void **tablep, BOOL order, HANDLE heap, DWORD flags,
2731 DWORD *size )
2733 MIB_UDP6TABLE *table;
2734 MIB_UDP6ROW_OWNER_MODULE row;
2735 DWORD ret = NO_ERROR, count = 16, table_size, row_size;
2737 if (!(table_size = get_udp6_table_sizes( class, count, &row_size )))
2738 return ERROR_INVALID_PARAMETER;
2740 if (!(table = HeapAlloc( heap, flags, table_size )))
2741 return ERROR_OUTOFMEMORY;
2743 table->dwNumEntries = 0;
2744 memset( &row, 0, sizeof(row) );
2746 #ifdef __linux__
2748 FILE *fp;
2750 if ((fp = fopen( "/proc/net/udp6", "r" )))
2752 char buf[512], *ptr;
2753 struct pid_map *map = NULL;
2754 unsigned int num_entries = 0;
2755 struct ipv6_addr_scope *addr_scopes;
2756 unsigned int addr_scopes_size = 0;
2757 unsigned int dummy;
2758 int inode;
2760 addr_scopes = get_ipv6_addr_scope_table(&addr_scopes_size);
2762 if (class >= UDP_TABLE_OWNER_PID) map = get_pid_map( &num_entries );
2764 /* skip header line */
2765 ptr = fgets( buf, sizeof(buf), fp );
2766 while ((ptr = fgets( buf, sizeof(buf), fp )))
2768 DWORD in6_addr32[4];
2770 if (sscanf( ptr, "%u: %8x%8x%8x%8x:%x %*s %*s %*s %*s %*s %*s %*s %d", &dummy,
2771 &in6_addr32[0], &in6_addr32[1], &in6_addr32[2], &in6_addr32[3],
2772 &row.dwLocalPort, &inode ) != 7)
2773 continue;
2774 memcpy(&row.ucLocalAddr, in6_addr32, sizeof(row.ucLocalAddr));
2775 row.dwLocalScopeId = find_ipv6_addr_scope((const IN6_ADDR *)&row.ucLocalAddr, addr_scopes, addr_scopes_size);
2776 row.dwLocalPort = htons( row.dwLocalPort );
2778 if (class >= UDP_TABLE_OWNER_PID)
2779 row.dwOwningPid = find_owning_pid( map, num_entries, inode );
2780 if (class >= UDP_TABLE_OWNER_MODULE)
2782 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
2783 row.u.dwFlags = 0;
2784 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
2786 if (!(table = append_udp6_row( class, heap, flags, table, &count, &row, row_size )))
2787 break;
2789 HeapFree( GetProcessHeap(), 0, map );
2790 HeapFree( GetProcessHeap(), 0, addr_scopes );
2791 fclose( fp );
2793 else ret = ERROR_NOT_SUPPORTED;
2795 #else
2796 FIXME( "not implemented\n" );
2797 ret = ERROR_NOT_SUPPORTED;
2798 #endif
2800 if (!table) return ERROR_OUTOFMEMORY;
2801 if (!ret)
2803 if (order && table->dwNumEntries)
2804 qsort( table->table, table->dwNumEntries, row_size, compare_udp6_rows );
2805 *tablep = table;
2807 else HeapFree( heap, flags, table );
2808 if (size) *size = get_udp6_table_sizes( class, count, NULL );
2809 TRACE( "returning ret %u table %p\n", ret, table );
2810 return ret;
2813 /******************************************************************
2814 * AllocateAndGetUdpTableFromStack (IPHLPAPI.@)
2816 * Get the UDP listener table.
2817 * Like GetUdpTable(), but allocate the returned table from heap.
2819 * PARAMS
2820 * ppUdpTable [Out] pointer into which the MIB_UDPTABLE is
2821 * allocated and returned.
2822 * bOrder [In] whether to sort the table
2823 * heap [In] heap from which the table is allocated
2824 * flags [In] flags to HeapAlloc
2826 * RETURNS
2827 * ERROR_INVALID_PARAMETER if ppUdpTable is NULL, whatever GetUdpTable()
2828 * returns otherwise.
2830 DWORD WINAPI AllocateAndGetUdpTableFromStack(PMIB_UDPTABLE *ppUdpTable, BOOL bOrder,
2831 HANDLE heap, DWORD flags)
2833 TRACE("table %p, bOrder %d, heap %p, flags 0x%08x\n", ppUdpTable, bOrder, heap, flags);
2835 if (!ppUdpTable) return ERROR_INVALID_PARAMETER;
2836 return build_udp_table( UDP_TABLE_BASIC, (void **)ppUdpTable, bOrder, heap, flags, NULL );