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