Detect clang and llvm-gcc.
[obnox/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  * $Id$
9  *
10  * Wiretap Library
11  * Copyright (c) 1998 by Gilbert Ramirez <gram@alumni.rice.edu>
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
26  */
27
28 #ifdef HAVE_CONFIG_H
29 #include "config.h"
30 #endif
31 #include <stdlib.h>
32 #include <string.h>
33 #include <errno.h>
34
35 #include "wtap-int.h"
36 #include "wtap.h"
37 #include "file_wrappers.h"
38 #include "buffer.h"
39 #include "k12.h"
40
41 #include <wsutil/str_util.h>
42
43 /* #define DEBUG_K12 */
44 #ifdef DEBUG_K12
45 #include <stdio.h>
46 #include <ctype.h>
47 #include <stdarg.h>
48 #include <wsutil/file_util.h>
49
50 FILE* dbg_out = NULL;
51 char* env_file = NULL;
52
53 static unsigned debug_level = 0;
54
55 void k12_fprintf(char* fmt, ...) {
56     va_list ap;
57
58     va_start(ap,fmt);
59     vfprintf(dbg_out, fmt, ap);
60     va_end(ap);
61 }
62
63 #define CAT(a,b) a##b
64 #define K12_DBG(level,args) do { if (level <= debug_level) { \
65         fprintf(dbg_out,"%s:%d: ",CAT(__FI,LE__),CAT(__LI,NE__)); \
66         k12_fprintf args ; \
67         fprintf(dbg_out,"\n"); \
68 } } while(0)
69
70 void k12_hexdump(guint level, gint64 offset, char* label, unsigned char* b, unsigned len) {
71     static const char* c2t[] = {
72         "00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f",
73         "10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f",
74         "20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f",
75         "30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f",
76         "40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f",
77         "50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f",
78         "60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f",
79         "70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f",
80         "80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f",
81         "90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f",
82         "a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af",
83         "b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf",
84         "c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf",
85         "d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df",
86         "e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef",
87         "f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"
88     };
89     unsigned i;
90
91     if (debug_level < level) return;
92
93     fprintf(dbg_out,"%s(%.8" G_GINT64_MODIFIER "x,%.4x): ",label,offset,len);
94
95     for (i=0 ; i<len ; i++) {
96
97         if (!(i%32))
98             fprintf(dbg_out,"\n");
99         else if (!(i%4))
100             fprintf(dbg_out," ");
101
102         fprintf(dbg_out, "%s", c2t[b[i]]);
103     }
104
105         fprintf(dbg_out,"\n");
106 }
107
108 #define K12_HEXDMP(x,a,b,c,d) k12_hexdump(x,a,b,c,d)
109
110 #else
111 #define K12_DBG(level,args) (void)0
112 #define K12_HEXDMP(x,a,b,c,d)
113 #endif
114
115
116
117 /*
118  * the 32 bits .rf5 file contains:
119  *  an 8 byte magic number
120  *  32bit length
121  *  32bit number of records
122  *  other 0x200 bytes bytes of uncharted territory
123  *     1 or more copies of the num_of_records in there
124  *  the records whose first 32bits word is the length
125  *     they are stuffed by one to four words every 0x2000 bytes
126  *  and a 2 byte terminator FFFF
127  */
128
129 static const guint8 k12_file_magic[] = { 0x00, 0x00, 0x02, 0x00 ,0x12, 0x05, 0x00, 0x10 };
130
131 typedef struct {
132     guint32 file_len;
133     guint32 num_of_records; /* XXX: not sure about this */
134
135     GHashTable* src_by_id; /* k12_srcdsc_recs by input */
136     GHashTable* src_by_name; /* k12_srcdsc_recs by stack_name */
137
138     Buffer extra_info; /* Buffer to hold per packet extra information */
139 } k12_t;
140
141 typedef struct _k12_src_desc_t {
142     guint32 input;
143     guint32 input_type;
144     gchar* input_name;
145     gchar* stack_file;
146     k12_input_info_t input_info;
147 } k12_src_desc_t;
148
149
150 /* so far we've seen these types of records */
151 #define K12_REC_PACKET        0x00010020 /* an actual packet */
152 #define K12_REC_SRCDSC        0x00070041 /* port-stack mapping + more, the key of the whole thing */
153 #define K12_REC_SCENARIO      0x00070040 /* what appears as the window's title */
154 #define K12_REC_STK_FILE      0x00070042 /* a dump of an stk file */
155 #define K12_REC_SRCDSC2       0x00070043 /* another port-stack mapping */
156 #define K12_REC_TEXT          0x00070044 /* a string containing something with a grammar (conditions/responses?) */
157 #define K12_REC_START         0x00020030 /* a string containing human readable start time  */
158 #define K12_REC_STOP          0x00020031 /* a string containing human readable stop time */
159
160 #define K12_MASK_PACKET       0xfffffff0  /* the last nibble in packet records somentimes change (not yet understood why) */
161
162 /* offsets of elements in the records */
163 #define K12_RECORD_LEN         0x0 /* uint32, in bytes */
164 #define K12_RECORD_TYPE        0x4 /* uint32, see above */
165 #define K12_RECORD_FRAME_LEN   0x8 /* uint32, in bytes */
166 #define K12_RECORD_SRC_ID      0xc /* uint32 */
167
168 /*
169  * Some records from K15 files have a port ID of an undeclared
170  * interface which happens to be the only one with the first byte changed.
171  * It is still unknown how to recognize when this happens.
172  * If the lookup of the interface record fails we'll mask it
173  * and retry.
174  */
175 #define K12_RECORD_SRC_ID_MASK 0x00ffffff
176
177 /* elements of packet records */
178 #define K12_PACKET_TIMESTAMP  0x18 /* int64 (8b) representing 1/2us since 01-01-1990 Z00:00:00 */
179
180 #define K12_PACKET_FRAME      0x20 /* start of the actual frame in the record */
181
182 #define K12_PACKET_OFFSET_VP  0x08 /* 2 bytes, big endian */
183 #define K12_PACKET_OFFSET_VC  0x0a /* 2 bytes, big endian */
184 #define K12_PACKET_OFFSET_CID 0x0c /* 1 byte */
185
186 /* elements of the source description records */
187 #define K12_SRCDESC_COLOR_FOREGROUND 0x12 /* 1 byte */
188 #define K12_SRCDESC_COLOR_BACKGROUND 0x13 /* 1 byte */
189
190 #define K12_SRCDESC_PORT_TYPE  0x1a   /* 1 byte */
191 #define K12_SRCDESC_EXTRALEN   0x1e   /* uint16, big endian */
192 #define K12_SRCDESC_NAMELEN    0x20   /* uint16, big endian */
193 #define K12_SRCDESC_STACKLEN   0x22   /* uint16, big endian */
194
195 #define K12_SRCDESC_EXTRATYPE  0x24   /* uint32, big endian */
196 #define K12_SRCDESC_ATM_VPI    0x38   /* uint16, big endian */
197 #define K12_SRCDESC_ATM_VCI    0x3a   /* uint16, big endian */
198
199 #define K12_SRCDESC_ATM_AAL    0x3c    /* 1 byte */
200 #define K12_SRCDESC_DS0_MASK   0x3c    /* 1 byte */
201
202
203 /*
204  * get_record: Get the next record into a buffer
205  *   Every about 0x2000 bytes 0x10 bytes are inserted in the file,
206  *   even in the middle of a record.
207  *   This reads the next record without the eventual 0x10 bytes.
208  *   returns the length of the record + the stuffing (if any)
209  *
210  * XXX: works at most with 0x1FFF bytes per record
211  */
212 static gint get_record(guint8** bufferp, FILE* fh, gint64 file_offset) {
213     static guint8* buffer = NULL;
214     static guint buffer_len = 0x2000 ;
215     guint bytes_read;
216     guint last_read;
217     guint actual_len, left;
218     guint8 junk[0x14];
219     guint8* writep;
220
221     /* where the next unknown 0x10 bytes are stuffed to the file */
222     guint junky_offset = 0x2000 - (gint) ( (file_offset - 0x200) % 0x2000 );
223
224     K12_DBG(6,("get_record: ENTER: junky_offset=%" G_GINT64_MODIFIER "d, file_offset=%" G_GINT64_MODIFIER "d",junky_offset,file_offset));
225
226     /* no buffer is given, lets create it */
227     if (buffer == NULL) {
228         buffer = g_malloc(0x2000);
229         buffer_len = 0x2000;
230     }
231
232     *bufferp = buffer;
233
234     if  ( junky_offset == 0x2000 ) {
235         /* the length of the record is 0x10 bytes ahead from we are reading */
236         bytes_read = file_read(junk,1,0x14,fh);
237
238         if (bytes_read == 2 && junk[0] == 0xff && junk[1] == 0xff) {
239             K12_DBG(1,("get_record: EOF"));
240             return 0;
241         } else if ( bytes_read < 0x14 ){
242             K12_DBG(1,("get_record: SHORT READ"));
243             return -1;
244         }
245
246         memcpy(buffer,&(junk[0x10]),4);
247     } else {
248         /* the length of the record is right where we are reading */
249         bytes_read = file_read(buffer,1, 0x4, fh);
250
251         if (bytes_read == 2 && buffer[0] == 0xff && buffer[1] == 0xff) {
252             K12_DBG(1,("get_record: EOF"));
253             return 0;
254         } else if ( bytes_read != 0x4 ) {
255             K12_DBG(1,("get_record: SHORT READ"));
256             return -1;
257         }
258     }
259
260     actual_len = left = pntohl(buffer);
261     junky_offset -= 0x4;
262
263     K12_DBG(5,("get_record: GET length=%u",left));
264
265     /* XXX - Is WTAP_MAX_PACKET_SIZE */
266     if (left < 4 || left > WTAP_MAX_PACKET_SIZE) {
267         K12_DBG(1,("get_record: Invalid GET length=%u",left));
268         errno = WTAP_ERR_BAD_RECORD;
269         return -1;
270     }
271
272     while (left > buffer_len) *bufferp = buffer = g_realloc(buffer,buffer_len*=2);
273
274     writep = buffer + 4;
275     left -= 4;
276
277     do {
278         K12_DBG(6,("get_record: looping left=%d junky_offset=%" G_GINT64_MODIFIER "d",left,junky_offset));
279
280         if (junky_offset > left) {
281             bytes_read += last_read = file_read(writep,1, left, fh);
282
283             if ( last_read != left ) {
284                 K12_DBG(1,("get_record: SHORT READ"));
285                 return -1;
286             } else {
287                 K12_HEXDMP(5,file_offset, "GOT record", buffer, actual_len);
288                 return bytes_read;
289             }
290         } else {
291             bytes_read += last_read = file_read(writep,1, junky_offset, fh);
292
293             if ( last_read != junky_offset ) {
294                 K12_DBG(1,("get_record: SHORT READ, read=%d expected=%d",last_read, junky_offset));
295                 return -1;
296             }
297
298             writep += last_read;
299
300             bytes_read += last_read = file_read(junk,1, 0x10, fh);
301
302             if ( last_read != 0x10 ) {
303                 K12_DBG(1,("get_record: SHORT READ"));
304                 return -1;
305             }
306
307             left -= junky_offset;
308             junky_offset = 0x2000;
309         }
310
311     } while(left);
312
313     K12_HEXDMP(5,file_offset, "GOT record", buffer, actual_len);
314     return bytes_read;
315 }
316
317 static gboolean k12_read(wtap *wth, int *err, gchar **err_info _U_, gint64 *data_offset) {
318     k12_t *k12 = (k12_t *)wth->priv;
319     k12_src_desc_t* src_desc;
320     guint8* buffer = NULL;
321     gint64 offset;
322     gint len;
323     guint32 type;
324     guint32 src_id;
325     guint64 ts;
326     guint32 extra_len;
327
328     offset = wth->data_offset;
329
330     /* ignore the record if it isn't a packet */
331     do {
332         K12_DBG(5,("k12_read: offset=%i",offset));
333
334         *data_offset = offset;
335
336         len = get_record(&buffer, wth->fh, offset);
337
338         if (len < 0) {
339             *err = WTAP_ERR_SHORT_READ;
340             return FALSE;
341         } else if (len == 0) {
342             *err = 0;
343             return FALSE;
344         }
345
346         type = pntohl(buffer + K12_RECORD_TYPE);
347         src_id = pntohl(buffer + K12_RECORD_SRC_ID);
348
349
350         if ( ! (src_desc = g_hash_table_lookup(k12->src_by_id,GUINT_TO_POINTER(src_id))) ) {
351             /*
352              * Some records from K15 files have a port ID of an undeclared
353              * interface which happens to be the only one with the first byte changed.
354              * It is still unknown how to recognize when this happens.
355              * If the lookup of the interface record fails we'll mask it
356              * and retry.
357              */
358             src_desc = g_hash_table_lookup(k12->src_by_id,GUINT_TO_POINTER(src_id&K12_RECORD_SRC_ID_MASK));
359         }
360
361         K12_DBG(5,("k12_read: record type=%x src_id=%x",type,src_id));
362
363         offset += len;
364
365     } while ( ((type & K12_MASK_PACKET) != K12_REC_PACKET) || !src_id || !src_desc );
366
367     wth->data_offset = offset;
368
369     ts = pntohll(buffer + K12_PACKET_TIMESTAMP);
370
371     wth->phdr.ts.secs = (guint32) ((ts / 2000000) + 631152000);
372     wth->phdr.ts.nsecs = (guint32) ( (ts % 2000000) * 500 );
373
374     K12_DBG(3,("k12_read: PACKET RECORD type=%x src_id=%x secs=%u nsecs=%u",type,src_id, wth->phdr.ts.secs,wth->phdr.ts.nsecs));
375
376     wth->phdr.len = wth->phdr.caplen = pntohl(buffer + K12_RECORD_FRAME_LEN) & 0x00001FFF;
377     extra_len = len - K12_PACKET_FRAME - wth->phdr.caplen;
378
379     /* the frame */
380     buffer_assure_space(wth->frame_buffer, wth->phdr.caplen);
381     memcpy(buffer_start_ptr(wth->frame_buffer), buffer + K12_PACKET_FRAME, wth->phdr.caplen);
382
383     /* extra information need by some protocols */
384     buffer_assure_space(&(k12->extra_info), extra_len);
385     memcpy(buffer_start_ptr(&(k12->extra_info)),
386            buffer + K12_PACKET_FRAME + wth->phdr.caplen, extra_len);
387     wth->pseudo_header.k12.extra_info = (void*)buffer_start_ptr(&(k12->extra_info));
388     wth->pseudo_header.k12.extra_length = extra_len;
389
390     wth->pseudo_header.k12.input = src_id;
391
392     K12_DBG(5,("k12_read: wth->pseudo_header.k12.input=%x wth->phdr.len=%i input_name='%s' stack_file='%s' type=%x",
393                wth->pseudo_header.k12.input,wth->phdr.len,src_desc->input_name,src_desc->stack_file,src_desc->input_type));\
394
395     wth->pseudo_header.k12.input_name = src_desc->input_name;
396     wth->pseudo_header.k12.stack_file = src_desc->stack_file;
397     wth->pseudo_header.k12.input_type = src_desc->input_type;
398
399     switch(src_desc->input_type) {
400         case K12_PORT_ATMPVC:
401         if ((long)(K12_PACKET_FRAME + wth->phdr.len + K12_PACKET_OFFSET_CID) < len) {
402             wth->pseudo_header.k12.input_info.atm.vp =  pntohs(buffer + (K12_PACKET_FRAME + wth->phdr.caplen + K12_PACKET_OFFSET_VP));
403             wth->pseudo_header.k12.input_info.atm.vc =  pntohs(buffer + (K12_PACKET_FRAME + wth->phdr.caplen + K12_PACKET_OFFSET_VC));
404             wth->pseudo_header.k12.input_info.atm.cid =  *((unsigned char*)(buffer + K12_PACKET_FRAME + wth->phdr.len + K12_PACKET_OFFSET_CID));
405             break;
406         }
407         /* Fall through */
408         default:
409         memcpy(&(wth->pseudo_header.k12.input_info),&(src_desc->input_info),sizeof(src_desc->input_info));
410         break;
411
412     }
413
414     wth->pseudo_header.k12.stuff = k12;
415
416     return TRUE;
417 }
418
419
420 static gboolean k12_seek_read(wtap *wth, gint64 seek_off, union wtap_pseudo_header *pseudo_header, guchar *pd, int length, int *err _U_, gchar **err_info _U_) {
421     k12_t *k12 = (k12_t *)wth->priv;
422     k12_src_desc_t* src_desc;
423     guint8* buffer;
424     gint len;
425     guint32 extra_len;
426     guint32 input;
427
428     K12_DBG(5,("k12_seek_read: ENTER"));
429
430     if ( file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) {
431         K12_DBG(5,("k12_seek_read: SEEK ERROR"));
432         return FALSE;
433     }
434
435     if ((len = get_record(&buffer, wth->random_fh, seek_off)) < 1) {
436         K12_DBG(5,("k12_seek_read: READ ERROR"));
437         return FALSE;
438     }
439
440     memcpy(pd, buffer + K12_PACKET_FRAME, length);
441
442     extra_len = len - K12_PACKET_FRAME - length;
443     buffer_assure_space(&(k12->extra_info), extra_len);
444     memcpy(buffer_start_ptr(&(k12->extra_info)),
445            buffer + K12_PACKET_FRAME + length, extra_len);
446     wth->pseudo_header.k12.extra_info = (void*)buffer_start_ptr(&(k12->extra_info));
447     wth->pseudo_header.k12.extra_length = extra_len;
448     if (pseudo_header) {
449         pseudo_header->k12.extra_info = (void*)buffer_start_ptr(&(k12->extra_info));
450         pseudo_header->k12.extra_length = extra_len;
451     }
452
453     input = pntohl(buffer + K12_RECORD_SRC_ID);
454     K12_DBG(5,("k12_seek_read: input=%.8x",input));
455
456         if ( ! (src_desc = g_hash_table_lookup(k12->src_by_id,GUINT_TO_POINTER(input))) ) {
457                 /*
458                  * Some records from K15 files have a port ID of an undeclared
459                  * interface which happens to be the only one with the first byte changed.
460                  * It is still unknown how to recognize when this happens.
461                  * If the lookup of the interface record fails we'll mask it
462                  * and retry.
463                  */
464                 src_desc = g_hash_table_lookup(k12->src_by_id,GUINT_TO_POINTER(input&K12_RECORD_SRC_ID_MASK));
465         }
466
467     if (src_desc) {
468         K12_DBG(5,("k12_seek_read: input_name='%s' stack_file='%s' type=%x",src_desc->input_name,src_desc->stack_file,src_desc->input_type));
469         if (pseudo_header) {
470             pseudo_header->k12.input_name = src_desc->input_name;
471             pseudo_header->k12.stack_file = src_desc->stack_file;
472             pseudo_header->k12.input_type = src_desc->input_type;
473
474             switch(src_desc->input_type) {
475             case K12_PORT_ATMPVC:
476                 if ((long)(K12_PACKET_FRAME + length + K12_PACKET_OFFSET_CID) < len) {
477                 pseudo_header->k12.input_info.atm.vp =  pntohs(buffer + K12_PACKET_FRAME + length + K12_PACKET_OFFSET_VP);
478                 pseudo_header->k12.input_info.atm.vc =  pntohs(buffer + K12_PACKET_FRAME + length + K12_PACKET_OFFSET_VC);
479                 pseudo_header->k12.input_info.atm.cid =  *((unsigned char*)(buffer + K12_PACKET_FRAME + length + K12_PACKET_OFFSET_CID));
480                 break;
481                 }
482                 /* Fall through */
483             default:
484                 memcpy(&(pseudo_header->k12.input_info),&(src_desc->input_info),sizeof(src_desc->input_info));
485                 break;
486             }
487         }
488
489         wth->pseudo_header.k12.input_name = src_desc->input_name;
490         wth->pseudo_header.k12.stack_file = src_desc->stack_file;
491         wth->pseudo_header.k12.input_type = src_desc->input_type;
492
493         switch(src_desc->input_type) {
494             case K12_PORT_ATMPVC:
495             if ((long)(K12_PACKET_FRAME + length + K12_PACKET_OFFSET_CID) < len) {
496                 wth->pseudo_header.k12.input_info.atm.vp =  pntohs(buffer + K12_PACKET_FRAME + length + K12_PACKET_OFFSET_VP);
497                 wth->pseudo_header.k12.input_info.atm.vc =  pntohs(buffer + K12_PACKET_FRAME + length + K12_PACKET_OFFSET_VC);
498                 wth->pseudo_header.k12.input_info.atm.cid =  *((unsigned char*)(buffer + K12_PACKET_FRAME + length + K12_PACKET_OFFSET_CID));
499             }
500             break;
501             /* Fall through */
502             default:
503             memcpy(&(wth->pseudo_header.k12.input_info),&(src_desc->input_info),sizeof(src_desc->input_info));
504             break;
505         }
506
507     } else {
508         K12_DBG(5,("k12_seek_read: NO SRC_RECORD FOUND"));
509
510         if (pseudo_header) {
511             memset(&(pseudo_header->k12),0,sizeof(pseudo_header->k12));
512             pseudo_header->k12.input_name = "unknown port";
513             pseudo_header->k12.stack_file = "unknown stack file";
514         }
515
516         memset(&(wth->pseudo_header.k12),0,sizeof(wth->pseudo_header.k12));
517         wth->pseudo_header.k12.input_name = "unknown port";
518         wth->pseudo_header.k12.stack_file = "unknown stack file";
519
520     }
521
522     if (pseudo_header) {
523         pseudo_header->k12.input = input;
524         pseudo_header->k12.stuff = k12;
525     }
526
527     wth->pseudo_header.k12.input = input;
528     wth->pseudo_header.k12.stuff = k12;
529
530     K12_DBG(5,("k12_seek_read: DONE OK"));
531
532     return TRUE;
533 }
534
535
536 static k12_t* new_k12_file_data(void) {
537     k12_t* fd = g_malloc(sizeof(k12_t));
538
539     fd->file_len = 0;
540     fd->num_of_records = 0;
541     fd->src_by_name = g_hash_table_new(g_str_hash,g_str_equal);
542     fd->src_by_id = g_hash_table_new(g_direct_hash,g_direct_equal);
543
544     buffer_init(&(fd->extra_info), 100);
545
546     return fd;
547 }
548
549 static gboolean destroy_srcdsc(gpointer k _U_, gpointer v, gpointer p _U_) {
550     k12_src_desc_t* rec = v;
551
552     g_free(rec->input_name);
553     g_free(rec->stack_file);
554     g_free(rec);
555
556     return TRUE;
557 }
558
559 static void destroy_k12_file_data(k12_t* fd) {
560     g_hash_table_destroy(fd->src_by_id);
561     g_hash_table_foreach_remove(fd->src_by_name,destroy_srcdsc,NULL);
562     g_hash_table_destroy(fd->src_by_name);
563     buffer_free(&(fd->extra_info));
564     g_free(fd);
565 }
566
567 static void k12_close(wtap *wth) {
568     k12_t *k12 = (k12_t *)wth->priv;
569
570     destroy_k12_file_data(k12);
571     wth->priv = NULL;   /* destroy_k12_file_data freed it */
572 #ifdef DEBUG_K12
573     K12_DBG(5,("k12_close: CLOSED"));
574     if (env_file) fclose(dbg_out);
575 #endif
576 }
577
578
579 int k12_open(wtap *wth, int *err, gchar **err_info _U_) {
580     k12_src_desc_t* rec;
581     guint8 header_buffer[0x200];
582     guint8* read_buffer;
583     guint32 type;
584     long offset;
585     long len;
586     guint32 rec_len;
587     guint32 extra_len;
588     guint32 name_len;
589     guint32 stack_len;
590     guint i;
591     k12_t* file_data;
592
593 #ifdef DEBUG_K12
594     gchar* env_level = getenv("K12_DEBUG_LEVEL");
595     env_file = getenv("K12_DEBUG_FILENAME");
596     if ( env_file ) dbg_out = ws_fopen(env_file,"w");
597     else dbg_out = stderr;
598     if ( env_level ) debug_level = strtoul(env_level,NULL,10);
599     K12_DBG(1,("k12_open: ENTER debug_level=%u",debug_level));
600 #endif
601
602     if ( file_read(header_buffer,1,0x200,wth->fh) != 0x200 ) {
603         K12_DBG(1,("k12_open: FILE HEADER TOO SHORT"));
604         return 0;
605     } else {
606         if ( memcmp(header_buffer,k12_file_magic,8) != 0 ) {
607             K12_DBG(1,("k12_open: BAD MAGIC"));
608             return 0;
609         }
610     }
611
612     offset = 0x200;
613
614     file_data = new_k12_file_data();
615
616     file_data->file_len = pntohl( header_buffer + 0x8);
617     file_data->num_of_records = pntohl( header_buffer + 0xC );
618
619     K12_DBG(5,("k12_open: FILE_HEADER OK: offset=%x file_len=%i records=%i",
620             offset,
621             file_data->file_len,
622             file_data->num_of_records ));
623
624     do {
625
626         len = get_record(&read_buffer, wth->fh, offset);
627
628         if ( len <= 0 ) {
629             K12_DBG(1,("k12_open: BAD HEADER RECORD",len));
630             destroy_k12_file_data(file_data);
631             g_free(file_data);
632             return -1;
633         }
634
635
636         type = pntohl( read_buffer + K12_RECORD_TYPE );
637
638         if ( (type & K12_MASK_PACKET) == K12_REC_PACKET) {
639             /*
640              * we are at the first packet record, rewind and leave.
641              */
642             if (file_seek(wth->fh, offset, SEEK_SET, err) == -1) {
643                 destroy_k12_file_data(file_data);
644                 g_free(file_data);
645                 return -1;
646             }
647             K12_DBG(5,("k12_open: FIRST PACKET offset=%x",offset));
648             break;
649         } else if (type == K12_REC_SRCDSC || type == K12_REC_SRCDSC2 ) {
650             rec = g_malloc0(sizeof(k12_src_desc_t));
651
652             rec_len = pntohl( read_buffer + K12_RECORD_LEN );
653             extra_len = pntohs( read_buffer + K12_SRCDESC_EXTRALEN );
654             name_len = pntohs( read_buffer + K12_SRCDESC_NAMELEN );
655             stack_len = pntohs( read_buffer + K12_SRCDESC_STACKLEN );
656
657             rec->input = pntohl( read_buffer + K12_RECORD_SRC_ID );
658
659             K12_DBG(5,("k12_open: INTERFACE RECORD offset=%x interface=%x",offset,rec->input));
660
661             if (name_len == 0 || stack_len == 0
662                 || 0x20 + extra_len + name_len + stack_len > rec_len ) {
663                 g_free(rec);
664                 K12_DBG(5,("k12_open: failed (name_len == 0 || stack_len == 0 "
665                         "|| 0x20 + extra_len + name_len + stack_len > rec_len)  extra_len=%i name_len=%i stack_len=%i"));
666                 destroy_k12_file_data(file_data);
667                 g_free(file_data);
668                 return 0;
669             }
670
671             if (extra_len)
672                 switch(( rec->input_type = pntohl( read_buffer + K12_SRCDESC_EXTRATYPE ) )) {
673                     case K12_PORT_DS0S:
674                         rec->input_info.ds0mask = 0x00000000;
675
676                         for (i = 0; i < 32; i++) {
677                             rec->input_info.ds0mask |= ( *(read_buffer + K12_SRCDESC_DS0_MASK + i) == 0xff ) ? 0x1<<(31-i) : 0x0;
678                         }
679
680                             break;
681                     case K12_PORT_ATMPVC:
682                         rec->input_info.atm.vp = pntohs( read_buffer + K12_SRCDESC_ATM_VPI );
683                         rec->input_info.atm.vc = pntohs( read_buffer + K12_SRCDESC_ATM_VCI );
684                         break;
685                     default:
686                         break;
687                 }
688             else {    /* Record viewer generated files
689                    don't have this information */
690                 if (read_buffer[K12_SRCDESC_PORT_TYPE] >= 0x14
691                     && read_buffer[K12_SRCDESC_PORT_TYPE] <= 0x17)
692                     /* For ATM2_E1DS1, ATM2_E3DS3,
693                        ATM2_STM1EL and ATM2_STM1OP */
694                     rec->input_type = K12_PORT_ATMPVC;
695             }
696
697             /* XXX - this is assumed, in a number of places (not just in the
698                ascii_strdown_inplace() call below) to be null-terminated;
699                is that guaranteed (even with a corrupt file)? */
700             rec->input_name = g_memdup(read_buffer + K12_SRCDESC_EXTRATYPE + extra_len, name_len);
701             rec->stack_file = g_memdup(read_buffer + K12_SRCDESC_EXTRATYPE + extra_len + name_len, stack_len);
702
703             ascii_strdown_inplace (rec->stack_file);
704
705             g_hash_table_insert(file_data->src_by_id,GUINT_TO_POINTER(rec->input),rec);
706             g_hash_table_insert(file_data->src_by_name,rec->stack_file,rec);
707
708             offset += len;
709             continue;
710         } else {
711             offset += len;
712             continue;
713         }
714     } while(1);
715
716     wth->data_offset = offset;
717     wth->file_type = WTAP_FILE_K12;
718     wth->file_encap = WTAP_ENCAP_K12;
719     wth->snapshot_length = 0;
720     wth->subtype_read = k12_read;
721     wth->subtype_seek_read = k12_seek_read;
722     wth->subtype_close = k12_close;
723     wth->priv = (void *)file_data;
724     wth->tsprecision = WTAP_FILE_TSPREC_NSEC;
725
726     return 1;
727 }
728
729 typedef struct {
730         guint32 file_len;
731         guint32 num_of_records;
732         guint32 file_offset;
733 } k12_dump_t;
734
735 int k12_dump_can_write_encap(int encap) {
736
737     if (encap == WTAP_ENCAP_PER_PACKET)
738         return WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
739
740     if (encap != WTAP_ENCAP_K12)
741         return WTAP_ERR_UNSUPPORTED_ENCAP;
742
743     return 0;
744 }
745
746 static const gchar dumpy_junk[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
747
748 static gboolean do_fwrite(const void *data, size_t size, size_t count, FILE *stream, int *err_p) {
749     size_t nwritten;
750
751     nwritten = fwrite(data, size, count, stream);
752     if (nwritten != count) {
753         if (nwritten == 0 && ferror(stream))
754             *err_p = errno;
755         else
756             *err_p = WTAP_ERR_SHORT_WRITE;
757         return FALSE;
758     }
759     return TRUE;
760 }
761
762 static gboolean k12_dump_record(wtap_dumper *wdh, guint32 len,  guint8* buffer, int *err_p) {
763     k12_dump_t *k12 = (k12_dump_t *)wdh->priv;
764     guint32 junky_offset = (0x2000 - ( (k12->file_offset - 0x200) % 0x2000 )) % 0x2000;
765
766     if (len > junky_offset) {
767         if (junky_offset) {
768             if (! do_fwrite(buffer, 1, junky_offset, wdh->fh, err_p))
769                 return FALSE;
770         }
771         if (! do_fwrite(dumpy_junk, 1, 0x10, wdh->fh, err_p))
772             return FALSE;
773
774         if (! do_fwrite(buffer+junky_offset, 1, len - junky_offset, wdh->fh, err_p))
775             return FALSE;
776
777         k12->file_offset += len + 0x10;
778     } else {
779         if (! do_fwrite(buffer, 1, len, wdh->fh, err_p))
780             return FALSE;
781         k12->file_offset += len;
782     }
783
784     k12->num_of_records++;
785     return TRUE;
786 }
787
788 static void k12_dump_src_setting(gpointer k _U_, gpointer v, gpointer p) {
789     k12_src_desc_t* src_desc = v;
790     wtap_dumper *wdh = p;
791     guint32 len;
792     guint offset;
793     guint i;
794     int   errxxx; /* dummy */
795
796     union {
797         guint8 buffer[0x2000];
798
799         struct {
800             guint32 len;
801             guint32 type;
802             guint32 unk32_1;
803             guint32 input;
804
805             guint16 unk32_2;
806             guint16 color;
807             guint32 unk32_3;
808             guint32 unk32_4;
809             guint16 unk16_1;
810             guint16 extra_len;
811
812             guint16 name_len;
813             guint16 stack_len;
814
815             struct {
816                 guint32 type;
817
818                 union {
819                     struct {
820                         guint32 unk32;
821                         guint8 mask[32];
822                     } ds0mask;
823
824                     struct {
825                         guint8 unk_data[0x10];
826                         guint16 vp;
827                         guint16 vc;
828                     } atm;
829
830                     guint32 unk;
831                 } desc;
832             } extra;
833         } record;
834     } obj;
835
836     obj.record.type = g_htonl(K12_REC_SRCDSC);
837     obj.record.unk32_1 = g_htonl(0x00000001);
838     obj.record.input = g_htonl(src_desc->input);
839
840     obj.record.unk32_2 = g_htons(0x0000);
841     obj.record.color = g_htons(0x060f);
842     obj.record.unk32_3 = g_htonl(0x00000003);
843     switch (src_desc->input_type) {
844         case K12_PORT_ATMPVC:
845             obj.record.unk32_4 = g_htonl(0x01001400);
846             break;
847         default:
848             obj.record.unk32_4 = g_htonl(0x01000100);
849     }
850
851     obj.record.unk16_1 = g_htons(0x0000);
852     obj.record.name_len = (guint16) strlen(src_desc->input_name) + 1;
853     obj.record.stack_len = (guint16) strlen(src_desc->stack_file) + 1;
854
855     obj.record.extra.type = g_htonl(src_desc->input_type);
856
857     switch (src_desc->input_type) {
858         case K12_PORT_ATMPVC:
859             obj.record.extra_len = g_htons(0x18);
860             obj.record.extra.desc.atm.vp = g_htons(src_desc->input_info.atm.vp);
861             obj.record.extra.desc.atm.vc = g_htons(src_desc->input_info.atm.vc);
862             offset = 0x3c;
863             break;
864         case K12_PORT_DS0S:
865             obj.record.extra_len = g_htons(0x18);
866             for( i=0; i<32; i++ ) {
867                 obj.record.extra.desc.ds0mask.mask[i] =
868                 (src_desc->input_info.ds0mask & (1 << i)) ? 0xff : 0x00;
869             }
870                 offset = 0x3c;
871             break;
872         default:
873             obj.record.extra_len = g_htons(0x08);
874             offset = 0x2c;
875             break;
876     }
877
878     memcpy(obj.buffer + offset,
879            src_desc->input_name,
880            obj.record.name_len);
881
882     memcpy(obj.buffer + offset + obj.record.name_len,
883            src_desc->stack_file,
884            obj.record.stack_len);
885
886     len = offset + obj.record.name_len + obj.record.stack_len;
887     len += (len % 4) ? 4 - (len % 4) : 0;
888
889     obj.record.len = g_htonl(len);
890     obj.record.name_len =  g_htons(obj.record.name_len);
891     obj.record.stack_len = g_htons(obj.record.stack_len);
892
893     k12_dump_record(wdh,len,obj.buffer, &errxxx); /* fwrite errs ignored: see k12_dump below */
894 }
895
896 static gboolean k12_dump(wtap_dumper *wdh, const struct wtap_pkthdr *phdr,
897                          const union wtap_pseudo_header *pseudo_header,
898                          const guchar *pd, int *err) {
899     k12_dump_t *k12 = (k12_dump_t *)wdh->priv;
900     guint32 len;
901     union {
902         guint8 buffer[0x2000];
903         struct {
904             guint32 len;
905             guint32 type;
906             guint32 frame_len;
907             guint32 input;
908
909             guint32 datum_1;
910             guint32 datum_2;
911             guint64 ts;
912
913             guint8 frame[0x1fc0];
914         } record;
915     } obj;
916
917     if (k12->num_of_records == 0) {
918         k12_t* file_data = pseudo_header->k12.stuff;
919         /* XXX: We'll assume that any fwrite errors in k12_dump_src_setting will    */
920         /*      repeat during the final k12_dump_record at the end of k12_dump      */
921         /*      (and thus cause an error return from k12_dump).                     */
922         /*      (I don't see a reasonably clean way to handle any fwrite errors     */
923         /*       encountered in k12_dump_src_setting).                              */
924         g_hash_table_foreach(file_data->src_by_id,k12_dump_src_setting,wdh);
925     }
926     obj.record.len = 0x20 + phdr->len;
927     obj.record.len += (obj.record.len % 4) ? 4 - obj.record.len % 4 : 0;
928
929     len = obj.record.len;
930
931     obj.record.len = g_htonl(obj.record.len);
932
933     obj.record.type = g_htonl(K12_REC_PACKET);
934     obj.record.frame_len = g_htonl(phdr->len);
935     obj.record.input = g_htonl(pseudo_header->k12.input);
936
937     obj.record.ts = GUINT64_TO_BE((((guint64)phdr->ts.secs - 631152000) * 2000000) + (phdr->ts.nsecs / 1000 * 2));
938
939     memcpy(obj.record.frame,pd,phdr->len);
940
941     return k12_dump_record(wdh,len,obj.buffer, err);
942 }
943
944 static const guint8 k12_eof[] = {0xff,0xff};
945
946 static gboolean k12_dump_close(wtap_dumper *wdh, int *err) {
947     k12_dump_t *k12 = (k12_dump_t *)wdh->priv;
948     union {
949         guint8 b[sizeof(guint32)];
950         guint32 u;
951     } d;
952
953     if (! do_fwrite(k12_eof, 1, 2, wdh->fh, err))
954         return FALSE;
955
956     if (fseek(wdh->fh, 8, SEEK_SET) == -1) {
957         *err = errno;
958         return FALSE;
959     }
960
961     d.u = g_htonl(k12->file_len);
962
963     if (! do_fwrite(d.b, 1, 4, wdh->fh, err))
964         return FALSE;
965
966     d.u = g_htonl(k12->num_of_records);
967
968     if (! do_fwrite(d.b, 1, 4, wdh->fh, err))
969         return FALSE;
970
971     return TRUE;
972 }
973
974
975 gboolean k12_dump_open(wtap_dumper *wdh, gboolean cant_seek, int *err) {
976     k12_dump_t *k12;
977
978     if (cant_seek) {
979         *err = WTAP_ERR_CANT_WRITE_TO_PIPE;
980         return FALSE;
981     }
982
983     if ( ! do_fwrite(k12_file_magic, 1, 8, wdh->fh, err)) {
984         return FALSE;
985     }
986
987     if (fseek(wdh->fh, 0x200, SEEK_SET) == -1) {
988         *err = errno;
989         return FALSE;
990     }
991
992     wdh->subtype_write = k12_dump;
993     wdh->subtype_close = k12_dump_close;
994
995     k12 = (k12_dump_t *)g_malloc(sizeof(k12_dump_t));
996     wdh->priv = (void *)k12;
997     k12->file_len = 0x200;
998     k12->num_of_records = 0;
999     k12->file_offset  = 0x200;
1000
1001     return TRUE;
1002 }
1003
1004