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