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