Signed vs. unsigned fix.
[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  * $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 struct _k12_t {
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 };
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_src_desc_t* src_desc;
319     guint8* buffer = NULL;
320     gint64 offset;
321     gint len;
322     guint32 type;
323     guint32 src_id;
324     guint64 ts;
325     guint32 extra_len;
326
327     offset = wth->data_offset;
328
329     /* ignore the record if it isn't a packet */
330     do {
331         K12_DBG(5,("k12_read: offset=%i",offset));
332
333         *data_offset = offset;
334
335         len = get_record(&buffer, wth->fh, offset);
336
337         if (len < 0) {
338             *err = WTAP_ERR_SHORT_READ;
339             return FALSE;
340         } else if (len == 0) {
341             *err = 0;
342             return FALSE;
343         }
344
345         type = pntohl(buffer + K12_RECORD_TYPE);
346         src_id = pntohl(buffer + K12_RECORD_SRC_ID);
347
348
349         if ( ! (src_desc = g_hash_table_lookup(wth->capture.k12->src_by_id,GUINT_TO_POINTER(src_id))) ) {
350             /*
351              * Some records from K15 files have a port ID of an undeclared
352              * interface which happens to be the only one with the first byte changed.
353              * It is still unknown how to recognize when this happens.
354              * If the lookup of the interface record fails we'll mask it
355              * and retry.
356              */
357             src_desc = g_hash_table_lookup(wth->capture.k12->src_by_id,GUINT_TO_POINTER(src_id&K12_RECORD_SRC_ID_MASK));
358         }
359
360         K12_DBG(5,("k12_read: record type=%x src_id=%x",type,src_id));
361
362         offset += len;
363
364     } while ( ((type & K12_MASK_PACKET) != K12_REC_PACKET) || !src_id || !src_desc );
365
366     wth->data_offset = offset;
367
368     ts = pntohll(buffer + K12_PACKET_TIMESTAMP);
369
370     wth->phdr.ts.secs = (guint32) ((ts / 2000000) + 631152000);
371     wth->phdr.ts.nsecs = (guint32) ( (ts % 2000000) * 500 );
372
373     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));
374
375     wth->phdr.len = wth->phdr.caplen = pntohl(buffer + K12_RECORD_FRAME_LEN) & 0x00001FFF;
376     extra_len = len - K12_PACKET_FRAME - wth->phdr.caplen;
377
378     /* the frame */
379     buffer_assure_space(wth->frame_buffer, wth->phdr.caplen);
380     memcpy(buffer_start_ptr(wth->frame_buffer), buffer + K12_PACKET_FRAME, wth->phdr.caplen);
381
382     /* extra information need by some protocols */
383     buffer_assure_space(&(wth->capture.k12->extra_info), extra_len);
384     memcpy(buffer_start_ptr(&(wth->capture.k12->extra_info)),
385            buffer + K12_PACKET_FRAME + wth->phdr.caplen, extra_len);
386     wth->pseudo_header.k12.extra_info = (void*)buffer_start_ptr(&(wth->capture.k12->extra_info));
387     wth->pseudo_header.k12.extra_length = extra_len;
388
389     wth->pseudo_header.k12.input = src_id;
390
391     K12_DBG(5,("k12_read: wth->pseudo_header.k12.input=%x wth->phdr.len=%i input_name='%s' stack_file='%s' type=%x",
392                wth->pseudo_header.k12.input,wth->phdr.len,src_desc->input_name,src_desc->stack_file,src_desc->input_type));\
393
394     wth->pseudo_header.k12.input_name = src_desc->input_name;
395     wth->pseudo_header.k12.stack_file = src_desc->stack_file;
396     wth->pseudo_header.k12.input_type = src_desc->input_type;
397
398     switch(src_desc->input_type) {
399         case K12_PORT_ATMPVC:
400         if ((long)(K12_PACKET_FRAME + wth->phdr.len + K12_PACKET_OFFSET_CID) < len) {
401             wth->pseudo_header.k12.input_info.atm.vp =  pntohs(buffer + (K12_PACKET_FRAME + wth->phdr.caplen + K12_PACKET_OFFSET_VP));
402             wth->pseudo_header.k12.input_info.atm.vc =  pntohs(buffer + (K12_PACKET_FRAME + wth->phdr.caplen + K12_PACKET_OFFSET_VC));
403             wth->pseudo_header.k12.input_info.atm.cid =  *((unsigned char*)(buffer + K12_PACKET_FRAME + wth->phdr.len + K12_PACKET_OFFSET_CID));
404             break;
405         }
406         /* Fall through */
407         default:
408         memcpy(&(wth->pseudo_header.k12.input_info),&(src_desc->input_info),sizeof(src_desc->input_info));
409         break;
410
411     }
412
413     wth->pseudo_header.k12.stuff = wth->capture.k12;
414
415     return TRUE;
416 }
417
418
419 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_) {
420     k12_src_desc_t* src_desc;
421     guint8* buffer;
422     gint len;
423     guint32 extra_len;
424     guint32 input;
425
426     K12_DBG(5,("k12_seek_read: ENTER"));
427
428     if ( file_seek(wth->random_fh, seek_off, SEEK_SET, err) == -1) {
429         K12_DBG(5,("k12_seek_read: SEEK ERROR"));
430         return FALSE;
431     }
432
433     if ((len = get_record(&buffer, wth->random_fh, seek_off)) < 1) {
434         K12_DBG(5,("k12_seek_read: READ ERROR"));
435         return FALSE;
436     }
437
438     memcpy(pd, buffer + K12_PACKET_FRAME, length);
439
440     extra_len = len - K12_PACKET_FRAME - length;
441     buffer_assure_space(&(wth->capture.k12->extra_info), extra_len);
442     memcpy(buffer_start_ptr(&(wth->capture.k12->extra_info)),
443            buffer + K12_PACKET_FRAME + length, extra_len);
444     wth->pseudo_header.k12.extra_info = (void*)buffer_start_ptr(&(wth->capture.k12->extra_info));
445     wth->pseudo_header.k12.extra_length = extra_len;
446     if (pseudo_header) {
447         pseudo_header->k12.extra_info = (void*)buffer_start_ptr(&(wth->capture.k12->extra_info));
448         pseudo_header->k12.extra_length = extra_len;
449     }
450
451     input = pntohl(buffer + K12_RECORD_SRC_ID);
452     K12_DBG(5,("k12_seek_read: input=%.8x",input));
453
454         if ( ! (src_desc = g_hash_table_lookup(wth->capture.k12->src_by_id,GUINT_TO_POINTER(input))) ) {
455                 /*
456                  * Some records from K15 files have a port ID of an undeclared
457                  * interface which happens to be the only one with the first byte changed.
458                  * It is still unknown how to recognize when this happens.
459                  * If the lookup of the interface record fails we'll mask it
460                  * and retry.
461                  */
462                 src_desc = g_hash_table_lookup(wth->capture.k12->src_by_id,GUINT_TO_POINTER(input&K12_RECORD_SRC_ID_MASK));
463         }
464
465     if (src_desc) {
466         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));
467         if (pseudo_header) {
468             pseudo_header->k12.input_name = src_desc->input_name;
469             pseudo_header->k12.stack_file = src_desc->stack_file;
470             pseudo_header->k12.input_type = src_desc->input_type;
471
472             switch(src_desc->input_type) {
473             case K12_PORT_ATMPVC:
474                 if ((long)(K12_PACKET_FRAME + length + K12_PACKET_OFFSET_CID) < len) {
475                 pseudo_header->k12.input_info.atm.vp =  pntohs(buffer + K12_PACKET_FRAME + length + K12_PACKET_OFFSET_VP);
476                 pseudo_header->k12.input_info.atm.vc =  pntohs(buffer + K12_PACKET_FRAME + length + K12_PACKET_OFFSET_VC);
477                 pseudo_header->k12.input_info.atm.cid =  *((unsigned char*)(buffer + K12_PACKET_FRAME + length + K12_PACKET_OFFSET_CID));
478                 break;
479                 }
480                 /* Fall through */
481             default:
482                 memcpy(&(pseudo_header->k12.input_info),&(src_desc->input_info),sizeof(src_desc->input_info));
483                 break;
484             }
485         }
486
487         wth->pseudo_header.k12.input_name = src_desc->input_name;
488         wth->pseudo_header.k12.stack_file = src_desc->stack_file;
489         wth->pseudo_header.k12.input_type = src_desc->input_type;
490
491         switch(src_desc->input_type) {
492             case K12_PORT_ATMPVC:
493             if ((long)(K12_PACKET_FRAME + length + K12_PACKET_OFFSET_CID) < len) {
494                 wth->pseudo_header.k12.input_info.atm.vp =  pntohs(buffer + K12_PACKET_FRAME + length + K12_PACKET_OFFSET_VP);
495                 wth->pseudo_header.k12.input_info.atm.vc =  pntohs(buffer + K12_PACKET_FRAME + length + K12_PACKET_OFFSET_VC);
496                 wth->pseudo_header.k12.input_info.atm.cid =  *((unsigned char*)(buffer + K12_PACKET_FRAME + length + K12_PACKET_OFFSET_CID));
497             }
498             break;
499             /* Fall through */
500             default:
501             memcpy(&(wth->pseudo_header.k12.input_info),&(src_desc->input_info),sizeof(src_desc->input_info));
502             break;
503         }
504
505     } else {
506         K12_DBG(5,("k12_seek_read: NO SRC_RECORD FOUND"));
507
508         if (pseudo_header) {
509             memset(&(pseudo_header->k12),0,sizeof(pseudo_header->k12));
510             pseudo_header->k12.input_name = "unknown port";
511             pseudo_header->k12.stack_file = "unknown stack file";
512         }
513
514         memset(&(wth->pseudo_header.k12),0,sizeof(wth->pseudo_header.k12));
515         wth->pseudo_header.k12.input_name = "unknown port";
516         wth->pseudo_header.k12.stack_file = "unknown stack file";
517
518     }
519
520     if (pseudo_header) {
521         pseudo_header->k12.input = input;
522         pseudo_header->k12.stuff = wth->capture.k12;
523     }
524
525     wth->pseudo_header.k12.input = input;
526     wth->pseudo_header.k12.stuff = wth->capture.k12;
527
528     K12_DBG(5,("k12_seek_read: DONE OK"));
529
530     return TRUE;
531 }
532
533
534 static k12_t* new_k12_file_data(void) {
535     k12_t* fd = g_malloc(sizeof(k12_t));
536
537     fd->file_len = 0;
538     fd->num_of_records = 0;
539     fd->src_by_name = g_hash_table_new(g_str_hash,g_str_equal);
540     fd->src_by_id = g_hash_table_new(g_direct_hash,g_direct_equal);
541
542     buffer_init(&(fd->extra_info), 100);
543
544     return fd;
545 }
546
547 static gboolean destroy_srcdsc(gpointer k _U_, gpointer v, gpointer p _U_) {
548     k12_src_desc_t* rec = v;
549
550     g_free(rec->input_name);
551     g_free(rec->stack_file);
552     g_free(rec);
553
554     return TRUE;
555 }
556
557 static void destroy_k12_file_data(k12_t* fd) {
558     g_hash_table_destroy(fd->src_by_id);
559     g_hash_table_foreach_remove(fd->src_by_name,destroy_srcdsc,NULL);
560     g_hash_table_destroy(fd->src_by_name);
561     buffer_free(&(fd->extra_info));
562     g_free(fd);
563 }
564
565 static void k12_close(wtap *wth) {
566     destroy_k12_file_data(wth->capture.k12);
567 #ifdef DEBUG_K12
568     K12_DBG(5,("k12_close: CLOSED"));
569     if (env_file) fclose(dbg_out);
570 #endif
571 }
572
573
574 int k12_open(wtap *wth, int *err, gchar **err_info _U_) {
575     k12_src_desc_t* rec;
576     guint8 header_buffer[0x200];
577     guint8* read_buffer;
578     guint32 type;
579     long offset;
580     long len;
581     guint32 rec_len;
582     guint32 extra_len;
583     guint32 name_len;
584     guint32 stack_len;
585     guint i;
586     k12_t* file_data;
587
588 #ifdef DEBUG_K12
589     gchar* env_level = getenv("K12_DEBUG_LEVEL");
590     env_file = getenv("K12_DEBUG_FILENAME");
591     if ( env_file ) dbg_out = ws_fopen(env_file,"w");
592     else dbg_out = stderr;
593     if ( env_level ) debug_level = strtoul(env_level,NULL,10);
594     K12_DBG(1,("k12_open: ENTER debug_level=%u",debug_level));
595 #endif
596
597     if ( file_read(header_buffer,1,0x200,wth->fh) != 0x200 ) {
598         K12_DBG(1,("k12_open: FILE HEADER TOO SHORT"));
599         return 0;
600     } else {
601         if ( memcmp(header_buffer,k12_file_magic,8) != 0 ) {
602             K12_DBG(1,("k12_open: BAD MAGIC"));
603             return 0;
604         }
605     }
606
607     offset = 0x200;
608
609     file_data = new_k12_file_data();
610
611     file_data->file_len = pntohl( header_buffer + 0x8);
612     file_data->num_of_records = pntohl( header_buffer + 0xC );
613
614     K12_DBG(5,("k12_open: FILE_HEADER OK: offset=%x file_len=%i records=%i",
615             offset,
616             file_data->file_len,
617             file_data->num_of_records ));
618
619     do {
620
621         len = get_record(&read_buffer, wth->fh, offset);
622
623         if ( len <= 0 ) {
624             K12_DBG(1,("k12_open: BAD HEADER RECORD",len));
625             return -1;
626         }
627
628
629         type = pntohl( read_buffer + K12_RECORD_TYPE );
630
631         if ( (type & K12_MASK_PACKET) == K12_REC_PACKET) {
632             /*
633              * we are at the first packet record, rewind and leave.
634              */
635             if (file_seek(wth->fh, offset, SEEK_SET, err) == -1) {
636                 destroy_k12_file_data(file_data);
637                 return -1;
638             }
639             K12_DBG(5,("k12_open: FIRST PACKET offset=%x",offset));
640             break;
641         } else if (type == K12_REC_SRCDSC || type == K12_REC_SRCDSC2 ) {
642             rec = g_malloc0(sizeof(k12_src_desc_t));
643
644             rec_len = pntohl( read_buffer + K12_RECORD_LEN );
645             extra_len = pntohs( read_buffer + K12_SRCDESC_EXTRALEN );
646             name_len = pntohs( read_buffer + K12_SRCDESC_NAMELEN );
647             stack_len = pntohs( read_buffer + K12_SRCDESC_STACKLEN );
648
649             rec->input = pntohl( read_buffer + K12_RECORD_SRC_ID );
650
651             K12_DBG(5,("k12_open: INTERFACE RECORD offset=%x interface=%x",offset,rec->input));
652
653             if (name_len == 0 || stack_len == 0
654                 || 0x20 + extra_len + name_len + stack_len > rec_len ) {
655                 g_free(rec);
656                 K12_DBG(5,("k12_open: failed (name_len == 0 || stack_len == 0 "
657                         "|| 0x20 + extra_len + name_len + stack_len > rec_len)  extra_len=%i name_len=%i stack_len=%i"));
658                 return 0;
659             }
660
661             if (extra_len)
662                 switch(( rec->input_type = pntohl( read_buffer + K12_SRCDESC_EXTRATYPE ) )) {
663                     case K12_PORT_DS0S:
664                         rec->input_info.ds0mask = 0x00000000;
665
666                         for (i = 0; i < 32; i++) {
667                             rec->input_info.ds0mask |= ( *(read_buffer + K12_SRCDESC_DS0_MASK + i) == 0xff ) ? 0x1<<(31-i) : 0x0;
668                         }
669
670                             break;
671                     case K12_PORT_ATMPVC:
672                         rec->input_info.atm.vp = pntohs( read_buffer + K12_SRCDESC_ATM_VPI );
673                         rec->input_info.atm.vc = pntohs( read_buffer + K12_SRCDESC_ATM_VCI );
674                         break;
675                     default:
676                         break;
677                 }
678             else {    /* Record viewer generated files
679                    don't have this information */
680                 if (read_buffer[K12_SRCDESC_PORT_TYPE] >= 0x14
681                     && read_buffer[K12_SRCDESC_PORT_TYPE] <= 0x17)
682                     /* For ATM2_E1DS1, ATM2_E3DS3,
683                        ATM2_STM1EL and ATM2_STM1OP */
684                     rec->input_type = K12_PORT_ATMPVC;
685             }
686
687             /* XXX - this is assumed, in a number of places (not just in the
688                ascii_strdown_inplace() call below) to be null-terminated;
689                is that guaranteed (even with a corrupt file)? */
690             rec->input_name = g_memdup(read_buffer + K12_SRCDESC_EXTRATYPE + extra_len, name_len);
691             rec->stack_file = g_memdup(read_buffer + K12_SRCDESC_EXTRATYPE + extra_len + name_len, stack_len);
692
693             ascii_strdown_inplace (rec->stack_file);
694
695             g_hash_table_insert(file_data->src_by_id,GUINT_TO_POINTER(rec->input),rec);
696             g_hash_table_insert(file_data->src_by_name,rec->stack_file,rec);
697
698             offset += len;
699             continue;
700         } else {
701             offset += len;
702             continue;
703         }
704     } while(1);
705
706     wth->data_offset = offset;
707     wth->file_type = WTAP_FILE_K12;
708     wth->file_encap = WTAP_ENCAP_K12;
709     wth->snapshot_length = 0;
710     wth->subtype_read = k12_read;
711     wth->subtype_seek_read = k12_seek_read;
712     wth->subtype_close = k12_close;
713     wth->capture.k12 = file_data;
714     wth->tsprecision = WTAP_FILE_TSPREC_NSEC;
715
716     return 1;
717 }
718
719 int k12_dump_can_write_encap(int encap) {
720
721     if (encap == WTAP_ENCAP_PER_PACKET)
722         return WTAP_ERR_ENCAP_PER_PACKET_UNSUPPORTED;
723
724     if (encap != WTAP_ENCAP_K12)
725         return WTAP_ERR_UNSUPPORTED_ENCAP;
726
727     return 0;
728 }
729
730 static const gchar dumpy_junk[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 };
731
732 static gboolean do_fwrite(const void *data, size_t size, size_t count, FILE *stream, int *err_p) {
733     size_t nwritten;
734
735     nwritten = fwrite(data, size, count, stream);
736     if (nwritten != count) {
737         if (nwritten == 0 && ferror(stream))
738             *err_p = errno;
739         else
740             *err_p = WTAP_ERR_SHORT_WRITE;
741         return FALSE;
742     }
743     return TRUE;
744 }
745
746 static gboolean k12_dump_record(wtap_dumper *wdh, guint32 len,  guint8* buffer, int *err_p) {
747     guint32 junky_offset = (0x2000 - ( (wdh->dump.k12->file_offset - 0x200) % 0x2000 )) % 0x2000;
748
749     if (len > junky_offset) {
750         if (junky_offset) {
751             if (! do_fwrite(buffer, 1, junky_offset, wdh->fh, err_p))
752                 return FALSE;
753         }
754         if (! do_fwrite(dumpy_junk, 1, 0x10, wdh->fh, err_p))
755             return FALSE;
756
757         if (! do_fwrite(buffer+junky_offset, 1, len - junky_offset, wdh->fh, err_p))
758             return FALSE;
759
760         wdh->dump.k12->file_offset += len + 0x10;
761     } else {
762         if (! do_fwrite(buffer, 1, len, wdh->fh, err_p))
763             return FALSE;
764         wdh->dump.k12->file_offset += len;
765     }
766
767     wdh->dump.k12->num_of_records++;
768     return TRUE;
769 }
770
771 static void k12_dump_src_setting(gpointer k _U_, gpointer v, gpointer p) {
772     k12_src_desc_t* src_desc = v;
773     wtap_dumper *wdh = p;
774     guint32 len;
775     guint offset;
776     guint i;
777     int   errxxx; /* dummy */
778
779     union {
780         guint8 buffer[0x2000];
781
782         struct {
783             guint32 len;
784             guint32 type;
785             guint32 unk32_1;
786             guint32 input;
787
788             guint16 unk32_2;
789             guint16 color;
790             guint32 unk32_3;
791             guint32 unk32_4;
792             guint16 unk16_1;
793             guint16 extra_len;
794
795             guint16 name_len;
796             guint16 stack_len;
797
798             struct {
799                 guint32 type;
800
801                 union {
802                     struct {
803                         guint32 unk32;
804                         guint8 mask[32];
805                     } ds0mask;
806
807                     struct {
808                         guint8 unk_data[0x10];
809                         guint16 vp;
810                         guint16 vc;
811                     } atm;
812
813                     guint32 unk;
814                 } desc;
815             } extra;
816         } record;
817     } obj;
818
819     obj.record.type = g_htonl(K12_REC_SRCDSC);
820     obj.record.unk32_1 = g_htonl(0x00000001);
821     obj.record.input = g_htonl(src_desc->input);
822
823     obj.record.unk32_2 = g_htons(0x0000);
824     obj.record.color = g_htons(0x060f);
825     obj.record.unk32_3 = g_htonl(0x00000003);
826     switch (src_desc->input_type) {
827         case K12_PORT_ATMPVC:
828             obj.record.unk32_4 = g_htonl(0x01001400);
829             break;
830         default:
831             obj.record.unk32_4 = g_htonl(0x01000100);
832     }
833
834     obj.record.unk16_1 = g_htons(0x0000);
835     obj.record.name_len = (guint16) strlen(src_desc->input_name) + 1;
836     obj.record.stack_len = (guint16) strlen(src_desc->stack_file) + 1;
837
838     obj.record.extra.type = g_htonl(src_desc->input_type);
839
840     switch (src_desc->input_type) {
841         case K12_PORT_ATMPVC:
842             obj.record.extra_len = g_htons(0x18);
843             obj.record.extra.desc.atm.vp = g_htons(src_desc->input_info.atm.vp);
844             obj.record.extra.desc.atm.vc = g_htons(src_desc->input_info.atm.vc);
845             offset = 0x3c;
846             break;
847         case K12_PORT_DS0S:
848             obj.record.extra_len = g_htons(0x18);
849             for( i=0; i<32; i++ ) {
850                 obj.record.extra.desc.ds0mask.mask[i] =
851                 (src_desc->input_info.ds0mask & (1 << i)) ? 0xff : 0x00;
852             }
853                 offset = 0x3c;
854             break;
855         default:
856             obj.record.extra_len = g_htons(0x08);
857             offset = 0x2c;
858             break;
859     }
860
861     memcpy(obj.buffer + offset,
862            src_desc->input_name,
863            obj.record.name_len);
864
865     memcpy(obj.buffer + offset + obj.record.name_len,
866            src_desc->stack_file,
867            obj.record.stack_len);
868
869     len = offset + obj.record.name_len + obj.record.stack_len;
870     len += (len % 4) ? 4 - (len % 4) : 0;
871
872     obj.record.len = g_htonl(len);
873     obj.record.name_len =  g_htons(obj.record.name_len);
874     obj.record.stack_len = g_htons(obj.record.stack_len);
875
876     k12_dump_record(wdh,len,obj.buffer, &errxxx); /* fwrite errs ignored: see k12_dump below */
877 }
878
879 static gboolean k12_dump(wtap_dumper *wdh, const struct wtap_pkthdr *phdr,
880                          const union wtap_pseudo_header *pseudo_header,
881                          const guchar *pd, int *err) {
882     guint32 len;
883     union {
884         guint8 buffer[0x2000];
885         struct {
886             guint32 len;
887             guint32 type;
888             guint32 frame_len;
889             guint32 input;
890
891             guint32 datum_1;
892             guint32 datum_2;
893             guint64 ts;
894
895             guint8 frame[0x1fc0];
896         } record;
897     } obj;
898
899     if (wdh->dump.k12->num_of_records == 0) {
900         k12_t* file_data = pseudo_header->k12.stuff;
901         /* XXX: We'll assume that any fwrite errors in k12_dump_src_setting will    */
902         /*      repeat during the final k12_dump_record at the end of k12_dump      */
903         /*      (and thus cause an error return from k12_dump).                     */
904         /*      (I don't see a reasonably clean way to handle any fwrite errors     */
905         /*       encountered in k12_dump_src_setting).                              */
906         g_hash_table_foreach(file_data->src_by_id,k12_dump_src_setting,wdh);
907     }
908     obj.record.len = 0x20 + phdr->len;
909     obj.record.len += (obj.record.len % 4) ? 4 - obj.record.len % 4 : 0;
910
911     len = obj.record.len;
912
913     obj.record.len = g_htonl(obj.record.len);
914
915     obj.record.type = g_htonl(K12_REC_PACKET);
916     obj.record.frame_len = g_htonl(phdr->len);
917     obj.record.input = g_htonl(pseudo_header->k12.input);
918
919     obj.record.ts = GUINT64_TO_BE((((guint64)phdr->ts.secs - 631152000) * 2000000) + (phdr->ts.nsecs / 1000 * 2));
920
921     memcpy(obj.record.frame,pd,phdr->len);
922
923     return k12_dump_record(wdh,len,obj.buffer, err);
924 }
925
926 static const guint8 k12_eof[] = {0xff,0xff};
927
928 static gboolean k12_dump_close(wtap_dumper *wdh, int *err) {
929     union {
930         guint8 b[sizeof(guint32)];
931         guint32 u;
932     } d;
933
934     if (! do_fwrite(k12_eof, 1, 2, wdh->fh, err))
935         return FALSE;
936
937     if (fseek(wdh->fh, 8, SEEK_SET) == -1) {
938         *err = errno;
939         return FALSE;
940     }
941
942     d.u = g_htonl(wdh->dump.k12->file_len);
943
944     if (! do_fwrite(d.b, 1, 4, wdh->fh, err))
945         return FALSE;
946
947     d.u = g_htonl(wdh->dump.k12->num_of_records);
948
949     if (! do_fwrite(d.b, 1, 4, wdh->fh, err))
950         return FALSE;
951
952     return TRUE;
953 }
954
955
956 gboolean k12_dump_open(wtap_dumper *wdh, gboolean cant_seek, int *err) {
957
958     if (cant_seek) {
959         *err = WTAP_ERR_CANT_WRITE_TO_PIPE;
960         return FALSE;
961     }
962
963     if ( ! do_fwrite(k12_file_magic, 1, 8, wdh->fh, err)) {
964         return FALSE;
965     }
966
967     if (fseek(wdh->fh, 0x200, SEEK_SET) == -1) {
968         *err = errno;
969         return FALSE;
970     }
971
972     wdh->subtype_write = k12_dump;
973     wdh->subtype_close = k12_dump_close;
974
975     wdh->dump.k12 = g_malloc(sizeof(k12_dump_t));
976     wdh->dump.k12->file_len = 0x200;
977     wdh->dump.k12->num_of_records = 0;
978     wdh->dump.k12->file_offset  = 0x200;
979
980     return TRUE;
981 }
982
983