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