makefiles: Don't use standard libs for programs that specify -nodefaultlibs.
[wine/zf.git] / dlls / iphlpapi / ipstats.c
blobefb4d64c90d6baae10ce2173bce4d55a25d835d2
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
142 #ifdef HAVE_IFADDRS_H
143 #include <ifaddrs.h>
144 #endif
146 #ifndef ROUNDUP
147 #define ROUNDUP(a) \
148 ((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
149 #endif
150 #ifndef ADVANCE
151 #define ADVANCE(x, n) (x += ROUNDUP(((struct sockaddr *)n)->sa_len))
152 #endif
154 #include "ntstatus.h"
155 #define WIN32_NO_STATUS
156 #define NONAMELESSUNION
157 #define USE_WS_PREFIX
158 #include "winsock2.h"
159 #include "ws2ipdef.h"
160 #include "ifenum.h"
161 #include "ipstats.h"
162 #include "iphlpapi.h"
164 #include "wine/debug.h"
165 #include "wine/server.h"
166 #include "wine/unicode.h"
168 #ifndef HAVE_NETINET_TCP_FSM_H
169 #define TCPS_ESTABLISHED 1
170 #define TCPS_SYN_SENT 2
171 #define TCPS_SYN_RECEIVED 3
172 #define TCPS_FIN_WAIT_1 4
173 #define TCPS_FIN_WAIT_2 5
174 #define TCPS_TIME_WAIT 6
175 #define TCPS_CLOSED 7
176 #define TCPS_CLOSE_WAIT 8
177 #define TCPS_LAST_ACK 9
178 #define TCPS_LISTEN 10
179 #define TCPS_CLOSING 11
180 #endif
182 #ifndef RTF_MULTICAST
183 #define RTF_MULTICAST 0 /* Not available on NetBSD/OpenBSD */
184 #endif
186 #ifndef RTF_LLINFO
187 #define RTF_LLINFO 0 /* Not available on FreeBSD 8 and above */
188 #endif
190 WINE_DEFAULT_DEBUG_CHANNEL(iphlpapi);
192 #ifdef HAVE_LIBKSTAT
193 static DWORD kstat_get_ui32( kstat_t *ksp, const char *name )
195 unsigned int i;
196 kstat_named_t *data = ksp->ks_data;
198 for (i = 0; i < ksp->ks_ndata; i++)
199 if (!strcmp( data[i].name, name )) return data[i].value.ui32;
200 return 0;
203 static ULONGLONG kstat_get_ui64( kstat_t *ksp, const char *name )
205 unsigned int i;
206 kstat_named_t *data = ksp->ks_data;
208 for (i = 0; i < ksp->ks_ndata; i++)
209 if (!strcmp( data[i].name, name )) return data[i].value.ui64;
210 return 0;
212 #endif
214 #if defined(HAVE_SYS_TIHDR_H) && defined(T_OPTMGMT_ACK)
215 static int open_streams_mib( const char *proto )
217 int fd;
218 struct strbuf buf;
219 struct request
221 struct T_optmgmt_req req_header;
222 struct opthdr opt_header;
223 } request;
225 if ((fd = open( "/dev/arp", O_RDWR )) == -1)
227 WARN( "could not open /dev/arp: %s\n", strerror(errno) );
228 return -1;
230 if (proto) ioctl( fd, I_PUSH, proto );
232 request.req_header.PRIM_type = T_SVR4_OPTMGMT_REQ;
233 request.req_header.OPT_length = sizeof(request.opt_header);
234 request.req_header.OPT_offset = FIELD_OFFSET( struct request, opt_header );
235 request.req_header.MGMT_flags = T_CURRENT;
236 request.opt_header.level = MIB2_IP;
237 request.opt_header.name = 0;
238 request.opt_header.len = 0;
240 buf.len = sizeof(request);
241 buf.buf = (caddr_t)&request;
242 if (putmsg( fd, &buf, NULL, 0 ) == -1)
244 WARN( "putmsg: %s\n", strerror(errno) );
245 close( fd );
246 fd = -1;
248 return fd;
251 static void *read_mib_entry( int fd, int level, int name, int *len )
253 struct strbuf buf;
254 void *data;
255 int ret, flags = 0;
257 struct reply
259 struct T_optmgmt_ack ack_header;
260 struct opthdr opt_header;
261 } reply;
263 for (;;)
265 buf.maxlen = sizeof(reply);
266 buf.buf = (caddr_t)&reply;
267 if ((ret = getmsg( fd, &buf, NULL, &flags )) < 0) return NULL;
268 if (!(ret & MOREDATA)) return NULL;
269 if (reply.ack_header.PRIM_type != T_OPTMGMT_ACK) return NULL;
270 if (buf.len < sizeof(reply.ack_header)) return NULL;
271 if (reply.ack_header.OPT_length < sizeof(reply.opt_header)) return NULL;
273 if (!(data = HeapAlloc( GetProcessHeap(), 0, reply.opt_header.len ))) return NULL;
274 buf.maxlen = reply.opt_header.len;
275 buf.buf = (caddr_t)data;
276 flags = 0;
277 if (getmsg( fd, NULL, &buf, &flags ) >= 0 &&
278 reply.opt_header.level == level &&
279 reply.opt_header.name == name)
281 *len = buf.len;
282 return data;
284 HeapFree( GetProcessHeap(), 0, data );
287 #endif /* HAVE_SYS_TIHDR_H && T_OPTMGMT_ACK */
289 DWORD getInterfaceStatsByName(const char *name, PMIB_IFROW entry)
291 DWORD ret = ERROR_NOT_SUPPORTED;
293 if (!name || !entry) return ERROR_INVALID_PARAMETER;
295 #ifdef __linux__
297 FILE *fp;
299 if ((fp = fopen("/proc/net/dev", "r")))
301 DWORD skip;
302 char buf[512], *ptr;
303 int nameLen = strlen(name);
305 while ((ptr = fgets(buf, sizeof(buf), fp)))
307 while (*ptr && isspace(*ptr)) ptr++;
308 if (_strnicmp(ptr, name, nameLen) == 0 && *(ptr + nameLen) == ':')
310 ptr += nameLen + 1;
311 sscanf( ptr, "%u %u %u %u %u %u %u %u %u %u %u %u",
312 &entry->dwInOctets, &entry->dwInUcastPkts,
313 &entry->dwInErrors, &entry->dwInDiscards,
314 &skip, &skip, &skip,
315 &entry->dwInNUcastPkts, &entry->dwOutOctets,
316 &entry->dwOutUcastPkts, &entry->dwOutErrors,
317 &entry->dwOutDiscards );
318 break;
321 fclose(fp);
322 ret = NO_ERROR;
325 #elif defined(HAVE_LIBKSTAT)
327 kstat_ctl_t *kc;
328 kstat_t *ksp;
330 if ((kc = kstat_open()) &&
331 (ksp = kstat_lookup( kc, NULL, -1, (char *)name )) &&
332 kstat_read( kc, ksp, NULL ) != -1 &&
333 ksp->ks_type == KSTAT_TYPE_NAMED)
335 entry->dwMtu = 1500; /* FIXME */
336 entry->dwSpeed = min( kstat_get_ui64( ksp, "ifspeed" ), ~0u );
337 entry->dwInOctets = kstat_get_ui32( ksp, "rbytes" );
338 entry->dwInNUcastPkts = kstat_get_ui32( ksp, "multircv" );
339 entry->dwInNUcastPkts += kstat_get_ui32( ksp, "brdcstrcv" );
340 entry->dwInUcastPkts = kstat_get_ui32( ksp, "ipackets" ) - entry->dwInNUcastPkts;
341 entry->dwInDiscards = kstat_get_ui32( ksp, "norcvbuf" );
342 entry->dwInErrors = kstat_get_ui32( ksp, "ierrors" );
343 entry->dwInUnknownProtos = kstat_get_ui32( ksp, "unknowns" );
344 entry->dwOutOctets = kstat_get_ui32( ksp, "obytes" );
345 entry->dwOutNUcastPkts = kstat_get_ui32( ksp, "multixmt" );
346 entry->dwOutNUcastPkts += kstat_get_ui32( ksp, "brdcstxmt" );
347 entry->dwOutUcastPkts = kstat_get_ui32( ksp, "opackets" ) - entry->dwOutNUcastPkts;
348 entry->dwOutDiscards = 0; /* FIXME */
349 entry->dwOutErrors = kstat_get_ui32( ksp, "oerrors" );
350 entry->dwOutQLen = kstat_get_ui32( ksp, "noxmtbuf" );
351 ret = NO_ERROR;
353 if (kc) kstat_close( kc );
355 #elif defined(HAVE_SYS_SYSCTL_H) && defined(NET_RT_IFLIST)
357 int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_IFLIST, if_nametoindex(name)};
358 size_t needed;
359 char *buf = NULL, *end;
360 struct if_msghdr *ifm;
361 struct if_data ifdata;
363 if(sysctl(mib, ARRAY_SIZE(mib), NULL, &needed, NULL, 0) == -1)
365 ERR ("failed to get size of iflist\n");
366 goto done;
368 buf = HeapAlloc (GetProcessHeap (), 0, needed);
369 if (!buf)
371 ret = ERROR_OUTOFMEMORY;
372 goto done;
374 if(sysctl(mib, ARRAY_SIZE(mib), buf, &needed, NULL, 0) == -1)
376 ERR ("failed to get iflist\n");
377 goto done;
379 for ( end = buf + needed; buf < end; buf += ifm->ifm_msglen)
381 ifm = (struct if_msghdr *) buf;
382 if(ifm->ifm_type == RTM_IFINFO)
384 ifdata = ifm->ifm_data;
385 entry->dwMtu = ifdata.ifi_mtu;
386 entry->dwSpeed = ifdata.ifi_baudrate;
387 entry->dwInOctets = ifdata.ifi_ibytes;
388 entry->dwInErrors = ifdata.ifi_ierrors;
389 entry->dwInDiscards = ifdata.ifi_iqdrops;
390 entry->dwInUcastPkts = ifdata.ifi_ipackets;
391 entry->dwInNUcastPkts = ifdata.ifi_imcasts;
392 entry->dwOutOctets = ifdata.ifi_obytes;
393 entry->dwOutUcastPkts = ifdata.ifi_opackets;
394 entry->dwOutErrors = ifdata.ifi_oerrors;
395 ret = NO_ERROR;
396 break;
399 done:
400 HeapFree (GetProcessHeap (), 0, buf);
402 #else
403 FIXME( "unimplemented\n" );
404 #endif
405 return ret;
409 /******************************************************************
410 * GetIcmpStatistics (IPHLPAPI.@)
412 * Get the ICMP statistics for the local computer.
414 * PARAMS
415 * stats [Out] buffer for ICMP statistics
417 * RETURNS
418 * Success: NO_ERROR
419 * Failure: error code from winerror.h
421 DWORD WINAPI GetIcmpStatistics(PMIB_ICMP stats)
423 DWORD ret = ERROR_NOT_SUPPORTED;
425 if (!stats) return ERROR_INVALID_PARAMETER;
426 memset( stats, 0, sizeof(MIB_ICMP) );
428 #ifdef __linux__
430 FILE *fp;
432 if ((fp = fopen("/proc/net/snmp", "r")))
434 static const char hdr[] = "Icmp:";
435 char buf[512], *ptr;
437 while ((ptr = fgets(buf, sizeof(buf), fp)))
439 if (_strnicmp(buf, hdr, sizeof(hdr) - 1)) continue;
440 /* last line was a header, get another */
441 if (!(ptr = fgets(buf, sizeof(buf), fp))) break;
442 if (!_strnicmp(buf, hdr, sizeof(hdr) - 1))
444 ptr += sizeof(hdr);
445 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",
446 &stats->stats.icmpInStats.dwMsgs,
447 &stats->stats.icmpInStats.dwErrors,
448 &stats->stats.icmpInStats.dwDestUnreachs,
449 &stats->stats.icmpInStats.dwTimeExcds,
450 &stats->stats.icmpInStats.dwParmProbs,
451 &stats->stats.icmpInStats.dwSrcQuenchs,
452 &stats->stats.icmpInStats.dwRedirects,
453 &stats->stats.icmpInStats.dwEchoReps,
454 &stats->stats.icmpInStats.dwTimestamps,
455 &stats->stats.icmpInStats.dwTimestampReps,
456 &stats->stats.icmpInStats.dwAddrMasks,
457 &stats->stats.icmpInStats.dwAddrMaskReps,
458 &stats->stats.icmpOutStats.dwMsgs,
459 &stats->stats.icmpOutStats.dwErrors,
460 &stats->stats.icmpOutStats.dwDestUnreachs,
461 &stats->stats.icmpOutStats.dwTimeExcds,
462 &stats->stats.icmpOutStats.dwParmProbs,
463 &stats->stats.icmpOutStats.dwSrcQuenchs,
464 &stats->stats.icmpOutStats.dwRedirects,
465 &stats->stats.icmpOutStats.dwEchoReps,
466 &stats->stats.icmpOutStats.dwTimestamps,
467 &stats->stats.icmpOutStats.dwTimestampReps,
468 &stats->stats.icmpOutStats.dwAddrMasks,
469 &stats->stats.icmpOutStats.dwAddrMaskReps );
470 break;
473 fclose(fp);
474 ret = NO_ERROR;
477 #elif defined(HAVE_LIBKSTAT)
479 static char ip[] = "ip", icmp[] = "icmp";
480 kstat_ctl_t *kc;
481 kstat_t *ksp;
483 if ((kc = kstat_open()) &&
484 (ksp = kstat_lookup( kc, ip, 0, icmp )) &&
485 kstat_read( kc, ksp, NULL ) != -1 &&
486 ksp->ks_type == KSTAT_TYPE_NAMED)
488 stats->stats.icmpInStats.dwMsgs = kstat_get_ui32( ksp, "inMsgs" );
489 stats->stats.icmpInStats.dwErrors = kstat_get_ui32( ksp, "inErrors" );
490 stats->stats.icmpInStats.dwDestUnreachs = kstat_get_ui32( ksp, "inDestUnreachs" );
491 stats->stats.icmpInStats.dwTimeExcds = kstat_get_ui32( ksp, "inTimeExcds" );
492 stats->stats.icmpInStats.dwParmProbs = kstat_get_ui32( ksp, "inParmProbs" );
493 stats->stats.icmpInStats.dwSrcQuenchs = kstat_get_ui32( ksp, "inSrcQuenchs" );
494 stats->stats.icmpInStats.dwRedirects = kstat_get_ui32( ksp, "inRedirects" );
495 stats->stats.icmpInStats.dwEchos = kstat_get_ui32( ksp, "inEchos" );
496 stats->stats.icmpInStats.dwEchoReps = kstat_get_ui32( ksp, "inEchoReps" );
497 stats->stats.icmpInStats.dwTimestamps = kstat_get_ui32( ksp, "inTimestamps" );
498 stats->stats.icmpInStats.dwTimestampReps = kstat_get_ui32( ksp, "inTimestampReps" );
499 stats->stats.icmpInStats.dwAddrMasks = kstat_get_ui32( ksp, "inAddrMasks" );
500 stats->stats.icmpInStats.dwAddrMaskReps = kstat_get_ui32( ksp, "inAddrMaskReps" );
501 stats->stats.icmpOutStats.dwMsgs = kstat_get_ui32( ksp, "outMsgs" );
502 stats->stats.icmpOutStats.dwErrors = kstat_get_ui32( ksp, "outErrors" );
503 stats->stats.icmpOutStats.dwDestUnreachs = kstat_get_ui32( ksp, "outDestUnreachs" );
504 stats->stats.icmpOutStats.dwTimeExcds = kstat_get_ui32( ksp, "outTimeExcds" );
505 stats->stats.icmpOutStats.dwParmProbs = kstat_get_ui32( ksp, "outParmProbs" );
506 stats->stats.icmpOutStats.dwSrcQuenchs = kstat_get_ui32( ksp, "outSrcQuenchs" );
507 stats->stats.icmpOutStats.dwRedirects = kstat_get_ui32( ksp, "outRedirects" );
508 stats->stats.icmpOutStats.dwEchos = kstat_get_ui32( ksp, "outEchos" );
509 stats->stats.icmpOutStats.dwEchoReps = kstat_get_ui32( ksp, "outEchoReps" );
510 stats->stats.icmpOutStats.dwTimestamps = kstat_get_ui32( ksp, "outTimestamps" );
511 stats->stats.icmpOutStats.dwTimestampReps = kstat_get_ui32( ksp, "outTimestampReps" );
512 stats->stats.icmpOutStats.dwAddrMasks = kstat_get_ui32( ksp, "outAddrMasks" );
513 stats->stats.icmpOutStats.dwAddrMaskReps = kstat_get_ui32( ksp, "outAddrMaskReps" );
514 ret = NO_ERROR;
516 if (kc) kstat_close( kc );
518 #elif defined(HAVE_SYS_SYSCTL_H) && defined(ICMPCTL_STATS) && (defined(HAVE_STRUCT_ICMPSTAT_ICPS_INHIST) || defined(HAVE_STRUCT_ICMPSTAT_ICPS_OUTHIST))
520 int mib[] = {CTL_NET, PF_INET, IPPROTO_ICMP, ICMPCTL_STATS};
521 struct icmpstat icmp_stat;
522 size_t needed = sizeof(icmp_stat);
523 int i;
525 if(sysctl(mib, ARRAY_SIZE(mib), &icmp_stat, &needed, NULL, 0) != -1)
527 #ifdef HAVE_STRUCT_ICMPSTAT_ICPS_INHIST
528 /*in stats */
529 stats->stats.icmpInStats.dwMsgs = icmp_stat.icps_badcode + icmp_stat.icps_checksum + icmp_stat.icps_tooshort + icmp_stat.icps_badlen;
530 for(i = 0; i <= ICMP_MAXTYPE; i++)
531 stats->stats.icmpInStats.dwMsgs += icmp_stat.icps_inhist[i];
533 stats->stats.icmpInStats.dwErrors = icmp_stat.icps_badcode + icmp_stat.icps_tooshort + icmp_stat.icps_checksum + icmp_stat.icps_badlen;
535 stats->stats.icmpInStats.dwDestUnreachs = icmp_stat.icps_inhist[ICMP_UNREACH];
536 stats->stats.icmpInStats.dwTimeExcds = icmp_stat.icps_inhist[ICMP_TIMXCEED];
537 stats->stats.icmpInStats.dwParmProbs = icmp_stat.icps_inhist[ICMP_PARAMPROB];
538 stats->stats.icmpInStats.dwSrcQuenchs = icmp_stat.icps_inhist[ICMP_SOURCEQUENCH];
539 stats->stats.icmpInStats.dwRedirects = icmp_stat.icps_inhist[ICMP_REDIRECT];
540 stats->stats.icmpInStats.dwEchos = icmp_stat.icps_inhist[ICMP_ECHO];
541 stats->stats.icmpInStats.dwEchoReps = icmp_stat.icps_inhist[ICMP_ECHOREPLY];
542 stats->stats.icmpInStats.dwTimestamps = icmp_stat.icps_inhist[ICMP_TSTAMP];
543 stats->stats.icmpInStats.dwTimestampReps = icmp_stat.icps_inhist[ICMP_TSTAMPREPLY];
544 stats->stats.icmpInStats.dwAddrMasks = icmp_stat.icps_inhist[ICMP_MASKREQ];
545 stats->stats.icmpInStats.dwAddrMaskReps = icmp_stat.icps_inhist[ICMP_MASKREPLY];
546 #endif
548 #ifdef HAVE_STRUCT_ICMPSTAT_ICPS_OUTHIST
549 /* out stats */
550 stats->stats.icmpOutStats.dwMsgs = icmp_stat.icps_oldshort + icmp_stat.icps_oldicmp;
551 for(i = 0; i <= ICMP_MAXTYPE; i++)
552 stats->stats.icmpOutStats.dwMsgs += icmp_stat.icps_outhist[i];
554 stats->stats.icmpOutStats.dwErrors = icmp_stat.icps_oldshort + icmp_stat.icps_oldicmp;
556 stats->stats.icmpOutStats.dwDestUnreachs = icmp_stat.icps_outhist[ICMP_UNREACH];
557 stats->stats.icmpOutStats.dwTimeExcds = icmp_stat.icps_outhist[ICMP_TIMXCEED];
558 stats->stats.icmpOutStats.dwParmProbs = icmp_stat.icps_outhist[ICMP_PARAMPROB];
559 stats->stats.icmpOutStats.dwSrcQuenchs = icmp_stat.icps_outhist[ICMP_SOURCEQUENCH];
560 stats->stats.icmpOutStats.dwRedirects = icmp_stat.icps_outhist[ICMP_REDIRECT];
561 stats->stats.icmpOutStats.dwEchos = icmp_stat.icps_outhist[ICMP_ECHO];
562 stats->stats.icmpOutStats.dwEchoReps = icmp_stat.icps_outhist[ICMP_ECHOREPLY];
563 stats->stats.icmpOutStats.dwTimestamps = icmp_stat.icps_outhist[ICMP_TSTAMP];
564 stats->stats.icmpOutStats.dwTimestampReps = icmp_stat.icps_outhist[ICMP_TSTAMPREPLY];
565 stats->stats.icmpOutStats.dwAddrMasks = icmp_stat.icps_outhist[ICMP_MASKREQ];
566 stats->stats.icmpOutStats.dwAddrMaskReps = icmp_stat.icps_outhist[ICMP_MASKREPLY];
567 #endif /* HAVE_STRUCT_ICMPSTAT_ICPS_OUTHIST */
568 ret = NO_ERROR;
571 #else /* ICMPCTL_STATS */
572 FIXME( "unimplemented\n" );
573 #endif
574 return ret;
577 /******************************************************************
578 * GetIcmpStatisticsEx (IPHLPAPI.@)
580 * Get the IPv4 and IPv6 ICMP statistics for the local computer.
582 * PARAMS
583 * stats [Out] buffer for ICMP statistics
584 * family [In] specifies whether IPv4 or IPv6 statistics are returned
586 * RETURNS
587 * Success: NO_ERROR
588 * Failure: error code from winerror.h
590 DWORD WINAPI GetIcmpStatisticsEx(PMIB_ICMP_EX stats, DWORD family)
592 DWORD ret = ERROR_NOT_SUPPORTED;
593 MIB_ICMP ipv4stats;
595 if (!stats) return ERROR_INVALID_PARAMETER;
596 if (family != WS_AF_INET && family != WS_AF_INET6) return ERROR_INVALID_PARAMETER;
597 memset( stats, 0, sizeof(MIB_ICMP_EX) );
599 if (family == WS_AF_INET6)
601 #ifdef __linux__
603 FILE *fp;
605 if ((fp = fopen("/proc/net/snmp6", "r")))
607 struct icmpstatstruct{
608 const char *name;
609 DWORD pos;
611 static const struct icmpstatstruct icmpinstatlist[] = {
612 { "Icmp6InDestUnreachs", ICMP6_DST_UNREACH },
613 { "Icmp6InPktTooBigs", ICMP6_PACKET_TOO_BIG },
614 { "Icmp6InTimeExcds", ICMP6_TIME_EXCEEDED },
615 { "Icmp6InParmProblems", ICMP6_PARAM_PROB },
616 { "Icmp6InEchos", ICMP6_ECHO_REQUEST },
617 { "Icmp6InEchoReplies", ICMP6_ECHO_REPLY },
618 { "Icmp6InGroupMembQueries", ICMP6_MEMBERSHIP_QUERY },
619 { "Icmp6InGroupMembResponses", ICMP6_MEMBERSHIP_REPORT },
620 { "Icmp6InGroupMembReductions", ICMP6_MEMBERSHIP_REDUCTION },
621 { "Icmp6InRouterSolicits", ND_ROUTER_SOLICIT },
622 { "Icmp6InRouterAdvertisements", ND_ROUTER_ADVERT },
623 { "Icmp6InNeighborSolicits", ND_NEIGHBOR_SOLICIT },
624 { "Icmp6InNeighborAdvertisements", ND_NEIGHBOR_ADVERT },
625 { "Icmp6InRedirects", ND_REDIRECT },
626 { "Icmp6InMLDv2Reports", ICMP6_V2_MEMBERSHIP_REPORT },
628 static const struct icmpstatstruct icmpoutstatlist[] = {
629 { "Icmp6OutDestUnreachs", ICMP6_DST_UNREACH },
630 { "Icmp6OutPktTooBigs", ICMP6_PACKET_TOO_BIG },
631 { "Icmp6OutTimeExcds", ICMP6_TIME_EXCEEDED },
632 { "Icmp6OutParmProblems", ICMP6_PARAM_PROB },
633 { "Icmp6OutEchos", ICMP6_ECHO_REQUEST },
634 { "Icmp6OutEchoReplies", ICMP6_ECHO_REPLY },
635 { "Icmp6OutGroupMembQueries", ICMP6_MEMBERSHIP_QUERY },
636 { "Icmp6OutGroupMembResponses", ICMP6_MEMBERSHIP_REPORT },
637 { "Icmp6OutGroupMembReductions", ICMP6_MEMBERSHIP_REDUCTION },
638 { "Icmp6OutRouterSolicits", ND_ROUTER_SOLICIT },
639 { "Icmp6OutRouterAdvertisements", ND_ROUTER_ADVERT },
640 { "Icmp6OutNeighborSolicits", ND_NEIGHBOR_SOLICIT },
641 { "Icmp6OutNeighborAdvertisements", ND_NEIGHBOR_ADVERT },
642 { "Icmp6OutRedirects", ND_REDIRECT },
643 { "Icmp6OutMLDv2Reports", ICMP6_V2_MEMBERSHIP_REPORT },
645 char buf[512], *ptr, *value;
646 DWORD res, i;
648 while ((ptr = fgets(buf, sizeof(buf), fp)))
650 if (!(value = strchr(buf, ' ')))
651 continue;
653 /* terminate the valuename */
654 ptr = value - 1;
655 *(ptr + 1) = '\0';
657 /* and strip leading spaces from value */
658 value += 1;
659 while (*value==' ') value++;
660 if ((ptr = strchr(value, '\n')))
661 *ptr='\0';
663 if (!_strnicmp(buf, "Icmp6InMsgs", -1))
665 if (sscanf(value, "%d", &res)) stats->icmpInStats.dwMsgs = res;
666 continue;
669 if (!_strnicmp(buf, "Icmp6InErrors", -1))
671 if (sscanf(value, "%d", &res)) stats->icmpInStats.dwErrors = res;
672 continue;
675 for (i = 0; i < ARRAY_SIZE(icmpinstatlist); i++)
677 if (!_strnicmp(buf, icmpinstatlist[i].name, -1))
679 if (sscanf(value, "%d", &res))
680 stats->icmpInStats.rgdwTypeCount[icmpinstatlist[i].pos] = res;
681 break;
685 if (!_strnicmp(buf, "Icmp6OutMsgs", -1))
687 if (sscanf(value, "%d", &res)) stats->icmpOutStats.dwMsgs = res;
688 continue;
691 if (!_strnicmp(buf, "Icmp6OutErrors", -1))
693 if (sscanf(value, "%d", &res)) stats->icmpOutStats.dwErrors = res;
694 continue;
697 for (i = 0; i < ARRAY_SIZE(icmpoutstatlist); i++)
699 if (!_strnicmp(buf, icmpoutstatlist[i].name, -1))
701 if (sscanf(value, "%d", &res))
702 stats->icmpOutStats.rgdwTypeCount[icmpoutstatlist[i].pos] = res;
703 break;
708 fclose(fp);
709 ret = NO_ERROR;
712 #else
713 FIXME( "unimplemented for IPv6\n" );
714 #endif
715 return ret;
718 ret = GetIcmpStatistics(&ipv4stats);
719 if (!ret)
721 stats->icmpInStats.dwMsgs = ipv4stats.stats.icmpInStats.dwMsgs;
722 stats->icmpInStats.dwErrors = ipv4stats.stats.icmpInStats.dwErrors;
723 stats->icmpInStats.rgdwTypeCount[ICMP4_DST_UNREACH] = ipv4stats.stats.icmpInStats.dwDestUnreachs;
724 stats->icmpInStats.rgdwTypeCount[ICMP4_SOURCE_QUENCH] = ipv4stats.stats.icmpInStats.dwSrcQuenchs;
725 stats->icmpInStats.rgdwTypeCount[ICMP4_REDIRECT] = ipv4stats.stats.icmpInStats.dwRedirects;
726 stats->icmpInStats.rgdwTypeCount[ICMP4_ECHO_REQUEST] = ipv4stats.stats.icmpInStats.dwEchos;
727 stats->icmpInStats.rgdwTypeCount[ICMP4_TIME_EXCEEDED] = ipv4stats.stats.icmpInStats.dwTimeExcds;
728 stats->icmpInStats.rgdwTypeCount[ICMP4_PARAM_PROB] = ipv4stats.stats.icmpInStats.dwParmProbs;
729 stats->icmpInStats.rgdwTypeCount[ICMP4_TIMESTAMP_REQUEST] = ipv4stats.stats.icmpInStats.dwTimestamps;
730 stats->icmpInStats.rgdwTypeCount[ICMP4_TIMESTAMP_REPLY] = ipv4stats.stats.icmpInStats.dwTimestampReps;
731 stats->icmpInStats.rgdwTypeCount[ICMP4_MASK_REQUEST] = ipv4stats.stats.icmpInStats.dwAddrMasks;
732 stats->icmpInStats.rgdwTypeCount[ICMP4_MASK_REPLY] = ipv4stats.stats.icmpInStats.dwAddrMaskReps;
734 stats->icmpOutStats.dwMsgs = ipv4stats.stats.icmpOutStats.dwMsgs;
735 stats->icmpOutStats.dwErrors = ipv4stats.stats.icmpOutStats.dwErrors;
736 stats->icmpOutStats.rgdwTypeCount[ICMP4_DST_UNREACH] = ipv4stats.stats.icmpOutStats.dwDestUnreachs;
737 stats->icmpOutStats.rgdwTypeCount[ICMP4_SOURCE_QUENCH] = ipv4stats.stats.icmpOutStats.dwSrcQuenchs;
738 stats->icmpOutStats.rgdwTypeCount[ICMP4_REDIRECT] = ipv4stats.stats.icmpOutStats.dwRedirects;
739 stats->icmpOutStats.rgdwTypeCount[ICMP4_ECHO_REQUEST] = ipv4stats.stats.icmpOutStats.dwEchos;
740 stats->icmpOutStats.rgdwTypeCount[ICMP4_TIME_EXCEEDED] = ipv4stats.stats.icmpOutStats.dwTimeExcds;
741 stats->icmpOutStats.rgdwTypeCount[ICMP4_PARAM_PROB] = ipv4stats.stats.icmpOutStats.dwParmProbs;
742 stats->icmpOutStats.rgdwTypeCount[ICMP4_TIMESTAMP_REQUEST] = ipv4stats.stats.icmpOutStats.dwTimestamps;
743 stats->icmpOutStats.rgdwTypeCount[ICMP4_TIMESTAMP_REPLY] = ipv4stats.stats.icmpOutStats.dwTimestampReps;
744 stats->icmpOutStats.rgdwTypeCount[ICMP4_MASK_REQUEST] = ipv4stats.stats.icmpOutStats.dwAddrMasks;
745 stats->icmpOutStats.rgdwTypeCount[ICMP4_MASK_REPLY] = ipv4stats.stats.icmpOutStats.dwAddrMaskReps;
747 return ret;
750 /******************************************************************
751 * GetIpStatisticsEx (IPHLPAPI.@)
753 * Get the IPv4 and IPv6 statistics for the local computer.
755 * PARAMS
756 * stats [Out] buffer for IP statistics
757 * family [In] specifies whether IPv4 or IPv6 statistics are returned
759 * RETURNS
760 * Success: NO_ERROR
761 * Failure: error code from winerror.h
763 DWORD WINAPI GetIpStatisticsEx(PMIB_IPSTATS stats, DWORD family)
765 DWORD ret = ERROR_NOT_SUPPORTED;
766 MIB_IPFORWARDTABLE *fwd_table;
768 if (!stats) return ERROR_INVALID_PARAMETER;
769 if (family != WS_AF_INET && family != WS_AF_INET6) return ERROR_INVALID_PARAMETER;
770 memset( stats, 0, sizeof(*stats) );
772 stats->dwNumIf = stats->dwNumAddr = get_interface_indices( FALSE, NULL );
773 if (!AllocateAndGetIpForwardTableFromStack( &fwd_table, FALSE, GetProcessHeap(), 0 ))
775 stats->dwNumRoutes = fwd_table->dwNumEntries;
776 HeapFree( GetProcessHeap(), 0, fwd_table );
779 if (family == WS_AF_INET6)
781 #ifdef __linux__
783 FILE *fp;
785 if ((fp = fopen("/proc/net/snmp6", "r")))
787 struct {
788 const char *name;
789 DWORD *elem;
790 } ipstatlist[] = {
791 { "Ip6InReceives", &stats->dwInReceives },
792 { "Ip6InHdrErrors", &stats->dwInHdrErrors },
793 { "Ip6InAddrErrors", &stats->dwInAddrErrors },
794 { "Ip6OutForwDatagrams", &stats->dwForwDatagrams },
795 { "Ip6InUnknownProtos", &stats->dwInUnknownProtos },
796 { "Ip6InDiscards", &stats->dwInDiscards },
797 { "Ip6InDelivers", &stats->dwInDelivers },
798 { "Ip6OutRequests", &stats->dwOutRequests },
799 { "Ip6OutDiscards", &stats->dwOutDiscards },
800 { "Ip6OutNoRoutes", &stats->dwOutNoRoutes },
801 { "Ip6ReasmTimeout", &stats->dwReasmTimeout },
802 { "Ip6ReasmReqds", &stats->dwReasmReqds },
803 { "Ip6ReasmOKs", &stats->dwReasmOks },
804 { "Ip6ReasmFails", &stats->dwReasmFails },
805 { "Ip6FragOKs", &stats->dwFragOks },
806 { "Ip6FragFails", &stats->dwFragFails },
807 { "Ip6FragCreates", &stats->dwFragCreates },
808 /* hmm, no routingDiscards, defaultTTL and forwarding? */
810 char buf[512], *ptr, *value;
811 DWORD res, i;
813 while ((ptr = fgets(buf, sizeof(buf), fp)))
815 if (!(value = strchr(buf, ' ')))
816 continue;
818 /* terminate the valuename */
819 ptr = value - 1;
820 *(ptr + 1) = '\0';
822 /* and strip leading spaces from value */
823 value += 1;
824 while (*value==' ') value++;
825 if ((ptr = strchr(value, '\n')))
826 *ptr='\0';
828 for (i = 0; i < ARRAY_SIZE(ipstatlist); i++)
829 if (!_strnicmp(buf, ipstatlist[i].name, -1) && sscanf(value, "%d", &res))
830 *ipstatlist[i].elem = res;
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 (_strnicmp(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 (!_strnicmp(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 /* ip.forwarding is 0 or 1 on BSD */
955 stats->u.dwForwarding = ip_forwarding+1;
956 stats->dwDefaultTTL = ip_ttl;
957 stats->dwInReceives = ip_stat.ips_total;
958 stats->dwInHdrErrors = ip_stat.ips_badhlen + ip_stat.ips_badsum + ip_stat.ips_tooshort + ip_stat.ips_badlen +
959 ip_stat.ips_badvers + ip_stat.ips_badoptions;
960 /* ips_badaddr also includes outgoing packets with a bad address, but we can't account for that right now */
961 stats->dwInAddrErrors = ip_stat.ips_cantforward + ip_stat.ips_badaddr + ip_stat.ips_notmember;
962 stats->dwForwDatagrams = ip_stat.ips_forward;
963 stats->dwInUnknownProtos = ip_stat.ips_noproto;
964 stats->dwInDiscards = ip_stat.ips_fragdropped;
965 stats->dwInDelivers = ip_stat.ips_delivered;
966 stats->dwOutRequests = ip_stat.ips_localout;
967 /*stats->dwRoutingDiscards = 0;*/ /* FIXME */
968 stats->dwOutDiscards = ip_stat.ips_odropped;
969 stats->dwOutNoRoutes = ip_stat.ips_noroute;
970 stats->dwReasmTimeout = ip_stat.ips_fragtimeout;
971 stats->dwReasmReqds = ip_stat.ips_fragments;
972 stats->dwReasmOks = ip_stat.ips_reassembled;
973 stats->dwReasmFails = ip_stat.ips_fragments - ip_stat.ips_reassembled;
974 stats->dwFragOks = ip_stat.ips_fragmented;
975 stats->dwFragFails = ip_stat.ips_cantfrag;
976 stats->dwFragCreates = ip_stat.ips_ofragments;
977 ret = NO_ERROR;
979 #else
980 FIXME( "unimplemented for IPv4\n" );
981 #endif
982 return ret;
985 /******************************************************************
986 * GetIpStatistics (IPHLPAPI.@)
988 * Get the IP statistics for the local computer.
990 * PARAMS
991 * stats [Out] buffer for IP statistics
993 * RETURNS
994 * Success: NO_ERROR
995 * Failure: error code from winerror.h
997 DWORD WINAPI GetIpStatistics(PMIB_IPSTATS stats)
999 return GetIpStatisticsEx(stats, WS_AF_INET);
1002 /******************************************************************
1003 * GetTcpStatisticsEx (IPHLPAPI.@)
1005 * Get the IPv4 and IPv6 TCP statistics for the local computer.
1007 * PARAMS
1008 * stats [Out] buffer for TCP statistics
1009 * family [In] specifies whether IPv4 or IPv6 statistics are returned
1011 * RETURNS
1012 * Success: NO_ERROR
1013 * Failure: error code from winerror.h
1015 DWORD WINAPI GetTcpStatisticsEx(PMIB_TCPSTATS stats, DWORD family)
1017 DWORD ret = ERROR_NOT_SUPPORTED;
1019 if (!stats) return ERROR_INVALID_PARAMETER;
1020 if (family != WS_AF_INET && family != WS_AF_INET6) return ERROR_INVALID_PARAMETER;
1021 memset( stats, 0, sizeof(*stats) );
1023 if (family == WS_AF_INET6)
1025 FIXME( "unimplemented for IPv6\n" );
1026 return ret;
1029 #ifdef __linux__
1031 FILE *fp;
1033 if ((fp = fopen("/proc/net/snmp", "r")))
1035 static const char hdr[] = "Tcp:";
1036 MIB_TCPTABLE *tcp_table;
1037 char buf[512], *ptr;
1039 while ((ptr = fgets(buf, sizeof(buf), fp)))
1041 if (_strnicmp(buf, hdr, sizeof(hdr) - 1)) continue;
1042 /* last line was a header, get another */
1043 if (!(ptr = fgets(buf, sizeof(buf), fp))) break;
1044 if (!_strnicmp(buf, hdr, sizeof(hdr) - 1))
1046 ptr += sizeof(hdr);
1047 sscanf( ptr, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u",
1048 &stats->u.dwRtoAlgorithm,
1049 &stats->dwRtoMin,
1050 &stats->dwRtoMax,
1051 &stats->dwMaxConn,
1052 &stats->dwActiveOpens,
1053 &stats->dwPassiveOpens,
1054 &stats->dwAttemptFails,
1055 &stats->dwEstabResets,
1056 &stats->dwCurrEstab,
1057 &stats->dwInSegs,
1058 &stats->dwOutSegs,
1059 &stats->dwRetransSegs,
1060 &stats->dwInErrs,
1061 &stats->dwOutRsts );
1062 break;
1065 if (!AllocateAndGetTcpTableFromStack( &tcp_table, FALSE, GetProcessHeap(), 0 ))
1067 stats->dwNumConns = tcp_table->dwNumEntries;
1068 HeapFree( GetProcessHeap(), 0, tcp_table );
1070 fclose(fp);
1071 ret = NO_ERROR;
1074 #elif defined(HAVE_LIBKSTAT)
1076 static char tcp[] = "tcp";
1077 kstat_ctl_t *kc;
1078 kstat_t *ksp;
1080 if ((kc = kstat_open()) &&
1081 (ksp = kstat_lookup( kc, tcp, 0, tcp )) &&
1082 kstat_read( kc, ksp, NULL ) != -1 &&
1083 ksp->ks_type == KSTAT_TYPE_NAMED)
1085 stats->u.dwRtoAlgorithm = kstat_get_ui32( ksp, "rtoAlgorithm" );
1086 stats->dwRtoMin = kstat_get_ui32( ksp, "rtoMin" );
1087 stats->dwRtoMax = kstat_get_ui32( ksp, "rtoMax" );
1088 stats->dwMaxConn = kstat_get_ui32( ksp, "maxConn" );
1089 stats->dwActiveOpens = kstat_get_ui32( ksp, "activeOpens" );
1090 stats->dwPassiveOpens = kstat_get_ui32( ksp, "passiveOpens" );
1091 stats->dwAttemptFails = kstat_get_ui32( ksp, "attemptFails" );
1092 stats->dwEstabResets = kstat_get_ui32( ksp, "estabResets" );
1093 stats->dwCurrEstab = kstat_get_ui32( ksp, "currEstab" );
1094 stats->dwInSegs = kstat_get_ui32( ksp, "inSegs" );
1095 stats->dwOutSegs = kstat_get_ui32( ksp, "outSegs" );
1096 stats->dwRetransSegs = kstat_get_ui32( ksp, "retransSegs" );
1097 stats->dwInErrs = kstat_get_ui32( ksp, "inErrs" );
1098 stats->dwOutRsts = kstat_get_ui32( ksp, "outRsts" );
1099 stats->dwNumConns = kstat_get_ui32( ksp, "connTableSize" );
1100 ret = NO_ERROR;
1102 if (kc) kstat_close( kc );
1104 #elif defined(HAVE_SYS_SYSCTL_H) && defined(TCPCTL_STATS) && (defined(HAVE_STRUCT_TCPSTAT_TCPS_CONNATTEMPT) || defined(HAVE_STRUCT_TCP_STATS_TCPS_CONNATTEMPT))
1106 #ifndef TCPTV_MIN /* got removed in Mac OS X for some reason */
1107 #define TCPTV_MIN 2
1108 #define TCPTV_REXMTMAX 128
1109 #endif
1110 int mib[] = {CTL_NET, PF_INET, IPPROTO_TCP, TCPCTL_STATS};
1111 #define hz 1000
1112 #if defined(HAVE_STRUCT_TCPSTAT_TCPS_CONNATTEMPT)
1113 struct tcpstat tcp_stat;
1114 #elif defined(HAVE_STRUCT_TCP_STATS_TCPS_CONNATTEMPT)
1115 struct tcp_stats tcp_stat;
1116 #endif
1117 size_t needed = sizeof(tcp_stat);
1119 if(sysctl(mib, ARRAY_SIZE(mib), &tcp_stat, &needed, NULL, 0) != -1)
1121 stats->u.RtoAlgorithm = MIB_TCP_RTO_VANJ;
1122 stats->dwRtoMin = TCPTV_MIN;
1123 stats->dwRtoMax = TCPTV_REXMTMAX;
1124 stats->dwMaxConn = -1;
1125 stats->dwActiveOpens = tcp_stat.tcps_connattempt;
1126 stats->dwPassiveOpens = tcp_stat.tcps_accepts;
1127 stats->dwAttemptFails = tcp_stat.tcps_conndrops;
1128 stats->dwEstabResets = tcp_stat.tcps_drops;
1129 stats->dwCurrEstab = 0;
1130 stats->dwInSegs = tcp_stat.tcps_rcvtotal;
1131 stats->dwOutSegs = tcp_stat.tcps_sndtotal - tcp_stat.tcps_sndrexmitpack;
1132 stats->dwRetransSegs = tcp_stat.tcps_sndrexmitpack;
1133 stats->dwInErrs = tcp_stat.tcps_rcvbadsum + tcp_stat.tcps_rcvbadoff + tcp_stat.tcps_rcvmemdrop + tcp_stat.tcps_rcvshort;
1134 stats->dwOutRsts = tcp_stat.tcps_sndctrl - tcp_stat.tcps_closed;
1135 stats->dwNumConns = tcp_stat.tcps_connects;
1136 ret = NO_ERROR;
1138 else ERR ("failed to get tcpstat\n");
1140 #else
1141 FIXME( "unimplemented\n" );
1142 #endif
1143 return ret;
1146 /******************************************************************
1147 * GetTcpStatistics (IPHLPAPI.@)
1149 * Get the TCP statistics for the local computer.
1151 * PARAMS
1152 * stats [Out] buffer for TCP statistics
1154 * RETURNS
1155 * Success: NO_ERROR
1156 * Failure: error code from winerror.h
1158 DWORD WINAPI GetTcpStatistics(PMIB_TCPSTATS stats)
1160 return GetTcpStatisticsEx(stats, WS_AF_INET);
1163 /******************************************************************
1164 * GetUdpStatistics (IPHLPAPI.@)
1166 * Get the IPv4 and IPv6 UDP statistics for the local computer.
1168 * PARAMS
1169 * stats [Out] buffer for UDP statistics
1170 * family [In] specifies whether IPv4 or IPv6 statistics are returned
1172 * RETURNS
1173 * Success: NO_ERROR
1174 * Failure: error code from winerror.h
1176 DWORD WINAPI GetUdpStatisticsEx(PMIB_UDPSTATS stats, DWORD family)
1178 DWORD ret = ERROR_NOT_SUPPORTED;
1180 if (!stats) return ERROR_INVALID_PARAMETER;
1181 if (family != WS_AF_INET && family != WS_AF_INET6) return ERROR_INVALID_PARAMETER;
1182 memset( stats, 0, sizeof(*stats) );
1184 stats->dwNumAddrs = get_interface_indices( FALSE, NULL );
1186 if (family == WS_AF_INET6)
1188 #ifdef __linux__
1190 FILE *fp;
1192 if ((fp = fopen("/proc/net/snmp6", "r")))
1194 struct {
1195 const char *name;
1196 DWORD *elem;
1197 } udpstatlist[] = {
1198 { "Udp6InDatagrams", &stats->dwInDatagrams },
1199 { "Udp6NoPorts", &stats->dwNoPorts },
1200 { "Udp6InErrors", &stats->dwInErrors },
1201 { "Udp6OutDatagrams", &stats->dwOutDatagrams },
1203 char buf[512], *ptr, *value;
1204 DWORD res, i;
1206 while ((ptr = fgets(buf, sizeof(buf), fp)))
1208 if (!(value = strchr(buf, ' ')))
1209 continue;
1211 /* terminate the valuename */
1212 ptr = value - 1;
1213 *(ptr + 1) = '\0';
1215 /* and strip leading spaces from value */
1216 value += 1;
1217 while (*value==' ') value++;
1218 if ((ptr = strchr(value, '\n')))
1219 *ptr='\0';
1221 for (i = 0; i < ARRAY_SIZE(udpstatlist); i++)
1222 if (!_strnicmp(buf, udpstatlist[i].name, -1) && sscanf(value, "%d", &res))
1223 *udpstatlist[i].elem = res;
1225 fclose(fp);
1226 ret = NO_ERROR;
1229 #else
1230 FIXME( "unimplemented for IPv6\n" );
1231 #endif
1232 return ret;
1235 #ifdef __linux__
1237 FILE *fp;
1239 if ((fp = fopen("/proc/net/snmp", "r")))
1241 static const char hdr[] = "Udp:";
1242 char buf[512], *ptr;
1244 while ((ptr = fgets(buf, sizeof(buf), fp)))
1246 if (_strnicmp(buf, hdr, sizeof(hdr) - 1)) continue;
1247 /* last line was a header, get another */
1248 if (!(ptr = fgets(buf, sizeof(buf), fp))) break;
1249 if (!_strnicmp(buf, hdr, sizeof(hdr) - 1))
1251 ptr += sizeof(hdr);
1252 sscanf( ptr, "%u %u %u %u %u",
1253 &stats->dwInDatagrams, &stats->dwNoPorts,
1254 &stats->dwInErrors, &stats->dwOutDatagrams, &stats->dwNumAddrs );
1255 break;
1258 fclose(fp);
1259 ret = NO_ERROR;
1262 #elif defined(HAVE_LIBKSTAT)
1264 static char udp[] = "udp";
1265 kstat_ctl_t *kc;
1266 kstat_t *ksp;
1267 MIB_UDPTABLE *udp_table;
1269 if ((kc = kstat_open()) &&
1270 (ksp = kstat_lookup( kc, udp, 0, udp )) &&
1271 kstat_read( kc, ksp, NULL ) != -1 &&
1272 ksp->ks_type == KSTAT_TYPE_NAMED)
1274 stats->dwInDatagrams = kstat_get_ui32( ksp, "inDatagrams" );
1275 stats->dwNoPorts = 0; /* FIXME */
1276 stats->dwInErrors = kstat_get_ui32( ksp, "inErrors" );
1277 stats->dwOutDatagrams = kstat_get_ui32( ksp, "outDatagrams" );
1278 if (!AllocateAndGetUdpTableFromStack( &udp_table, FALSE, GetProcessHeap(), 0 ))
1280 stats->dwNumAddrs = udp_table->dwNumEntries;
1281 HeapFree( GetProcessHeap(), 0, udp_table );
1283 ret = NO_ERROR;
1285 if (kc) kstat_close( kc );
1287 #elif defined(HAVE_SYS_SYSCTL_H) && defined(UDPCTL_STATS) && defined(HAVE_STRUCT_UDPSTAT_UDPS_IPACKETS)
1289 int mib[] = {CTL_NET, PF_INET, IPPROTO_UDP, UDPCTL_STATS};
1290 struct udpstat udp_stat;
1291 MIB_UDPTABLE *udp_table;
1292 size_t needed = sizeof(udp_stat);
1294 if(sysctl(mib, ARRAY_SIZE(mib), &udp_stat, &needed, NULL, 0) != -1)
1296 stats->dwInDatagrams = udp_stat.udps_ipackets;
1297 stats->dwOutDatagrams = udp_stat.udps_opackets;
1298 stats->dwNoPorts = udp_stat.udps_noport;
1299 stats->dwInErrors = udp_stat.udps_hdrops + udp_stat.udps_badsum + udp_stat.udps_fullsock + udp_stat.udps_badlen;
1300 if (!AllocateAndGetUdpTableFromStack( &udp_table, FALSE, GetProcessHeap(), 0 ))
1302 stats->dwNumAddrs = udp_table->dwNumEntries;
1303 HeapFree( GetProcessHeap(), 0, udp_table );
1305 ret = NO_ERROR;
1307 else ERR ("failed to get udpstat\n");
1309 #else
1310 FIXME( "unimplemented for IPv4\n" );
1311 #endif
1312 return ret;
1315 /******************************************************************
1316 * GetUdpStatistics (IPHLPAPI.@)
1318 * Get the UDP statistics for the local computer.
1320 * PARAMS
1321 * stats [Out] buffer for UDP statistics
1323 * RETURNS
1324 * Success: NO_ERROR
1325 * Failure: error code from winerror.h
1327 DWORD WINAPI GetUdpStatistics(PMIB_UDPSTATS stats)
1329 return GetUdpStatisticsEx(stats, WS_AF_INET);
1332 static void *append_table_row( HANDLE heap, DWORD flags, void *table, DWORD *table_size, DWORD *table_capacity,
1333 const void *row, DWORD row_size )
1335 DWORD *num_entries = table; /* this must be the first field */
1336 if (*num_entries == *table_capacity)
1338 void *new_table;
1339 *table_size += *table_capacity * row_size;
1340 if (!(new_table = HeapReAlloc( heap, flags, table, *table_size )))
1342 HeapFree( heap, 0, table );
1343 return NULL;
1345 num_entries = table = new_table;
1346 *table_capacity *= 2;
1348 memcpy( (char *)table + *table_size - (*table_capacity - *num_entries) * row_size, row, row_size );
1349 (*num_entries)++;
1350 return table;
1353 static int compare_ipforward_rows(const void *a, const void *b)
1355 const MIB_IPFORWARDROW *rowA = a;
1356 const MIB_IPFORWARDROW *rowB = b;
1357 int ret;
1359 if ((ret = rowA->dwForwardDest - rowB->dwForwardDest) != 0) return ret;
1360 if ((ret = rowA->u2.dwForwardProto - rowB->u2.dwForwardProto) != 0) return ret;
1361 if ((ret = rowA->dwForwardPolicy - rowB->dwForwardPolicy) != 0) return ret;
1362 return rowA->dwForwardNextHop - rowB->dwForwardNextHop;
1365 /******************************************************************
1366 * AllocateAndGetIpForwardTableFromStack (IPHLPAPI.@)
1368 * Get the route table.
1369 * Like GetIpForwardTable(), but allocate the returned table from heap.
1371 * PARAMS
1372 * ppIpForwardTable [Out] pointer into which the MIB_IPFORWARDTABLE is
1373 * allocated and returned.
1374 * bOrder [In] whether to sort the table
1375 * heap [In] heap from which the table is allocated
1376 * flags [In] flags to HeapAlloc
1378 * RETURNS
1379 * ERROR_INVALID_PARAMETER if ppIfTable is NULL, other error codes
1380 * on failure, NO_ERROR on success.
1382 DWORD WINAPI AllocateAndGetIpForwardTableFromStack(PMIB_IPFORWARDTABLE *ppIpForwardTable, BOOL bOrder,
1383 HANDLE heap, DWORD flags)
1385 MIB_IPFORWARDTABLE *table;
1386 MIB_IPFORWARDROW row;
1387 DWORD ret = NO_ERROR, count = 16, table_size = FIELD_OFFSET( MIB_IPFORWARDTABLE, table[count] );
1389 TRACE("table %p, bOrder %d, heap %p, flags 0x%08x\n", ppIpForwardTable, bOrder, heap, flags);
1391 if (!ppIpForwardTable) return ERROR_INVALID_PARAMETER;
1393 if (!(table = HeapAlloc( heap, flags, table_size )))
1394 return ERROR_OUTOFMEMORY;
1396 table->dwNumEntries = 0;
1398 #ifdef __linux__
1400 FILE *fp;
1402 if ((fp = fopen("/proc/net/route", "r")))
1404 char buf[512], *ptr;
1405 DWORD flags;
1407 /* skip header line */
1408 ptr = fgets(buf, sizeof(buf), fp);
1409 while ((ptr = fgets(buf, sizeof(buf), fp)))
1411 memset( &row, 0, sizeof(row) );
1413 while (!isspace(*ptr)) ptr++;
1414 *ptr++ = 0;
1415 if (getInterfaceIndexByName(buf, &row.dwForwardIfIndex) != NO_ERROR)
1416 continue;
1418 row.dwForwardDest = strtoul(ptr, &ptr, 16);
1419 row.dwForwardNextHop = strtoul(ptr + 1, &ptr, 16);
1420 flags = strtoul(ptr + 1, &ptr, 16);
1422 if (!(flags & RTF_UP)) row.u1.ForwardType = MIB_IPROUTE_TYPE_INVALID;
1423 else if (flags & RTF_GATEWAY) row.u1.ForwardType = MIB_IPROUTE_TYPE_INDIRECT;
1424 else row.u1.ForwardType = MIB_IPROUTE_TYPE_DIRECT;
1426 strtoul(ptr + 1, &ptr, 16); /* refcount, skip */
1427 strtoul(ptr + 1, &ptr, 16); /* use, skip */
1428 row.dwForwardMetric1 = strtoul(ptr + 1, &ptr, 16);
1429 row.dwForwardMask = strtoul(ptr + 1, &ptr, 16);
1430 /* FIXME: other protos might be appropriate, e.g. the default
1431 * route is typically set with MIB_IPPROTO_NETMGMT instead */
1432 row.u2.ForwardProto = MIB_IPPROTO_LOCAL;
1434 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, sizeof(row) )))
1435 break;
1437 fclose(fp);
1439 else ret = ERROR_NOT_SUPPORTED;
1441 #elif defined(HAVE_SYS_TIHDR_H) && defined(T_OPTMGMT_ACK)
1443 void *data;
1444 int fd, len, namelen;
1445 mib2_ipRouteEntry_t *entry;
1446 char name[64];
1448 if ((fd = open_streams_mib( NULL )) != -1)
1450 if ((data = read_mib_entry( fd, MIB2_IP, MIB2_IP_ROUTE, &len )))
1452 for (entry = data; (char *)(entry + 1) <= (char *)data + len; entry++)
1454 row.dwForwardDest = entry->ipRouteDest;
1455 row.dwForwardMask = entry->ipRouteMask;
1456 row.dwForwardPolicy = 0;
1457 row.dwForwardNextHop = entry->ipRouteNextHop;
1458 row.u1.dwForwardType = entry->ipRouteType;
1459 row.u2.dwForwardProto = entry->ipRouteProto;
1460 row.dwForwardAge = entry->ipRouteAge;
1461 row.dwForwardNextHopAS = 0;
1462 row.dwForwardMetric1 = entry->ipRouteMetric1;
1463 row.dwForwardMetric2 = entry->ipRouteMetric2;
1464 row.dwForwardMetric3 = entry->ipRouteMetric3;
1465 row.dwForwardMetric4 = entry->ipRouteMetric4;
1466 row.dwForwardMetric5 = entry->ipRouteMetric5;
1467 namelen = min( sizeof(name) - 1, entry->ipRouteIfIndex.o_length );
1468 memcpy( name, entry->ipRouteIfIndex.o_bytes, namelen );
1469 name[namelen] = 0;
1470 getInterfaceIndexByName( name, &row.dwForwardIfIndex );
1471 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, sizeof(row) )))
1472 break;
1474 HeapFree( GetProcessHeap(), 0, data );
1476 close( fd );
1478 else ret = ERROR_NOT_SUPPORTED;
1480 #elif defined(HAVE_SYS_SYSCTL_H) && defined(NET_RT_DUMP)
1482 int mib[6] = {CTL_NET, PF_ROUTE, 0, PF_INET, NET_RT_DUMP, 0};
1483 size_t needed;
1484 char *buf = NULL, *lim, *next, *addrPtr;
1485 struct rt_msghdr *rtm;
1487 if (sysctl (mib, 6, NULL, &needed, NULL, 0) < 0)
1489 ERR ("sysctl 1 failed!\n");
1490 ret = ERROR_NOT_SUPPORTED;
1491 goto done;
1494 buf = HeapAlloc (GetProcessHeap (), 0, needed);
1495 if (!buf)
1497 ret = ERROR_OUTOFMEMORY;
1498 goto done;
1501 if (sysctl (mib, 6, buf, &needed, NULL, 0) < 0)
1503 ret = ERROR_NOT_SUPPORTED;
1504 goto done;
1507 lim = buf + needed;
1508 for (next = buf; next < lim; next += rtm->rtm_msglen)
1510 int i;
1512 rtm = (struct rt_msghdr *)next;
1514 if (rtm->rtm_type != RTM_GET)
1516 WARN ("Got unexpected message type 0x%x!\n",
1517 rtm->rtm_type);
1518 continue;
1521 /* Ignore gateway routes which are multicast */
1522 if ((rtm->rtm_flags & RTF_GATEWAY) && (rtm->rtm_flags & RTF_MULTICAST))
1523 continue;
1525 memset( &row, 0, sizeof(row) );
1526 row.dwForwardIfIndex = rtm->rtm_index;
1527 row.u1.ForwardType = (rtm->rtm_flags & RTF_GATEWAY) ? MIB_IPROUTE_TYPE_INDIRECT : MIB_IPROUTE_TYPE_DIRECT;
1528 row.dwForwardMetric1 = rtm->rtm_rmx.rmx_hopcount;
1529 row.u2.ForwardProto = MIB_IPPROTO_LOCAL;
1531 addrPtr = (char *)(rtm + 1);
1533 for (i = 1; i; i <<= 1)
1535 struct sockaddr *sa;
1536 DWORD addr;
1538 if (!(i & rtm->rtm_addrs))
1539 continue;
1541 sa = (struct sockaddr *)addrPtr;
1542 ADVANCE (addrPtr, sa);
1544 /* default routes are encoded by length-zero sockaddr */
1545 if (sa->sa_len == 0) {
1546 addr = 0;
1547 }else {
1548 switch(sa->sa_family) {
1549 case AF_INET: {
1550 struct sockaddr_in *sin = (struct sockaddr_in *)sa;
1551 addr = sin->sin_addr.s_addr;
1552 break;
1554 #ifdef AF_LINK
1555 case AF_LINK:
1556 if(i == RTA_GATEWAY && row.u1.ForwardType == MIB_IPROUTE_TYPE_DIRECT) {
1557 /* For direct route we may simply use dest addr as next hop */
1558 C_ASSERT(RTA_DST < RTA_GATEWAY);
1559 addr = row.dwForwardDest;
1560 break;
1562 /* fallthrough */
1563 #endif
1564 default:
1565 WARN ("Received unsupported sockaddr family 0x%x\n", sa->sa_family);
1566 addr = 0;
1570 switch (i)
1572 case RTA_DST: row.dwForwardDest = addr; break;
1573 case RTA_GATEWAY: row.dwForwardNextHop = addr; break;
1574 case RTA_NETMASK: row.dwForwardMask = addr; break;
1575 default:
1576 WARN ("Unexpected address type 0x%x\n", i);
1580 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, sizeof(row) )))
1581 break;
1583 done:
1584 HeapFree( GetProcessHeap (), 0, buf );
1586 #else
1587 FIXME( "not implemented\n" );
1588 ret = ERROR_NOT_SUPPORTED;
1589 #endif
1591 if (!table) return ERROR_OUTOFMEMORY;
1592 if (!ret)
1594 if (bOrder && table->dwNumEntries)
1595 qsort( table->table, table->dwNumEntries, sizeof(row), compare_ipforward_rows );
1596 *ppIpForwardTable = table;
1598 else HeapFree( heap, flags, table );
1599 TRACE( "returning ret %u table %p\n", ret, table );
1600 return ret;
1603 static int compare_ipnet_rows(const void *a, const void *b)
1605 const MIB_IPNETROW *rowA = a;
1606 const MIB_IPNETROW *rowB = b;
1608 return ntohl(rowA->dwAddr) - ntohl(rowB->dwAddr);
1612 /******************************************************************
1613 * AllocateAndGetIpNetTableFromStack (IPHLPAPI.@)
1615 * Get the IP-to-physical address mapping table.
1616 * Like GetIpNetTable(), but allocate the returned table from heap.
1618 * PARAMS
1619 * ppIpNetTable [Out] pointer into which the MIB_IPNETTABLE is
1620 * allocated and returned.
1621 * bOrder [In] whether to sort the table
1622 * heap [In] heap from which the table is allocated
1623 * flags [In] flags to HeapAlloc
1625 * RETURNS
1626 * ERROR_INVALID_PARAMETER if ppIpNetTable is NULL, other error codes
1627 * on failure, NO_ERROR on success.
1629 DWORD WINAPI AllocateAndGetIpNetTableFromStack(PMIB_IPNETTABLE *ppIpNetTable, BOOL bOrder,
1630 HANDLE heap, DWORD flags)
1632 MIB_IPNETTABLE *table;
1633 MIB_IPNETROW row;
1634 DWORD ret = NO_ERROR, count = 16, table_size = FIELD_OFFSET( MIB_IPNETTABLE, table[count] );
1636 TRACE("table %p, bOrder %d, heap %p, flags 0x%08x\n", ppIpNetTable, bOrder, heap, flags);
1638 if (!ppIpNetTable) return ERROR_INVALID_PARAMETER;
1640 if (!(table = HeapAlloc( heap, flags, table_size )))
1641 return ERROR_OUTOFMEMORY;
1643 table->dwNumEntries = 0;
1645 #ifdef __linux__
1647 FILE *fp;
1649 if ((fp = fopen("/proc/net/arp", "r")))
1651 char buf[512], *ptr;
1652 DWORD flags;
1654 /* skip header line */
1655 ptr = fgets(buf, sizeof(buf), fp);
1656 while ((ptr = fgets(buf, sizeof(buf), fp)))
1658 memset( &row, 0, sizeof(row) );
1660 row.dwAddr = inet_addr(ptr);
1661 while (*ptr && !isspace(*ptr)) ptr++;
1662 strtoul(ptr + 1, &ptr, 16); /* hw type (skip) */
1663 flags = strtoul(ptr + 1, &ptr, 16);
1665 #ifdef ATF_COM
1666 if (flags & ATF_COM) row.u.Type = MIB_IPNET_TYPE_DYNAMIC;
1667 else
1668 #endif
1669 #ifdef ATF_PERM
1670 if (flags & ATF_PERM) row.u.Type = MIB_IPNET_TYPE_STATIC;
1671 else
1672 #endif
1673 row.u.Type = MIB_IPNET_TYPE_OTHER;
1675 while (*ptr && isspace(*ptr)) ptr++;
1676 while (*ptr && !isspace(*ptr))
1678 row.bPhysAddr[row.dwPhysAddrLen++] = strtoul(ptr, &ptr, 16);
1679 if (*ptr) ptr++;
1681 while (*ptr && isspace(*ptr)) ptr++;
1682 while (*ptr && !isspace(*ptr)) ptr++; /* mask (skip) */
1683 while (*ptr && isspace(*ptr)) ptr++;
1684 getInterfaceIndexByName(ptr, &row.dwIndex);
1686 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, sizeof(row) )))
1687 break;
1689 fclose(fp);
1691 else ret = ERROR_NOT_SUPPORTED;
1693 #elif defined(HAVE_SYS_TIHDR_H) && defined(T_OPTMGMT_ACK)
1695 void *data;
1696 int fd, len, namelen;
1697 mib2_ipNetToMediaEntry_t *entry;
1698 char name[64];
1700 if ((fd = open_streams_mib( NULL )) != -1)
1702 if ((data = read_mib_entry( fd, MIB2_IP, MIB2_IP_MEDIA, &len )))
1704 for (entry = data; (char *)(entry + 1) <= (char *)data + len; entry++)
1706 row.dwPhysAddrLen = min( entry->ipNetToMediaPhysAddress.o_length, MAXLEN_PHYSADDR );
1707 memcpy( row.bPhysAddr, entry->ipNetToMediaPhysAddress.o_bytes, row.dwPhysAddrLen );
1708 row.dwAddr = entry->ipNetToMediaNetAddress;
1709 row.u.Type = entry->ipNetToMediaType;
1710 namelen = min( sizeof(name) - 1, entry->ipNetToMediaIfIndex.o_length );
1711 memcpy( name, entry->ipNetToMediaIfIndex.o_bytes, namelen );
1712 name[namelen] = 0;
1713 getInterfaceIndexByName( name, &row.dwIndex );
1714 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, sizeof(row) )))
1715 break;
1717 HeapFree( GetProcessHeap(), 0, data );
1719 close( fd );
1721 else ret = ERROR_NOT_SUPPORTED;
1723 #elif defined(HAVE_SYS_SYSCTL_H) && defined(NET_RT_DUMP)
1725 int mib[] = {CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_LLINFO};
1726 size_t needed;
1727 char *buf = NULL, *lim, *next;
1728 struct rt_msghdr *rtm;
1729 struct sockaddr_inarp *sinarp;
1730 struct sockaddr_dl *sdl;
1732 if (sysctl (mib, ARRAY_SIZE(mib), NULL, &needed, NULL, 0) == -1)
1734 ERR ("failed to get arp table\n");
1735 ret = ERROR_NOT_SUPPORTED;
1736 goto done;
1739 buf = HeapAlloc (GetProcessHeap (), 0, needed);
1740 if (!buf)
1742 ret = ERROR_OUTOFMEMORY;
1743 goto done;
1746 if (sysctl (mib, ARRAY_SIZE(mib), buf, &needed, NULL, 0) == -1)
1748 ret = ERROR_NOT_SUPPORTED;
1749 goto done;
1752 lim = buf + needed;
1753 next = buf;
1754 while(next < lim)
1756 rtm = (struct rt_msghdr *)next;
1757 sinarp=(struct sockaddr_inarp *)(rtm + 1);
1758 sdl = (struct sockaddr_dl *)((char *)sinarp + ROUNDUP(sinarp->sin_len));
1759 if(sdl->sdl_alen) /* arp entry */
1761 memset( &row, 0, sizeof(row) );
1762 row.dwAddr = sinarp->sin_addr.s_addr;
1763 row.dwIndex = sdl->sdl_index;
1764 row.dwPhysAddrLen = min( 8, sdl->sdl_alen );
1765 memcpy( row.bPhysAddr, &sdl->sdl_data[sdl->sdl_nlen], row.dwPhysAddrLen );
1766 if(rtm->rtm_rmx.rmx_expire == 0) row.u.Type = MIB_IPNET_TYPE_STATIC;
1767 else if(sinarp->sin_other & SIN_PROXY) row.u.Type = MIB_IPNET_TYPE_OTHER;
1768 else if(rtm->rtm_rmx.rmx_expire != 0) row.u.Type = MIB_IPNET_TYPE_DYNAMIC;
1769 else row.u.Type = MIB_IPNET_TYPE_INVALID;
1771 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, sizeof(row) )))
1772 break;
1774 next += rtm->rtm_msglen;
1776 done:
1777 HeapFree( GetProcessHeap (), 0, buf );
1779 #else
1780 FIXME( "not implemented\n" );
1781 ret = ERROR_NOT_SUPPORTED;
1782 #endif
1784 if (!table) return ERROR_OUTOFMEMORY;
1785 if (!ret)
1787 if (bOrder && table->dwNumEntries)
1788 qsort( table->table, table->dwNumEntries, sizeof(row), compare_ipnet_rows );
1789 *ppIpNetTable = table;
1791 else HeapFree( heap, flags, table );
1792 TRACE( "returning ret %u table %p\n", ret, table );
1793 return ret;
1796 static DWORD get_tcp_table_sizes( TCP_TABLE_CLASS class, DWORD row_count, DWORD *row_size )
1798 DWORD table_size;
1800 switch (class)
1802 case TCP_TABLE_BASIC_LISTENER:
1803 case TCP_TABLE_BASIC_CONNECTIONS:
1804 case TCP_TABLE_BASIC_ALL:
1806 table_size = FIELD_OFFSET(MIB_TCPTABLE, table[row_count]);
1807 if (row_size) *row_size = sizeof(MIB_TCPROW);
1808 break;
1810 case TCP_TABLE_OWNER_PID_LISTENER:
1811 case TCP_TABLE_OWNER_PID_CONNECTIONS:
1812 case TCP_TABLE_OWNER_PID_ALL:
1814 table_size = FIELD_OFFSET(MIB_TCPTABLE_OWNER_PID, table[row_count]);
1815 if (row_size) *row_size = sizeof(MIB_TCPROW_OWNER_PID);
1816 break;
1818 case TCP_TABLE_OWNER_MODULE_LISTENER:
1819 case TCP_TABLE_OWNER_MODULE_CONNECTIONS:
1820 case TCP_TABLE_OWNER_MODULE_ALL:
1822 table_size = FIELD_OFFSET(MIB_TCPTABLE_OWNER_MODULE, table[row_count]);
1823 if (row_size) *row_size = sizeof(MIB_TCPROW_OWNER_MODULE);
1824 break;
1826 default:
1827 ERR("unhandled class %u\n", class);
1828 return 0;
1830 return table_size;
1833 /* Why not a lookup table? Because the TCPS_* constants are different
1834 on different platforms */
1835 static inline MIB_TCP_STATE TCPStateToMIBState (int state)
1837 switch (state)
1839 case TCPS_ESTABLISHED: return MIB_TCP_STATE_ESTAB;
1840 case TCPS_SYN_SENT: return MIB_TCP_STATE_SYN_SENT;
1841 case TCPS_SYN_RECEIVED: return MIB_TCP_STATE_SYN_RCVD;
1842 case TCPS_FIN_WAIT_1: return MIB_TCP_STATE_FIN_WAIT1;
1843 case TCPS_FIN_WAIT_2: return MIB_TCP_STATE_FIN_WAIT2;
1844 case TCPS_TIME_WAIT: return MIB_TCP_STATE_TIME_WAIT;
1845 case TCPS_CLOSE_WAIT: return MIB_TCP_STATE_CLOSE_WAIT;
1846 case TCPS_LAST_ACK: return MIB_TCP_STATE_LAST_ACK;
1847 case TCPS_LISTEN: return MIB_TCP_STATE_LISTEN;
1848 case TCPS_CLOSING: return MIB_TCP_STATE_CLOSING;
1849 default:
1850 case TCPS_CLOSED: return MIB_TCP_STATE_CLOSED;
1854 static int compare_tcp_rows(const void *a, const void *b)
1856 const MIB_TCPROW *rowA = a;
1857 const MIB_TCPROW *rowB = b;
1858 int ret;
1860 if ((ret = ntohl (rowA->dwLocalAddr) - ntohl (rowB->dwLocalAddr)) != 0) return ret;
1861 if ((ret = ntohs ((unsigned short)rowA->dwLocalPort) -
1862 ntohs ((unsigned short)rowB->dwLocalPort)) != 0) return ret;
1863 if ((ret = ntohl (rowA->dwRemoteAddr) - ntohl (rowB->dwRemoteAddr)) != 0) return ret;
1864 return ntohs ((unsigned short)rowA->dwRemotePort) - ntohs ((unsigned short)rowB->dwRemotePort);
1867 struct pid_map
1869 unsigned int pid;
1870 unsigned int unix_pid;
1873 static struct pid_map *get_pid_map( unsigned int *num_entries )
1875 HANDLE snapshot = NULL;
1876 struct pid_map *map;
1877 unsigned int i = 0, count = 16, size = count * sizeof(*map);
1878 NTSTATUS ret;
1880 if (!(map = HeapAlloc( GetProcessHeap(), 0, size ))) return NULL;
1882 SERVER_START_REQ( create_snapshot )
1884 req->flags = SNAP_PROCESS;
1885 req->attributes = 0;
1886 if (!(ret = wine_server_call( req )))
1887 snapshot = wine_server_ptr_handle( reply->handle );
1889 SERVER_END_REQ;
1891 *num_entries = 0;
1892 while (ret == STATUS_SUCCESS)
1894 SERVER_START_REQ( next_process )
1896 req->handle = wine_server_obj_handle( snapshot );
1897 req->reset = (i == 0);
1898 if (!(ret = wine_server_call( req )))
1900 if (i >= count)
1902 struct pid_map *new_map;
1903 count *= 2;
1904 size = count * sizeof(*new_map);
1906 if (!(new_map = HeapReAlloc( GetProcessHeap(), 0, map, size )))
1908 HeapFree( GetProcessHeap(), 0, map );
1909 map = NULL;
1910 goto done;
1912 map = new_map;
1914 map[i].pid = reply->pid;
1915 map[i].unix_pid = reply->unix_pid;
1916 (*num_entries)++;
1917 i++;
1920 SERVER_END_REQ;
1923 done:
1924 NtClose( snapshot );
1925 return map;
1928 static unsigned int find_owning_pid( struct pid_map *map, unsigned int num_entries, UINT_PTR inode )
1930 #ifdef __linux__
1931 unsigned int i, len_socket;
1932 char socket[32];
1934 sprintf( socket, "socket:[%lu]", inode );
1935 len_socket = strlen( socket );
1936 for (i = 0; i < num_entries; i++)
1938 char dir[32];
1939 struct dirent *dirent;
1940 DIR *dirfd;
1942 sprintf( dir, "/proc/%u/fd", map[i].unix_pid );
1943 if ((dirfd = opendir( dir )))
1945 while ((dirent = readdir( dirfd )))
1947 char link[sizeof(dirent->d_name) + 32], name[32];
1948 int len;
1950 sprintf( link, "/proc/%u/fd/%s", map[i].unix_pid, dirent->d_name );
1951 if ((len = readlink( link, name, sizeof(name) - 1 )) > 0) name[len] = 0;
1952 if (len == len_socket && !strcmp( socket, name ))
1954 closedir( dirfd );
1955 return map[i].pid;
1958 closedir( dirfd );
1961 return 0;
1962 #elif defined(HAVE_LIBPROCSTAT)
1963 struct procstat *pstat;
1964 struct kinfo_proc *proc;
1965 struct filestat_list *fds;
1966 struct filestat *fd;
1967 struct sockstat sock;
1968 unsigned int i, proc_count;
1970 pstat = procstat_open_sysctl();
1971 if (!pstat) return 0;
1973 for (i = 0; i < num_entries; i++)
1975 proc = procstat_getprocs( pstat, KERN_PROC_PID, map[i].unix_pid, &proc_count );
1976 if (!proc || proc_count < 1) continue;
1978 fds = procstat_getfiles( pstat, proc, 0 );
1979 if (!fds)
1981 procstat_freeprocs( pstat, proc );
1982 continue;
1985 STAILQ_FOREACH( fd, fds, next )
1987 char errbuf[_POSIX2_LINE_MAX];
1989 if (fd->fs_type != PS_FST_TYPE_SOCKET) continue;
1991 procstat_get_socket_info( pstat, fd, &sock, errbuf );
1993 if (sock.so_pcb == inode)
1995 procstat_freefiles( pstat, fds );
1996 procstat_freeprocs( pstat, proc );
1997 procstat_close( pstat );
1998 return map[i].pid;
2002 procstat_freefiles( pstat, fds );
2003 procstat_freeprocs( pstat, proc );
2006 procstat_close( pstat );
2007 return 0;
2008 #elif defined(HAVE_PROC_PIDINFO)
2009 struct proc_fdinfo *fds;
2010 struct socket_fdinfo sock;
2011 unsigned int i, j, n;
2013 for (i = 0; i < num_entries; i++)
2015 int fd_len = proc_pidinfo( map[i].unix_pid, PROC_PIDLISTFDS, 0, NULL, 0 );
2016 if (fd_len <= 0) continue;
2018 fds = HeapAlloc( GetProcessHeap(), 0, fd_len );
2019 if (!fds) continue;
2021 proc_pidinfo( map[i].unix_pid, PROC_PIDLISTFDS, 0, fds, fd_len );
2022 n = fd_len / sizeof(struct proc_fdinfo);
2023 for (j = 0; j < n; j++)
2025 if (fds[j].proc_fdtype != PROX_FDTYPE_SOCKET) continue;
2027 proc_pidfdinfo( map[i].unix_pid, fds[j].proc_fd, PROC_PIDFDSOCKETINFO, &sock, sizeof(sock) );
2028 if (sock.psi.soi_pcb == inode)
2030 HeapFree( GetProcessHeap(), 0, fds );
2031 return map[i].pid;
2035 HeapFree( GetProcessHeap(), 0, fds );
2037 return 0;
2038 #else
2039 FIXME( "not implemented\n" );
2040 return 0;
2041 #endif
2044 static BOOL match_class( TCP_TABLE_CLASS class, MIB_TCP_STATE state )
2046 switch (class)
2048 case TCP_TABLE_BASIC_ALL:
2049 case TCP_TABLE_OWNER_PID_ALL:
2050 case TCP_TABLE_OWNER_MODULE_ALL:
2051 return TRUE;
2053 case TCP_TABLE_BASIC_LISTENER:
2054 case TCP_TABLE_OWNER_PID_LISTENER:
2055 case TCP_TABLE_OWNER_MODULE_LISTENER:
2056 if (state == MIB_TCP_STATE_LISTEN) return TRUE;
2057 return FALSE;
2059 case TCP_TABLE_BASIC_CONNECTIONS:
2060 case TCP_TABLE_OWNER_PID_CONNECTIONS:
2061 case TCP_TABLE_OWNER_MODULE_CONNECTIONS:
2062 if (state == MIB_TCP_STATE_ESTAB) return TRUE;
2063 return FALSE;
2065 default:
2066 ERR( "unhandled class %u\n", class );
2067 return FALSE;
2071 DWORD build_tcp_table( TCP_TABLE_CLASS class, void **tablep, BOOL order, HANDLE heap, DWORD flags,
2072 DWORD *size )
2074 MIB_TCPTABLE *table;
2075 MIB_TCPROW_OWNER_MODULE row;
2076 DWORD ret = NO_ERROR, count = 16, table_size, row_size;
2078 if (!(table_size = get_tcp_table_sizes( class, count, &row_size )))
2079 return ERROR_INVALID_PARAMETER;
2081 if (!(table = HeapAlloc( heap, flags, table_size )))
2082 return ERROR_OUTOFMEMORY;
2084 table->dwNumEntries = 0;
2086 #ifdef __linux__
2088 FILE *fp;
2090 if ((fp = fopen("/proc/net/tcp", "r")))
2092 char buf[512], *ptr;
2093 struct pid_map *map = NULL;
2094 unsigned int num_entries = 0;
2095 int inode;
2097 if (class >= TCP_TABLE_OWNER_PID_LISTENER) map = get_pid_map( &num_entries );
2099 /* skip header line */
2100 ptr = fgets(buf, sizeof(buf), fp);
2101 while ((ptr = fgets(buf, sizeof(buf), fp)))
2103 if (sscanf( ptr, "%*x: %x:%x %x:%x %x %*s %*s %*s %*s %*s %d",
2104 &row.dwLocalAddr, &row.dwLocalPort, &row.dwRemoteAddr,
2105 &row.dwRemotePort, &row.dwState, &inode ) != 6)
2106 continue;
2107 row.dwLocalPort = htons( row.dwLocalPort );
2108 row.dwRemotePort = htons( row.dwRemotePort );
2109 row.dwState = TCPStateToMIBState( row.dwState );
2110 if (!match_class( class, row.dwState )) continue;
2112 if (class >= TCP_TABLE_OWNER_PID_LISTENER)
2113 row.dwOwningPid = find_owning_pid( map, num_entries, inode );
2114 if (class >= TCP_TABLE_OWNER_MODULE_LISTENER)
2116 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
2117 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
2119 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, row_size )))
2120 break;
2122 HeapFree( GetProcessHeap(), 0, map );
2123 fclose( fp );
2125 else ret = ERROR_NOT_SUPPORTED;
2127 #elif defined(HAVE_SYS_TIHDR_H) && defined(T_OPTMGMT_ACK)
2129 void *data;
2130 int fd, len;
2131 mib2_tcpConnEntry_t *entry;
2133 if ((fd = open_streams_mib( "tcp" )) != -1)
2135 if ((data = read_mib_entry( fd, MIB2_TCP, MIB2_TCP_CONN, &len )))
2137 for (entry = data; (char *)(entry + 1) <= (char *)data + len; entry++)
2139 row.dwLocalAddr = entry->tcpConnLocalAddress;
2140 row.dwLocalPort = htons( entry->tcpConnLocalPort );
2141 row.dwRemoteAddr = entry->tcpConnRemAddress;
2142 row.dwRemotePort = htons( entry->tcpConnRemPort );
2143 row.dwState = entry->tcpConnState;
2144 if (!match_class( class, row.dwState )) continue;
2145 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, row_size )))
2146 break;
2148 HeapFree( GetProcessHeap(), 0, data );
2150 close( fd );
2152 else ret = ERROR_NOT_SUPPORTED;
2154 #elif defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_STRUCT_XINPGEN)
2156 size_t Len = 0;
2157 char *Buf = NULL;
2158 struct xinpgen *pXIG, *pOrigXIG;
2159 struct pid_map *pMap = NULL;
2160 unsigned NumEntries;
2162 if (sysctlbyname ("net.inet.tcp.pcblist", NULL, &Len, NULL, 0) < 0)
2164 ERR ("Failure to read net.inet.tcp.pcblist via sysctlbyname!\n");
2165 ret = ERROR_NOT_SUPPORTED;
2166 goto done;
2169 Buf = HeapAlloc (GetProcessHeap (), 0, Len);
2170 if (!Buf)
2172 ret = ERROR_OUTOFMEMORY;
2173 goto done;
2176 if (sysctlbyname ("net.inet.tcp.pcblist", Buf, &Len, NULL, 0) < 0)
2178 ERR ("Failure to read net.inet.tcp.pcblist via sysctlbyname!\n");
2179 ret = ERROR_NOT_SUPPORTED;
2180 goto done;
2183 if (class >= TCP_TABLE_OWNER_PID_LISTENER) pMap = get_pid_map( &NumEntries );
2185 /* Might be nothing here; first entry is just a header it seems */
2186 if (Len <= sizeof (struct xinpgen)) goto done;
2188 pOrigXIG = (struct xinpgen *)Buf;
2189 pXIG = pOrigXIG;
2191 for (pXIG = (struct xinpgen *)((char *)pXIG + pXIG->xig_len);
2192 pXIG->xig_len > sizeof (struct xinpgen);
2193 pXIG = (struct xinpgen *)((char *)pXIG + pXIG->xig_len))
2195 #if __FreeBSD_version >= 1200026
2196 struct xtcpcb *pTCPData = (struct xtcpcb *)pXIG;
2197 struct xinpcb *pINData = &pTCPData->xt_inp;
2198 struct xsocket *pSockData = &pINData->xi_socket;
2199 #else
2200 struct tcpcb *pTCPData = &((struct xtcpcb *)pXIG)->xt_tp;
2201 struct inpcb *pINData = &((struct xtcpcb *)pXIG)->xt_inp;
2202 struct xsocket *pSockData = &((struct xtcpcb *)pXIG)->xt_socket;
2203 #endif
2205 /* Ignore sockets for other protocols */
2206 if (pSockData->xso_protocol != IPPROTO_TCP)
2207 continue;
2209 /* Ignore PCBs that were freed while generating the data */
2210 if (pINData->inp_gencnt > pOrigXIG->xig_gen)
2211 continue;
2213 /* we're only interested in IPv4 addresses */
2214 if (!(pINData->inp_vflag & INP_IPV4) ||
2215 (pINData->inp_vflag & INP_IPV6))
2216 continue;
2218 /* If all 0's, skip it */
2219 if (!pINData->inp_laddr.s_addr &&
2220 !pINData->inp_lport &&
2221 !pINData->inp_faddr.s_addr &&
2222 !pINData->inp_fport)
2223 continue;
2225 /* Fill in structure details */
2226 row.dwLocalAddr = pINData->inp_laddr.s_addr;
2227 row.dwLocalPort = pINData->inp_lport;
2228 row.dwRemoteAddr = pINData->inp_faddr.s_addr;
2229 row.dwRemotePort = pINData->inp_fport;
2230 row.dwState = TCPStateToMIBState (pTCPData->t_state);
2231 if (!match_class( class, row.dwState )) continue;
2232 if (class >= TCP_TABLE_OWNER_PID_LISTENER)
2233 row.dwOwningPid = find_owning_pid( pMap, NumEntries, (UINT_PTR)pSockData->so_pcb );
2234 if (class >= TCP_TABLE_OWNER_MODULE_LISTENER)
2236 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
2237 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
2239 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, row_size )))
2240 break;
2243 done:
2244 HeapFree( GetProcessHeap(), 0, pMap );
2245 HeapFree (GetProcessHeap (), 0, Buf);
2247 #else
2248 FIXME( "not implemented\n" );
2249 ret = ERROR_NOT_SUPPORTED;
2250 #endif
2252 if (!table) return ERROR_OUTOFMEMORY;
2253 if (!ret)
2255 if (order && table->dwNumEntries)
2256 qsort( table->table, table->dwNumEntries, row_size, compare_tcp_rows );
2257 *tablep = table;
2259 else HeapFree( heap, flags, table );
2260 if (size) *size = get_tcp_table_sizes( class, count, NULL );
2261 TRACE( "returning ret %u table %p\n", ret, table );
2262 return ret;
2265 /******************************************************************
2266 * AllocateAndGetTcpTableFromStack (IPHLPAPI.@)
2268 * Get the TCP connection table.
2269 * Like GetTcpTable(), but allocate the returned table from heap.
2271 * PARAMS
2272 * ppTcpTable [Out] pointer into which the MIB_TCPTABLE is
2273 * allocated and returned.
2274 * bOrder [In] whether to sort the table
2275 * heap [In] heap from which the table is allocated
2276 * flags [In] flags to HeapAlloc
2278 * RETURNS
2279 * ERROR_INVALID_PARAMETER if ppTcpTable is NULL, whatever GetTcpTable()
2280 * returns otherwise.
2282 DWORD WINAPI AllocateAndGetTcpTableFromStack( PMIB_TCPTABLE *ppTcpTable, BOOL bOrder,
2283 HANDLE heap, DWORD flags )
2285 TRACE("table %p, bOrder %d, heap %p, flags 0x%08x\n", ppTcpTable, bOrder, heap, flags);
2287 if (!ppTcpTable) return ERROR_INVALID_PARAMETER;
2288 return build_tcp_table( TCP_TABLE_BASIC_ALL, (void **)ppTcpTable, bOrder, heap, flags, NULL );
2291 /******************************************************************
2292 * AllocateAndGetTcpExTableFromStack (IPHLPAPI.@)
2294 * Get the TCP connection table.
2295 * Like GetTcpTable(), but allocate the returned table from heap.
2297 * PARAMS
2298 * ppTcpTable [Out] pointer into which the MIB_TCPTABLE_EX is
2299 * allocated and returned.
2300 * bOrder [In] whether to sort the table
2301 * heap [In] heap from which the table is allocated
2302 * flags [In] flags to HeapAlloc
2303 * family [In] address family [AF_INET|AF_INET6]
2305 * RETURNS
2306 * ERROR_INVALID_PARAMETER if ppTcpTable is NULL, whatever GetTcpTable()
2307 * returns otherwise.
2309 DWORD WINAPI AllocateAndGetTcpExTableFromStack( VOID **ppTcpTable, BOOL bOrder,
2310 HANDLE heap, DWORD flags, DWORD family )
2312 TRACE("table %p, bOrder %d, heap %p, flags 0x%08x, family %u\n",
2313 ppTcpTable, bOrder, heap, flags, family);
2315 if (!ppTcpTable || !family)
2316 return ERROR_INVALID_PARAMETER;
2318 if (family != WS_AF_INET)
2320 FIXME( "family = %u not supported\n", family );
2321 return ERROR_NOT_SUPPORTED;
2324 return build_tcp_table( TCP_TABLE_OWNER_PID_ALL, ppTcpTable, bOrder, heap, flags, NULL );
2327 static DWORD get_udp_table_sizes( UDP_TABLE_CLASS class, DWORD row_count, DWORD *row_size )
2329 DWORD table_size;
2331 switch (class)
2333 case UDP_TABLE_BASIC:
2335 table_size = FIELD_OFFSET(MIB_UDPTABLE, table[row_count]);
2336 if (row_size) *row_size = sizeof(MIB_UDPROW);
2337 break;
2339 case UDP_TABLE_OWNER_PID:
2341 table_size = FIELD_OFFSET(MIB_UDPTABLE_OWNER_PID, table[row_count]);
2342 if (row_size) *row_size = sizeof(MIB_UDPROW_OWNER_PID);
2343 break;
2345 case UDP_TABLE_OWNER_MODULE:
2347 table_size = FIELD_OFFSET(MIB_UDPTABLE_OWNER_MODULE, table[row_count]);
2348 if (row_size) *row_size = sizeof(MIB_UDPROW_OWNER_MODULE);
2349 break;
2351 default:
2352 ERR("unhandled class %u\n", class);
2353 return 0;
2355 return table_size;
2358 static int compare_udp_rows(const void *a, const void *b)
2360 const MIB_UDPROW *rowA = a;
2361 const MIB_UDPROW *rowB = b;
2362 int ret;
2364 if ((ret = rowA->dwLocalAddr - rowB->dwLocalAddr) != 0) return ret;
2365 return rowA->dwLocalPort - rowB->dwLocalPort;
2368 DWORD build_udp_table( UDP_TABLE_CLASS class, void **tablep, BOOL order, HANDLE heap, DWORD flags,
2369 DWORD *size )
2371 MIB_UDPTABLE *table;
2372 MIB_UDPROW_OWNER_MODULE row;
2373 DWORD ret = NO_ERROR, count = 16, table_size, row_size;
2375 if (!(table_size = get_udp_table_sizes( class, count, &row_size )))
2376 return ERROR_INVALID_PARAMETER;
2378 if (!(table = HeapAlloc( heap, flags, table_size )))
2379 return ERROR_OUTOFMEMORY;
2381 table->dwNumEntries = 0;
2382 memset( &row, 0, sizeof(row) );
2384 #ifdef __linux__
2386 FILE *fp;
2388 if ((fp = fopen( "/proc/net/udp", "r" )))
2390 char buf[512], *ptr;
2391 struct pid_map *map = NULL;
2392 unsigned int num_entries = 0;
2393 int inode;
2395 if (class >= UDP_TABLE_OWNER_PID) map = get_pid_map( &num_entries );
2397 /* skip header line */
2398 ptr = fgets( buf, sizeof(buf), fp );
2399 while ((ptr = fgets( buf, sizeof(buf), fp )))
2401 if (sscanf( ptr, "%*u: %x:%x %*s %*s %*s %*s %*s %*s %*s %d",
2402 &row.dwLocalAddr, &row.dwLocalPort, &inode ) != 3)
2403 continue;
2404 row.dwLocalPort = htons( row.dwLocalPort );
2406 if (class >= UDP_TABLE_OWNER_PID)
2407 row.dwOwningPid = find_owning_pid( map, num_entries, inode );
2408 if (class >= UDP_TABLE_OWNER_MODULE)
2410 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
2411 row.u.dwFlags = 0;
2412 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
2414 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, row_size )))
2415 break;
2417 HeapFree( GetProcessHeap(), 0, map );
2418 fclose( fp );
2420 else ret = ERROR_NOT_SUPPORTED;
2422 #elif defined(HAVE_SYS_TIHDR_H) && defined(T_OPTMGMT_ACK)
2424 void *data;
2425 int fd, len;
2426 mib2_udpEntry_t *entry;
2428 if ((fd = open_streams_mib( "udp" )) != -1)
2430 if ((data = read_mib_entry( fd, MIB2_UDP, MIB2_UDP_ENTRY, &len )))
2432 for (entry = data; (char *)(entry + 1) <= (char *)data + len; entry++)
2434 row.dwLocalAddr = entry->udpLocalAddress;
2435 row.dwLocalPort = htons( entry->udpLocalPort );
2436 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, row_size )))
2437 break;
2439 HeapFree( GetProcessHeap(), 0, data );
2441 close( fd );
2443 else ret = ERROR_NOT_SUPPORTED;
2445 #elif defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_STRUCT_XINPGEN)
2447 size_t Len = 0;
2448 char *Buf = NULL;
2449 struct xinpgen *pXIG, *pOrigXIG;
2450 struct pid_map *pMap = NULL;
2451 unsigned NumEntries;
2453 if (sysctlbyname ("net.inet.udp.pcblist", NULL, &Len, NULL, 0) < 0)
2455 ERR ("Failure to read net.inet.udp.pcblist via sysctlbyname!\n");
2456 ret = ERROR_NOT_SUPPORTED;
2457 goto done;
2460 Buf = HeapAlloc (GetProcessHeap (), 0, Len);
2461 if (!Buf)
2463 ret = ERROR_OUTOFMEMORY;
2464 goto done;
2467 if (sysctlbyname ("net.inet.udp.pcblist", Buf, &Len, NULL, 0) < 0)
2469 ERR ("Failure to read net.inet.udp.pcblist via sysctlbyname!\n");
2470 ret = ERROR_NOT_SUPPORTED;
2471 goto done;
2474 if (class >= UDP_TABLE_OWNER_PID)
2475 pMap = get_pid_map( &NumEntries );
2477 /* Might be nothing here; first entry is just a header it seems */
2478 if (Len <= sizeof (struct xinpgen)) goto done;
2480 pOrigXIG = (struct xinpgen *)Buf;
2481 pXIG = pOrigXIG;
2483 for (pXIG = (struct xinpgen *)((char *)pXIG + pXIG->xig_len);
2484 pXIG->xig_len > sizeof (struct xinpgen);
2485 pXIG = (struct xinpgen *)((char *)pXIG + pXIG->xig_len))
2487 #if __FreeBSD_version >= 1200026
2488 struct xinpcb *pINData = (struct xinpcb *)pXIG;
2489 struct xsocket *pSockData = &pINData->xi_socket;
2490 #else
2491 struct inpcb *pINData = &((struct xinpcb *)pXIG)->xi_inp;
2492 struct xsocket *pSockData = &((struct xinpcb *)pXIG)->xi_socket;
2493 #endif
2495 /* Ignore sockets for other protocols */
2496 if (pSockData->xso_protocol != IPPROTO_UDP)
2497 continue;
2499 /* Ignore PCBs that were freed while generating the data */
2500 if (pINData->inp_gencnt > pOrigXIG->xig_gen)
2501 continue;
2503 /* we're only interested in IPv4 addresses */
2504 if (!(pINData->inp_vflag & INP_IPV4) ||
2505 (pINData->inp_vflag & INP_IPV6))
2506 continue;
2508 /* If all 0's, skip it */
2509 if (!pINData->inp_laddr.s_addr &&
2510 !pINData->inp_lport)
2511 continue;
2513 /* Fill in structure details */
2514 row.dwLocalAddr = pINData->inp_laddr.s_addr;
2515 row.dwLocalPort = pINData->inp_lport;
2516 if (class >= UDP_TABLE_OWNER_PID)
2517 row.dwOwningPid = find_owning_pid( pMap, NumEntries, (UINT_PTR)pSockData->so_pcb );
2518 if (class >= UDP_TABLE_OWNER_MODULE)
2520 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
2521 row.u.dwFlags = 0;
2522 row.u.SpecificPortBind = !(pINData->inp_flags & INP_ANONPORT);
2523 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
2525 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, row_size )))
2526 break;
2529 done:
2530 HeapFree( GetProcessHeap(), 0, pMap );
2531 HeapFree (GetProcessHeap (), 0, Buf);
2533 #else
2534 FIXME( "not implemented\n" );
2535 ret = ERROR_NOT_SUPPORTED;
2536 #endif
2538 if (!table) return ERROR_OUTOFMEMORY;
2539 if (!ret)
2541 if (order && table->dwNumEntries)
2542 qsort( table->table, table->dwNumEntries, row_size, compare_udp_rows );
2543 *tablep = table;
2545 else HeapFree( heap, flags, table );
2546 if (size) *size = get_udp_table_sizes( class, count, NULL );
2547 TRACE( "returning ret %u table %p\n", ret, table );
2548 return ret;
2551 static DWORD get_tcp6_table_sizes( TCP_TABLE_CLASS class, DWORD row_count, DWORD *row_size )
2553 DWORD table_size;
2555 switch (class)
2557 case TCP_TABLE_BASIC_LISTENER:
2558 case TCP_TABLE_BASIC_CONNECTIONS:
2559 case TCP_TABLE_BASIC_ALL:
2561 table_size = FIELD_OFFSET(MIB_TCP6TABLE, table[row_count]);
2562 if (row_size) *row_size = sizeof(MIB_TCP6ROW);
2563 break;
2565 case TCP_TABLE_OWNER_PID_LISTENER:
2566 case TCP_TABLE_OWNER_PID_CONNECTIONS:
2567 case TCP_TABLE_OWNER_PID_ALL:
2569 table_size = FIELD_OFFSET(MIB_TCP6TABLE_OWNER_PID, table[row_count]);
2570 if (row_size) *row_size = sizeof(MIB_TCP6ROW_OWNER_PID);
2571 break;
2573 case TCP_TABLE_OWNER_MODULE_LISTENER:
2574 case TCP_TABLE_OWNER_MODULE_CONNECTIONS:
2575 case TCP_TABLE_OWNER_MODULE_ALL:
2577 table_size = FIELD_OFFSET(MIB_TCP6TABLE_OWNER_MODULE, table[row_count]);
2578 if (row_size) *row_size = sizeof(MIB_TCP6ROW_OWNER_MODULE);
2579 break;
2581 default:
2582 ERR("unhandled class %u\n", class);
2583 return 0;
2585 return table_size;
2588 static int compare_tcp6_basic_rows(const void *a, const void *b)
2590 const MIB_TCP6ROW *rowA = a;
2591 const MIB_TCP6ROW *rowB = b;
2592 int ret;
2594 if ((ret = memcmp(&rowA->LocalAddr, &rowB->LocalAddr, sizeof(rowA->LocalAddr)) != 0)) return ret;
2595 if ((ret = rowA->dwLocalScopeId - rowB->dwLocalScopeId) != 0) return ret;
2596 if ((ret = rowA->dwLocalPort - rowB->dwLocalPort) != 0) return ret;
2597 if ((ret = memcmp(&rowA->RemoteAddr, &rowB->RemoteAddr, sizeof(rowA->RemoteAddr)) != 0)) return ret;
2598 if ((ret = rowA->dwRemoteScopeId - rowB->dwRemoteScopeId) != 0) return ret;
2599 return rowA->dwRemotePort - rowB->dwRemotePort;
2602 static int compare_tcp6_owner_rows(const void *a, const void *b)
2604 const MIB_TCP6ROW_OWNER_PID *rowA = a;
2605 const MIB_TCP6ROW_OWNER_PID *rowB = b;
2606 int ret;
2608 if ((ret = memcmp(&rowA->ucLocalAddr, &rowB->ucLocalAddr, sizeof(rowA->ucLocalAddr)) != 0)) return ret;
2609 if ((ret = rowA->dwLocalScopeId - rowB->dwLocalScopeId) != 0) return ret;
2610 if ((ret = rowA->dwLocalPort - rowB->dwLocalPort) != 0) return ret;
2611 if ((ret = memcmp(&rowA->ucRemoteAddr, &rowB->ucRemoteAddr, sizeof(rowA->ucRemoteAddr)) != 0)) return ret;
2612 if ((ret = rowA->dwRemoteScopeId - rowB->dwRemoteScopeId) != 0) return ret;
2613 return rowA->dwRemotePort - rowB->dwRemotePort;
2616 static DWORD get_udp6_table_sizes( UDP_TABLE_CLASS class, DWORD row_count, DWORD *row_size )
2618 DWORD table_size;
2620 switch (class)
2622 case UDP_TABLE_BASIC:
2624 table_size = FIELD_OFFSET(MIB_UDP6TABLE, table[row_count]);
2625 if (row_size) *row_size = sizeof(MIB_UDP6ROW);
2626 break;
2628 case UDP_TABLE_OWNER_PID:
2630 table_size = FIELD_OFFSET(MIB_UDP6TABLE_OWNER_PID, table[row_count]);
2631 if (row_size) *row_size = sizeof(MIB_UDP6ROW_OWNER_PID);
2632 break;
2634 case UDP_TABLE_OWNER_MODULE:
2636 table_size = FIELD_OFFSET(MIB_UDP6TABLE_OWNER_MODULE, table[row_count]);
2637 if (row_size) *row_size = sizeof(MIB_UDP6ROW_OWNER_MODULE);
2638 break;
2640 default:
2641 ERR("unhandled class %u\n", class);
2642 return 0;
2644 return table_size;
2647 static int compare_udp6_rows(const void *a, const void *b)
2649 const MIB_UDP6ROW *rowA = a;
2650 const MIB_UDP6ROW *rowB = b;
2651 int ret;
2653 if ((ret = memcmp(&rowA->dwLocalAddr, &rowB->dwLocalAddr, sizeof(rowA->dwLocalAddr)) != 0)) return ret;
2654 if ((ret = rowA->dwLocalScopeId - rowB->dwLocalScopeId) != 0) return ret;
2655 return rowA->dwLocalPort - rowB->dwLocalPort;
2658 #if defined(__linux__) || (defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_STRUCT_XINPGEN))
2659 struct ipv6_addr_scope
2661 IN6_ADDR addr;
2662 DWORD scope;
2665 static struct ipv6_addr_scope *get_ipv6_addr_scope_table(unsigned int *size)
2667 struct ipv6_addr_scope *table = NULL;
2668 unsigned int table_size = 0;
2669 #ifdef __linux__
2670 char buf[512], *ptr;
2671 FILE *fp;
2672 #elif defined(HAVE_GETIFADDRS)
2673 struct ifaddrs *addrs, *cur;
2674 #endif
2676 if (!(table = HeapAlloc( GetProcessHeap(), 0, sizeof(table[0]) )))
2677 return NULL;
2679 #ifdef __linux__
2680 if (!(fp = fopen( "/proc/net/if_inet6", "r" )))
2681 goto failed;
2683 while ((ptr = fgets( buf, sizeof(buf), fp )))
2685 WORD a[8];
2686 DWORD scope;
2687 struct ipv6_addr_scope *new_table;
2688 struct ipv6_addr_scope *entry;
2689 unsigned int i;
2691 if (sscanf( ptr, "%4hx%4hx%4hx%4hx%4hx%4hx%4hx%4hx %*s %*s %x",
2692 &a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7], &scope ) != 9)
2693 continue;
2695 table_size++;
2696 if (!(new_table = HeapReAlloc( GetProcessHeap(), 0, table, table_size * sizeof(table[0]) )))
2698 fclose(fp);
2699 goto failed;
2702 table = new_table;
2703 entry = &table[table_size - 1];
2705 i = 0;
2706 while (i < 8)
2708 entry->addr.u.Word[i] = htons(a[i]);
2709 i++;
2712 entry->scope = htons(scope);
2715 fclose(fp);
2716 #elif defined(HAVE_GETIFADDRS)
2717 if (getifaddrs(&addrs) == -1)
2718 goto failed;
2720 for (cur = addrs; cur; cur = cur->ifa_next)
2722 struct sockaddr_in6 *sin6;
2723 struct ipv6_addr_scope *new_table;
2724 struct ipv6_addr_scope *entry;
2726 if (cur->ifa_addr->sa_family != AF_INET6)
2727 continue;
2729 sin6 = (struct sockaddr_in6 *)cur->ifa_addr;
2731 table_size++;
2732 if (!(new_table = HeapReAlloc( GetProcessHeap(), 0, table, table_size * sizeof(table[0]) )))
2734 freeifaddrs(addrs);
2735 goto failed;
2738 table = new_table;
2739 entry = &table[table_size - 1];
2741 memcpy(&entry->addr, &sin6->sin6_addr, sizeof(entry->addr));
2742 entry->scope = sin6->sin6_scope_id;
2745 freeifaddrs(addrs);
2746 #else
2747 FIXME( "not implemented\n" );
2748 goto failed;
2749 #endif
2751 *size = table_size;
2752 return table;
2754 failed:
2755 HeapFree( GetProcessHeap(), 0, table );
2756 return NULL;
2759 static DWORD find_ipv6_addr_scope(const IN6_ADDR *addr, const struct ipv6_addr_scope *table, unsigned int size)
2761 const BYTE multicast_scope_mask = 0x0F;
2762 const BYTE multicast_scope_shift = 0;
2763 unsigned int i = 0;
2765 if (WS_IN6_IS_ADDR_UNSPECIFIED(addr))
2766 return 0;
2768 if (WS_IN6_IS_ADDR_MULTICAST(addr))
2769 return htons((addr->u.Byte[1] & multicast_scope_mask) >> multicast_scope_shift);
2771 if (!table)
2772 return -1;
2774 while (i < size)
2776 if (memcmp(&table[i].addr, addr, sizeof(table[i].addr)) == 0)
2777 return table[i].scope;
2778 i++;
2781 return -1;
2783 #endif
2785 DWORD build_tcp6_table( TCP_TABLE_CLASS class, void **tablep, BOOL order, HANDLE heap, DWORD flags,
2786 DWORD *size )
2788 MIB_TCP6TABLE *table;
2789 DWORD ret = NO_ERROR, count = 16, table_size, row_size;
2791 if (!(table_size = get_tcp6_table_sizes( class, count, &row_size )))
2792 return ERROR_INVALID_PARAMETER;
2794 if (!(table = HeapAlloc( heap, flags, table_size )))
2795 return ERROR_OUTOFMEMORY;
2797 table->dwNumEntries = 0;
2799 #ifdef __linux__
2801 MIB_TCP6ROW_OWNER_MODULE row;
2802 FILE *fp;
2804 if ((fp = fopen( "/proc/net/tcp6", "r" )))
2806 char buf[512], *ptr;
2807 struct pid_map *map = NULL;
2808 unsigned int num_entries = 0;
2809 struct ipv6_addr_scope *addr_scopes;
2810 unsigned int addr_scopes_size = 0;
2811 int inode;
2813 addr_scopes = get_ipv6_addr_scope_table(&addr_scopes_size);
2815 if (class >= TCP_TABLE_OWNER_PID_LISTENER) map = get_pid_map( &num_entries );
2817 /* skip header line */
2818 ptr = fgets( buf, sizeof(buf), fp );
2819 while ((ptr = fgets( buf, sizeof(buf), fp )))
2821 DWORD *local_addr = (DWORD *)&row.ucLocalAddr;
2822 DWORD *remote_addr = (DWORD *)&row.ucRemoteAddr;
2824 if (sscanf( ptr, "%*u: %8x%8x%8x%8x:%x %8x%8x%8x%8x:%x %x %*s %*s %*s %*s %*s %*s %*s %d",
2825 &local_addr[0], &local_addr[1], &local_addr[2], &local_addr[3], &row.dwLocalPort,
2826 &remote_addr[0], &remote_addr[1], &remote_addr[2], &remote_addr[3], &row.dwRemotePort,
2827 &row.dwState, &inode ) != 12)
2828 continue;
2829 row.dwState = TCPStateToMIBState( row.dwState );
2830 if (!match_class( class, row.dwState )) continue;
2831 row.dwLocalScopeId = find_ipv6_addr_scope((const IN6_ADDR *)&row.ucLocalAddr, addr_scopes, addr_scopes_size);
2832 row.dwLocalPort = htons( row.dwLocalPort );
2833 row.dwRemoteScopeId = find_ipv6_addr_scope((const IN6_ADDR *)&row.ucRemoteAddr, addr_scopes, addr_scopes_size);
2834 row.dwRemotePort = htons( row.dwRemotePort );
2836 if (class <= TCP_TABLE_BASIC_ALL)
2838 /* MIB_TCP6ROW has a different field order */
2839 MIB_TCP6ROW basic_row;
2840 basic_row.State = row.dwState;
2841 memcpy( &basic_row.LocalAddr, &row.ucLocalAddr, sizeof(row.ucLocalAddr) );
2842 basic_row.dwLocalScopeId = row.dwLocalScopeId;
2843 basic_row.dwLocalPort = row.dwLocalPort;
2844 memcpy( &basic_row.RemoteAddr, &row.ucRemoteAddr, sizeof(row.ucRemoteAddr) );
2845 basic_row.dwRemoteScopeId = row.dwRemoteScopeId;
2846 basic_row.dwRemotePort = row.dwRemotePort;
2847 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &basic_row, row_size )))
2848 break;
2849 continue;
2852 row.dwOwningPid = find_owning_pid( map, num_entries, inode );
2853 if (class >= TCP_TABLE_OWNER_MODULE_LISTENER)
2855 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
2856 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
2858 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, row_size )))
2859 break;
2861 HeapFree( GetProcessHeap(), 0, map );
2862 HeapFree( GetProcessHeap(), 0, addr_scopes );
2863 fclose( fp );
2865 else ret = ERROR_NOT_SUPPORTED;
2867 #elif defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_STRUCT_XINPGEN)
2869 static const char zero[sizeof(IN6_ADDR)] = {0};
2871 MIB_TCP6ROW_OWNER_MODULE row;
2872 size_t len = 0;
2873 char *buf = NULL;
2874 struct xinpgen *xig, *orig_xig;
2875 struct pid_map *map = NULL;
2876 unsigned num_entries;
2877 struct ipv6_addr_scope *addr_scopes = NULL;
2878 unsigned int addr_scopes_size = 0;
2880 if (sysctlbyname( "net.inet.tcp.pcblist", NULL, &len, NULL, 0 ) < 0)
2882 ERR( "Failure to read net.inet.tcp.pcblist via sysctlbyname!\n" );
2883 ret = ERROR_NOT_SUPPORTED;
2884 goto done;
2887 buf = HeapAlloc( GetProcessHeap(), 0, len );
2888 if (!buf)
2890 ret = ERROR_OUTOFMEMORY;
2891 goto done;
2894 if (sysctlbyname( "net.inet.tcp.pcblist", buf, &len, NULL, 0 ) < 0)
2896 ERR( "Failure to read net.inet.tcp.pcblist via sysctlbyname!\n" );
2897 ret = ERROR_NOT_SUPPORTED;
2898 goto done;
2901 addr_scopes = get_ipv6_addr_scope_table( &addr_scopes_size );
2902 if (!addr_scopes)
2904 ret = ERROR_OUTOFMEMORY;
2905 goto done;
2908 if (class >= TCP_TABLE_OWNER_PID_LISTENER) map = get_pid_map( &num_entries );
2910 /* Might be nothing here; first entry is just a header it seems */
2911 if (len <= sizeof (struct xinpgen)) goto done;
2913 orig_xig = (struct xinpgen *)buf;
2914 xig = orig_xig;
2916 for (xig = (struct xinpgen *)((char *)xig + xig->xig_len);
2917 xig->xig_len > sizeof (struct xinpgen);
2918 xig = (struct xinpgen *)((char *)xig + xig->xig_len))
2920 #if __FreeBSD_version >= 1200026
2921 struct xtcpcb *tcp = (struct xtcpcb *)xig;
2922 struct xinpcb *in = &tcp->xt_inp;
2923 struct xsocket *sock = &in->xi_socket;
2924 #else
2925 struct tcpcb *tcp = &((struct xtcpcb *)xig)->xt_tp;
2926 struct inpcb *in = &((struct xtcpcb *)xig)->xt_inp;
2927 struct xsocket *sock = &((struct xtcpcb *)xig)->xt_socket;
2928 #endif
2930 /* Ignore sockets for other protocols */
2931 if (sock->xso_protocol != IPPROTO_TCP)
2932 continue;
2934 /* Ignore PCBs that were freed while generating the data */
2935 if (in->inp_gencnt > orig_xig->xig_gen)
2936 continue;
2938 /* we're only interested in IPv6 addresses */
2939 if (!(in->inp_vflag & INP_IPV6) ||
2940 (in->inp_vflag & INP_IPV4))
2941 continue;
2943 /* If all 0's, skip it */
2944 if (!memcmp( &in->in6p_laddr, zero, sizeof(zero) ) && !in->inp_lport &&
2945 !memcmp( &in->in6p_faddr, zero, sizeof(zero) ) && !in->inp_fport)
2946 continue;
2948 /* Fill in structure details */
2949 memcpy( &row.ucLocalAddr, &in->in6p_laddr.s6_addr, sizeof(row.ucLocalAddr) );
2950 row.dwLocalPort = in->inp_lport;
2951 row.dwLocalScopeId = find_ipv6_addr_scope( (const IN6_ADDR *)&row.ucLocalAddr, addr_scopes, addr_scopes_size );
2952 memcpy( &row.ucRemoteAddr, &in->in6p_faddr.s6_addr, sizeof(row.ucRemoteAddr) );
2953 row.dwRemotePort = in->inp_fport;
2954 row.dwLocalScopeId = find_ipv6_addr_scope( (const IN6_ADDR *)&row.ucRemoteAddr, addr_scopes, addr_scopes_size );
2955 row.dwState = TCPStateToMIBState( tcp->t_state );
2956 if (!match_class( class, row.dwState )) continue;
2958 if (class <= TCP_TABLE_BASIC_ALL)
2960 /* MIB_TCP6ROW has a different field order */
2961 MIB_TCP6ROW basic_row;
2962 basic_row.State = row.dwState;
2963 memcpy( &basic_row.LocalAddr, &row.ucLocalAddr, sizeof(row.ucLocalAddr) );
2964 basic_row.dwLocalScopeId = row.dwLocalScopeId;
2965 basic_row.dwLocalPort = row.dwLocalPort;
2966 memcpy( &basic_row.RemoteAddr, &row.ucRemoteAddr, sizeof(row.ucRemoteAddr) );
2967 basic_row.dwRemoteScopeId = row.dwRemoteScopeId;
2968 basic_row.dwRemotePort = row.dwRemotePort;
2969 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &basic_row, row_size )))
2970 break;
2971 continue;
2974 row.dwOwningPid = find_owning_pid( map, num_entries, (UINT_PTR)sock->so_pcb );
2975 if (class >= TCP_TABLE_OWNER_MODULE_LISTENER)
2977 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
2978 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
2980 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, row_size )))
2981 break;
2984 done:
2985 HeapFree( GetProcessHeap(), 0, map );
2986 HeapFree( GetProcessHeap(), 0, buf );
2987 HeapFree( GetProcessHeap(), 0, addr_scopes );
2989 #else
2990 FIXME( "not implemented\n" );
2991 ret = ERROR_NOT_SUPPORTED;
2992 #endif
2994 if (!table) return ERROR_OUTOFMEMORY;
2995 if (!ret)
2997 if (order && table->dwNumEntries)
2999 qsort( table->table, table->dwNumEntries, row_size,
3000 class <= TCP_TABLE_BASIC_ALL ? compare_tcp6_basic_rows : compare_tcp6_owner_rows );
3002 *tablep = table;
3004 else HeapFree( heap, flags, table );
3005 if (size) *size = get_tcp6_table_sizes( class, count, NULL );
3006 TRACE( "returning ret %u table %p\n", ret, table );
3007 return ret;
3010 DWORD build_udp6_table( UDP_TABLE_CLASS class, void **tablep, BOOL order, HANDLE heap, DWORD flags,
3011 DWORD *size )
3013 MIB_UDP6TABLE *table;
3014 MIB_UDP6ROW_OWNER_MODULE row;
3015 DWORD ret = NO_ERROR, count = 16, table_size, row_size;
3017 if (!(table_size = get_udp6_table_sizes( class, count, &row_size )))
3018 return ERROR_INVALID_PARAMETER;
3020 if (!(table = HeapAlloc( heap, flags, table_size )))
3021 return ERROR_OUTOFMEMORY;
3023 table->dwNumEntries = 0;
3024 memset( &row, 0, sizeof(row) );
3026 #ifdef __linux__
3028 FILE *fp;
3030 if ((fp = fopen( "/proc/net/udp6", "r" )))
3032 char buf[512], *ptr;
3033 struct pid_map *map = NULL;
3034 unsigned int num_entries = 0;
3035 struct ipv6_addr_scope *addr_scopes;
3036 unsigned int addr_scopes_size = 0;
3037 int inode;
3039 addr_scopes = get_ipv6_addr_scope_table(&addr_scopes_size);
3041 if (class >= UDP_TABLE_OWNER_PID) map = get_pid_map( &num_entries );
3043 /* skip header line */
3044 ptr = fgets( buf, sizeof(buf), fp );
3045 while ((ptr = fgets( buf, sizeof(buf), fp )))
3047 DWORD *local_addr = (DWORD *)&row.ucLocalAddr;
3049 if (sscanf( ptr, "%*u: %8x%8x%8x%8x:%x %*s %*s %*s %*s %*s %*s %*s %d",
3050 &local_addr[0], &local_addr[1], &local_addr[2], &local_addr[3],
3051 &row.dwLocalPort, &inode ) != 6)
3052 continue;
3053 row.dwLocalScopeId = find_ipv6_addr_scope((const IN6_ADDR *)&row.ucLocalAddr, addr_scopes, addr_scopes_size);
3054 row.dwLocalPort = htons( row.dwLocalPort );
3056 if (class >= UDP_TABLE_OWNER_PID)
3057 row.dwOwningPid = find_owning_pid( map, num_entries, inode );
3058 if (class >= UDP_TABLE_OWNER_MODULE)
3060 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
3061 row.u.dwFlags = 0;
3062 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
3064 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, row_size )))
3065 break;
3067 HeapFree( GetProcessHeap(), 0, map );
3068 HeapFree( GetProcessHeap(), 0, addr_scopes );
3069 fclose( fp );
3071 else ret = ERROR_NOT_SUPPORTED;
3073 #elif defined(HAVE_SYS_SYSCTL_H) && defined(HAVE_STRUCT_XINPGEN)
3075 static const char zero[sizeof(IN6_ADDR)] = {0};
3077 size_t len = 0;
3078 char *buf = NULL;
3079 struct xinpgen *xig, *orig_xig;
3080 struct pid_map *map = NULL;
3081 unsigned num_entries;
3082 struct ipv6_addr_scope *addr_scopes = NULL;
3083 unsigned int addr_scopes_size = 0;
3085 if (sysctlbyname( "net.inet.udp.pcblist", NULL, &len, NULL, 0 ) < 0)
3087 ERR( "Failure to read net.inet.udp.pcblist via sysctlbyname!\n" );
3088 ret = ERROR_NOT_SUPPORTED;
3089 goto done;
3092 buf = HeapAlloc( GetProcessHeap(), 0, len );
3093 if (!buf)
3095 ret = ERROR_OUTOFMEMORY;
3096 goto done;
3099 if (sysctlbyname( "net.inet.udp.pcblist", buf, &len, NULL, 0 ) < 0)
3101 ERR ("Failure to read net.inet.udp.pcblist via sysctlbyname!\n");
3102 ret = ERROR_NOT_SUPPORTED;
3103 goto done;
3106 addr_scopes = get_ipv6_addr_scope_table( &addr_scopes_size );
3107 if (!addr_scopes)
3109 ret = ERROR_OUTOFMEMORY;
3110 goto done;
3113 if (class >= UDP_TABLE_OWNER_PID) map = get_pid_map( &num_entries );
3115 /* Might be nothing here; first entry is just a header it seems */
3116 if (len <= sizeof (struct xinpgen)) goto done;
3118 orig_xig = (struct xinpgen *)buf;
3119 xig = orig_xig;
3121 for (xig = (struct xinpgen *)((char *)xig + xig->xig_len);
3122 xig->xig_len > sizeof (struct xinpgen);
3123 xig = (struct xinpgen *)((char *)xig + xig->xig_len))
3125 #if __FreeBSD_version >= 1200026
3126 struct xinpcb *in = (struct xinpcb *)xig;
3127 struct xsocket *sock = &in->xi_socket;
3128 #else
3129 struct inpcb *in = &((struct xinpcb *)xig)->xi_inp;
3130 struct xsocket *sock = &((struct xinpcb *)xig)->xi_socket;
3131 #endif
3133 /* Ignore sockets for other protocols */
3134 if (sock->xso_protocol != IPPROTO_UDP)
3135 continue;
3137 /* Ignore PCBs that were freed while generating the data */
3138 if (in->inp_gencnt > orig_xig->xig_gen)
3139 continue;
3141 /* we're only interested in IPv6 addresses */
3142 if (!(in->inp_vflag & INP_IPV6) ||
3143 (in->inp_vflag & INP_IPV4))
3144 continue;
3146 /* If all 0's, skip it */
3147 if (!memcmp( &in->in6p_laddr.s6_addr, zero, sizeof(zero) ) && !in->inp_lport)
3148 continue;
3150 /* Fill in structure details */
3151 memcpy(row.ucLocalAddr, &in->in6p_laddr.s6_addr, sizeof(row.ucLocalAddr));
3152 row.dwLocalPort = in->inp_lport;
3153 row.dwLocalScopeId = find_ipv6_addr_scope((const IN6_ADDR *)&row.ucLocalAddr, addr_scopes, addr_scopes_size);
3154 if (class >= UDP_TABLE_OWNER_PID)
3155 row.dwOwningPid = find_owning_pid( map, num_entries, (UINT_PTR)sock->so_pcb );
3156 if (class >= UDP_TABLE_OWNER_MODULE)
3158 row.liCreateTimestamp.QuadPart = 0; /* FIXME */
3159 row.u.dwFlags = 0;
3160 row.u.SpecificPortBind = !(in->inp_flags & INP_ANONPORT);
3161 memset( &row.OwningModuleInfo, 0, sizeof(row.OwningModuleInfo) );
3163 if (!(table = append_table_row( heap, flags, table, &table_size, &count, &row, row_size )))
3164 break;
3167 done:
3168 HeapFree( GetProcessHeap(), 0, map );
3169 HeapFree( GetProcessHeap(), 0, buf );
3170 HeapFree( GetProcessHeap(), 0, addr_scopes );
3172 #else
3173 FIXME( "not implemented\n" );
3174 ret = ERROR_NOT_SUPPORTED;
3175 #endif
3177 if (!table) return ERROR_OUTOFMEMORY;
3178 if (!ret)
3180 if (order && table->dwNumEntries)
3181 qsort( table->table, table->dwNumEntries, row_size, compare_udp6_rows );
3182 *tablep = table;
3184 else HeapFree( heap, flags, table );
3185 if (size) *size = get_udp6_table_sizes( class, count, NULL );
3186 TRACE( "returning ret %u table %p\n", ret, table );
3187 return ret;
3190 /******************************************************************
3191 * AllocateAndGetUdpTableFromStack (IPHLPAPI.@)
3193 * Get the UDP listener table.
3194 * Like GetUdpTable(), but allocate the returned table from heap.
3196 * PARAMS
3197 * ppUdpTable [Out] pointer into which the MIB_UDPTABLE is
3198 * allocated and returned.
3199 * bOrder [In] whether to sort the table
3200 * heap [In] heap from which the table is allocated
3201 * flags [In] flags to HeapAlloc
3203 * RETURNS
3204 * ERROR_INVALID_PARAMETER if ppUdpTable is NULL, whatever GetUdpTable()
3205 * returns otherwise.
3207 DWORD WINAPI AllocateAndGetUdpTableFromStack(PMIB_UDPTABLE *ppUdpTable, BOOL bOrder,
3208 HANDLE heap, DWORD flags)
3210 TRACE("table %p, bOrder %d, heap %p, flags 0x%08x\n", ppUdpTable, bOrder, heap, flags);
3212 if (!ppUdpTable) return ERROR_INVALID_PARAMETER;
3213 return build_udp_table( UDP_TABLE_BASIC, (void **)ppUdpTable, bOrder, heap, flags, NULL );