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