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