Setting tag sliver-openvswitch-2.2.90-1
[sliver-openvswitch.git] / lib / pcap-file.c
1 /*
2  * Copyright (c) 2009, 2010, 2012, 2013, 2014 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "pcap-file.h"
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/stat.h>
24 #include "byte-order.h"
25 #include "compiler.h"
26 #include "flow.h"
27 #include "hmap.h"
28 #include "ofpbuf.h"
29 #include "packets.h"
30 #include "timeval.h"
31 #include "unaligned.h"
32 #include "vlog.h"
33
34 VLOG_DEFINE_THIS_MODULE(pcap);
35
36 struct pcap_hdr {
37     uint32_t magic_number;   /* magic number */
38     uint16_t version_major;  /* major version number */
39     uint16_t version_minor;  /* minor version number */
40     int32_t thiszone;        /* GMT to local correction */
41     uint32_t sigfigs;        /* accuracy of timestamps */
42     uint32_t snaplen;        /* max length of captured packets */
43     uint32_t network;        /* data link type */
44 };
45 BUILD_ASSERT_DECL(sizeof(struct pcap_hdr) == 24);
46
47 struct pcaprec_hdr {
48     uint32_t ts_sec;         /* timestamp seconds */
49     uint32_t ts_usec;        /* timestamp microseconds */
50     uint32_t incl_len;       /* number of octets of packet saved in file */
51     uint32_t orig_len;       /* actual length of packet */
52 };
53 BUILD_ASSERT_DECL(sizeof(struct pcaprec_hdr) == 16);
54
55 FILE *
56 ovs_pcap_open(const char *file_name, const char *mode)
57 {
58     struct stat s;
59     FILE *file;
60     int error;
61
62     ovs_assert(!strcmp(mode, "rb") ||
63                !strcmp(mode, "wb") ||
64                !strcmp(mode, "ab"));
65
66     file = fopen(file_name, mode);
67     if (file == NULL) {
68         VLOG_WARN("%s: failed to open pcap file for %s (%s)", file_name,
69                   (mode[0] == 'r' ? "reading"
70                    : mode[0] == 'w' ? "writing"
71                    : "appending"),
72                   ovs_strerror(errno));
73         return NULL;
74     }
75
76     switch (mode[0]) {
77     case 'r':
78         error = ovs_pcap_read_header(file);
79         if (error) {
80             errno = error;
81             fclose(file);
82             return NULL;
83         }
84         break;
85
86     case 'w':
87         ovs_pcap_write_header(file);
88         break;
89
90     case 'a':
91         if (!fstat(fileno(file), &s) && !s.st_size) {
92             ovs_pcap_write_header(file);
93         }
94         break;
95
96     default:
97         OVS_NOT_REACHED();
98     }
99     return file;
100 }
101
102 int
103 ovs_pcap_read_header(FILE *file)
104 {
105     struct pcap_hdr ph;
106     if (fread(&ph, sizeof ph, 1, file) != 1) {
107         int error = ferror(file) ? errno : EOF;
108         VLOG_WARN("failed to read pcap header: %s", ovs_retval_to_string(error));
109         return error;
110     }
111     if (ph.magic_number != 0xa1b2c3d4 && ph.magic_number != 0xd4c3b2a1) {
112         VLOG_WARN("bad magic 0x%08"PRIx32" reading pcap file "
113                   "(expected 0xa1b2c3d4 or 0xd4c3b2a1)", ph.magic_number);
114         return EPROTO;
115     }
116     return 0;
117 }
118
119 void
120 ovs_pcap_write_header(FILE *file)
121 {
122     /* The pcap reader is responsible for figuring out endianness based on the
123      * magic number, so the lack of htonX calls here is intentional. */
124     struct pcap_hdr ph;
125     ph.magic_number = 0xa1b2c3d4;
126     ph.version_major = 2;
127     ph.version_minor = 4;
128     ph.thiszone = 0;
129     ph.sigfigs = 0;
130     ph.snaplen = 1518;
131     ph.network = 1;             /* Ethernet */
132     ignore(fwrite(&ph, sizeof ph, 1, file));
133 }
134
135 int
136 ovs_pcap_read(FILE *file, struct ofpbuf **bufp, long long int *when)
137 {
138     struct pcaprec_hdr prh;
139     struct ofpbuf *buf;
140     void *data;
141     size_t len;
142     bool swap;
143
144     *bufp = NULL;
145
146     /* Read header. */
147     if (fread(&prh, sizeof prh, 1, file) != 1) {
148         if (ferror(file)) {
149             int error = errno;
150             VLOG_WARN("failed to read pcap record header: %s",
151                       ovs_retval_to_string(error));
152             return error;
153         } else {
154             return EOF;
155         }
156     }
157
158     /* Calculate length. */
159     len = prh.incl_len;
160     swap = len > 0xffff;
161     if (swap) {
162         len = uint32_byteswap(len);
163         if (len > 0xffff) {
164             VLOG_WARN("bad packet length %"PRIuSIZE" or %"PRIu32
165                       "reading pcap file",
166                       len, uint32_byteswap(len));
167             return EPROTO;
168         }
169     }
170
171     /* Calculate time. */
172     if (when) {
173         uint32_t ts_sec = swap ? uint32_byteswap(prh.ts_sec) : prh.ts_sec;
174         uint32_t ts_usec = swap ? uint32_byteswap(prh.ts_usec) : prh.ts_usec;
175         *when = ts_sec * 1000LL + ts_usec / 1000;
176     }
177
178     /* Read packet. */
179     buf = ofpbuf_new(len);
180     data = ofpbuf_put_uninit(buf, len);
181     if (fread(data, len, 1, file) != 1) {
182         int error = ferror(file) ? errno : EOF;
183         VLOG_WARN("failed to read pcap packet: %s",
184                   ovs_retval_to_string(error));
185         ofpbuf_delete(buf);
186         return error;
187     }
188     *bufp = buf;
189     return 0;
190 }
191
192 void
193 ovs_pcap_write(FILE *file, struct ofpbuf *buf)
194 {
195     struct pcaprec_hdr prh;
196     struct timeval tv;
197
198     xgettimeofday(&tv);
199     prh.ts_sec = tv.tv_sec;
200     prh.ts_usec = tv.tv_usec;
201     prh.incl_len = ofpbuf_size(buf);
202     prh.orig_len = ofpbuf_size(buf);
203     ignore(fwrite(&prh, sizeof prh, 1, file));
204     ignore(fwrite(ofpbuf_data(buf), ofpbuf_size(buf), 1, file));
205 }
206 \f
207 struct tcp_key {
208     ovs_be32 nw_src, nw_dst;
209     ovs_be16 tp_src, tp_dst;
210 };
211
212 struct tcp_stream {
213     struct hmap_node hmap_node;
214     struct tcp_key key;
215     uint32_t seq_no;
216     struct ofpbuf payload;
217 };
218
219 struct tcp_reader {
220     struct hmap streams;
221 };
222
223 static void
224 tcp_stream_destroy(struct tcp_reader *r, struct tcp_stream *stream)
225 {
226     hmap_remove(&r->streams, &stream->hmap_node);
227     ofpbuf_uninit(&stream->payload);
228     free(stream);
229 }
230
231 /* Returns a new data structure for extracting TCP stream data from an
232  * Ethernet packet capture */
233 struct tcp_reader *
234 tcp_reader_open(void)
235 {
236     struct tcp_reader *r;
237
238     r = xmalloc(sizeof *r);
239     hmap_init(&r->streams);
240     return r;
241 }
242
243 /* Closes and frees 'r'. */
244 void
245 tcp_reader_close(struct tcp_reader *r)
246 {
247     struct tcp_stream *stream, *next_stream;
248
249     HMAP_FOR_EACH_SAFE (stream, next_stream, hmap_node, &r->streams) {
250         tcp_stream_destroy(r, stream);
251     }
252     hmap_destroy(&r->streams);
253     free(r);
254 }
255
256 static struct tcp_stream *
257 tcp_stream_lookup(struct tcp_reader *r,
258                   const struct tcp_key *key, uint32_t hash)
259 {
260     struct tcp_stream *stream;
261
262     HMAP_FOR_EACH_WITH_HASH (stream, hmap_node, hash, &r->streams) {
263         if (!memcmp(&stream->key, key, sizeof *key)) {
264             return stream;
265         }
266     }
267     return NULL;
268 }
269
270 static struct tcp_stream *
271 tcp_stream_new(struct tcp_reader *r, const struct tcp_key *key, uint32_t hash)
272 {
273     struct tcp_stream *stream;
274
275     stream = xmalloc(sizeof *stream);
276     hmap_insert(&r->streams, &stream->hmap_node, hash);
277     memcpy(&stream->key, key, sizeof *key);
278     stream->seq_no = 0;
279     ofpbuf_init(&stream->payload, 2048);
280     return stream;
281 }
282
283 /* Processes 'packet' through TCP reader 'r'.  The caller must have already
284  * extracted the packet's headers into 'flow', using flow_extract().
285  *
286  * If 'packet' is a TCP packet, then the reader attempts to reconstruct the
287  * data stream.  If successful, it returns an ofpbuf that represents the data
288  * stream so far.  The caller may examine the data in the ofpbuf and pull off
289  * any data that it has fully processed.  The remaining data that the caller
290  * does not pull off will be presented again in future calls if more data
291  * arrives in the stream.
292  *
293  * Returns null if 'packet' doesn't add new data to a TCP stream. */
294 struct ofpbuf *
295 tcp_reader_run(struct tcp_reader *r, const struct flow *flow,
296                const struct ofpbuf *packet)
297 {
298     struct tcp_stream *stream;
299     struct tcp_header *tcp;
300     struct ofpbuf *payload;
301     unsigned int l7_length;
302     struct tcp_key key;
303     uint32_t hash;
304     uint32_t seq;
305     uint8_t flags;
306     const char *l7 = ofpbuf_get_tcp_payload(packet);
307
308     if (flow->dl_type != htons(ETH_TYPE_IP)
309         || flow->nw_proto != IPPROTO_TCP
310         || !l7) {
311         return NULL;
312     }
313     tcp = ofpbuf_l4(packet);
314     flags = TCP_FLAGS(tcp->tcp_ctl);
315     l7_length = (char *) ofpbuf_tail(packet) - l7;
316     seq = ntohl(get_16aligned_be32(&tcp->tcp_seq));
317
318     /* Construct key. */
319     memset(&key, 0, sizeof key);
320     key.nw_src = flow->nw_src;
321     key.nw_dst = flow->nw_dst;
322     key.tp_src = flow->tp_src;
323     key.tp_dst = flow->tp_dst;
324     hash = hash_bytes(&key, sizeof key, 0);
325
326     /* Find existing stream or start a new one for a SYN or if there's data. */
327     stream = tcp_stream_lookup(r, &key, hash);
328     if (!stream) {
329         if (flags & TCP_SYN || l7_length) {
330             stream = tcp_stream_new(r, &key, hash);
331             stream->seq_no = flags & TCP_SYN ? seq + 1 : seq;
332         } else {
333             return NULL;
334         }
335     }
336
337     payload = &stream->payload;
338     if (flags & TCP_SYN || !stream->seq_no) {
339         ofpbuf_clear(payload);
340         stream->seq_no = seq + 1;
341         return NULL;
342     } else if (flags & (TCP_FIN | TCP_RST)) {
343         tcp_stream_destroy(r, stream);
344         return NULL;
345     } else if (seq == stream->seq_no) {
346         /* Shift all of the existing payload to the very beginning of the
347          * allocated space, so that we reuse allocated space instead of
348          * continually expanding it. */
349         ofpbuf_shift(payload, (char *) ofpbuf_base(payload) - (char *) ofpbuf_data(payload));
350
351         ofpbuf_put(payload, l7, l7_length);
352         stream->seq_no += l7_length;
353         return payload;
354     } else {
355         return NULL;
356     }
357 }