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