crypt32: Free the encoded msg (Coverity).
[wine] / programs / netstat / netstat.c
1 /*
2  * Copyright 2011-2013 AndrĂ© Hentschel
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 #define NONAMELESSUNION
20 #include "netstat.h"
21 #include <winsock2.h>
22 #include <iphlpapi.h>
23 #include "wine/unicode.h"
24 #include "wine/debug.h"
25
26 WINE_DEFAULT_DEBUG_CHANNEL(netstat);
27
28 static const WCHAR ipW[] = {'I', 'P', 0};
29 static const WCHAR ipv6W[] = {'I', 'P', 'v', '6', 0};
30 static const WCHAR icmpW[] = {'I', 'C', 'M', 'P', 0};
31 static const WCHAR icmpv6W[] = {'I', 'C', 'M', 'P', 'v', '6', 0};
32 static const WCHAR tcpW[] = {'T', 'C', 'P', 0};
33 static const WCHAR tcpv6W[] = {'T', 'C', 'P', 'v', '6', 0};
34 static const WCHAR udpW[] = {'U', 'D', 'P', 0};
35 static const WCHAR udpv6W[] = {'U', 'D', 'P', 'v', '6', 0};
36
37 static const WCHAR fmtport[] = {'%', 'd', 0};
38 static const WCHAR fmtip[] = {'%', 'd', '.', '%', 'd', '.', '%', 'd', '.', '%', 'd', 0};
39 static const WCHAR fmtn[] = {'\n', 0};
40 static const WCHAR fmtnn[] = {'\n', '%', 's', '\n', 0};
41 static const WCHAR fmtcolon[] = {'%', 's', ':', '%', 's', 0};
42 static const WCHAR fmttcpout[] = {' ', ' ', '%', '-', '6', 's', ' ', '%', '-', '2', '2', 's', ' ', '%', '-', '2', '2', 's', ' ', '%', 's', '\n', 0};
43 static const WCHAR fmtudpout[] = {' ', ' ', '%', '-', '6', 's', ' ', '%', '-', '2', '2', 's', ' ', '*', ':', '*', '\n', 0};
44 static const WCHAR fmtethout[] = {'%', '-', '2', '0', 's', ' ', '%', '1', '4', 'l', 'u', ' ', '%', '1', '5', 'l', 'u', '\n', 0};
45 static const WCHAR fmtethoutu[] = {'%', '-', '2', '0', 's', ' ', '%', '1', '4', 'l', 'u', '\n', '\n', 0};
46 static const WCHAR fmtethheader[] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
47                                      ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
48                                      ' ', '%', '-', '1', '9', 's', ' ', '%', 's', '\n', '\n', 0};
49
50 static const WCHAR tcpstatesW[][16] = {
51     {'?', '?', '?', 0},
52     {'C', 'L', 'O', 'S', 'E', 'D', 0},
53     {'L', 'I', 'S', 'T', 'E', 'N', 'I', 'N', 'G', 0},
54     {'S', 'Y', 'N', '_', 'S', 'E', 'N', 'T', 0},
55     {'S', 'Y', 'N', '_', 'R', 'C', 'V', 'D', 0},
56     {'E', 'S', 'T', 'A', 'B', 'L', 'I', 'S', 'H', 'E', 'D', 0},
57     {'F', 'I', 'N', '_', 'W', 'A', 'I', 'T', '1', 0},
58     {'F', 'I', 'N', '_', 'W', 'A', 'I', 'T', '2', 0},
59     {'C', 'L', 'O', 'S', 'E', '_', 'W', 'A', 'I', 'T', 0},
60     {'C', 'L', 'O', 'S', 'I', 'N', 'G', 0},
61     {'L', 'A', 'S', 'T', '_', 'A', 'C', 'K', 0},
62     {'T', 'I', 'M', 'E', '_', 'W', 'A', 'I', 'T', 0},
63     {'D', 'E', 'L', 'E', 'T', 'E', '_', 'T', 'C', 'B', 0},
64 };
65
66 /* =========================================================================
67  *  Output a unicode string. Ideally this will go to the console
68  *  and hence required WriteConsoleW to output it, however if file i/o is
69  *  redirected, it needs to be WriteFile'd using OEM (not ANSI) format
70  * ========================================================================= */
71 static int __cdecl NETSTAT_wprintf(const WCHAR *format, ...)
72 {
73     static WCHAR *output_bufW = NULL;
74     static char  *output_bufA = NULL;
75     static BOOL  toConsole    = TRUE;
76     static BOOL  traceOutput  = FALSE;
77 #define MAX_WRITECONSOLE_SIZE 65535
78
79     __ms_va_list parms;
80     DWORD   nOut;
81     int len;
82     DWORD   res = 0;
83
84     /*
85      * Allocate buffer to use when writing to console
86      * Note: Not freed - memory will be allocated once and released when
87      *         xcopy ends
88      */
89
90     if (!output_bufW) output_bufW = HeapAlloc(GetProcessHeap(), 0,
91                                               MAX_WRITECONSOLE_SIZE);
92     if (!output_bufW) {
93         WINE_FIXME("Out of memory - could not allocate 2 x 64K buffers\n");
94         return 0;
95     }
96
97     __ms_va_start(parms, format);
98     len = wvsprintfW(output_bufW, format, parms);
99     __ms_va_end(parms);
100
101     /* Try to write as unicode all the time we think its a console */
102     if (toConsole) {
103         res = WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE),
104                             output_bufW, len, &nOut, NULL);
105     }
106
107     /* If writing to console has failed (ever) we assume its file
108        i/o so convert to OEM codepage and output                  */
109     if (!res) {
110         BOOL usedDefaultChar = FALSE;
111         DWORD convertedChars;
112
113         toConsole = FALSE;
114
115         /*
116          * Allocate buffer to use when writing to file. Not freed, as above
117          */
118         if (!output_bufA) output_bufA = HeapAlloc(GetProcessHeap(), 0,
119                                                   MAX_WRITECONSOLE_SIZE);
120         if (!output_bufA) {
121             WINE_FIXME("Out of memory - could not allocate 2 x 64K buffers\n");
122             return 0;
123         }
124
125         /* Convert to OEM, then output */
126         convertedChars = WideCharToMultiByte(GetConsoleOutputCP(), 0, output_bufW,
127                                              len, output_bufA, MAX_WRITECONSOLE_SIZE,
128                                              "?", &usedDefaultChar);
129         WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), output_bufA, convertedChars,
130                   &nOut, FALSE);
131     }
132
133     /* Trace whether screen or console */
134     if (!traceOutput) {
135         WINE_TRACE("Writing to console? (%d)\n", toConsole);
136         traceOutput = TRUE;
137     }
138     return nOut;
139 }
140
141 static WCHAR *NETSTAT_load_message(UINT id) {
142     static WCHAR msg[2048];
143     static const WCHAR failedW[]  = {'F','a','i','l','e','d','!','\0'};
144
145     if (!LoadStringW(GetModuleHandleW(NULL), id, msg, sizeof(msg)/sizeof(WCHAR))) {
146         WINE_FIXME("LoadString failed with %d\n", GetLastError());
147         strcpyW(msg, failedW);
148     }
149     return msg;
150 }
151
152 static WCHAR *NETSTAT_port_name(UINT port, WCHAR name[])
153 {
154     /* FIXME: can we get the name? */
155     sprintfW(name, fmtport, htons((WORD)port));
156     return name;
157 }
158
159 static WCHAR *NETSTAT_host_name(UINT ip, WCHAR name[])
160 {
161     UINT nip;
162
163     /* FIXME: can we get the name? */
164     nip = htonl(ip);
165     sprintfW(name, fmtip, (nip >> 24) & 0xFF, (nip >> 16) & 0xFF, (nip >> 8) & 0xFF, (nip) & 0xFF);
166     return name;
167 }
168
169 static void NETSTAT_conn_header(void)
170 {
171     WCHAR local[22], remote[22], state[22];
172     NETSTAT_wprintf(fmtnn, NETSTAT_load_message(IDS_TCP_ACTIVE_CONN));
173     NETSTAT_wprintf(fmtn);
174     strcpyW(local, NETSTAT_load_message(IDS_TCP_LOCAL_ADDR));
175     strcpyW(remote, NETSTAT_load_message(IDS_TCP_REMOTE_ADDR));
176     strcpyW(state, NETSTAT_load_message(IDS_TCP_STATE));
177     NETSTAT_wprintf(fmttcpout, NETSTAT_load_message(IDS_TCP_PROTO), local, remote, state);
178 }
179
180 static void NETSTAT_eth_stats(void)
181 {
182     PMIB_IFTABLE table;
183     DWORD err, size, i;
184     DWORD octets[2], ucastpkts[2], nucastpkts[2], discards[2], errors[2], unknown;
185     WCHAR recv[19];
186
187     size = sizeof(MIB_IFTABLE);
188     do
189     {
190         table = (PMIB_IFTABLE)HeapAlloc(GetProcessHeap(), 0, size);
191         err = GetIfTable(table, &size, FALSE);
192         if (err != NO_ERROR) HeapFree(GetProcessHeap(), 0, table);
193     } while (err == ERROR_INSUFFICIENT_BUFFER);
194
195     if (err) return;
196
197     NETSTAT_wprintf(NETSTAT_load_message(IDS_ETH_STAT));
198     NETSTAT_wprintf(fmtn);
199     NETSTAT_wprintf(fmtn);
200     strcpyW(recv, NETSTAT_load_message(IDS_ETH_RECV));
201     NETSTAT_wprintf(fmtethheader, recv, NETSTAT_load_message(IDS_ETH_SENT));
202
203     octets[0] = octets[1] = 0;
204     ucastpkts[0] = ucastpkts[1] = 0;
205     nucastpkts[0] = nucastpkts[1] = 0;
206     discards[0] = discards[1] = 0;
207     errors[0] = errors[1] = 0;
208     unknown = 0;
209
210     for (i = 0; i < table->dwNumEntries; i++)
211     {
212         octets[0] += table->table[i].dwInOctets;
213         octets[1] += table->table[i].dwOutOctets;
214         ucastpkts[0] += table->table[i].dwInUcastPkts;
215         ucastpkts[1] += table->table[i].dwOutUcastPkts;
216         nucastpkts[0] += table->table[i].dwInNUcastPkts;
217         nucastpkts[1] += table->table[i].dwOutNUcastPkts;
218         discards[0] += table->table[i].dwInDiscards;
219         discards[1] += table->table[i].dwOutDiscards;
220         errors[0] += table->table[i].dwInErrors;
221         errors[1] += table->table[i].dwOutErrors;
222         unknown += table->table[i].dwInUnknownProtos;
223     }
224
225     NETSTAT_wprintf(fmtethout, NETSTAT_load_message(IDS_ETH_BYTES), octets[0], octets[1]);
226     NETSTAT_wprintf(fmtethout, NETSTAT_load_message(IDS_ETH_UNICAST), ucastpkts[0], ucastpkts[1]);
227     NETSTAT_wprintf(fmtethout, NETSTAT_load_message(IDS_ETH_NUNICAST), nucastpkts[0], nucastpkts[1]);
228     NETSTAT_wprintf(fmtethout, NETSTAT_load_message(IDS_ETH_DISCARDS), discards[0], discards[1]);
229     NETSTAT_wprintf(fmtethout, NETSTAT_load_message(IDS_ETH_ERRORS), errors[0], errors[1]);
230     NETSTAT_wprintf(fmtethoutu, NETSTAT_load_message(IDS_ETH_UNKNOWN), unknown);
231
232     HeapFree(GetProcessHeap(), 0, table);
233 }
234
235 static void NETSTAT_tcp_table(void)
236 {
237     PMIB_TCPTABLE table;
238     DWORD err, size, i;
239     WCHAR HostIp[MAX_HOSTNAME_LEN], HostPort[32];
240     WCHAR RemoteIp[MAX_HOSTNAME_LEN], RemotePort[32];
241     WCHAR Host[MAX_HOSTNAME_LEN + 32];
242     WCHAR Remote[MAX_HOSTNAME_LEN + 32];
243
244     size = sizeof(MIB_TCPTABLE);
245     do
246     {
247         table = (PMIB_TCPTABLE)HeapAlloc(GetProcessHeap(), 0, size);
248         err = GetTcpTable(table, &size, TRUE);
249         if (err != NO_ERROR) HeapFree(GetProcessHeap(), 0, table);
250     } while (err == ERROR_INSUFFICIENT_BUFFER);
251
252     if (err) return;
253
254     for (i = 0; i < table->dwNumEntries; i++)
255     {
256         if ((table->table[i].u.dwState ==  MIB_TCP_STATE_CLOSE_WAIT) ||
257             (table->table[i].u.dwState ==  MIB_TCP_STATE_ESTAB) ||
258             (table->table[i].u.dwState ==  MIB_TCP_STATE_TIME_WAIT))
259         {
260             NETSTAT_host_name(table->table[i].dwLocalAddr, HostIp);
261             NETSTAT_port_name(table->table[i].dwLocalPort, HostPort);
262             NETSTAT_host_name(table->table[i].dwRemoteAddr, RemoteIp);
263             NETSTAT_port_name(table->table[i].dwRemotePort, RemotePort);
264
265             sprintfW(Host, fmtcolon, HostIp, HostPort);
266             sprintfW(Remote, fmtcolon, RemoteIp, RemotePort);
267             NETSTAT_wprintf(fmttcpout, tcpW, Host, Remote, tcpstatesW[table->table[i].u.dwState]);
268         }
269     }
270     HeapFree(GetProcessHeap(), 0, table);
271 }
272
273 static void NETSTAT_udp_table(void)
274 {
275     PMIB_UDPTABLE table;
276     DWORD err, size, i;
277     WCHAR HostIp[MAX_HOSTNAME_LEN], HostPort[32];
278     WCHAR Host[MAX_HOSTNAME_LEN + 32];
279
280     size = sizeof(MIB_UDPTABLE);
281     do
282     {
283         table = (PMIB_UDPTABLE)HeapAlloc(GetProcessHeap(), 0, size);
284         err = GetUdpTable(table, &size, TRUE);
285         if (err != NO_ERROR) HeapFree(GetProcessHeap(), 0, table);
286     } while (err == ERROR_INSUFFICIENT_BUFFER);
287
288     if (err) return;
289
290     for (i = 0; i < table->dwNumEntries; i++)
291     {
292         NETSTAT_host_name(table->table[i].dwLocalAddr, HostIp);
293         NETSTAT_port_name(table->table[i].dwLocalPort, HostPort);
294
295         sprintfW(Host, fmtcolon, HostIp, HostPort);
296         NETSTAT_wprintf(fmtudpout, udpW, Host);
297     }
298     HeapFree(GetProcessHeap(), 0, table);
299 }
300
301 static NETSTATPROTOCOLS NETSTAT_get_protocol(WCHAR name[])
302 {
303     if (!strcmpiW(name, ipW)) return PROT_IP;
304     if (!strcmpiW(name, ipv6W)) return PROT_IPV6;
305     if (!strcmpiW(name, icmpW)) return PROT_ICMP;
306     if (!strcmpiW(name, icmpv6W)) return PROT_ICMPV6;
307     if (!strcmpiW(name, tcpW)) return PROT_TCP;
308     if (!strcmpiW(name, tcpv6W)) return PROT_TCPV6;
309     if (!strcmpiW(name, udpW)) return PROT_UDP;
310     if (!strcmpiW(name, udpv6W)) return PROT_UDPV6;
311     return PROT_UNKNOWN;
312 }
313
314 int wmain(int argc, WCHAR *argv[])
315 {
316     WSADATA wsa_data;
317
318     if (WSAStartup(MAKEWORD(2, 2), &wsa_data))
319     {
320         WINE_ERR("WSAStartup failed: %d\n", WSAGetLastError());
321         return 1;
322     }
323
324     if (argc == 1)
325     {
326         /* No options */
327         NETSTAT_conn_header();
328         NETSTAT_tcp_table();
329         return 0;
330     }
331
332     while (argv[1] && argv[1][0] == '-')
333     {
334         switch (argv[1][1])
335         {
336         case 'a':
337             NETSTAT_conn_header();
338             NETSTAT_tcp_table();
339             NETSTAT_udp_table();
340             return 0;
341         case 'e':
342             NETSTAT_eth_stats();
343             return 0;
344         case 'p':
345             argv++; argc--;
346             if (argc == 1) return 1;
347             switch (NETSTAT_get_protocol(argv[1]))
348             {
349                 case PROT_TCP:
350                     NETSTAT_conn_header();
351                     NETSTAT_tcp_table();
352                     break;
353                 case PROT_UDP:
354                     NETSTAT_conn_header();
355                     NETSTAT_udp_table();
356                     break;
357                 default:
358                     WINE_FIXME("Protocol not yet implemented: %s\n", debugstr_w(argv[1]));
359             }
360             return 0;
361         default:
362             WINE_FIXME("Unknown option: %s\n", debugstr_w(argv[1]));
363             return 1;
364         }
365         argv++; argc--;
366     }
367
368     return 0;
369 }