From Francesco Fondelli:
[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
43 #include "util.h"
44
45 /*
46  * Collect command-line arguments as a string consisting of the arguments,
47  * separated by spaces.
48  */
49 char *
50 get_args_as_string(int argc, char **argv, int optind)
51 {
52         int len;
53         int i;
54         char *argstring;
55
56         /*
57          * Find out how long the string will be.
58          */
59         len = 0;
60         for (i = optind; i < argc; i++) {
61                 len += strlen(argv[i]);
62                 len++;  /* space, or '\0' if this is the last argument */
63         }
64
65         /*
66          * Allocate the buffer for the string.
67          */
68         argstring = g_malloc(len);
69
70         /*
71          * Now construct the string.
72          */
73         strcpy(argstring, "");
74         i = optind;
75         for (;;) {
76                 strcat(argstring, argv[i]);
77                 i++;
78                 if (i == argc)
79                         break;
80                 strcat(argstring, " ");
81         }
82         return argstring;
83 }
84
85 /* Compute the difference between two seconds/microseconds time stamps. */
86 void
87 compute_timestamp_diff(gint *diffsec, gint *diffusec,
88         guint32 sec1, guint32 usec1, guint32 sec2, guint32 usec2)
89 {
90   if (sec1 == sec2) {
91     /* The seconds part of the first time is the same as the seconds
92        part of the second time, so if the microseconds part of the first
93        time is less than the microseconds part of the second time, the
94        first time is before the second time.  The microseconds part of
95        the delta should just be the difference between the microseconds
96        part of the first time and the microseconds part of the second
97        time; don't adjust the seconds part of the delta, as it's OK if
98        the microseconds part is negative. */
99
100     *diffsec = sec1 - sec2;
101     *diffusec = usec1 - usec2;
102   } else if (sec1 <= sec2) {
103     /* The seconds part of the first time is less than the seconds part
104        of the second time, so the first time is before the second time.
105
106        Both the "seconds" and "microseconds" value of the delta
107        should have the same sign, so if the difference between the
108        microseconds values would be *positive*, subtract 1,000,000
109        from it, and add one to the seconds value. */
110     *diffsec = sec1 - sec2;
111     if (usec2 >= usec1) {
112       *diffusec = usec1 - usec2;
113     } else {
114       *diffusec = (usec1 - 1000000) - usec2;
115       (*diffsec)++;
116     }
117   } else {
118     /* Oh, good, we're not caught in a chronosynclastic infindibulum. */
119     *diffsec = sec1 - sec2;
120     if (usec2 <= usec1) {
121       *diffusec = usec1 - usec2;
122     } else {
123       *diffusec = (usec1 + 1000000) - usec2;
124       (*diffsec)--;
125     }
126   }
127 }
128
129 /* Try to figure out if we're remotely connected, e.g. via ssh or
130    Terminal Server, and create a capture filter that matches aspects of the
131    connection.  We match the following environment variables:
132
133    SSH_CONNECTION (ssh): <remote IP> <remote port> <local IP> <local port>
134    SSH_CLIENT (ssh): <remote IP> <remote port> <local port>
135    REMOTEHOST (tcsh, others?): <remote name>
136    DISPLAY (x11): [remote name]:<display num>
137    SESSIONNAME (terminal server): <remote name>
138  */
139
140 const gchar *get_conn_cfilter(void) {
141         static GString *filter_str = NULL;
142         gchar *env, **tokens;
143         char *lastp, *lastc, *p;
144         char *pprotocol = NULL;
145         char *phostname = NULL;
146         size_t hostlen;
147
148         if (filter_str == NULL) {
149                 filter_str = g_string_new("");
150         }
151         if ((env = getenv("SSH_CONNECTION")) != NULL) {
152                 tokens = g_strsplit(env, " ", 4);
153                 if (tokens[3]) {
154                         g_string_sprintf(filter_str, "not (tcp port %s and %s host %s "
155                                                          "and tcp port %s and %s host %s)", tokens[1], host_ip_af(tokens[0]), tokens[0],
156                                 tokens[3], host_ip_af(tokens[2]), tokens[2]);
157                         return filter_str->str;
158                 }
159         } else if ((env = getenv("SSH_CLIENT")) != NULL) {
160                 tokens = g_strsplit(env, " ", 3);
161                 g_string_sprintf(filter_str, "not (tcp port %s and %s host %s "
162                         "and tcp port %s)", tokens[1], host_ip_af(tokens[0]), tokens[0], tokens[2]);
163                 return filter_str->str;
164         } else if ((env = getenv("REMOTEHOST")) != NULL) {
165                 if (strcasecmp(env, "localhost") == 0 || strcmp(env, "127.0.0.1") == 0) {
166                         return "";
167                 }
168                 g_string_sprintf(filter_str, "not %s host %s", host_ip_af(env), env);
169                 return filter_str->str;
170         } else if ((env = getenv("DISPLAY")) != NULL) {
171                 /*
172                  * This mirrors what _X11TransConnectDisplay() does.
173                  * Note that, on some systems, the hostname can
174                  * being with "/", which means that it's a pathname
175                  * of a UNIX domain socket to connect to.
176                  *
177                  * The comments mirror those in _X11TransConnectDisplay(),
178                  * too. :-)
179                  *
180                  * Display names may be of the following format:
181                  *
182                  *    [protoco./] [hostname] : [:] displaynumber [.screennumber]
183                  *
184                  * A string with exactly two colons separating hostname
185                  * from the display indicates a DECnet style name.  Colons
186                  * in the hostname may occur if an IPv6 numeric address
187                  * is used as the hostname.  An IPv6 numeric address may
188                  * also end in a double colon, so three colons in a row
189                  * indicates an IPv6 address ending in :: followed by
190                  * :display.  To make it easier for people to read, an
191                  * IPv6 numeric address hostname may be surrounded by []
192                  * in a similar fashion to the IPv6 numeric address URL
193                  * syntax defined by IETF RFC 2732.
194                  *
195                  * If no hostname and no protocol is specified, the string
196                  * is interpreted as the most efficient local connection
197                  * to a server on the same machine.  This is usually:
198                  *
199                  *    o shared memory
200                  *    o local stream
201                  *    o UNIX domain socket
202                  *    o TCP to local host.
203                  */
204
205                 p = env;
206
207                 /*
208                  * Step 0, find the protocol.  This is delimited by
209                  * the optional slash ('/').
210                  */
211                 for (lastp = p; *p != '\0' && *p != ':' && *p != '/'; p++)
212                         ;
213                 if (*p == '\0')
214                         return "";      /* must have a colon */
215
216                 if (p != lastp && *p != ':') {  /* protocol given? */
217                         /* Yes */
218                         pprotocol = p;
219
220                         /* Is it TCP? */
221                         if (p - lastp != 3 || strncasecmp(lastp, "tcp", 3) != 0)
222                                 return "";      /* not TCP */
223                         p++;                    /* skip the '/' */
224                 } else
225                         p = env;                /* reset the pointer in
226                                                    case no protocol was given */
227
228                 /*
229                  * Step 1, find the hostname.  This is delimited either by
230                  * one colon, or two colons in the case of DECnet (DECnet
231                  * Phase V allows a single colon in the hostname).  (See
232                  * note above regarding IPv6 numeric addresses with
233                  * triple colons or [] brackets.)
234                  */
235                 lastp = p;
236                 lastc = NULL;
237                 for (; *p != '\0'; p++)
238                         if (*p == ':')
239                                 lastc = p;
240
241                 if (lastc == NULL)
242                         return "";              /* must have a colon */
243
244                 if ((lastp != lastc) && (*(lastc - 1) == ':')
245                     && (((lastc - 1) == lastp) || (*(lastc - 2) != ':'))) {
246                         /* DECnet display specified */
247                         return "";
248                 } else
249                         hostlen = lastc - lastp;
250
251                 if (hostlen == 0)
252                         return "";      /* no hostname supplied */
253
254                 phostname = g_malloc(hostlen + 1);
255                 memcpy(phostname, lastp, hostlen);
256                 phostname[hostlen] = '\0';
257
258                 if (pprotocol == NULL) {
259                         /*
260                          * No protocol was explicitly specified, so it
261                          * could be a local connection over a transport
262                          * that we won't see.
263                          *
264                          * Does the host name refer to the local host?
265                          * If so, the connection would probably be a
266                          * local connection.
267                          *
268                          * XXX - compare against our host name?
269                          * _X11TransConnectDisplay() does.
270                          */
271                         if (strcasecmp(phostname, "localhost") == 0 ||
272                             strcmp(phostname, "127.0.0.1") == 0) {
273                                 g_free(phostname);
274                                 return "";
275                         }
276
277                         /*
278                          * A host name of "unix" (case-sensitive) also
279                          * causes a local connection.
280                          */
281                         if (strcmp(phostname, "unix") == 0) {
282                                 g_free(phostname);
283                                 return "";
284                         }
285
286                         /*
287                          * Does the host name begin with "/"?  If so,
288                          * it's presumed to be the pathname of a
289                          * UNIX domain socket.
290                          */
291                         if (phostname[0] == '/') {
292                                 g_free(phostname);
293                                 return "";
294                         }
295                 }
296
297                 g_string_sprintf(filter_str, "not %s host %s",
298                         host_ip_af(phostname), phostname);
299                 g_free(phostname);
300                 return filter_str->str;
301         } else if ((env = getenv("SESSIONNAME")) != NULL) {
302                 /* Apparently the KB article at
303                  * http://technet2.microsoft.com/WindowsServer/en/library/6caf87bf-3d70-4801-9485-87e9ec3df0171033.mspx?mfr=true
304                  * is incorrect.  There are _plenty_ of cases where CLIENTNAME
305                  * and SESSIONNAME are set outside of a Terminal Terver session.
306                  * It looks like Terminal Server sets SESSIONNAME to RDP-TCP#<number>
307                  * for "real" sessions.
308                  *
309                  * XXX - There's a better way to do this described at
310                  * http://www.microsoft.com/technet/archive/termsrv/maintain/featusability/tsrvapi.mspx?mfr=true
311                  */
312                 if (g_strncasecmp(env, "rdp", 3) == 0) {
313                         g_string_sprintf(filter_str, "not tcp port 3389");
314                         return filter_str->str;
315                 }
316         }
317         return "";
318 }