Handle the new LINKTYPE_CAN_SOCKETCAN_HOSTENDIAN.
[metze/wireshark/wip.git] / wiretap / k12.c
1 /*
2  * k12.c
3  *
4  *  routines for importing tektronix k12xx *.rf5 files
5  *
6  *  Copyright (c) 2005, Luis E. Garia Ontanon <luis@ontanon.org>
7  *
8  * Wiretap Library
9  * Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License
13  * as published by the Free Software Foundation; either version 2
14  * of the License, or (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24  */
25
26 #include "config.h"
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.h>
30
31 #include "wtap-int.h"
32 #include "file_wrappers.h"
33 #include "k12.h"
34
35 #include <wsutil/str_util.h>
36
37 /*
38  * See
39  *
40  *  http://www.tek.com/manual/record-file-api-programmer-manual
41  *
42  * for some information about the file format.  You may have to fill in
43  * a form to download the document ("Record File API Programmer Manual").
44  *
45  * Unfortunately, it describes an API that delivers records from an rf5
46  * file, not the raw format of an rf5 file, so, while it gives the formats
47  * of the records with various types, it does not indicate how those records
48  * are stored in the file.
49  */
50
51 /* #define DEBUG_K12 */
52 #ifdef DEBUG_K12
53 #include <stdio.h>
54 #include <stdarg.h>
55 #include <wsutil/file_util.h>
56
57 FILE* dbg_out = NULL;
58 char* env_file = NULL;
59
60 static unsigned int debug_level = 0;
61
62 void k12_fprintf(const char* fmt, ...) {
63     va_list ap;
64
65     va_start(ap,fmt);
66     vfprintf(dbg_out, fmt, ap);
67     va_end(ap);
68 }
69
70 #define CAT(a,b) a##b
71 #define K12_DBG(level,args) do { if (level <= debug_level) { \
72             fprintf(dbg_out,"%s:%d: ",CAT(__FI,LE__),CAT(__LI,NE__));   \
73             k12_fprintf args ;                                          \
74             fprintf(dbg_out,"\n");                                      \
75 } } while(0)
76
77 void k12_hex_ascii_dump(guint level, gint64 offset, const char* label, const unsigned char* b, unsigned int len) {
78     static const char* c2t[] = {
79         "00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f",
80         "10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f",
81         "20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f",
82         "30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f",
83         "40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f",
84         "50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f",
85         "60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f",
86         "70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f",
87         "80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f",
88         "90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f",
89         "a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af",
90         "b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf",
91         "c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf",
92         "d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df",
93         "e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef",
94         "f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"
95     };
96     unsigned int i, j;
97
98     if (debug_level < level) return;
99
100     fprintf(dbg_out,"%s(%.8" G_GINT64_MODIFIER "x,%.4x):\n",label,offset,len);
101
102     for (i=0 ; i<len ; i += 16) {
103         for (j=0; j<16; j++) {
104             if ((j%4)==0)
105                 fprintf(dbg_out," ");
106             if ((i+j)<len)
107                 fprintf(dbg_out, "%s", c2t[b[i+j]]);
108             else
109                 fprintf(dbg_out, "  ");
110         }
111         fprintf(dbg_out, "    ");
112         for (j=0; j<16; j++) {
113             if ((i+j)<len)
114                 fprintf(dbg_out, "%c", g_ascii_isprint(b[i+j]) ? b[i+j] : '.');
115         }
116         fprintf(dbg_out,"\n");
117     }
118 }
119
120 #define K12_HEX_ASCII_DUMP(x,a,b,c,d) k12_hex_ascii_dump(x,a,b,c,d)
121
122 void k12_ascii_dump(guint level, guint8 *buf, guint32 len, guint32 buf_offset) {
123     guint32 i;
124
125     if (debug_level < level) return;
126
127     for (i = buf_offset; i < len; i++) {
128         if (g_ascii_isprint(buf[i]) || buf[i] == '\n' || buf[i] == '\t')
129             putc(buf[i], dbg_out);
130         else if (buf[i] == '\0')
131             fprintf(dbg_out, "(NUL)\n");
132     }
133 }
134
135 #define K12_ASCII_DUMP(x,a,b,c) k12_ascii_dump(x,a,b,c)
136
137 #else
138 #define K12_DBG(level,args) (void)0
139 #define K12_HEX_ASCII_DUMP(x,a,b,c,d)
140 #define K12_ASCII_DUMP(x,a,b,c)
141 #endif
142
143
144
145 /*
146  * A 32-bit .rf5 file begins with a 512-byte file header, containing:
147  *
148  *  a 32-bit big-endian file header length, in bytes - always 512 in
149  *  the files we've seen;
150  *
151  *  4 unknown bytes, always 0x12 0x05 0x00 0x10;
152  *
153  *  a 32-bit big-endian file length, giving the total length of the file,
154  *  in bytes;
155  *
156  *  a 32-bit big-endian number giving the "page size" of the file, in
157  *  bytes, which is normally 8192;
158  *
159  *  20 unknown bytes;
160  *
161  *  a 32-bit count of the number of records in the file;
162  *
163  *  4 unknown bytes;
164  *
165  *  a 32-bit count of the number of records in the file;
166  *
167  *  464 unknown bytes;
168  *
169  * followed by a sequence of records containing:
170  *
171  *  a 32-bit big-endian record length;
172  *
173  *  a 32-bit big-endian record type;
174  *
175  *  a 32-bit big-endian frame length;
176  *
177  *  a 32-bit big-endian source ID.
178  *
179  * Every 8192 bytes, starting immediately after the 512-byte header,
180  * there's a 16-byte blob; it's not part of the record data.
181  * There's no obvious pattern to the data; it might be junk left
182  * in memory as the file was being written.
183  *
184  * There's a 16-bit terminator FFFF at the end.
185  *
186  * Older versions of the Wireshark .rf5 writing code incorrectly wrote
187  * the header - they put 512 in the file length field (counting only the
188  * header), put a count of records into the "page size" field, and wrote
189  * out zeroes in the rest of the header.  We detect those files by
190  * checking whether the rest of the header is zero.
191  */
192
193 /*
194  * We use the first 8 bytes of the file header as a magic number.
195  */
196 static const guint8 k12_file_magic[] = { 0x00, 0x00, 0x02, 0x00 ,0x12, 0x05, 0x00, 0x10 };
197
198 #define K12_FILE_HDR_LEN      512
199
200 /*
201  * Offsets in the file header.
202  */
203 #define K12_FILE_HDR_MAGIC_NUMBER   0x00
204 #define K12_FILE_HDR_FILE_SIZE      0x08
205 #define K12_FILE_HDR_PAGE_SIZE      0x0C
206 #define K12_FILE_HDR_RECORD_COUNT_1 0x24
207 #define K12_FILE_HDR_RECORD_COUNT_2 0x2C
208
209 #define K12_FILE_BLOB_LEN     16
210
211 typedef struct {
212     guint32 file_len;
213     guint32 num_of_records;   /* XXX: not sure about this */
214
215     GHashTable* src_by_id;    /* k12_srcdsc_recs by input */
216     GHashTable* src_by_name;  /* k12_srcdsc_recs by stack_name */
217
218     guint8 *seq_read_buff;    /* read buffer for sequential reading */
219     guint seq_read_buff_len;  /* length of that buffer */
220     guint8 *rand_read_buff;   /* read buffer for random reading */
221     guint rand_read_buff_len; /* length of that buffer */
222
223     Buffer extra_info;        /* Buffer to hold per packet extra information */
224 } k12_t;
225
226 typedef struct _k12_src_desc_t {
227     guint32 input;
228     guint32 input_type;
229     gchar* input_name;
230     gchar* stack_file;
231     k12_input_info_t input_info;
232 } k12_src_desc_t;
233
234
235 /*
236  * According to the Tektronix documentation, this value is a combination of
237  * a "group" code and a "type" code, with both being 2-byte values and
238  * with the "group" code followe by the "type" code.  The "group" values
239  * are:
240  *
241  *      0x0001 - "data event"
242  *      0x0002 - "text or L1 event"
243  *      0x0007 - "configuration event"
244  *
245  * and the "type" values are:
246  *
247  *  data events:
248  *      0x0020 - "frame" (i.e., "an actual packet")
249  *      0x0021 - "transparent frame"
250  *      0x0022 - "bit data (TRAU frame)"
251  *      0x0024 - "used to mark the frame which is a fragment"
252  *      0x0026 - "used to mark the frame which is a fragment"
253  *      0x0028 - "used to mark the frame which is generated by the LSA"
254  *      0x002A - "used to mark the frame which is generated by the LSA"
255  *
256  *  text or L1 events:
257  *      0x0030 - "text event"
258  *      0x0031 - "L1 event"
259  *      0x0032 - "L1 event (BAI)"
260  *      0x0033 - "L1 event (VX)"
261  *
262  *  configuration events:
263  *      0x0040 - Logical Data Source configuration event
264  *      0x0041 - Logical Link configuration event
265  */
266 /* so far we've seen these types of records */
267 #define K12_REC_PACKET        0x00010020 /* an actual packet */
268 #define K12_REC_D0020         0x000d0020 /* an actual packet, seen in a k18 file */
269 #define K12_REC_SCENARIO      0x00070040 /* what appears as the window's title */
270 #define K12_REC_SRCDSC        0x00070041 /* port-stack mapping + more, the key of the whole thing */
271 #define K12_REC_STK_FILE      0x00070042 /* a dump of an stk file */
272 #define K12_REC_SRCDSC2       0x00070043 /* another port-stack mapping */
273 #define K12_REC_TEXT          0x00070044 /* a string containing something with a grammar (conditions/responses?) */
274 #define K12_REC_START         0x00020030 /* a string containing human readable start time  */
275 #define K12_REC_STOP          0x00020031 /* a string containing human readable stop time */
276
277 /*
278  * According to the Tektronix documentation, packets, i.e. "data events",
279  * have several different group/type values, which differ in the last
280  * nibble of the type code.  For now, we just mask that nibble off; the
281  * format of the items are different, so we might have to treat different
282  * data event types differently.
283  */
284 #define K12_MASK_PACKET       0xfffffff0
285
286 /* offsets of elements in the records */
287 #define K12_RECORD_LEN         0x0 /* uint32, in bytes */
288 #define K12_RECORD_TYPE        0x4 /* uint32, see above */
289 #define K12_RECORD_FRAME_LEN   0x8 /* uint32, in bytes */
290 #define K12_RECORD_SRC_ID      0xc /* uint32 */
291
292 /*
293  * Some records from K15 files have a port ID of an undeclared
294  * interface which happens to be the only one with the first byte changed.
295  * It is still unknown how to recognize when this happens.
296  * If the lookup of the interface record fails we'll mask it
297  * and retry.
298  */
299 #define K12_RECORD_SRC_ID_MASK 0x00ffffff
300
301 /* elements of packet records */
302 #define K12_PACKET_TIMESTAMP  0x18 /* int64 (8b) representing 1/2us since 01-01-1990 Z00:00:00 */
303
304 #define K12_PACKET_FRAME      0x20 /* start of the actual frame in the record */
305 #define K12_PACKET_FRAME_D0020 0x34 /* start of the actual frame in the record */
306
307 #define K12_PACKET_OFFSET_VP  0x08 /* 2 bytes, big endian */
308 #define K12_PACKET_OFFSET_VC  0x0a /* 2 bytes, big endian */
309 #define K12_PACKET_OFFSET_CID 0x0c /* 1 byte */
310
311 /* elements of the source description records */
312 #define K12_SRCDESC_COLOR_FOREGROUND 0x12 /* 1 byte */
313 #define K12_SRCDESC_COLOR_BACKGROUND 0x13 /* 1 byte */
314
315 #define K12_SRCDESC_PORT_TYPE  0x1a /* 1 byte */
316 #define K12_SRCDESC_HWPARTLEN  0x1e /* uint16, big endian */
317 #define K12_SRCDESC_NAMELEN    0x20 /* uint16, big endian */
318 #define K12_SRCDESC_STACKLEN   0x22 /* uint16, big endian */
319
320 /* Hardware part of the record */
321 #define K12_SRCDESC_HWPART     0x24 /* offset of the hardware part */
322
323 /* Offsets relative to the beginning of the hardware part */
324 #define K12_SRCDESC_HWPARTTYPE 0    /* uint32, big endian */
325
326 #define K12_SRCDESC_DS0_MASK   24   /* variable-length */
327
328 #define K12_SRCDESC_ATM_VPI    20   /* uint16, big endian */
329 #define K12_SRCDESC_ATM_VCI    22   /* uint16, big endian */
330 #define K12_SRCDESC_ATM_AAL    24   /* 1 byte */
331
332 /*
333  * A "stack file", as appears in a K12_REC_STK_FILE record, is a text
334  * file (with CR-LF line endings) with a sequence of lines, each of
335  * which begins with a keyword, and has white-space-separated tokens
336  * after that.
337  *
338  * They appear to be:
339  *
340  *   STKVER, which is followed by a number (presumably a version number
341  *   for the stack file format)
342  *
343  *   STACK, which is followed by a quoted string ("ProtocolStack" in one
344  *   file) and two numbers
345  *
346  *   PATH, which is followed by a non-quoted string giving the pathname
347  *   of the directory containing the stack file
348  *
349  *   HLAYER, which is followed by a quoted string, a path for something
350  *   (protocol module?), a keyword ("LOADED", in one file), and a
351  *   quoted string giving a description - this is probably a protocol
352  *   layer of some sort
353  *
354  *   LAYER, which has a similar syntax to HLAYER - the first quoted
355  *   string is a protocol name
356  *
357  *   RELATION, which has a quoted string giving a protocol name,
358  *   another quoted string giving a protocol name, and a condition
359  *   specifier of some sort, which probably says the second protocol
360  *   is layered atop the first protocol if the condition is true.
361  *   The first protocol can also be "BASE", which means that the
362  *   second protocol is the lowest-level protocol.
363  *   The conditions are:
364  *
365  *     CPLX, which may mean "complex" - it has parenthesized expressions
366  *     including "&", presumably a boolean AND, with the individual
367  *     tests being L:expr, where L is a letter such as "L", "D", or "P",
368  *     and expr is:
369  *
370  *        0x........ for L, where each . is a hex digit or a ?, presumably
371  *        meaning "don't care"
372  *
373  *        0;0{=,!=}0b........ for D, where . is presumably a bit or a ?
374  *
375  *        param=value for P, where param is something such as "src_port"
376  *        and value is a value, presumably to test, for example, TCP or
377  *        UDP ports
378  *
379  *     UNCOND, presumably meaning "always"
380  *
381  *     PARAM, followed by a parameter name (as with P:) and a value,
382  *     possibly followed by LAYPARAM and a hex value
383  *
384  *   DECKRNL, followed by a quoted string protocol name, un-quoted
385  *   "LSBF" or "MSBF" (Least/Most Significant Byte First?), and
386  *   an un-quoted string ending with _DK
387  *
388  *   LAYPARAM, followed by a quoted protocol name and a number (-2147221504
389  *   in one file, which is 0x80040000)
390  *
391  *   SPC_CONF, folloed by a number, a quoted string with numbers separated
392  *   by hyphens, and another number
393  *
394  *   CIC_CONF, with a similar syntax to SPC_CONF
395  *
396  *   LAYPOS, followed by a protocol name or "BASE" and 3 numbers.
397  *
398  * Most of this is probably not useful, but the RELATION lines with
399  * "BASE" could be used to figure out how to start the dissection
400  * (if we knew what "L" and "D" did), and *some* of the others might
401  * be useful if they don't match what's already in various dissector
402  * tables (the ones for IP and a higher-level protocol, for example,
403  * aren't very useful, as those are standardized, but the ones for
404  * TCP, UDP, and SCTP ports, and SCTP PPIs, might be useful).
405  */
406
407 /*
408  * get_record: Get the next record into a buffer
409  *   Every 8192 bytes 16 bytes are inserted in the file,
410  *   even in the middle of a record.
411  *   This reads the next record without the eventual 16 bytes.
412  *   returns the length of the record + the stuffing (if any)
413  *
414  *   Returns number of bytes read on success, 0 on EOF, -1 on error;
415  *   if -1 is returned, *err is set to the error indication and, for
416  *   errors where that's appropriate, *err_info is set to an additional
417  *   error string.
418  *
419  * XXX: works at most with 8191 bytes per record
420  */
421 static gint get_record(k12_t *file_data, FILE_T fh, gint64 file_offset,
422                        gboolean is_random, int *err, gchar **err_info) {
423     guint8 *buffer = is_random ? file_data->rand_read_buff : file_data->seq_read_buff;
424     guint buffer_len = is_random ? file_data->rand_read_buff_len : file_data->seq_read_buff_len;
425     guint total_read = 0;
426     guint left;
427     guint8* writep;
428 #ifdef DEBUG_K12
429     guint actual_len;
430 #endif
431
432     /*
433      * Where the next unknown 16 bytes are stuffed to the file.
434      * Following the file header, they appear every 8192 bytes,
435      * starting right after the file header, so if the file offset
436      * relative to the file header is a multiple of 8192, the
437      * 16-byte blob is there.
438      */
439     guint junky_offset = 8192 - (gint) ( (file_offset - K12_FILE_HDR_LEN) % 8192 );
440
441     K12_DBG(6,("get_record: ENTER: junky_offset=%" G_GINT64_MODIFIER "d, file_offset=%" G_GINT64_MODIFIER "d",junky_offset,file_offset));
442
443     /* no buffer is given, lets create it */
444     if (buffer == NULL) {
445         buffer = (guint8*)g_malloc(8192);
446         buffer_len = 8192;
447         if (is_random) {
448             file_data->rand_read_buff = buffer;
449             file_data->rand_read_buff_len = buffer_len;
450         } else {
451             file_data->seq_read_buff = buffer;
452             file_data->seq_read_buff_len = buffer_len;
453         }
454     }
455
456     if ( junky_offset == 8192 ) {
457         /*
458          * We're at the beginning of one of the 16-byte blobs,
459          * so we first need to skip the blob.
460          *
461          * XXX - what if the blob is in the middle of the record
462          * length?  If the record length is always a multiple of
463          * 4 bytes, that won't happen.
464          */
465         if ( ! file_skip( fh, K12_FILE_BLOB_LEN, err ) )
466             return -1;
467         total_read += K12_FILE_BLOB_LEN;
468     }
469
470     /*
471      * Read the record length.
472      */
473     if ( !wtap_read_bytes( fh, buffer, 4, err, err_info ) )
474         return -1;
475     total_read += 4;
476
477     left = pntoh32(buffer + K12_RECORD_LEN);
478 #ifdef DEBUG_K12
479     actual_len = left;
480 #endif
481     junky_offset -= 4;
482
483     K12_DBG(5,("get_record: GET length=%u",left));
484
485     /*
486      * Record length must be at least large enough for the length
487      * and type, hence 8 bytes.
488      *
489      * XXX - is WTAP_MAX_PACKET_SIZE the right check for a maximum
490      * record size?  Should we report this error differently?
491      */
492     if (left < 8) {
493         *err = WTAP_ERR_BAD_FILE;
494         *err_info = g_strdup_printf("k12: Record length %u is less than 8 bytes long",left);
495         return -1;
496     }
497     if (left > WTAP_MAX_PACKET_SIZE) {
498         *err = WTAP_ERR_BAD_FILE;
499         *err_info = g_strdup_printf("k12: Record length %u is greater than the maximum %u",left,WTAP_MAX_PACKET_SIZE);
500         return -1;
501     }
502
503     /*
504      * XXX - calculate the lowest power of 2 >= left, rather than just
505      * looping.
506      */
507     while (left > buffer_len) {
508         buffer = (guint8*)g_realloc(buffer,buffer_len*=2);
509         if (is_random) {
510             file_data->rand_read_buff = buffer;
511             file_data->rand_read_buff_len = buffer_len;
512         } else {
513             file_data->seq_read_buff = buffer;
514             file_data->seq_read_buff_len = buffer_len;
515         }
516     }
517
518     writep = buffer + 4;
519     left -= 4;
520
521     /* Read the rest of the record. */
522     do {
523         K12_DBG(6,("get_record: looping left=%d junky_offset=%" G_GINT64_MODIFIER "d",left,junky_offset));
524
525         if (junky_offset > left) {
526             /*
527              * The next 16-byte blob is past the end of this record.
528              * Just read the rest of the record.
529              */
530             if ( !wtap_read_bytes( fh, writep, left, err, err_info ) )
531                 return -1;
532             total_read += left;
533             break;
534         } else {
535             /*
536              * The next 16-byte blob is part of this record.
537              * Read up to the blob.
538              */
539             if ( !wtap_read_bytes( fh, writep, junky_offset, err, err_info ) )
540                 return -1;
541
542             total_read += junky_offset;
543             writep += junky_offset;
544
545             /*
546              * Skip the blob.
547              */
548             if ( !file_skip( fh, K12_FILE_BLOB_LEN, err ) )
549                 return -1;
550             total_read += K12_FILE_BLOB_LEN;
551
552             left -= junky_offset;
553             junky_offset = 8192;
554         }
555
556     } while(left);
557
558     K12_HEX_ASCII_DUMP(5,file_offset, "GOT record", buffer, actual_len);
559     return total_read;
560 }
561
562 static gboolean
563 memiszero(const void *ptr, size_t count)
564 {
565     const guint8 *p = (const guint8 *)ptr;
566
567     while (count != 0) {
568         if (*p != 0)
569             return FALSE;
570         p++;
571         count--;
572     }
573     return TRUE;
574 }
575
576 static void
577 process_packet_data(struct wtap_pkthdr *phdr, Buffer *target, guint8 *buffer,
578                     gint len, k12_t *k12)
579 {
580     guint32 type;
581     guint   buffer_offset;
582     guint64 ts;
583     guint32 length;
584     guint32 extra_len;
585     guint32 src_id;
586     k12_src_desc_t* src_desc;
587
588     phdr->rec_type = REC_TYPE_PACKET;
589     phdr->presence_flags = WTAP_HAS_TS;
590
591     ts = pntoh64(buffer + K12_PACKET_TIMESTAMP);
592
593     phdr->ts.secs = (guint32) ((ts / 2000000) + 631152000);
594     phdr->ts.nsecs = (guint32) ( (ts % 2000000) * 500 );
595
596     length = pntoh32(buffer + K12_RECORD_FRAME_LEN) & 0x00001FFF;
597     phdr->len = phdr->caplen = length;
598
599     type = pntoh32(buffer + K12_RECORD_TYPE);
600     buffer_offset = (type == K12_REC_D0020) ? K12_PACKET_FRAME_D0020 : K12_PACKET_FRAME;
601
602     ws_buffer_assure_space(target, length);
603     memcpy(ws_buffer_start_ptr(target), buffer + buffer_offset, length);
604
605     /* extra information need by some protocols */
606     extra_len = len - buffer_offset - length;
607     ws_buffer_assure_space(&(k12->extra_info), extra_len);
608     memcpy(ws_buffer_start_ptr(&(k12->extra_info)),
609            buffer + buffer_offset + length, extra_len);
610     phdr->pseudo_header.k12.extra_info = (guint8*)ws_buffer_start_ptr(&(k12->extra_info));
611     phdr->pseudo_header.k12.extra_length = extra_len;
612
613     src_id = pntoh32(buffer + K12_RECORD_SRC_ID);
614     K12_DBG(5,("process_packet_data: src_id=%.8x",src_id));
615     phdr->pseudo_header.k12.input = src_id;
616
617     if ( ! (src_desc = (k12_src_desc_t*)g_hash_table_lookup(k12->src_by_id,GUINT_TO_POINTER(src_id))) ) {
618         /*
619          * Some records from K15 files have a port ID of an undeclared
620          * interface which happens to be the only one with the first byte changed.
621          * It is still unknown how to recognize when this happens.
622          * If the lookup of the interface record fails we'll mask it
623          * and retry.
624          */
625         src_desc = (k12_src_desc_t*)g_hash_table_lookup(k12->src_by_id,GUINT_TO_POINTER(src_id&K12_RECORD_SRC_ID_MASK));
626     }
627
628     if (src_desc) {
629         K12_DBG(5,("process_packet_data: input_name='%s' stack_file='%s' type=%x",src_desc->input_name,src_desc->stack_file,src_desc->input_type));
630         phdr->pseudo_header.k12.input_name = src_desc->input_name;
631         phdr->pseudo_header.k12.stack_file = src_desc->stack_file;
632         phdr->pseudo_header.k12.input_type = src_desc->input_type;
633
634         switch(src_desc->input_type) {
635             case K12_PORT_ATMPVC:
636                 if ((long)(buffer_offset + length + K12_PACKET_OFFSET_CID) < len) {
637                     phdr->pseudo_header.k12.input_info.atm.vp =  pntoh16(buffer + buffer_offset + length + K12_PACKET_OFFSET_VP);
638                     phdr->pseudo_header.k12.input_info.atm.vc =  pntoh16(buffer + buffer_offset + length + K12_PACKET_OFFSET_VC);
639                     phdr->pseudo_header.k12.input_info.atm.cid =  *((unsigned char*)(buffer + buffer_offset + length + K12_PACKET_OFFSET_CID));
640                     break;
641                 }
642                 /* Fall through */
643             default:
644                 memcpy(&(phdr->pseudo_header.k12.input_info),&(src_desc->input_info),sizeof(src_desc->input_info));
645                 break;
646         }
647     } else {
648         K12_DBG(5,("process_packet_data: NO SRC_RECORD FOUND"));
649
650         memset(&(phdr->pseudo_header.k12),0,sizeof(phdr->pseudo_header.k12));
651         phdr->pseudo_header.k12.input_name = "unknown port";
652         phdr->pseudo_header.k12.stack_file = "unknown stack file";
653     }
654
655     phdr->pseudo_header.k12.input = src_id;
656     phdr->pseudo_header.k12.stuff = k12;
657 }
658
659 static gboolean k12_read(wtap *wth, int *err, gchar **err_info, gint64 *data_offset) {
660     k12_t *k12 = (k12_t *)wth->priv;
661     k12_src_desc_t* src_desc;
662     guint8* buffer;
663     gint64 offset;
664     gint len;
665     guint32 type;
666     guint32 src_id;
667
668     offset = file_tell(wth->fh);
669
670     /* ignore the record if it isn't a packet */
671     do {
672         if ( k12->num_of_records == 0 ) {
673             /* No more records */
674             *err = 0;
675             return FALSE;
676         }
677
678         K12_DBG(5,("k12_read: offset=%i",offset));
679
680         *data_offset = offset;
681
682         len = get_record(k12, wth->fh, offset, FALSE, err, err_info);
683
684         if (len < 0) {
685             /* read error */
686             return FALSE;
687         } else if (len == 0) {
688             /* EOF */
689             *err = WTAP_ERR_SHORT_READ;
690             return FALSE;
691         } else if (len < K12_RECORD_SRC_ID + 4) {
692             /* Record not large enough to contain a src ID */
693             *err = WTAP_ERR_BAD_FILE;
694             *err_info = g_strdup_printf("data record length %d too short", len);
695             return FALSE;
696         }
697         k12->num_of_records--;
698
699         buffer = k12->seq_read_buff;
700
701         type = pntoh32(buffer + K12_RECORD_TYPE);
702         src_id = pntoh32(buffer + K12_RECORD_SRC_ID);
703
704
705         if ( ! (src_desc = (k12_src_desc_t*)g_hash_table_lookup(k12->src_by_id,GUINT_TO_POINTER(src_id))) ) {
706             /*
707              * Some records from K15 files have a port ID of an undeclared
708              * interface which happens to be the only one with the first byte changed.
709              * It is still unknown how to recognize when this happens.
710              * If the lookup of the interface record fails we'll mask it
711              * and retry.
712              */
713             src_desc = (k12_src_desc_t*)g_hash_table_lookup(k12->src_by_id,GUINT_TO_POINTER(src_id&K12_RECORD_SRC_ID_MASK));
714         }
715
716         K12_DBG(5,("k12_read: record type=%x src_id=%x",type,src_id));
717
718         offset += len;
719
720     } while ( ((type & K12_MASK_PACKET) != K12_REC_PACKET && (type & K12_MASK_PACKET) != K12_REC_D0020) || !src_id || !src_desc );
721
722     process_packet_data(&wth->phdr, wth->frame_buffer, buffer, len, k12);
723
724     return TRUE;
725 }
726
727
728 static gboolean k12_seek_read(wtap *wth, gint64 seek_off, struct wtap_pkthdr *phdr, Buffer *buf, int *err, gchar **err_info) {
729     k12_t *k12 = (k12_t *)wth->priv;
730     guint8* buffer;
731     gint len;
732
733     K12_DBG(5,("k12_seek_read: ENTER"));
734
735     if ( file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) {
736         K12_DBG(5,("k12_seek_read: SEEK ERROR"));
737         return FALSE;
738     }
739
740     len = get_record(k12, wth->random_fh, seek_off, TRUE, err, err_info);
741     if (len < 0) {
742         K12_DBG(5,("k12_seek_read: READ ERROR"));
743         return FALSE;
744     } else if (len < K12_RECORD_SRC_ID + 4) {
745         /* Record not large enough to contain a src ID */
746         K12_DBG(5,("k12_seek_read: SHORT READ"));
747         *err = WTAP_ERR_SHORT_READ;
748         return FALSE;
749     }
750
751     buffer = k12->rand_read_buff;
752
753     process_packet_data(phdr, buf, buffer, len, k12);
754
755     K12_DBG(5,("k12_seek_read: DONE OK"));
756
757     return TRUE;
758 }
759
760
761 static k12_t* new_k12_file_data(void) {
762     k12_t* fd = g_new(k12_t,1);
763
764     fd->file_len = 0;
765     fd->num_of_records = 0;
766     fd->src_by_name = g_hash_table_new(g_str_hash,g_str_equal);
767     fd->src_by_id = g_hash_table_new(g_direct_hash,g_direct_equal);
768     fd->seq_read_buff = NULL;
769     fd->seq_read_buff_len = 0;
770     fd->rand_read_buff = NULL;
771     fd->rand_read_buff_len = 0;
772
773     ws_buffer_init(&(fd->extra_info), 100);
774
775     return fd;
776 }
777
778 static gboolean destroy_srcdsc(gpointer k _U_, gpointer v, gpointer p _U_) {
779     k12_src_desc_t* rec = (k12_src_desc_t*)v;
780
781     g_free(rec->input_name);
782     g_free(rec->stack_file);
783     g_free(rec);
784
785     return TRUE;
786 }
787
788 static void destroy_k12_file_data(k12_t* fd) {
789     g_hash_table_destroy(fd->src_by_id);
790     g_hash_table_foreach_remove(fd->src_by_name,destroy_srcdsc,NULL);
791     g_hash_table_destroy(fd->src_by_name);
792     ws_buffer_free(&(fd->extra_info));
793     g_free(fd->seq_read_buff);
794     g_free(fd->rand_read_buff);
795     g_free(fd);
796 }
797
798 static void k12_close(wtap *wth) {
799     k12_t *k12 = (k12_t *)wth->priv;
800
801     destroy_k12_file_data(k12);
802     wth->priv = NULL;   /* destroy_k12_file_data freed it */
803 #ifdef DEBUG_K12
804     K12_DBG(5,("k12_close: CLOSED"));
805     if (env_file) fclose(dbg_out);
806 #endif
807 }
808
809
810 wtap_open_return_val k12_open(wtap *wth, int *err, gchar **err_info) {
811     k12_src_desc_t* rec;
812     guint8 header_buffer[K12_FILE_HDR_LEN];
813     guint8* read_buffer;
814     guint32 type;
815     long offset;
816     long len;
817     guint port_type;
818     guint32 rec_len;
819     guint32 hwpart_len;
820     guint32 name_len;
821     guint32 stack_len;
822     guint i;
823     k12_t* file_data;
824
825 #ifdef DEBUG_K12
826     gchar* env_level = getenv("K12_DEBUG_LEVEL");
827     env_file = getenv("K12_DEBUG_FILENAME");
828     if ( env_file ) {
829         dbg_out = ws_fopen(env_file,"w");
830         if (dbg_out == NULL) {
831                 dbg_out = stderr;
832                 K12_DBG(1,("unable to open K12 DEBUG FILENAME for writing!  Logging to standard error"));
833         }
834     }
835     else
836         dbg_out = stderr;
837     if ( env_level ) debug_level = (unsigned int)strtoul(env_level,NULL,10);
838     K12_DBG(1,("k12_open: ENTER debug_level=%u",debug_level));
839 #endif
840
841     if ( !wtap_read_bytes(wth->fh,header_buffer,K12_FILE_HDR_LEN,err,err_info) ) {
842         K12_DBG(1,("k12_open: FILE HEADER TOO SHORT OR READ ERROR"));
843         if (*err != WTAP_ERR_SHORT_READ) {
844             return WTAP_OPEN_ERROR;
845         }
846         return WTAP_OPEN_NOT_MINE;
847     }
848
849     if ( memcmp(header_buffer,k12_file_magic,8) != 0 ) {
850         K12_DBG(1,("k12_open: BAD MAGIC"));
851         return WTAP_OPEN_NOT_MINE;
852     }
853
854     offset = K12_FILE_HDR_LEN;
855
856     file_data = new_k12_file_data();
857
858     file_data->file_len = pntoh32( header_buffer + 0x8);
859     if (memiszero(header_buffer + 0x10, K12_FILE_HDR_LEN - 0x10)) {
860         /*
861          * The rest of the file header is all zeroes.  That means
862          * this is a file written by the old Wireshark code, and
863          * a count of records in the file is at an offset of 0x0C.
864          */
865         file_data->num_of_records = pntoh32( header_buffer + 0x0C );
866     } else {
867         /*
868          * There's at least one non-zero byte in the rest of the
869          * header.  The value 8192 is at 0xC (page size?), and
870          * what appears to be the number of records in the file
871          * is at an offset of 0x24 and at an offset of 0x2c.
872          *
873          * If the two values are not the same, we fail; if that's
874          * the case, we need to see the file to figure out which
875          * of those two values, if any, is the count.
876          */
877         file_data->num_of_records = pntoh32( header_buffer + K12_FILE_HDR_RECORD_COUNT_1 );
878         if ( file_data->num_of_records != pntoh32( header_buffer + K12_FILE_HDR_RECORD_COUNT_2 ) ) {
879             *err = WTAP_ERR_BAD_FILE;
880             *err_info = g_strdup_printf("k12: two different record counts, %u at 0x%02x and %u at 0x%02x",
881                                         file_data->num_of_records,
882                                         K12_FILE_HDR_RECORD_COUNT_1,
883                                         pntoh32( header_buffer + K12_FILE_HDR_RECORD_COUNT_2 ),
884                                         K12_FILE_HDR_RECORD_COUNT_2 );
885             return WTAP_OPEN_ERROR;
886         }
887     }
888
889     K12_DBG(5,("k12_open: FILE_HEADER OK: offset=%x file_len=%i records=%i",
890             offset,
891             file_data->file_len,
892             file_data->num_of_records ));
893
894     do {
895         if ( file_data->num_of_records == 0 ) {
896             *err = WTAP_ERR_SHORT_READ;
897             destroy_k12_file_data(file_data);
898             return WTAP_OPEN_ERROR;
899         }
900
901         len = get_record(file_data, wth->fh, offset, FALSE, err, err_info);
902
903         if ( len < 0 ) {
904             K12_DBG(1,("k12_open: BAD HEADER RECORD",len));
905             destroy_k12_file_data(file_data);
906             return WTAP_OPEN_ERROR;
907         }
908         if ( len == 0 ) {
909             K12_DBG(1,("k12_open: BAD HEADER RECORD",len));
910             *err = WTAP_ERR_SHORT_READ;
911             destroy_k12_file_data(file_data);
912             return WTAP_OPEN_ERROR;
913         }
914
915         read_buffer = file_data->seq_read_buff;
916
917         rec_len = pntoh32( read_buffer + K12_RECORD_LEN );
918         if (rec_len < K12_RECORD_TYPE + 4) {
919             /* Record isn't long enough to have a type field */
920             *err = WTAP_ERR_BAD_FILE;
921             *err_info = g_strdup_printf("k12_open: record length %u < %u",
922                                         rec_len, K12_RECORD_TYPE + 4);
923             return WTAP_OPEN_ERROR;
924         }
925         type = pntoh32( read_buffer + K12_RECORD_TYPE );
926
927         if ( (type & K12_MASK_PACKET) == K12_REC_PACKET ||
928              (type & K12_MASK_PACKET) == K12_REC_D0020) {
929             /*
930              * we are at the first packet record, rewind and leave.
931              */
932             if (file_seek(wth->fh, offset, SEEK_SET, err) == -1) {
933                 destroy_k12_file_data(file_data);
934                 return WTAP_OPEN_ERROR;
935             }
936             K12_DBG(5,("k12_open: FIRST PACKET offset=%x",offset));
937             break;
938         }
939
940         switch (type) {
941
942         case K12_REC_SRCDSC:
943         case K12_REC_SRCDSC2:
944             rec = g_new0(k12_src_desc_t,1);
945
946             if (rec_len < K12_SRCDESC_HWPART) {
947                 /*
948                  * Record isn't long enough to have the fixed-length portion
949                  * of the source descriptor field.
950                  */
951                 *err = WTAP_ERR_BAD_FILE;
952                 *err_info = g_strdup_printf("k12_open: source descriptor record length %u < %u",
953                                             rec_len, K12_SRCDESC_HWPART);
954                 destroy_k12_file_data(file_data);
955                 g_free(rec);
956                 return WTAP_OPEN_ERROR;
957             }
958             port_type = read_buffer[K12_SRCDESC_PORT_TYPE];
959             hwpart_len = pntoh16( read_buffer + K12_SRCDESC_HWPARTLEN );
960             name_len = pntoh16( read_buffer + K12_SRCDESC_NAMELEN );
961             stack_len = pntoh16( read_buffer + K12_SRCDESC_STACKLEN );
962
963             rec->input = pntoh32( read_buffer + K12_RECORD_SRC_ID );
964
965             K12_DBG(5,("k12_open: INTERFACE RECORD offset=%x interface=%x",offset,rec->input));
966
967             if (name_len == 0) {
968                 K12_DBG(5,("k12_open: failed (name_len == 0 in source description"));
969                 destroy_k12_file_data(file_data);
970                 g_free(rec);
971                 return WTAP_OPEN_NOT_MINE;
972             }
973             if (stack_len == 0) {
974                 K12_DBG(5,("k12_open: failed (stack_len == 0 in source description"));
975                 destroy_k12_file_data(file_data);
976                 g_free(rec);
977                 return WTAP_OPEN_NOT_MINE;
978             }
979             if (rec_len < K12_SRCDESC_HWPART + hwpart_len + name_len + stack_len) {
980                 /*
981                  * Record isn't long enough to have the full source descriptor
982                  * field, including the variable-length parts.
983                  */
984                 *err = WTAP_ERR_BAD_FILE;
985                 *err_info = g_strdup_printf("k12_open: source descriptor record length %u < %u (%u + %u + %u + %u)",
986                                             rec_len,
987                                             K12_SRCDESC_HWPART + hwpart_len + name_len + stack_len,
988                                             K12_SRCDESC_HWPART, hwpart_len, name_len, stack_len);
989                 destroy_k12_file_data(file_data);
990                 g_free(rec);
991                 return WTAP_OPEN_ERROR;
992             }
993
994             if (hwpart_len) {
995                 if (hwpart_len < 4) {
996                     /* Hardware part isn't long enough to have a type field */
997                     *err = WTAP_ERR_BAD_FILE;
998                     *err_info = g_strdup_printf("k12_open: source descriptor hardware part length %u < 4",
999                                                 hwpart_len);
1000                     destroy_k12_file_data(file_data);
1001                     g_free(rec);
1002                     return WTAP_OPEN_ERROR;
1003                 }
1004                 switch(( rec->input_type = pntoh32( read_buffer + K12_SRCDESC_HWPART + K12_SRCDESC_HWPARTTYPE ) )) {
1005                     case K12_PORT_DS0S:
1006                         /* This appears to be variable-length */
1007                         rec->input_info.ds0mask = 0x00000000;
1008                         if (hwpart_len > K12_SRCDESC_DS0_MASK) {
1009                             for (i = 0; i < hwpart_len - K12_SRCDESC_DS0_MASK; i++) {
1010                                 rec->input_info.ds0mask |= ( *(read_buffer + K12_SRCDESC_HWPART + K12_SRCDESC_DS0_MASK + i) == 0xff ) ? 1U<<(31-i) : 0x0;
1011                             }
1012                         }
1013                         break;
1014                     case K12_PORT_ATMPVC:
1015                         if (hwpart_len < K12_SRCDESC_ATM_VCI + 2) {
1016                             /* Hardware part isn't long enough to have ATM information */
1017                             *err = WTAP_ERR_BAD_FILE;
1018                             *err_info = g_strdup_printf("k12_open: source descriptor hardware part length %u < %u",
1019                                                         hwpart_len,
1020                                                         K12_SRCDESC_ATM_VCI + 2);
1021                             destroy_k12_file_data(file_data);
1022                             g_free(rec);
1023                             return WTAP_OPEN_ERROR;
1024                         }
1025
1026                         rec->input_info.atm.vp = pntoh16( read_buffer + K12_SRCDESC_HWPART + K12_SRCDESC_ATM_VPI );
1027                         rec->input_info.atm.vc = pntoh16( read_buffer + K12_SRCDESC_HWPART + K12_SRCDESC_ATM_VCI );
1028                         break;
1029                     default:
1030                         break;
1031                 }
1032             } else {
1033                 /* Record viewer generated files don't have this information */
1034                 if (port_type >= 0x14
1035                     && port_type <= 0x17) {
1036                     /* For ATM2_E1DS1, ATM2_E3DS3,
1037                        ATM2_STM1EL and ATM2_STM1OP */
1038                     rec->input_type = K12_PORT_ATMPVC;
1039                     rec->input_info.atm.vp = 0;
1040                     rec->input_info.atm.vc = 0;
1041                 }
1042             }
1043
1044             if (read_buffer[K12_SRCDESC_HWPART + hwpart_len + name_len - 1] != '\0') {
1045                 *err = WTAP_ERR_BAD_FILE;
1046                 *err_info = g_strdup("k12_open: source descriptor record contains non-null-terminated link-layer name");
1047                 destroy_k12_file_data(file_data);
1048                 g_free(rec);
1049                 return WTAP_OPEN_ERROR;
1050             }
1051             if (read_buffer[K12_SRCDESC_HWPART + hwpart_len + name_len + stack_len - 1] != '\0') {
1052                 *err = WTAP_ERR_BAD_FILE;
1053                 *err_info = g_strdup("k12_open: source descriptor record contains non-null-terminated stack path");
1054                 destroy_k12_file_data(file_data);
1055                 g_free(rec);
1056                 return WTAP_OPEN_ERROR;
1057             }
1058             rec->input_name = (gchar *)g_memdup(read_buffer + K12_SRCDESC_HWPART + hwpart_len, name_len);
1059             rec->stack_file = (gchar *)g_memdup(read_buffer + K12_SRCDESC_HWPART + hwpart_len + name_len, stack_len);
1060
1061             ascii_strdown_inplace (rec->stack_file);
1062
1063             g_hash_table_insert(file_data->src_by_id,GUINT_TO_POINTER(rec->input),rec);
1064             g_hash_table_insert(file_data->src_by_name,rec->stack_file,rec);
1065             break;
1066
1067         case K12_REC_STK_FILE:
1068             K12_DBG(1,("k12_open: K12_REC_STK_FILE"));
1069             K12_DBG(1,("Field 1: 0x%08x",pntoh32( read_buffer + 0x08 )));
1070             K12_DBG(1,("Field 2: 0x%08x",pntoh32( read_buffer + 0x0c )));
1071             K12_ASCII_DUMP(1, read_buffer, rec_len, 16);
1072             break;
1073
1074         default:
1075             K12_DBG(1,("k12_open: RECORD TYPE 0x%08x",type));
1076             break;
1077         }
1078         offset += len;
1079         file_data->num_of_records--;
1080     } while(1);
1081
1082     wth->file_type_subtype = WTAP_FILE_TYPE_SUBTYPE_K12;
1083     wth->file_encap = WTAP_ENCAP_K12;
1084     wth->snapshot_length = 0;
1085     wth->subtype_read = k12_read;
1086     wth->subtype_seek_read = k12_seek_read;
1087     wth->subtype_close = k12_close;
1088     wth->priv = (void *)file_data;
1089     wth->file_tsprec = WTAP_TSPREC_NSEC;
1090
1091     return WTAP_OPEN_MINE;
1092 }
1093
1094 typedef struct {
1095     guint32 file_len;
1096     guint32 num_of_records;
1097     guint32 file_offset;
1098 } k12_dump_t;
1099
1100 int k12_dump_can_write_encap(int encap) {
1101
1102     if (encap == WTAP_ENCAP_PER_PACKET)
1103         return WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
1104
1105     if (encap != WTAP_ENCAP_K12)
1106         return WTAP_ERR_UNWRITABLE_ENCAP;
1107
1108     return 0;
1109 }
1110
1111 static const gchar dumpy_junk[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
1112
1113 static gboolean k12_dump_record(wtap_dumper *wdh, guint32 len,  guint8* buffer, int *err_p) {
1114     k12_dump_t *k12 = (k12_dump_t *)wdh->priv;
1115     guint32 junky_offset = (8192 - ( (k12->file_offset - K12_FILE_HDR_LEN) % 8192 )) % 8192;
1116
1117     if (len > junky_offset) {
1118         if (junky_offset) {
1119             if (! wtap_dump_file_write(wdh, buffer, junky_offset, err_p))
1120                 return FALSE;
1121         }
1122         if (! wtap_dump_file_write(wdh, dumpy_junk, K12_FILE_BLOB_LEN, err_p))
1123             return FALSE;
1124
1125         if (! wtap_dump_file_write(wdh, buffer+junky_offset, len - junky_offset, err_p))
1126             return FALSE;
1127
1128         k12->file_offset += len + K12_FILE_BLOB_LEN;
1129         k12->file_len += len + K12_FILE_BLOB_LEN;
1130     } else {
1131         if (! wtap_dump_file_write(wdh, buffer, len, err_p))
1132             return FALSE;
1133         k12->file_offset += len;
1134         k12->file_len += len;
1135     }
1136
1137     k12->num_of_records++;
1138     return TRUE;
1139 }
1140
1141 static void k12_dump_src_setting(gpointer k _U_, gpointer v, gpointer p) {
1142     k12_src_desc_t* src_desc = (k12_src_desc_t*)v;
1143     wtap_dumper *wdh = (wtap_dumper *)p;
1144     guint32 len;
1145     guint offset;
1146     guint i;
1147     int   errxxx; /* dummy */
1148
1149     union {
1150         guint8 buffer[8192];
1151
1152         struct {
1153             guint32 len;
1154             guint32 type;
1155             guint32 unk32_1;
1156             guint32 input;
1157
1158             guint16 unk32_2;
1159             guint16 color;
1160             guint32 unk32_3;
1161             guint32 unk32_4;
1162             guint16 unk16_1;
1163             guint16 hwpart_len;
1164
1165             guint16 name_len;
1166             guint16 stack_len;
1167
1168             struct {
1169                 guint32 type;
1170
1171                 union {
1172                     struct {
1173                         guint32 unk32;
1174                         guint8 mask[32];
1175                     } ds0mask;
1176
1177                     struct {
1178                         guint8 unk_data[16];
1179                         guint16 vp;
1180                         guint16 vc;
1181                     } atm;
1182
1183                     guint32 unk;
1184                 } desc;
1185             } extra;
1186         } record;
1187     } obj;
1188
1189     obj.record.type = g_htonl(K12_REC_SRCDSC);
1190     obj.record.unk32_1 = g_htonl(0x00000001);
1191     obj.record.input = g_htonl(src_desc->input);
1192
1193     obj.record.unk32_2 = g_htons(0x0000);
1194     obj.record.color = g_htons(0x060f);
1195     obj.record.unk32_3 = g_htonl(0x00000003);
1196     switch (src_desc->input_type) {
1197         case K12_PORT_ATMPVC:
1198             obj.record.unk32_4 = g_htonl(0x01001400);
1199             break;
1200         default:
1201             obj.record.unk32_4 = g_htonl(0x01000100);
1202     }
1203
1204     obj.record.unk16_1 = g_htons(0x0000);
1205     obj.record.name_len = (guint16) strlen(src_desc->input_name) + 1;
1206     obj.record.stack_len = (guint16) strlen(src_desc->stack_file) + 1;
1207
1208     obj.record.extra.type = g_htonl(src_desc->input_type);
1209
1210     switch (src_desc->input_type) {
1211         case K12_PORT_ATMPVC:
1212             obj.record.hwpart_len = g_htons(0x18);
1213             obj.record.extra.desc.atm.vp = g_htons(src_desc->input_info.atm.vp);
1214             obj.record.extra.desc.atm.vc = g_htons(src_desc->input_info.atm.vc);
1215             offset = 0x3c;
1216             break;
1217         case K12_PORT_DS0S:
1218             obj.record.hwpart_len = g_htons(0x18);
1219             for( i=0; i<32; i++ ) {
1220                 obj.record.extra.desc.ds0mask.mask[i] =
1221                 (src_desc->input_info.ds0mask & (1 << i)) ? 0xff : 0x00;
1222             }
1223             offset = 0x3c;
1224             break;
1225         default:
1226             obj.record.hwpart_len = g_htons(0x08);
1227             offset = 0x2c;
1228             break;
1229     }
1230
1231     memcpy(obj.buffer + offset,
1232            src_desc->input_name,
1233            obj.record.name_len);
1234
1235     memcpy(obj.buffer + offset + obj.record.name_len,
1236            src_desc->stack_file,
1237            obj.record.stack_len);
1238
1239     len = offset + obj.record.name_len + obj.record.stack_len;
1240     len += (len % 4) ? 4 - (len % 4) : 0;
1241
1242     obj.record.len = g_htonl(len);
1243     obj.record.name_len =  g_htons(obj.record.name_len);
1244     obj.record.stack_len = g_htons(obj.record.stack_len);
1245
1246     k12_dump_record(wdh,len,obj.buffer, &errxxx); /* fwrite errs ignored: see k12_dump below */
1247 }
1248
1249 static gboolean k12_dump(wtap_dumper *wdh, const struct wtap_pkthdr *phdr,
1250                          const guint8 *pd, int *err, gchar **err_info _U_) {
1251     const union wtap_pseudo_header *pseudo_header = &phdr->pseudo_header;
1252     k12_dump_t *k12 = (k12_dump_t *)wdh->priv;
1253     guint32 len;
1254     union {
1255         guint8 buffer[8192];
1256         struct {
1257             guint32 len;
1258             guint32 type;
1259             guint32 frame_len;
1260             guint32 input;
1261
1262             guint32 datum_1;
1263             guint32 datum_2;
1264             guint64 ts;
1265
1266             guint8 frame[0x1fc0];
1267         } record;
1268     } obj;
1269
1270     /* We can only write packet records. */
1271     if (phdr->rec_type != REC_TYPE_PACKET) {
1272         *err = WTAP_ERR_UNWRITABLE_REC_TYPE;
1273         return FALSE;
1274     }
1275
1276     if (k12->num_of_records == 0) {
1277         k12_t* file_data = (k12_t*)pseudo_header->k12.stuff;
1278         /* XXX: We'll assume that any fwrite errors in k12_dump_src_setting will    */
1279         /*      repeat during the final k12_dump_record at the end of k12_dump      */
1280         /*      (and thus cause an error return from k12_dump).                     */
1281         /*      (I don't see a reasonably clean way to handle any fwrite errors     */
1282         /*       encountered in k12_dump_src_setting).                              */
1283         g_hash_table_foreach(file_data->src_by_id,k12_dump_src_setting,wdh);
1284     }
1285     obj.record.len = 0x20 + phdr->caplen;
1286     obj.record.len += (obj.record.len % 4) ? 4 - obj.record.len % 4 : 0;
1287
1288     len = obj.record.len;
1289
1290     obj.record.len = g_htonl(obj.record.len);
1291
1292     obj.record.type = g_htonl(K12_REC_PACKET);
1293     obj.record.frame_len = g_htonl(phdr->caplen);
1294     obj.record.input = g_htonl(pseudo_header->k12.input);
1295
1296     obj.record.ts = GUINT64_TO_BE((((guint64)phdr->ts.secs - 631152000) * 2000000) + (phdr->ts.nsecs / 1000 * 2));
1297
1298     memcpy(obj.record.frame,pd,phdr->caplen);
1299
1300     return k12_dump_record(wdh,len,obj.buffer, err);
1301 }
1302
1303 static const guint8 k12_eof[] = {0xff,0xff};
1304
1305 static gboolean k12_dump_finish(wtap_dumper *wdh, int *err) {
1306     k12_dump_t *k12 = (k12_dump_t *)wdh->priv;
1307     union {
1308         guint8 b[sizeof(guint32)];
1309         guint32 u;
1310     } d;
1311
1312     if (! wtap_dump_file_write(wdh, k12_eof, 2, err))
1313         return FALSE;
1314     k12->file_len += 2;
1315
1316     if (wtap_dump_file_seek(wdh, K12_FILE_HDR_FILE_SIZE, SEEK_SET, err) == -1)
1317         return FALSE;
1318
1319     d.u = g_htonl(k12->file_len);
1320
1321     if (! wtap_dump_file_write(wdh, d.b, 4, err))
1322         return FALSE;
1323
1324     if (wtap_dump_file_seek(wdh, K12_FILE_HDR_PAGE_SIZE, SEEK_SET, err) == -1)
1325         return FALSE;
1326
1327     d.u = g_htonl(8192);
1328
1329     if (! wtap_dump_file_write(wdh, d.b, 4, err))
1330         return FALSE;
1331
1332     if (wtap_dump_file_seek(wdh, K12_FILE_HDR_RECORD_COUNT_1, SEEK_SET, err) == -1)
1333         return FALSE;
1334
1335     d.u = g_htonl(k12->num_of_records);
1336
1337     if (! wtap_dump_file_write(wdh, d.b, 4, err))
1338         return FALSE;
1339
1340     if (wtap_dump_file_seek(wdh, K12_FILE_HDR_RECORD_COUNT_2, SEEK_SET, err) == -1)
1341         return FALSE;
1342
1343     d.u = g_htonl(k12->num_of_records);
1344
1345     if (! wtap_dump_file_write(wdh, d.b, 4, err))
1346         return FALSE;
1347
1348     return TRUE;
1349 }
1350
1351
1352 gboolean k12_dump_open(wtap_dumper *wdh, int *err) {
1353     k12_dump_t *k12;
1354
1355     if ( ! wtap_dump_file_write(wdh, k12_file_magic, 8, err)) {
1356         return FALSE;
1357     }
1358
1359     if (wtap_dump_file_seek(wdh, K12_FILE_HDR_LEN, SEEK_SET, err) == -1)
1360         return FALSE;
1361
1362     wdh->subtype_write = k12_dump;
1363     wdh->subtype_finish = k12_dump_finish;
1364
1365     k12 = (k12_dump_t *)g_malloc(sizeof(k12_dump_t));
1366     wdh->priv = (void *)k12;
1367     k12->file_len = K12_FILE_HDR_LEN;
1368     k12->num_of_records = 0;
1369     k12->file_offset  = K12_FILE_HDR_LEN;
1370
1371     return TRUE;
1372 }
1373
1374 /*
1375  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
1376  *
1377  * Local variables:
1378  * c-basic-offset: 4
1379  * tab-width: 8
1380  * indent-tabs-mode: nil
1381  * End:
1382  *
1383  * vi: set shiftwidth=4 tabstop=8 expandtab:
1384  * :indentSize=4:tabSize=8:noTabs=true:
1385  */