Rename "Secure Socket Layer" to "Secure Sockets Layer" (plural) and update
[obnox/wireshark/wip.git] / util.c
1 /* util.c
2  * Utility routines
3  *
4  * $Id$
5  *
6  * Wireshark - Network traffic analyzer
7  * By Gerald Combs <gerald@wireshark.org>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #include <glib.h>
30
31 #include <stdlib.h>
32 #include <string.h>
33 #include <stdio.h>
34 #include <errno.h>
35
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif
39
40 #include <epan/address.h>
41 #include <epan/addr_resolv.h>
42 #include <epan/strutil.h>
43
44 #include "util.h"
45
46 /*
47  * Collect command-line arguments as a string consisting of the arguments,
48  * separated by spaces.
49  */
50 char *
51 get_args_as_string(int argc, char **argv, int optindex)
52 {
53         int len;
54         int i;
55         char *argstring;
56
57         /*
58          * Find out how long the string will be.
59          */
60         len = 0;
61         for (i = optindex; i < argc; i++) {
62                 len += (int) strlen(argv[i]);
63                 len++;  /* space, or '\0' if this is the last argument */
64         }
65
66         /*
67          * Allocate the buffer for the string.
68          */
69         argstring = (char *)g_malloc(len);
70
71         /*
72          * Now construct the string.
73          */
74         argstring[0] = '\0';
75         i = optindex;
76         for (;;) {
77                 g_strlcat(argstring, argv[i], len);
78                 i++;
79                 if (i == argc)
80                         break;
81                 g_strlcat(argstring, " ", len);
82         }
83         return argstring;
84 }
85
86 /* Compute the difference between two seconds/microseconds time stamps. */
87 void
88 compute_timestamp_diff(gint *diffsec, gint *diffusec,
89         guint32 sec1, guint32 usec1, guint32 sec2, guint32 usec2)
90 {
91   if (sec1 == sec2) {
92     /* The seconds part of the first time is the same as the seconds
93        part of the second time, so if the microseconds part of the first
94        time is less than the microseconds part of the second time, the
95        first time is before the second time.  The microseconds part of
96        the delta should just be the difference between the microseconds
97        part of the first time and the microseconds part of the second
98        time; don't adjust the seconds part of the delta, as it's OK if
99        the microseconds part is negative. */
100
101     *diffsec = sec1 - sec2;
102     *diffusec = usec1 - usec2;
103   } else if (sec1 <= sec2) {
104     /* The seconds part of the first time is less than the seconds part
105        of the second time, so the first time is before the second time.
106
107        Both the "seconds" and "microseconds" value of the delta
108        should have the same sign, so if the difference between the
109        microseconds values would be *positive*, subtract 1,000,000
110        from it, and add one to the seconds value. */
111     *diffsec = sec1 - sec2;
112     if (usec2 >= usec1) {
113       *diffusec = usec1 - usec2;
114     } else {
115       *diffusec = (usec1 - 1000000) - usec2;
116       (*diffsec)++;
117     }
118   } else {
119     /* Oh, good, we're not caught in a chronosynclastic infindibulum. */
120     *diffsec = sec1 - sec2;
121     if (usec2 <= usec1) {
122       *diffusec = usec1 - usec2;
123     } else {
124       *diffusec = (usec1 + 1000000) - usec2;
125       (*diffsec)--;
126     }
127   }
128 }
129
130 /* Remove any %<interface_name> from an IP address. */
131 char *sanitize_filter_ip(char *hostname) {
132     gchar *end;
133     gchar *ret;
134
135     ret = g_strdup(hostname);
136     if (!ret)
137         return NULL;
138
139     end = strchr(ret, '%');
140     if (end)
141         *end = '\0';
142     return ret;
143 }
144
145 /* Try to figure out if we're remotely connected, e.g. via ssh or
146    Terminal Server, and create a capture filter that matches aspects of the
147    connection.  We match the following environment variables:
148
149    SSH_CONNECTION (ssh): <remote IP> <remote port> <local IP> <local port>
150    SSH_CLIENT (ssh): <remote IP> <remote port> <local port>
151    REMOTEHOST (tcsh, others?): <remote name>
152    DISPLAY (x11): [remote name]:<display num>
153    SESSIONNAME (terminal server): <remote name>
154  */
155
156 const gchar *get_conn_cfilter(void) {
157         static GString *filter_str = NULL;
158         gchar *env, **tokens;
159         char *lastp, *lastc, *p;
160         char *pprotocol = NULL;
161         char *phostname = NULL;
162         size_t hostlen;
163         char *remip, *locip;
164
165         if (filter_str == NULL) {
166                 filter_str = g_string_new("");
167         }
168         if ((env = getenv("SSH_CONNECTION")) != NULL) {
169                 tokens = g_strsplit(env, " ", 4);
170                 if (tokens[3]) {
171                         remip = sanitize_filter_ip(tokens[0]);
172                         locip = sanitize_filter_ip(tokens[2]);
173                         g_string_printf(filter_str, "not (tcp port %s and %s host %s "
174                                                          "and tcp port %s and %s host %s)", tokens[1], host_ip_af(remip), remip,
175                                 tokens[3], host_ip_af(locip), locip);
176                         g_free(remip);
177                         g_free(locip);
178                         return filter_str->str;
179                 }
180         } else if ((env = getenv("SSH_CLIENT")) != NULL) {
181                 tokens = g_strsplit(env, " ", 3);
182                 remip = sanitize_filter_ip(tokens[2]);
183                 g_string_printf(filter_str, "not (tcp port %s and %s host %s "
184                         "and tcp port %s)", tokens[1], host_ip_af(remip), tokens[0], remip);
185                 g_free(remip);
186                 return filter_str->str;
187         } else if ((env = getenv("REMOTEHOST")) != NULL) {
188                 /* FreeBSD 7.0 sets REMOTEHOST to an empty string */
189                 if (g_ascii_strcasecmp(env, "localhost") == 0 ||
190                     strcmp(env, "127.0.0.1") == 0 ||
191                     strcmp(env, "") == 0) {
192                         return "";
193                 }
194                 remip = sanitize_filter_ip(env);
195                 g_string_printf(filter_str, "not %s host %s", host_ip_af(remip), remip);
196                 g_free(remip);
197                 return filter_str->str;
198         } else if ((env = getenv("DISPLAY")) != NULL) {
199                 /*
200                  * This mirrors what _X11TransConnectDisplay() does.
201                  * Note that, on some systems, the hostname can
202                  * begin with "/", which means that it's a pathname
203                  * of a UNIX domain socket to connect to.
204                  *
205                  * The comments mirror those in _X11TransConnectDisplay(),
206                  * too. :-)
207                  *
208                  * Display names may be of the following format:
209                  *
210                  *    [protoco./] [hostname] : [:] displaynumber [.screennumber]
211                  *
212                  * A string with exactly two colons separating hostname
213                  * from the display indicates a DECnet style name.  Colons
214                  * in the hostname may occur if an IPv6 numeric address
215                  * is used as the hostname.  An IPv6 numeric address may
216                  * also end in a double colon, so three colons in a row
217                  * indicates an IPv6 address ending in :: followed by
218                  * :display.  To make it easier for people to read, an
219                  * IPv6 numeric address hostname may be surrounded by []
220                  * in a similar fashion to the IPv6 numeric address URL
221                  * syntax defined by IETF RFC 2732.
222                  *
223                  * If no hostname and no protocol is specified, the string
224                  * is interpreted as the most efficient local connection
225                  * to a server on the same machine.  This is usually:
226                  *
227                  *    o shared memory
228                  *    o local stream
229                  *    o UNIX domain socket
230                  *    o TCP to local host.
231                  */
232
233                 p = env;
234
235                 /*
236                  * Step 0, find the protocol.  This is delimited by
237                  * the optional slash ('/').
238                  */
239                 for (lastp = p; *p != '\0' && *p != ':' && *p != '/'; p++)
240                         ;
241                 if (*p == '\0')
242                         return "";      /* must have a colon */
243
244                 if (p != lastp && *p != ':') {  /* protocol given? */
245                         /* Yes */
246                         pprotocol = p;
247
248                         /* Is it TCP? */
249                         if (p - lastp != 3 || g_ascii_strncasecmp(lastp, "tcp", 3) != 0)
250                                 return "";      /* not TCP */
251                         p++;                    /* skip the '/' */
252                 } else
253                         p = env;                /* reset the pointer in
254                                                    case no protocol was given */
255
256                 /*
257                  * Step 1, find the hostname.  This is delimited either by
258                  * one colon, or two colons in the case of DECnet (DECnet
259                  * Phase V allows a single colon in the hostname).  (See
260                  * note above regarding IPv6 numeric addresses with
261                  * triple colons or [] brackets.)
262                  */
263                 lastp = p;
264                 lastc = NULL;
265                 for (; *p != '\0'; p++)
266                         if (*p == ':')
267                                 lastc = p;
268
269                 if (lastc == NULL)
270                         return "";              /* must have a colon */
271
272                 if ((lastp != lastc) && (*(lastc - 1) == ':')
273                     && (((lastc - 1) == lastp) || (*(lastc - 2) != ':'))) {
274                         /* DECnet display specified */
275                         return "";
276                 } else
277                         hostlen = lastc - lastp;
278
279                 if (hostlen == 0)
280                         return "";      /* no hostname supplied */
281
282                 phostname = (char *)g_malloc(hostlen + 1);
283                 memcpy(phostname, lastp, hostlen);
284                 phostname[hostlen] = '\0';
285
286                 if (pprotocol == NULL) {
287                         /*
288                          * No protocol was explicitly specified, so it
289                          * could be a local connection over a transport
290                          * that we won't see.
291                          *
292                          * Does the host name refer to the local host?
293                          * If so, the connection would probably be a
294                          * local connection.
295                          *
296                          * XXX - compare against our host name?
297                          * _X11TransConnectDisplay() does.
298                          */
299                         if (g_ascii_strcasecmp(phostname, "localhost") == 0 ||
300                             strcmp(phostname, "127.0.0.1") == 0) {
301                                 g_free(phostname);
302                                 return "";
303                         }
304
305                         /*
306                          * A host name of "unix" (case-sensitive) also
307                          * causes a local connection.
308                          */
309                         if (strcmp(phostname, "unix") == 0) {
310                                 g_free(phostname);
311                                 return "";
312                         }
313
314                         /*
315                          * Does the host name begin with "/"?  If so,
316                          * it's presumed to be the pathname of a
317                          * UNIX domain socket.
318                          */
319                         if (phostname[0] == '/') {
320                                 g_free(phostname);
321                                 return "";
322                         }
323                 }
324
325                 g_string_printf(filter_str, "not %s host %s",
326                         host_ip_af(phostname), phostname);
327                 g_free(phostname);
328                 return filter_str->str;
329         } else if ((env = getenv("SESSIONNAME")) != NULL) {
330                 /* Apparently the KB article at
331                  * http://technet2.microsoft.com/WindowsServer/en/library/6caf87bf-3d70-4801-9485-87e9ec3df0171033.mspx?mfr=true
332                  * is incorrect.  There are _plenty_ of cases where CLIENTNAME
333                  * and SESSIONNAME are set outside of a Terminal Terver session.
334                  * It looks like Terminal Server sets SESSIONNAME to RDP-TCP#<number>
335                  * for "real" sessions.
336                  *
337                  * XXX - There's a better way to do this described at
338                  * http://www.microsoft.com/technet/archive/termsrv/maintain/featusability/tsrvapi.mspx?mfr=true
339                  */
340                 if (g_ascii_strncasecmp(env, "rdp", 3) == 0) {
341                         g_string_printf(filter_str, "not tcp port 3389");
342                         return filter_str->str;
343                 }
344         }
345         return "";
346 }