iphlpapi: Rename a function and variables to make it clearer they're related to IPv4...
[wine] / dlls / iphlpapi / iphlpapi_main.c
1 /*
2  * iphlpapi dll implementation
3  *
4  * Copyright (C) 2003,2006 Juan Lang
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22
23 #include <stdarg.h>
24 #include <stdlib.h>
25 #include <sys/types.h>
26 #ifdef HAVE_SYS_SOCKET_H
27 #include <sys/socket.h>
28 #endif
29 #ifdef HAVE_NET_IF_H
30 #include <net/if.h>
31 #endif
32 #ifdef HAVE_NETINET_IN_H
33 # include <netinet/in.h>
34 #endif
35 #ifdef HAVE_ARPA_INET_H
36 # include <arpa/inet.h>
37 #endif
38 #ifdef HAVE_ARPA_NAMESER_H
39 # include <arpa/nameser.h>
40 #endif
41 #ifdef HAVE_RESOLV_H
42 # include <resolv.h>
43 #endif
44
45 #define NONAMELESSUNION
46 #define NONAMELESSSTRUCT
47 #include "windef.h"
48 #include "winbase.h"
49 #include "winreg.h"
50 #define USE_WS_PREFIX
51 #include "winsock2.h"
52 #include "iphlpapi.h"
53 #include "ifenum.h"
54 #include "ipstats.h"
55 #include "ipifcons.h"
56
57 #include "wine/debug.h"
58
59 WINE_DEFAULT_DEBUG_CHANNEL(iphlpapi);
60
61 #ifndef IF_NAMESIZE
62 #define IF_NAMESIZE 16
63 #endif
64
65 #ifndef INADDR_NONE
66 #define INADDR_NONE ~0UL
67 #endif
68
69 /* call res_init() just once because of a bug in Mac OS X 10.4 */
70 /* Call once per thread on systems that have per-thread _res. */
71 /* FIXME: should do same fix in dnsapi (or use dnsapi here?) */
72 static void initialise_resolver(void)
73 {
74     if ((_res.options & RES_INIT) == 0)
75         res_init();
76 }
77
78 BOOL WINAPI DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
79 {
80   switch (fdwReason) {
81     case DLL_PROCESS_ATTACH:
82       DisableThreadLibraryCalls( hinstDLL );
83       break;
84
85     case DLL_PROCESS_DETACH:
86       break;
87   }
88   return TRUE;
89 }
90
91 /******************************************************************
92  *    AddIPAddress (IPHLPAPI.@)
93  *
94  * Add an IP address to an adapter.
95  *
96  * PARAMS
97  *  Address     [In]  IP address to add to the adapter
98  *  IpMask      [In]  subnet mask for the IP address
99  *  IfIndex     [In]  adapter index to add the address
100  *  NTEContext  [Out] Net Table Entry (NTE) context for the IP address
101  *  NTEInstance [Out] NTE instance for the IP address
102  *
103  * RETURNS
104  *  Success: NO_ERROR
105  *  Failure: error code from winerror.h
106  *
107  * FIXME
108  *  Stub. Currently returns ERROR_NOT_SUPPORTED.
109  */
110 DWORD WINAPI AddIPAddress(IPAddr Address, IPMask IpMask, DWORD IfIndex, PULONG NTEContext, PULONG NTEInstance)
111 {
112   FIXME(":stub\n");
113   return ERROR_NOT_SUPPORTED;
114 }
115
116
117 /******************************************************************
118  *    AllocateAndGetIfTableFromStack (IPHLPAPI.@)
119  *
120  * Get table of local interfaces.
121  * Like GetIfTable(), but allocate the returned table from heap.
122  *
123  * PARAMS
124  *  ppIfTable [Out] pointer into which the MIB_IFTABLE is
125  *                  allocated and returned.
126  *  bOrder    [In]  whether to sort the table
127  *  heap      [In]  heap from which the table is allocated
128  *  flags     [In]  flags to HeapAlloc
129  *
130  * RETURNS
131  *  ERROR_INVALID_PARAMETER if ppIfTable is NULL, whatever
132  *  GetIfTable() returns otherwise.
133  */
134 DWORD WINAPI AllocateAndGetIfTableFromStack(PMIB_IFTABLE *ppIfTable,
135  BOOL bOrder, HANDLE heap, DWORD flags)
136 {
137   DWORD ret;
138
139   TRACE("ppIfTable %p, bOrder %d, heap %p, flags 0x%08x\n", ppIfTable,
140         bOrder, heap, flags);
141   if (!ppIfTable)
142     ret = ERROR_INVALID_PARAMETER;
143   else {
144     DWORD dwSize = 0;
145
146     ret = GetIfTable(*ppIfTable, &dwSize, bOrder);
147     if (ret == ERROR_INSUFFICIENT_BUFFER) {
148       *ppIfTable = HeapAlloc(heap, flags, dwSize);
149       ret = GetIfTable(*ppIfTable, &dwSize, bOrder);
150     }
151   }
152   TRACE("returning %d\n", ret);
153   return ret;
154 }
155
156
157 static int IpAddrTableSorter(const void *a, const void *b)
158 {
159   int ret;
160
161   if (a && b)
162     ret = ((const MIB_IPADDRROW*)a)->dwAddr - ((const MIB_IPADDRROW*)b)->dwAddr;
163   else
164     ret = 0;
165   return ret;
166 }
167
168
169 /******************************************************************
170  *    AllocateAndGetIpAddrTableFromStack (IPHLPAPI.@)
171  *
172  * Get interface-to-IP address mapping table. 
173  * Like GetIpAddrTable(), but allocate the returned table from heap.
174  *
175  * PARAMS
176  *  ppIpAddrTable [Out] pointer into which the MIB_IPADDRTABLE is
177  *                      allocated and returned.
178  *  bOrder        [In]  whether to sort the table
179  *  heap          [In]  heap from which the table is allocated
180  *  flags         [In]  flags to HeapAlloc
181  *
182  * RETURNS
183  *  ERROR_INVALID_PARAMETER if ppIpAddrTable is NULL, other error codes on
184  *  failure, NO_ERROR on success.
185  */
186 DWORD WINAPI AllocateAndGetIpAddrTableFromStack(PMIB_IPADDRTABLE *ppIpAddrTable,
187  BOOL bOrder, HANDLE heap, DWORD flags)
188 {
189   DWORD ret;
190
191   TRACE("ppIpAddrTable %p, bOrder %d, heap %p, flags 0x%08x\n",
192    ppIpAddrTable, bOrder, heap, flags);
193   ret = getIPAddrTable(ppIpAddrTable, heap, flags);
194   if (!ret && bOrder)
195     qsort((*ppIpAddrTable)->table, (*ppIpAddrTable)->dwNumEntries,
196      sizeof(MIB_IPADDRROW), IpAddrTableSorter);
197   TRACE("returning %d\n", ret);
198   return ret;
199 }
200
201
202 /******************************************************************
203  *    CreateIpForwardEntry (IPHLPAPI.@)
204  *
205  * Create a route in the local computer's IP table.
206  *
207  * PARAMS
208  *  pRoute [In] new route information
209  *
210  * RETURNS
211  *  Success: NO_ERROR
212  *  Failure: error code from winerror.h
213  *
214  * FIXME
215  *  Stub, always returns NO_ERROR.
216  */
217 DWORD WINAPI CreateIpForwardEntry(PMIB_IPFORWARDROW pRoute)
218 {
219   FIXME("(pRoute %p): stub\n", pRoute);
220   /* could use SIOCADDRT, not sure I want to */
221   return 0;
222 }
223
224
225 /******************************************************************
226  *    CreateIpNetEntry (IPHLPAPI.@)
227  *
228  * Create entry in the ARP table.
229  *
230  * PARAMS
231  *  pArpEntry [In] new ARP entry
232  *
233  * RETURNS
234  *  Success: NO_ERROR
235  *  Failure: error code from winerror.h
236  *
237  * FIXME
238  *  Stub, always returns NO_ERROR.
239  */
240 DWORD WINAPI CreateIpNetEntry(PMIB_IPNETROW pArpEntry)
241 {
242   FIXME("(pArpEntry %p)\n", pArpEntry);
243   /* could use SIOCSARP on systems that support it, not sure I want to */
244   return 0;
245 }
246
247
248 /******************************************************************
249  *    CreateProxyArpEntry (IPHLPAPI.@)
250  *
251  * Create a Proxy ARP (PARP) entry for an IP address.
252  *
253  * PARAMS
254  *  dwAddress [In] IP address for which this computer acts as a proxy. 
255  *  dwMask    [In] subnet mask for dwAddress
256  *  dwIfIndex [In] interface index
257  *
258  * RETURNS
259  *  Success: NO_ERROR
260  *  Failure: error code from winerror.h
261  *
262  * FIXME
263  *  Stub, returns ERROR_NOT_SUPPORTED.
264  */
265 DWORD WINAPI CreateProxyArpEntry(DWORD dwAddress, DWORD dwMask, DWORD dwIfIndex)
266 {
267   FIXME("(dwAddress 0x%08x, dwMask 0x%08x, dwIfIndex 0x%08x): stub\n",
268    dwAddress, dwMask, dwIfIndex);
269   return ERROR_NOT_SUPPORTED;
270 }
271
272
273 /******************************************************************
274  *    DeleteIPAddress (IPHLPAPI.@)
275  *
276  * Delete an IP address added with AddIPAddress().
277  *
278  * PARAMS
279  *  NTEContext [In] NTE context from AddIPAddress();
280  *
281  * RETURNS
282  *  Success: NO_ERROR
283  *  Failure: error code from winerror.h
284  *
285  * FIXME
286  *  Stub, returns ERROR_NOT_SUPPORTED.
287  */
288 DWORD WINAPI DeleteIPAddress(ULONG NTEContext)
289 {
290   FIXME("(NTEContext %d): stub\n", NTEContext);
291   return ERROR_NOT_SUPPORTED;
292 }
293
294
295 /******************************************************************
296  *    DeleteIpForwardEntry (IPHLPAPI.@)
297  *
298  * Delete a route.
299  *
300  * PARAMS
301  *  pRoute [In] route to delete
302  *
303  * RETURNS
304  *  Success: NO_ERROR
305  *  Failure: error code from winerror.h
306  *
307  * FIXME
308  *  Stub, returns NO_ERROR.
309  */
310 DWORD WINAPI DeleteIpForwardEntry(PMIB_IPFORWARDROW pRoute)
311 {
312   FIXME("(pRoute %p): stub\n", pRoute);
313   /* could use SIOCDELRT, not sure I want to */
314   return 0;
315 }
316
317
318 /******************************************************************
319  *    DeleteIpNetEntry (IPHLPAPI.@)
320  *
321  * Delete an ARP entry.
322  *
323  * PARAMS
324  *  pArpEntry [In] ARP entry to delete
325  *
326  * RETURNS
327  *  Success: NO_ERROR
328  *  Failure: error code from winerror.h
329  *
330  * FIXME
331  *  Stub, returns NO_ERROR.
332  */
333 DWORD WINAPI DeleteIpNetEntry(PMIB_IPNETROW pArpEntry)
334 {
335   FIXME("(pArpEntry %p): stub\n", pArpEntry);
336   /* could use SIOCDARP on systems that support it, not sure I want to */
337   return 0;
338 }
339
340
341 /******************************************************************
342  *    DeleteProxyArpEntry (IPHLPAPI.@)
343  *
344  * Delete a Proxy ARP entry.
345  *
346  * PARAMS
347  *  dwAddress [In] IP address for which this computer acts as a proxy. 
348  *  dwMask    [In] subnet mask for dwAddress
349  *  dwIfIndex [In] interface index
350  *
351  * RETURNS
352  *  Success: NO_ERROR
353  *  Failure: error code from winerror.h
354  *
355  * FIXME
356  *  Stub, returns ERROR_NOT_SUPPORTED.
357  */
358 DWORD WINAPI DeleteProxyArpEntry(DWORD dwAddress, DWORD dwMask, DWORD dwIfIndex)
359 {
360   FIXME("(dwAddress 0x%08x, dwMask 0x%08x, dwIfIndex 0x%08x): stub\n",
361    dwAddress, dwMask, dwIfIndex);
362   return ERROR_NOT_SUPPORTED;
363 }
364
365
366 /******************************************************************
367  *    EnableRouter (IPHLPAPI.@)
368  *
369  * Turn on ip forwarding.
370  *
371  * PARAMS
372  *  pHandle     [In/Out]
373  *  pOverlapped [In/Out] hEvent member should contain a valid handle.
374  *
375  * RETURNS
376  *  Success: ERROR_IO_PENDING
377  *  Failure: error code from winerror.h
378  *
379  * FIXME
380  *  Stub, returns ERROR_NOT_SUPPORTED.
381  */
382 DWORD WINAPI EnableRouter(HANDLE * pHandle, OVERLAPPED * pOverlapped)
383 {
384   FIXME("(pHandle %p, pOverlapped %p): stub\n", pHandle, pOverlapped);
385   /* could echo "1" > /proc/net/sys/net/ipv4/ip_forward, not sure I want to
386      could map EACCESS to ERROR_ACCESS_DENIED, I suppose
387    */
388   return ERROR_NOT_SUPPORTED;
389 }
390
391
392 /******************************************************************
393  *    FlushIpNetTable (IPHLPAPI.@)
394  *
395  * Delete all ARP entries of an interface
396  *
397  * PARAMS
398  *  dwIfIndex [In] interface index
399  *
400  * RETURNS
401  *  Success: NO_ERROR
402  *  Failure: error code from winerror.h
403  *
404  * FIXME
405  *  Stub, returns ERROR_NOT_SUPPORTED.
406  */
407 DWORD WINAPI FlushIpNetTable(DWORD dwIfIndex)
408 {
409   FIXME("(dwIfIndex 0x%08x): stub\n", dwIfIndex);
410   /* this flushes the arp cache of the given index */
411   return ERROR_NOT_SUPPORTED;
412 }
413
414
415 /******************************************************************
416  *    GetAdapterIndex (IPHLPAPI.@)
417  *
418  * Get interface index from its name.
419  *
420  * PARAMS
421  *  AdapterName [In]  unicode string with the adapter name
422  *  IfIndex     [Out] returns found interface index
423  *
424  * RETURNS
425  *  Success: NO_ERROR
426  *  Failure: error code from winerror.h
427  */
428 DWORD WINAPI GetAdapterIndex(LPWSTR AdapterName, PULONG IfIndex)
429 {
430   char adapterName[MAX_ADAPTER_NAME];
431   unsigned int i;
432   DWORD ret;
433
434   TRACE("(AdapterName %p, IfIndex %p)\n", AdapterName, IfIndex);
435   /* The adapter name is guaranteed not to have any unicode characters, so
436    * this translation is never lossy */
437   for (i = 0; i < sizeof(adapterName) - 1 && AdapterName[i]; i++)
438     adapterName[i] = (char)AdapterName[i];
439   adapterName[i] = '\0';
440   ret = getInterfaceIndexByName(adapterName, IfIndex);
441   TRACE("returning %d\n", ret);
442   return ret;
443 }
444
445
446 /******************************************************************
447  *    GetAdaptersInfo (IPHLPAPI.@)
448  *
449  * Get information about adapters.
450  *
451  * PARAMS
452  *  pAdapterInfo [Out] buffer for adapter infos
453  *  pOutBufLen   [In]  length of output buffer
454  *
455  * RETURNS
456  *  Success: NO_ERROR
457  *  Failure: error code from winerror.h
458  */
459 DWORD WINAPI GetAdaptersInfo(PIP_ADAPTER_INFO pAdapterInfo, PULONG pOutBufLen)
460 {
461   DWORD ret;
462
463   TRACE("pAdapterInfo %p, pOutBufLen %p\n", pAdapterInfo, pOutBufLen);
464   if (!pOutBufLen)
465     ret = ERROR_INVALID_PARAMETER;
466   else {
467     DWORD numNonLoopbackInterfaces = getNumNonLoopbackInterfaces();
468
469     if (numNonLoopbackInterfaces > 0) {
470       DWORD numIPAddresses = getNumIPAddresses();
471       ULONG size;
472
473       /* This may slightly overestimate the amount of space needed, because
474        * the IP addresses include the loopback address, but it's easier
475        * to make sure there's more than enough space than to make sure there's
476        * precisely enough space.
477        */
478       size = sizeof(IP_ADAPTER_INFO) * numNonLoopbackInterfaces;
479       size += numIPAddresses  * sizeof(IP_ADDR_STRING); 
480       if (!pAdapterInfo || *pOutBufLen < size) {
481         *pOutBufLen = size;
482         ret = ERROR_BUFFER_OVERFLOW;
483       }
484       else {
485         InterfaceIndexTable *table = NULL;
486         PMIB_IPADDRTABLE ipAddrTable = NULL;
487         PMIB_IPFORWARDTABLE routeTable = NULL;
488
489         ret = getIPAddrTable(&ipAddrTable, GetProcessHeap(), 0);
490         if (!ret)
491           ret = AllocateAndGetIpForwardTableFromStack(&routeTable, FALSE, GetProcessHeap(), 0);
492         if (!ret)
493           table = getNonLoopbackInterfaceIndexTable();
494         if (table) {
495           size = sizeof(IP_ADAPTER_INFO) * table->numIndexes;
496           size += ipAddrTable->dwNumEntries * sizeof(IP_ADDR_STRING); 
497           if (*pOutBufLen < size) {
498             *pOutBufLen = size;
499             ret = ERROR_INSUFFICIENT_BUFFER;
500           }
501           else {
502             DWORD ndx;
503             HKEY hKey;
504             BOOL winsEnabled = FALSE;
505             IP_ADDRESS_STRING primaryWINS, secondaryWINS;
506             PIP_ADDR_STRING nextIPAddr = (PIP_ADDR_STRING)((LPBYTE)pAdapterInfo
507              + numNonLoopbackInterfaces * sizeof(IP_ADAPTER_INFO));
508
509             memset(pAdapterInfo, 0, size);
510             /* @@ Wine registry key: HKCU\Software\Wine\Network */
511             if (RegOpenKeyA(HKEY_CURRENT_USER, "Software\\Wine\\Network",
512              &hKey) == ERROR_SUCCESS) {
513               DWORD size = sizeof(primaryWINS.String);
514               unsigned long addr;
515
516               RegQueryValueExA(hKey, "WinsServer", NULL, NULL,
517                (LPBYTE)primaryWINS.String, &size);
518               addr = inet_addr(primaryWINS.String);
519               if (addr != INADDR_NONE && addr != INADDR_ANY)
520                 winsEnabled = TRUE;
521               size = sizeof(secondaryWINS.String);
522               RegQueryValueExA(hKey, "BackupWinsServer", NULL, NULL,
523                (LPBYTE)secondaryWINS.String, &size);
524               addr = inet_addr(secondaryWINS.String);
525               if (addr != INADDR_NONE && addr != INADDR_ANY)
526                 winsEnabled = TRUE;
527               RegCloseKey(hKey);
528             }
529             for (ndx = 0; ndx < table->numIndexes; ndx++) {
530               PIP_ADAPTER_INFO ptr = &pAdapterInfo[ndx];
531               DWORD i;
532               PIP_ADDR_STRING currentIPAddr = &ptr->IpAddressList;
533               BOOL firstIPAddr = TRUE;
534
535               /* on Win98 this is left empty, but whatever */
536               getInterfaceNameByIndex(table->indexes[ndx], ptr->AdapterName);
537               getInterfaceNameByIndex(table->indexes[ndx], ptr->Description);
538               ptr->AddressLength = sizeof(ptr->Address);
539               getInterfacePhysicalByIndex(table->indexes[ndx],
540                &ptr->AddressLength, ptr->Address, &ptr->Type);
541               ptr->Index = table->indexes[ndx];
542               for (i = 0; i < ipAddrTable->dwNumEntries; i++) {
543                 if (ipAddrTable->table[i].dwIndex == ptr->Index) {
544                   if (firstIPAddr) {
545                     toIPAddressString(ipAddrTable->table[i].dwAddr,
546                      ptr->IpAddressList.IpAddress.String);
547                     toIPAddressString(ipAddrTable->table[i].dwMask,
548                      ptr->IpAddressList.IpMask.String);
549                     firstIPAddr = FALSE;
550                   }
551                   else {
552                     currentIPAddr->Next = nextIPAddr;
553                     currentIPAddr = nextIPAddr;
554                     toIPAddressString(ipAddrTable->table[i].dwAddr,
555                      currentIPAddr->IpAddress.String);
556                     toIPAddressString(ipAddrTable->table[i].dwMask,
557                      currentIPAddr->IpMask.String);
558                     nextIPAddr++;
559                   }
560                 }
561               }
562               /* Find first router through this interface, which we'll assume
563                * is the default gateway for this adapter */
564               for (i = 0; i < routeTable->dwNumEntries; i++)
565                 if (routeTable->table[i].dwForwardIfIndex == ptr->Index
566                  && routeTable->table[i].dwForwardType ==
567                  MIB_IPROUTE_TYPE_INDIRECT)
568                   toIPAddressString(routeTable->table[i].dwForwardNextHop,
569                    ptr->GatewayList.IpAddress.String);
570               if (winsEnabled) {
571                 ptr->HaveWins = TRUE;
572                 memcpy(ptr->PrimaryWinsServer.IpAddress.String,
573                  primaryWINS.String, sizeof(primaryWINS.String));
574                 memcpy(ptr->SecondaryWinsServer.IpAddress.String,
575                  secondaryWINS.String, sizeof(secondaryWINS.String));
576               }
577               if (ndx < table->numIndexes - 1)
578                 ptr->Next = &pAdapterInfo[ndx + 1];
579               else
580                 ptr->Next = NULL;
581             }
582             ret = NO_ERROR;
583           }
584           HeapFree(GetProcessHeap(), 0, table);
585         }
586         else
587           ret = ERROR_OUTOFMEMORY;
588         HeapFree(GetProcessHeap(), 0, routeTable);
589         HeapFree(GetProcessHeap(), 0, ipAddrTable);
590       }
591     }
592     else
593       ret = ERROR_NO_DATA;
594   }
595   TRACE("returning %d\n", ret);
596   return ret;
597 }
598
599 static DWORD typeFromMibType(DWORD mib_type)
600 {
601     switch (mib_type)
602     {
603     case MIB_IF_TYPE_ETHERNET:  return IF_TYPE_ETHERNET_CSMACD;
604     case MIB_IF_TYPE_TOKENRING: return IF_TYPE_ISO88025_TOKENRING;
605     case MIB_IF_TYPE_PPP:       return IF_TYPE_PPP;
606     case MIB_IF_TYPE_LOOPBACK:  return IF_TYPE_SOFTWARE_LOOPBACK;
607     default:                    return IF_TYPE_OTHER;
608     }
609 }
610
611 static ULONG v4addressesFromIndex(DWORD index, DWORD **addrs, ULONG *num_addrs)
612 {
613     ULONG ret, i, j;
614     MIB_IPADDRTABLE *at;
615
616     *num_addrs = 0;
617     if ((ret = getIPAddrTable(&at, GetProcessHeap(), 0))) return ret;
618     for (i = 0; i < at->dwNumEntries; i++)
619     {
620         if (at->table[i].dwIndex == index) (*num_addrs)++;
621     }
622     if (!(*addrs = HeapAlloc(GetProcessHeap(), 0, *num_addrs * sizeof(DWORD))))
623     {
624         HeapFree(GetProcessHeap(), 0, at);
625         return ERROR_OUTOFMEMORY;
626     }
627     for (i = 0, j = 0; i < at->dwNumEntries; i++)
628     {
629         if (at->table[i].dwIndex == index) (*addrs)[j++] = at->table[i].dwAddr;
630     }
631     HeapFree(GetProcessHeap(), 0, at);
632     return ERROR_SUCCESS;
633 }
634
635 static ULONG adapterAddressesFromIndex(DWORD index, IP_ADAPTER_ADDRESSES *aa, ULONG *size)
636 {
637     ULONG ret, i, num_v4addrs, total_size;
638     DWORD *v4addrs;
639
640     if ((ret = v4addressesFromIndex(index, &v4addrs, &num_v4addrs))) return ret;
641
642     total_size = sizeof(IP_ADAPTER_ADDRESSES);
643     total_size += IF_NAMESIZE;
644     total_size += IF_NAMESIZE * sizeof(WCHAR);
645     total_size += sizeof(IP_ADAPTER_UNICAST_ADDRESS) * num_v4addrs;
646     total_size += sizeof(struct sockaddr_in) * num_v4addrs;
647
648     if (aa && *size >= total_size)
649     {
650         char name[IF_NAMESIZE], *ptr = (char *)aa + sizeof(IP_ADAPTER_ADDRESSES), *src;
651         WCHAR *dst;
652         DWORD buflen, type, status;
653
654         memset(aa, 0, sizeof(IP_ADAPTER_ADDRESSES));
655         aa->u.s.Length  = sizeof(IP_ADAPTER_ADDRESSES);
656         aa->u.s.IfIndex = index;
657
658         getInterfaceNameByIndex(index, name);
659         memcpy(ptr, name, IF_NAMESIZE);
660         aa->AdapterName = ptr;
661         ptr += IF_NAMESIZE;
662         aa->FriendlyName = (WCHAR *)ptr;
663         for (src = name, dst = (WCHAR *)ptr; *src; src++, dst++)
664             *dst = *src;
665         *dst++ = 0;
666         ptr = (char *)dst;
667
668         if (num_v4addrs)
669         {
670             IP_ADAPTER_UNICAST_ADDRESS *ua;
671             struct sockaddr_in *sa;
672
673             ua = aa->FirstUnicastAddress = (IP_ADAPTER_UNICAST_ADDRESS *)ptr;
674             for (i = 0; i < num_v4addrs; i++)
675             {
676                 memset(ua, 0, sizeof(IP_ADAPTER_UNICAST_ADDRESS));
677                 ua->u.s.Length              = sizeof(IP_ADAPTER_UNICAST_ADDRESS);
678                 ua->Address.iSockaddrLength = sizeof(struct sockaddr_in);
679                 ua->Address.lpSockaddr      = (SOCKADDR *)((char *)ua + ua->u.s.Length);
680
681                 sa = (struct sockaddr_in *)ua->Address.lpSockaddr;
682                 sa->sin_family      = AF_INET;
683                 sa->sin_addr.s_addr = v4addrs[i];
684                 sa->sin_port        = 0;
685
686                 ptr += ua->u.s.Length + ua->Address.iSockaddrLength;
687                 if (i < num_v4addrs - 1)
688                 {
689                     ua->Next = (IP_ADAPTER_UNICAST_ADDRESS *)ptr;
690                     ua = ua->Next;
691                 }
692             }
693         }
694
695         buflen = MAX_INTERFACE_PHYSADDR;
696         getInterfacePhysicalByIndex(index, &buflen, aa->PhysicalAddress, &type);
697         aa->PhysicalAddressLength = buflen;
698         aa->IfType = typeFromMibType(type);
699
700         getInterfaceMtuByName(name, &aa->Mtu);
701
702         getInterfaceStatusByName(name, &status);
703         if (status == MIB_IF_OPER_STATUS_OPERATIONAL) aa->OperStatus = IfOperStatusUp;
704         else if (status == MIB_IF_OPER_STATUS_NON_OPERATIONAL) aa->OperStatus = IfOperStatusDown;
705         else aa->OperStatus = IfOperStatusUnknown;
706     }
707     *size = total_size;
708     HeapFree(GetProcessHeap(), 0, v4addrs);
709     return ERROR_SUCCESS;
710 }
711
712 ULONG WINAPI GetAdaptersAddresses(ULONG family, ULONG flags, PVOID reserved,
713                                   PIP_ADAPTER_ADDRESSES aa, PULONG buflen)
714 {
715     InterfaceIndexTable *table;
716     ULONG i, size, total_size, ret = ERROR_NO_DATA;
717
718     if (!buflen) return ERROR_INVALID_PARAMETER;
719
720     if (family == AF_INET6 || family == AF_UNSPEC)
721         FIXME("no support for IPv6 addresses\n");
722
723     if (family != AF_INET && family != AF_UNSPEC) return ERROR_NO_DATA;
724
725     table = getInterfaceIndexTable();
726     if (!table || !table->numIndexes)
727     {
728         HeapFree(GetProcessHeap(), 0, table);
729         return ERROR_NO_DATA;
730     }
731     total_size = 0;
732     for (i = 0; i < table->numIndexes; i++)
733     {
734         size = 0;
735         if ((ret = adapterAddressesFromIndex(table->indexes[i], NULL, &size)))
736         {
737             HeapFree(GetProcessHeap(), 0, table);
738             return ret;
739         }
740         total_size += size;
741     }
742     if (aa && *buflen >= total_size)
743     {
744         ULONG bytes_left = size = total_size;
745         for (i = 0; i < table->numIndexes; i++)
746         {
747             if ((ret = adapterAddressesFromIndex(table->indexes[i], aa, &size)))
748             {
749                 HeapFree(GetProcessHeap(), 0, table);
750                 return ret;
751             }
752             if (i < table->numIndexes - 1)
753             {
754                 aa->Next = (IP_ADAPTER_ADDRESSES *)((char *)aa + size);
755                 aa = aa->Next;
756                 size = bytes_left -= size;
757             }
758         }
759         ret = ERROR_SUCCESS;
760     }
761     if (*buflen < total_size) ret = ERROR_BUFFER_OVERFLOW;
762     *buflen = total_size;
763
764     TRACE("num adapters %u\n", table->numIndexes);
765     HeapFree(GetProcessHeap(), 0, table);
766     return ret;
767 }
768
769 /******************************************************************
770  *    GetBestInterface (IPHLPAPI.@)
771  *
772  * Get the interface, with the best route for the given IP address.
773  *
774  * PARAMS
775  *  dwDestAddr     [In]  IP address to search the interface for
776  *  pdwBestIfIndex [Out] found best interface
777  *
778  * RETURNS
779  *  Success: NO_ERROR
780  *  Failure: error code from winerror.h
781  */
782 DWORD WINAPI GetBestInterface(IPAddr dwDestAddr, PDWORD pdwBestIfIndex)
783 {
784     struct WS_sockaddr_in sa_in;
785     memset(&sa_in, 0, sizeof(sa_in));
786     sa_in.sin_family = AF_INET;
787     sa_in.sin_addr.S_un.S_addr = dwDestAddr;
788     return GetBestInterfaceEx((struct WS_sockaddr *)&sa_in, pdwBestIfIndex);
789 }
790
791 /******************************************************************
792  *    GetBestInterfaceEx (IPHLPAPI.@)
793  *
794  * Get the interface, with the best route for the given IP address.
795  *
796  * PARAMS
797  *  dwDestAddr     [In]  IP address to search the interface for
798  *  pdwBestIfIndex [Out] found best interface
799  *
800  * RETURNS
801  *  Success: NO_ERROR
802  *  Failure: error code from winerror.h
803  */
804 DWORD WINAPI GetBestInterfaceEx(struct WS_sockaddr *pDestAddr, PDWORD pdwBestIfIndex)
805 {
806   DWORD ret;
807
808   TRACE("pDestAddr %p, pdwBestIfIndex %p\n", pDestAddr, pdwBestIfIndex);
809   if (!pDestAddr || !pdwBestIfIndex)
810     ret = ERROR_INVALID_PARAMETER;
811   else {
812     MIB_IPFORWARDROW ipRow;
813
814     if (pDestAddr->sa_family == AF_INET) {
815       ret = GetBestRoute(((struct WS_sockaddr_in *)pDestAddr)->sin_addr.S_un.S_addr, 0, &ipRow);
816       if (ret == ERROR_SUCCESS)
817         *pdwBestIfIndex = ipRow.dwForwardIfIndex;
818     } else {
819       FIXME("address family %d not supported\n", pDestAddr->sa_family);
820       ret = ERROR_NOT_SUPPORTED;
821     }
822   }
823   TRACE("returning %d\n", ret);
824   return ret;
825 }
826
827
828 /******************************************************************
829  *    GetBestRoute (IPHLPAPI.@)
830  *
831  * Get the best route for the given IP address.
832  *
833  * PARAMS
834  *  dwDestAddr   [In]  IP address to search the best route for
835  *  dwSourceAddr [In]  optional source IP address
836  *  pBestRoute   [Out] found best route
837  *
838  * RETURNS
839  *  Success: NO_ERROR
840  *  Failure: error code from winerror.h
841  */
842 DWORD WINAPI GetBestRoute(DWORD dwDestAddr, DWORD dwSourceAddr, PMIB_IPFORWARDROW pBestRoute)
843 {
844   PMIB_IPFORWARDTABLE table;
845   DWORD ret;
846
847   TRACE("dwDestAddr 0x%08x, dwSourceAddr 0x%08x, pBestRoute %p\n", dwDestAddr,
848    dwSourceAddr, pBestRoute);
849   if (!pBestRoute)
850     return ERROR_INVALID_PARAMETER;
851
852   ret = AllocateAndGetIpForwardTableFromStack(&table, FALSE, GetProcessHeap(), 0);
853   if (!ret) {
854     DWORD ndx, matchedBits, matchedNdx = table->dwNumEntries;
855
856     for (ndx = 0, matchedBits = 0; ndx < table->dwNumEntries; ndx++) {
857       if (table->table[ndx].dwForwardType != MIB_IPROUTE_TYPE_INVALID &&
858        (dwDestAddr & table->table[ndx].dwForwardMask) ==
859        (table->table[ndx].dwForwardDest & table->table[ndx].dwForwardMask)) {
860         DWORD numShifts, mask;
861
862         for (numShifts = 0, mask = table->table[ndx].dwForwardMask;
863          mask && !(mask & 1); mask >>= 1, numShifts++)
864           ;
865         if (numShifts > matchedBits) {
866           matchedBits = numShifts;
867           matchedNdx = ndx;
868         }
869         else if (!matchedBits) {
870           matchedNdx = ndx;
871         }
872       }
873     }
874     if (matchedNdx < table->dwNumEntries) {
875       memcpy(pBestRoute, &table->table[matchedNdx], sizeof(MIB_IPFORWARDROW));
876       ret = ERROR_SUCCESS;
877     }
878     else {
879       /* No route matches, which can happen if there's no default route. */
880       ret = ERROR_HOST_UNREACHABLE;
881     }
882     HeapFree(GetProcessHeap(), 0, table);
883   }
884   TRACE("returning %d\n", ret);
885   return ret;
886 }
887
888
889 /******************************************************************
890  *    GetFriendlyIfIndex (IPHLPAPI.@)
891  *
892  * Get a "friendly" version of IfIndex, which is one that doesn't
893  * have the top byte set.  Doesn't validate whether IfIndex is a valid
894  * adapter index.
895  *
896  * PARAMS
897  *  IfIndex [In] interface index to get the friendly one for
898  *
899  * RETURNS
900  *  A friendly version of IfIndex.
901  */
902 DWORD WINAPI GetFriendlyIfIndex(DWORD IfIndex)
903 {
904   /* windows doesn't validate these, either, just makes sure the top byte is
905      cleared.  I assume my ifenum module never gives an index with the top
906      byte set. */
907   TRACE("returning %d\n", IfIndex);
908   return IfIndex;
909 }
910
911
912 /******************************************************************
913  *    GetIfEntry (IPHLPAPI.@)
914  *
915  * Get information about an interface.
916  *
917  * PARAMS
918  *  pIfRow [In/Out] In:  dwIndex of MIB_IFROW selects the interface.
919  *                  Out: interface information
920  *
921  * RETURNS
922  *  Success: NO_ERROR
923  *  Failure: error code from winerror.h
924  */
925 DWORD WINAPI GetIfEntry(PMIB_IFROW pIfRow)
926 {
927   DWORD ret;
928   char nameBuf[MAX_ADAPTER_NAME];
929   char *name;
930
931   TRACE("pIfRow %p\n", pIfRow);
932   if (!pIfRow)
933     return ERROR_INVALID_PARAMETER;
934
935   name = getInterfaceNameByIndex(pIfRow->dwIndex, nameBuf);
936   if (name) {
937     ret = getInterfaceEntryByName(name, pIfRow);
938     if (ret == NO_ERROR)
939       ret = getInterfaceStatsByName(name, pIfRow);
940   }
941   else
942     ret = ERROR_INVALID_DATA;
943   TRACE("returning %d\n", ret);
944   return ret;
945 }
946
947
948 static int IfTableSorter(const void *a, const void *b)
949 {
950   int ret;
951
952   if (a && b)
953     ret = ((const MIB_IFROW*)a)->dwIndex - ((const MIB_IFROW*)b)->dwIndex;
954   else
955     ret = 0;
956   return ret;
957 }
958
959
960 /******************************************************************
961  *    GetIfTable (IPHLPAPI.@)
962  *
963  * Get a table of local interfaces.
964  *
965  * PARAMS
966  *  pIfTable [Out]    buffer for local interfaces table
967  *  pdwSize  [In/Out] length of output buffer
968  *  bOrder   [In]     whether to sort the table
969  *
970  * RETURNS
971  *  Success: NO_ERROR
972  *  Failure: error code from winerror.h
973  *
974  * NOTES
975  *  If pdwSize is less than required, the function will return
976  *  ERROR_INSUFFICIENT_BUFFER, and *pdwSize will be set to the required byte
977  *  size.
978  *  If bOrder is true, the returned table will be sorted by interface index.
979  */
980 DWORD WINAPI GetIfTable(PMIB_IFTABLE pIfTable, PULONG pdwSize, BOOL bOrder)
981 {
982   DWORD ret;
983
984   TRACE("pIfTable %p, pdwSize %p, bOrder %d\n", pdwSize, pdwSize,
985    (DWORD)bOrder);
986   if (!pdwSize)
987     ret = ERROR_INVALID_PARAMETER;
988   else {
989     DWORD numInterfaces = getNumInterfaces();
990     ULONG size = sizeof(MIB_IFTABLE);
991
992     if (numInterfaces > 1)
993       size += (numInterfaces - 1) * sizeof(MIB_IFROW);
994     if (!pIfTable || *pdwSize < size) {
995       *pdwSize = size;
996       ret = ERROR_INSUFFICIENT_BUFFER;
997     }
998     else {
999       InterfaceIndexTable *table = getInterfaceIndexTable();
1000
1001       if (table) {
1002         size = sizeof(MIB_IFTABLE);
1003         if (table->numIndexes > 1)
1004           size += (table->numIndexes - 1) * sizeof(MIB_IFROW);
1005         if (*pdwSize < size) {
1006           *pdwSize = size;
1007           ret = ERROR_INSUFFICIENT_BUFFER;
1008         }
1009         else {
1010           DWORD ndx;
1011
1012           *pdwSize = size;
1013           pIfTable->dwNumEntries = 0;
1014           for (ndx = 0; ndx < table->numIndexes; ndx++) {
1015             pIfTable->table[ndx].dwIndex = table->indexes[ndx];
1016             GetIfEntry(&pIfTable->table[ndx]);
1017             pIfTable->dwNumEntries++;
1018           }
1019           if (bOrder)
1020             qsort(pIfTable->table, pIfTable->dwNumEntries, sizeof(MIB_IFROW),
1021              IfTableSorter);
1022           ret = NO_ERROR;
1023         }
1024         HeapFree(GetProcessHeap(), 0, table);
1025       }
1026       else
1027         ret = ERROR_OUTOFMEMORY;
1028     }
1029   }
1030   TRACE("returning %d\n", ret);
1031   return ret;
1032 }
1033
1034
1035 /******************************************************************
1036  *    GetInterfaceInfo (IPHLPAPI.@)
1037  *
1038  * Get a list of network interface adapters.
1039  *
1040  * PARAMS
1041  *  pIfTable    [Out] buffer for interface adapters
1042  *  dwOutBufLen [Out] if buffer is too small, returns required size
1043  *
1044  * RETURNS
1045  *  Success: NO_ERROR
1046  *  Failure: error code from winerror.h
1047  *
1048  * BUGS
1049  *  MSDN states this should return non-loopback interfaces only.
1050  */
1051 DWORD WINAPI GetInterfaceInfo(PIP_INTERFACE_INFO pIfTable, PULONG dwOutBufLen)
1052 {
1053   DWORD ret;
1054
1055   TRACE("pIfTable %p, dwOutBufLen %p\n", pIfTable, dwOutBufLen);
1056   if (!dwOutBufLen)
1057     ret = ERROR_INVALID_PARAMETER;
1058   else {
1059     DWORD numInterfaces = getNumInterfaces();
1060     ULONG size = sizeof(IP_INTERFACE_INFO);
1061
1062     if (numInterfaces > 1)
1063       size += (numInterfaces - 1) * sizeof(IP_ADAPTER_INDEX_MAP);
1064     if (!pIfTable || *dwOutBufLen < size) {
1065       *dwOutBufLen = size;
1066       ret = ERROR_INSUFFICIENT_BUFFER;
1067     }
1068     else {
1069       InterfaceIndexTable *table = getInterfaceIndexTable();
1070
1071       if (table) {
1072         size = sizeof(IP_INTERFACE_INFO);
1073         if (table->numIndexes > 1)
1074           size += (table->numIndexes - 1) * sizeof(IP_ADAPTER_INDEX_MAP);
1075         if (*dwOutBufLen < size) {
1076           *dwOutBufLen = size;
1077           ret = ERROR_INSUFFICIENT_BUFFER;
1078         }
1079         else {
1080           DWORD ndx;
1081           char nameBuf[MAX_ADAPTER_NAME];
1082
1083           *dwOutBufLen = size;
1084           pIfTable->NumAdapters = 0;
1085           for (ndx = 0; ndx < table->numIndexes; ndx++) {
1086             const char *walker, *name;
1087             WCHAR *assigner;
1088
1089             pIfTable->Adapter[ndx].Index = table->indexes[ndx];
1090             name = getInterfaceNameByIndex(table->indexes[ndx], nameBuf);
1091             for (walker = name, assigner = pIfTable->Adapter[ndx].Name;
1092              walker && *walker &&
1093              assigner - pIfTable->Adapter[ndx].Name < MAX_ADAPTER_NAME - 1;
1094              walker++, assigner++)
1095               *assigner = *walker;
1096             *assigner = 0;
1097             pIfTable->NumAdapters++;
1098           }
1099           ret = NO_ERROR;
1100         }
1101         HeapFree(GetProcessHeap(), 0, table);
1102       }
1103       else
1104         ret = ERROR_OUTOFMEMORY;
1105     }
1106   }
1107   TRACE("returning %d\n", ret);
1108   return ret;
1109 }
1110
1111
1112 /******************************************************************
1113  *    GetIpAddrTable (IPHLPAPI.@)
1114  *
1115  * Get interface-to-IP address mapping table. 
1116  *
1117  * PARAMS
1118  *  pIpAddrTable [Out]    buffer for mapping table
1119  *  pdwSize      [In/Out] length of output buffer
1120  *  bOrder       [In]     whether to sort the table
1121  *
1122  * RETURNS
1123  *  Success: NO_ERROR
1124  *  Failure: error code from winerror.h
1125  *
1126  * NOTES
1127  *  If pdwSize is less than required, the function will return
1128  *  ERROR_INSUFFICIENT_BUFFER, and *pdwSize will be set to the required byte
1129  *  size.
1130  *  If bOrder is true, the returned table will be sorted by the next hop and
1131  *  an assortment of arbitrary parameters.
1132  */
1133 DWORD WINAPI GetIpAddrTable(PMIB_IPADDRTABLE pIpAddrTable, PULONG pdwSize, BOOL bOrder)
1134 {
1135   DWORD ret;
1136
1137   TRACE("pIpAddrTable %p, pdwSize %p, bOrder %d\n", pIpAddrTable, pdwSize,
1138    (DWORD)bOrder);
1139   if (!pdwSize)
1140     ret = ERROR_INVALID_PARAMETER;
1141   else {
1142     PMIB_IPADDRTABLE table;
1143
1144     ret = getIPAddrTable(&table, GetProcessHeap(), 0);
1145     if (ret == NO_ERROR)
1146     {
1147       ULONG size = sizeof(MIB_IPADDRTABLE);
1148
1149       if (table->dwNumEntries > 1)
1150         size += (table->dwNumEntries - 1) * sizeof(MIB_IPADDRROW);
1151       if (!pIpAddrTable || *pdwSize < size) {
1152         *pdwSize = size;
1153         ret = ERROR_INSUFFICIENT_BUFFER;
1154       }
1155       else {
1156         *pdwSize = size;
1157         memcpy(pIpAddrTable, table, size);
1158         if (bOrder)
1159           qsort(pIpAddrTable->table, pIpAddrTable->dwNumEntries,
1160            sizeof(MIB_IPADDRROW), IpAddrTableSorter);
1161         ret = NO_ERROR;
1162       }
1163       HeapFree(GetProcessHeap(), 0, table);
1164     }
1165   }
1166   TRACE("returning %d\n", ret);
1167   return ret;
1168 }
1169
1170
1171 /******************************************************************
1172  *    GetIpForwardTable (IPHLPAPI.@)
1173  *
1174  * Get the route table.
1175  *
1176  * PARAMS
1177  *  pIpForwardTable [Out]    buffer for route table
1178  *  pdwSize         [In/Out] length of output buffer
1179  *  bOrder          [In]     whether to sort the table
1180  *
1181  * RETURNS
1182  *  Success: NO_ERROR
1183  *  Failure: error code from winerror.h
1184  *
1185  * NOTES
1186  *  If pdwSize is less than required, the function will return
1187  *  ERROR_INSUFFICIENT_BUFFER, and *pdwSize will be set to the required byte
1188  *  size.
1189  *  If bOrder is true, the returned table will be sorted by the next hop and
1190  *  an assortment of arbitrary parameters.
1191  */
1192 DWORD WINAPI GetIpForwardTable(PMIB_IPFORWARDTABLE pIpForwardTable, PULONG pdwSize, BOOL bOrder)
1193 {
1194     DWORD ret;
1195     PMIB_IPFORWARDTABLE table;
1196
1197     TRACE("pIpForwardTable %p, pdwSize %p, bOrder %d\n", pIpForwardTable, pdwSize, bOrder);
1198
1199     if (!pdwSize) return ERROR_INVALID_PARAMETER;
1200
1201     ret = AllocateAndGetIpForwardTableFromStack(&table, bOrder, GetProcessHeap(), 0);
1202     if (!ret) {
1203         DWORD size = FIELD_OFFSET( MIB_IPFORWARDTABLE, table[table->dwNumEntries] );
1204         if (!pIpForwardTable || *pdwSize < size) {
1205           *pdwSize = size;
1206           ret = ERROR_INSUFFICIENT_BUFFER;
1207         }
1208         else {
1209           *pdwSize = size;
1210           memcpy(pIpForwardTable, table, size);
1211         }
1212         HeapFree(GetProcessHeap(), 0, table);
1213     }
1214     TRACE("returning %d\n", ret);
1215     return ret;
1216 }
1217
1218
1219 /******************************************************************
1220  *    GetIpNetTable (IPHLPAPI.@)
1221  *
1222  * Get the IP-to-physical address mapping table.
1223  *
1224  * PARAMS
1225  *  pIpNetTable [Out]    buffer for mapping table
1226  *  pdwSize     [In/Out] length of output buffer
1227  *  bOrder      [In]     whether to sort the table
1228  *
1229  * RETURNS
1230  *  Success: NO_ERROR
1231  *  Failure: error code from winerror.h
1232  *
1233  * NOTES
1234  *  If pdwSize is less than required, the function will return
1235  *  ERROR_INSUFFICIENT_BUFFER, and *pdwSize will be set to the required byte
1236  *  size.
1237  *  If bOrder is true, the returned table will be sorted by IP address.
1238  */
1239 DWORD WINAPI GetIpNetTable(PMIB_IPNETTABLE pIpNetTable, PULONG pdwSize, BOOL bOrder)
1240 {
1241     DWORD ret;
1242     PMIB_IPNETTABLE table;
1243
1244     TRACE("pIpNetTable %p, pdwSize %p, bOrder %d\n", pIpNetTable, pdwSize, bOrder);
1245
1246     if (!pdwSize) return ERROR_INVALID_PARAMETER;
1247
1248     ret = AllocateAndGetIpNetTableFromStack( &table, bOrder, GetProcessHeap(), 0 );
1249     if (!ret) {
1250         DWORD size = FIELD_OFFSET( MIB_IPNETTABLE, table[table->dwNumEntries] );
1251         if (!pIpNetTable || *pdwSize < size) {
1252           *pdwSize = size;
1253           ret = ERROR_INSUFFICIENT_BUFFER;
1254         }
1255         else {
1256           *pdwSize = size;
1257           memcpy(pIpNetTable, table, size);
1258         }
1259         HeapFree(GetProcessHeap(), 0, table);
1260     }
1261     TRACE("returning %d\n", ret);
1262     return ret;
1263 }
1264
1265
1266 /******************************************************************
1267  *    GetNetworkParams (IPHLPAPI.@)
1268  *
1269  * Get the network parameters for the local computer.
1270  *
1271  * PARAMS
1272  *  pFixedInfo [Out]    buffer for network parameters
1273  *  pOutBufLen [In/Out] length of output buffer
1274  *
1275  * RETURNS
1276  *  Success: NO_ERROR
1277  *  Failure: error code from winerror.h
1278  *
1279  * NOTES
1280  *  If pOutBufLen is less than required, the function will return
1281  *  ERROR_INSUFFICIENT_BUFFER, and pOutBufLen will be set to the required byte
1282  *  size.
1283  */
1284 DWORD WINAPI GetNetworkParams(PFIXED_INFO pFixedInfo, PULONG pOutBufLen)
1285 {
1286   DWORD ret, size;
1287   LONG regReturn;
1288   HKEY hKey;
1289
1290   TRACE("pFixedInfo %p, pOutBufLen %p\n", pFixedInfo, pOutBufLen);
1291   if (!pOutBufLen)
1292     return ERROR_INVALID_PARAMETER;
1293
1294   initialise_resolver();
1295   size = sizeof(FIXED_INFO) + (_res.nscount > 0 ? (_res.nscount  - 1) *
1296    sizeof(IP_ADDR_STRING) : 0);
1297   if (!pFixedInfo || *pOutBufLen < size) {
1298     *pOutBufLen = size;
1299     return ERROR_BUFFER_OVERFLOW;
1300   }
1301
1302   memset(pFixedInfo, 0, size);
1303   size = sizeof(pFixedInfo->HostName);
1304   GetComputerNameExA(ComputerNameDnsHostname, pFixedInfo->HostName, &size);
1305   size = sizeof(pFixedInfo->DomainName);
1306   GetComputerNameExA(ComputerNameDnsDomain, pFixedInfo->DomainName, &size);
1307   if (_res.nscount > 0) {
1308     PIP_ADDR_STRING ptr;
1309     int i;
1310
1311     for (i = 0, ptr = &pFixedInfo->DnsServerList; i < _res.nscount && ptr;
1312      i++, ptr = ptr->Next) {
1313       toIPAddressString(_res.nsaddr_list[i].sin_addr.s_addr,
1314        ptr->IpAddress.String);
1315       if (i == _res.nscount - 1)
1316         ptr->Next = NULL;
1317       else if (i == 0)
1318         ptr->Next = (PIP_ADDR_STRING)((LPBYTE)pFixedInfo + sizeof(FIXED_INFO));
1319       else
1320         ptr->Next = (PIP_ADDR_STRING)((PBYTE)ptr + sizeof(IP_ADDR_STRING));
1321     }
1322   }
1323   pFixedInfo->NodeType = HYBRID_NODETYPE;
1324   regReturn = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
1325    "SYSTEM\\CurrentControlSet\\Services\\VxD\\MSTCP", 0, KEY_READ, &hKey);
1326   if (regReturn != ERROR_SUCCESS)
1327     regReturn = RegOpenKeyExA(HKEY_LOCAL_MACHINE,
1328      "SYSTEM\\CurrentControlSet\\Services\\NetBT\\Parameters", 0, KEY_READ,
1329      &hKey);
1330   if (regReturn == ERROR_SUCCESS)
1331   {
1332     DWORD size = sizeof(pFixedInfo->ScopeId);
1333
1334     RegQueryValueExA(hKey, "ScopeID", NULL, NULL, (LPBYTE)pFixedInfo->ScopeId, &size);
1335     RegCloseKey(hKey);
1336   }
1337
1338   /* FIXME: can check whether routing's enabled in /proc/sys/net/ipv4/ip_forward
1339      I suppose could also check for a listener on port 53 to set EnableDns */
1340   ret = NO_ERROR;
1341   TRACE("returning %d\n", ret);
1342   return ret;
1343 }
1344
1345
1346 /******************************************************************
1347  *    GetNumberOfInterfaces (IPHLPAPI.@)
1348  *
1349  * Get the number of interfaces.
1350  *
1351  * PARAMS
1352  *  pdwNumIf [Out] number of interfaces
1353  *
1354  * RETURNS
1355  *  NO_ERROR on success, ERROR_INVALID_PARAMETER if pdwNumIf is NULL.
1356  */
1357 DWORD WINAPI GetNumberOfInterfaces(PDWORD pdwNumIf)
1358 {
1359   DWORD ret;
1360
1361   TRACE("pdwNumIf %p\n", pdwNumIf);
1362   if (!pdwNumIf)
1363     ret = ERROR_INVALID_PARAMETER;
1364   else {
1365     *pdwNumIf = getNumInterfaces();
1366     ret = NO_ERROR;
1367   }
1368   TRACE("returning %d\n", ret);
1369   return ret;
1370 }
1371
1372
1373 /******************************************************************
1374  *    GetPerAdapterInfo (IPHLPAPI.@)
1375  *
1376  * Get information about an adapter corresponding to an interface.
1377  *
1378  * PARAMS
1379  *  IfIndex         [In]     interface info
1380  *  pPerAdapterInfo [Out]    buffer for per adapter info
1381  *  pOutBufLen      [In/Out] length of output buffer
1382  *
1383  * RETURNS
1384  *  Success: NO_ERROR
1385  *  Failure: error code from winerror.h
1386  *
1387  * FIXME
1388  *  Stub, returns empty IP_PER_ADAPTER_INFO in every case.
1389  */
1390 DWORD WINAPI GetPerAdapterInfo(ULONG IfIndex, PIP_PER_ADAPTER_INFO pPerAdapterInfo, PULONG pOutBufLen)
1391 {
1392   ULONG bytesNeeded = sizeof(IP_PER_ADAPTER_INFO);
1393
1394   TRACE("(IfIndex %d, pPerAdapterInfo %p, pOutBufLen %p)\n", IfIndex, pPerAdapterInfo, pOutBufLen);
1395
1396   if (!pOutBufLen) return ERROR_INVALID_PARAMETER;
1397
1398   if (!pPerAdapterInfo || *pOutBufLen < bytesNeeded)
1399   {
1400     *pOutBufLen = bytesNeeded;
1401     return ERROR_BUFFER_OVERFLOW;
1402   }
1403
1404   memset(pPerAdapterInfo, 0, bytesNeeded);
1405   return NO_ERROR;
1406 }
1407
1408
1409 /******************************************************************
1410  *    GetRTTAndHopCount (IPHLPAPI.@)
1411  *
1412  * Get round-trip time (RTT) and hop count.
1413  *
1414  * PARAMS
1415  *
1416  *  DestIpAddress [In]  destination address to get the info for
1417  *  HopCount      [Out] retrieved hop count
1418  *  MaxHops       [In]  maximum hops to search for the destination
1419  *  RTT           [Out] RTT in milliseconds
1420  *
1421  * RETURNS
1422  *  Success: TRUE
1423  *  Failure: FALSE
1424  *
1425  * FIXME
1426  *  Stub, returns FALSE.
1427  */
1428 BOOL WINAPI GetRTTAndHopCount(IPAddr DestIpAddress, PULONG HopCount, ULONG MaxHops, PULONG RTT)
1429 {
1430   FIXME("(DestIpAddress 0x%08x, HopCount %p, MaxHops %d, RTT %p): stub\n",
1431    DestIpAddress, HopCount, MaxHops, RTT);
1432   return FALSE;
1433 }
1434
1435
1436 /******************************************************************
1437  *    GetTcpTable (IPHLPAPI.@)
1438  *
1439  * Get the table of active TCP connections.
1440  *
1441  * PARAMS
1442  *  pTcpTable [Out]    buffer for TCP connections table
1443  *  pdwSize   [In/Out] length of output buffer
1444  *  bOrder    [In]     whether to order the table
1445  *
1446  * RETURNS
1447  *  Success: NO_ERROR
1448  *  Failure: error code from winerror.h
1449  *
1450  * NOTES
1451  *  If pdwSize is less than required, the function will return 
1452  *  ERROR_INSUFFICIENT_BUFFER, and *pdwSize will be set to 
1453  *  the required byte size.
1454  *  If bOrder is true, the returned table will be sorted, first by
1455  *  local address and port number, then by remote address and port
1456  *  number.
1457  */
1458 DWORD WINAPI GetTcpTable(PMIB_TCPTABLE pTcpTable, PDWORD pdwSize, BOOL bOrder)
1459 {
1460     DWORD ret;
1461     PMIB_TCPTABLE table;
1462
1463     TRACE("pTcpTable %p, pdwSize %p, bOrder %d\n", pTcpTable, pdwSize, bOrder);
1464
1465     if (!pdwSize) return ERROR_INVALID_PARAMETER;
1466
1467     ret = AllocateAndGetTcpTableFromStack(&table, bOrder, GetProcessHeap(), 0);
1468     if (!ret) {
1469         DWORD size = FIELD_OFFSET( MIB_TCPTABLE, table[table->dwNumEntries] );
1470         if (!pTcpTable || *pdwSize < size) {
1471           *pdwSize = size;
1472           ret = ERROR_INSUFFICIENT_BUFFER;
1473         }
1474         else {
1475           *pdwSize = size;
1476           memcpy(pTcpTable, table, size);
1477         }
1478         HeapFree(GetProcessHeap(), 0, table);
1479     }
1480     TRACE("returning %d\n", ret);
1481     return ret;
1482 }
1483
1484
1485 /******************************************************************
1486  *    GetUdpTable (IPHLPAPI.@)
1487  *
1488  * Get a table of active UDP connections.
1489  *
1490  * PARAMS
1491  *  pUdpTable [Out]    buffer for UDP connections table
1492  *  pdwSize   [In/Out] length of output buffer
1493  *  bOrder    [In]     whether to order the table
1494  *
1495  * RETURNS
1496  *  Success: NO_ERROR
1497  *  Failure: error code from winerror.h
1498  *
1499  * NOTES
1500  *  If pdwSize is less than required, the function will return 
1501  *  ERROR_INSUFFICIENT_BUFFER, and *pdwSize will be set to the
1502  *  required byte size.
1503  *  If bOrder is true, the returned table will be sorted, first by
1504  *  local address, then by local port number.
1505  */
1506 DWORD WINAPI GetUdpTable(PMIB_UDPTABLE pUdpTable, PDWORD pdwSize, BOOL bOrder)
1507 {
1508     DWORD ret;
1509     PMIB_UDPTABLE table;
1510
1511     TRACE("pUdpTable %p, pdwSize %p, bOrder %d\n", pUdpTable, pdwSize, bOrder);
1512
1513     if (!pdwSize) return ERROR_INVALID_PARAMETER;
1514
1515     ret = AllocateAndGetUdpTableFromStack( &table, bOrder, GetProcessHeap(), 0 );
1516     if (!ret) {
1517         DWORD size = FIELD_OFFSET( MIB_UDPTABLE, table[table->dwNumEntries] );
1518         if (!pUdpTable || *pdwSize < size) {
1519           *pdwSize = size;
1520           ret = ERROR_INSUFFICIENT_BUFFER;
1521         }
1522         else {
1523           *pdwSize = size;
1524           memcpy(pUdpTable, table, size);
1525         }
1526         HeapFree(GetProcessHeap(), 0, table);
1527     }
1528     TRACE("returning %d\n", ret);
1529     return ret;
1530 }
1531
1532
1533 /******************************************************************
1534  *    GetUniDirectionalAdapterInfo (IPHLPAPI.@)
1535  *
1536  * This is a Win98-only function to get information on "unidirectional"
1537  * adapters.  Since this is pretty nonsensical in other contexts, it
1538  * never returns anything.
1539  *
1540  * PARAMS
1541  *  pIPIfInfo   [Out] buffer for adapter infos
1542  *  dwOutBufLen [Out] length of the output buffer
1543  *
1544  * RETURNS
1545  *  Success: NO_ERROR
1546  *  Failure: error code from winerror.h
1547  *
1548  * FIXME
1549  *  Stub, returns ERROR_NOT_SUPPORTED.
1550  */
1551 DWORD WINAPI GetUniDirectionalAdapterInfo(PIP_UNIDIRECTIONAL_ADAPTER_ADDRESS pIPIfInfo, PULONG dwOutBufLen)
1552 {
1553   TRACE("pIPIfInfo %p, dwOutBufLen %p\n", pIPIfInfo, dwOutBufLen);
1554   /* a unidirectional adapter?? not bloody likely! */
1555   return ERROR_NOT_SUPPORTED;
1556 }
1557
1558
1559 /******************************************************************
1560  *    IpReleaseAddress (IPHLPAPI.@)
1561  *
1562  * Release an IP obtained through DHCP,
1563  *
1564  * PARAMS
1565  *  AdapterInfo [In] adapter to release IP address
1566  *
1567  * RETURNS
1568  *  Success: NO_ERROR
1569  *  Failure: error code from winerror.h
1570  *
1571  * NOTES
1572  *  Since GetAdaptersInfo never returns adapters that have DHCP enabled,
1573  *  this function does nothing.
1574  *
1575  * FIXME
1576  *  Stub, returns ERROR_NOT_SUPPORTED.
1577  */
1578 DWORD WINAPI IpReleaseAddress(PIP_ADAPTER_INDEX_MAP AdapterInfo)
1579 {
1580   TRACE("AdapterInfo %p\n", AdapterInfo);
1581   /* not a stub, never going to support this (and I never mark an adapter as
1582      DHCP enabled, see GetAdaptersInfo, so this should never get called) */
1583   return ERROR_NOT_SUPPORTED;
1584 }
1585
1586
1587 /******************************************************************
1588  *    IpRenewAddress (IPHLPAPI.@)
1589  *
1590  * Renew an IP obtained through DHCP.
1591  *
1592  * PARAMS
1593  *  AdapterInfo [In] adapter to renew IP address
1594  *
1595  * RETURNS
1596  *  Success: NO_ERROR
1597  *  Failure: error code from winerror.h
1598  *
1599  * NOTES
1600  *  Since GetAdaptersInfo never returns adapters that have DHCP enabled,
1601  *  this function does nothing.
1602  *
1603  * FIXME
1604  *  Stub, returns ERROR_NOT_SUPPORTED.
1605  */
1606 DWORD WINAPI IpRenewAddress(PIP_ADAPTER_INDEX_MAP AdapterInfo)
1607 {
1608   TRACE("AdapterInfo %p\n", AdapterInfo);
1609   /* not a stub, never going to support this (and I never mark an adapter as
1610      DHCP enabled, see GetAdaptersInfo, so this should never get called) */
1611   return ERROR_NOT_SUPPORTED;
1612 }
1613
1614
1615 /******************************************************************
1616  *    NotifyAddrChange (IPHLPAPI.@)
1617  *
1618  * Notify caller whenever the ip-interface map is changed.
1619  *
1620  * PARAMS
1621  *  Handle     [Out] handle usable in asynchronous notification
1622  *  overlapped [In]  overlapped structure that notifies the caller
1623  *
1624  * RETURNS
1625  *  Success: NO_ERROR
1626  *  Failure: error code from winerror.h
1627  *
1628  * FIXME
1629  *  Stub, returns ERROR_NOT_SUPPORTED.
1630  */
1631 DWORD WINAPI NotifyAddrChange(PHANDLE Handle, LPOVERLAPPED overlapped)
1632 {
1633   FIXME("(Handle %p, overlapped %p): stub\n", Handle, overlapped);
1634   return ERROR_NOT_SUPPORTED;
1635 }
1636
1637
1638 /******************************************************************
1639  *    NotifyRouteChange (IPHLPAPI.@)
1640  *
1641  * Notify caller whenever the ip routing table is changed.
1642  *
1643  * PARAMS
1644  *  Handle     [Out] handle usable in asynchronous notification
1645  *  overlapped [In]  overlapped structure that notifies the caller
1646  *
1647  * RETURNS
1648  *  Success: NO_ERROR
1649  *  Failure: error code from winerror.h
1650  *
1651  * FIXME
1652  *  Stub, returns ERROR_NOT_SUPPORTED.
1653  */
1654 DWORD WINAPI NotifyRouteChange(PHANDLE Handle, LPOVERLAPPED overlapped)
1655 {
1656   FIXME("(Handle %p, overlapped %p): stub\n", Handle, overlapped);
1657   return ERROR_NOT_SUPPORTED;
1658 }
1659
1660
1661 /******************************************************************
1662  *    SendARP (IPHLPAPI.@)
1663  *
1664  * Send an ARP request.
1665  *
1666  * PARAMS
1667  *  DestIP     [In]     attempt to obtain this IP
1668  *  SrcIP      [In]     optional sender IP address
1669  *  pMacAddr   [Out]    buffer for the mac address
1670  *  PhyAddrLen [In/Out] length of the output buffer
1671  *
1672  * RETURNS
1673  *  Success: NO_ERROR
1674  *  Failure: error code from winerror.h
1675  *
1676  * FIXME
1677  *  Stub, returns ERROR_NOT_SUPPORTED.
1678  */
1679 DWORD WINAPI SendARP(IPAddr DestIP, IPAddr SrcIP, PULONG pMacAddr, PULONG PhyAddrLen)
1680 {
1681   FIXME("(DestIP 0x%08x, SrcIP 0x%08x, pMacAddr %p, PhyAddrLen %p): stub\n",
1682    DestIP, SrcIP, pMacAddr, PhyAddrLen);
1683   return ERROR_NOT_SUPPORTED;
1684 }
1685
1686
1687 /******************************************************************
1688  *    SetIfEntry (IPHLPAPI.@)
1689  *
1690  * Set the administrative status of an interface.
1691  *
1692  * PARAMS
1693  *  pIfRow [In] dwAdminStatus member specifies the new status.
1694  *
1695  * RETURNS
1696  *  Success: NO_ERROR
1697  *  Failure: error code from winerror.h
1698  *
1699  * FIXME
1700  *  Stub, returns ERROR_NOT_SUPPORTED.
1701  */
1702 DWORD WINAPI SetIfEntry(PMIB_IFROW pIfRow)
1703 {
1704   FIXME("(pIfRow %p): stub\n", pIfRow);
1705   /* this is supposed to set an interface administratively up or down.
1706      Could do SIOCSIFFLAGS and set/clear IFF_UP, but, not sure I want to, and
1707      this sort of down is indistinguishable from other sorts of down (e.g. no
1708      link). */
1709   return ERROR_NOT_SUPPORTED;
1710 }
1711
1712
1713 /******************************************************************
1714  *    SetIpForwardEntry (IPHLPAPI.@)
1715  *
1716  * Modify an existing route.
1717  *
1718  * PARAMS
1719  *  pRoute [In] route with the new information
1720  *
1721  * RETURNS
1722  *  Success: NO_ERROR
1723  *  Failure: error code from winerror.h
1724  *
1725  * FIXME
1726  *  Stub, returns NO_ERROR.
1727  */
1728 DWORD WINAPI SetIpForwardEntry(PMIB_IPFORWARDROW pRoute)
1729 {
1730   FIXME("(pRoute %p): stub\n", pRoute);
1731   /* this is to add a route entry, how's it distinguishable from
1732      CreateIpForwardEntry?
1733      could use SIOCADDRT, not sure I want to */
1734   return 0;
1735 }
1736
1737
1738 /******************************************************************
1739  *    SetIpNetEntry (IPHLPAPI.@)
1740  *
1741  * Modify an existing ARP entry.
1742  *
1743  * PARAMS
1744  *  pArpEntry [In] ARP entry with the new information
1745  *
1746  * RETURNS
1747  *  Success: NO_ERROR
1748  *  Failure: error code from winerror.h
1749  *
1750  * FIXME
1751  *  Stub, returns NO_ERROR.
1752  */
1753 DWORD WINAPI SetIpNetEntry(PMIB_IPNETROW pArpEntry)
1754 {
1755   FIXME("(pArpEntry %p): stub\n", pArpEntry);
1756   /* same as CreateIpNetEntry here, could use SIOCSARP, not sure I want to */
1757   return 0;
1758 }
1759
1760
1761 /******************************************************************
1762  *    SetIpStatistics (IPHLPAPI.@)
1763  *
1764  * Toggle IP forwarding and det the default TTL value.
1765  *
1766  * PARAMS
1767  *  pIpStats [In] IP statistics with the new information
1768  *
1769  * RETURNS
1770  *  Success: NO_ERROR
1771  *  Failure: error code from winerror.h
1772  *
1773  * FIXME
1774  *  Stub, returns NO_ERROR.
1775  */
1776 DWORD WINAPI SetIpStatistics(PMIB_IPSTATS pIpStats)
1777 {
1778   FIXME("(pIpStats %p): stub\n", pIpStats);
1779   return 0;
1780 }
1781
1782
1783 /******************************************************************
1784  *    SetIpTTL (IPHLPAPI.@)
1785  *
1786  * Set the default TTL value.
1787  *
1788  * PARAMS
1789  *  nTTL [In] new TTL value
1790  *
1791  * RETURNS
1792  *  Success: NO_ERROR
1793  *  Failure: error code from winerror.h
1794  *
1795  * FIXME
1796  *  Stub, returns NO_ERROR.
1797  */
1798 DWORD WINAPI SetIpTTL(UINT nTTL)
1799 {
1800   FIXME("(nTTL %d): stub\n", nTTL);
1801   /* could echo nTTL > /proc/net/sys/net/ipv4/ip_default_ttl, not sure I
1802      want to.  Could map EACCESS to ERROR_ACCESS_DENIED, I suppose */
1803   return 0;
1804 }
1805
1806
1807 /******************************************************************
1808  *    SetTcpEntry (IPHLPAPI.@)
1809  *
1810  * Set the state of a TCP connection.
1811  *
1812  * PARAMS
1813  *  pTcpRow [In] specifies connection with new state
1814  *
1815  * RETURNS
1816  *  Success: NO_ERROR
1817  *  Failure: error code from winerror.h
1818  *
1819  * FIXME
1820  *  Stub, returns NO_ERROR.
1821  */
1822 DWORD WINAPI SetTcpEntry(PMIB_TCPROW pTcpRow)
1823 {
1824   FIXME("(pTcpRow %p): stub\n", pTcpRow);
1825   return 0;
1826 }
1827
1828
1829 /******************************************************************
1830  *    UnenableRouter (IPHLPAPI.@)
1831  *
1832  * Decrement the IP-forwarding reference count. Turn off IP-forwarding
1833  * if it reaches zero.
1834  *
1835  * PARAMS
1836  *  pOverlapped     [In/Out] should be the same as in EnableRouter()
1837  *  lpdwEnableCount [Out]    optional, receives reference count
1838  *
1839  * RETURNS
1840  *  Success: NO_ERROR
1841  *  Failure: error code from winerror.h
1842  *
1843  * FIXME
1844  *  Stub, returns ERROR_NOT_SUPPORTED.
1845  */
1846 DWORD WINAPI UnenableRouter(OVERLAPPED * pOverlapped, LPDWORD lpdwEnableCount)
1847 {
1848   FIXME("(pOverlapped %p, lpdwEnableCount %p): stub\n", pOverlapped,
1849    lpdwEnableCount);
1850   /* could echo "0" > /proc/net/sys/net/ipv4/ip_forward, not sure I want to
1851      could map EACCESS to ERROR_ACCESS_DENIED, I suppose
1852    */
1853   return ERROR_NOT_SUPPORTED;
1854 }