File: snmptrapfmt.c

package info (click to toggle)
snmptrapfmt 1.20
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 180 kB
  • sloc: ansic: 1,322; sh: 64; makefile: 26
file content (1594 lines) | stat: -rwxr-xr-x 41,926 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
/* ---------------------------------------------------------------------------
 *
 * snmptrapfmt.c - receive snmp trapd from a trap handler and log them
 *
 * formatted with `indent -gnu -di16 -nut -bls -bli0 -cli2 -cdb -sc -ts2 -ncdb -c33 -cs -npcs`
 * ---------------------------------------------------------------------------
 *  Copyright (C) 2001 Uwe Maier <Uwe.Maier@nice.de>
 *  Copyright (C) 2001 - 2005 Bernd Schumacher Hewlett Packard Consulting
 *                            <bernd.schumacher@hp.com>
 *  Copyright (C) 2005 - 2009 Jochen Friedrich <jochen@scram.de>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 *  See the GNU General Public License in the COPYING file at the
 *  root directory of this project for more details.
 *
 */

/* --- imprt section --- */
#include "snmptrapfmt.h"
#include "log.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/time.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <getopt.h>

#include <netinet/in.h>
#include <syslog.h>
#include <netdb.h>
#include <arpa/inet.h>

#include <net-snmp/net-snmp-config.h>
#include <net-snmp/library/asn1.h>
#include <net-snmp/library/snmp.h>
#include <net-snmp/library/snmp_impl.h>
#include <time.h>
#include <ctype.h>

/* --- local defines and type --- */
#define FREEMEM(x) if(x){free(x);}

#define PNAME   "snmptrapfmt"
#define LOGFILE "/var/tmp/snmptrapfmt.trc"
#define USAGE   "Usage: snmptrapfmt [-f cfgfile] [-D] [-d level]\n"
#define CFGNAME "/etc/snmp/snmptrapfmt.conf"
#define PIDFILE "/var/run/snmptrapfmt.pid"

/* definitions of standard OIDs */
#define OID_SYM_SNMPTRAPADDRESS    ".iso.org.dod.internet.snmpV2.snmpModules.snmpCommunityMIB.snmpCommunityMIBObjects.snmpTrapAddress.0"
#define OID_NUM_SNMPTRAPADDRESS    ".1.3.6.1.6.3.18.1.3.0"

#define OID_SYM_SNMPTRAPCOMMUNITY  ".iso.org.dod.internet.snmpV2.snmpModules.snmpCommunityMIB.snmpCommunityMIBObjects.snmpTrapCommunity.0"
#define OID_NUM_SNMPTRAPCOMMUNITY  ".1.3.6.1.6.3.18.1.4.0"

#define OID_SYM_SNMPTRAPENTERPRISE ".iso.org.dod.internet.snmpV2.snmpModules.snmpMIB.snmpMIBObjects.snmpTrap.snmpTrapEnterprise.0"
#define OID_NUM_SNMPTRAPENTERPRISE ".1.3.6.1.6.3.1.1.4.3.0"

typedef struct
{                               /* --- a trap variable --- */
  char           *v_oid;        /* the oid */
  char           *v_val;        /* the value */
}
t_var;

typedef struct
{                               /* --- a received trap --- */
  char           *s_agentname;  /* hostname of agent (in PDU) */
  char           *s_agentaddr;  /* IP of agent (in PDU) */
  char           *s_senderaddr; /* IP of trap sender (real) */
  char           *s_uptime;     /* uptime of agent */
  char           *s_trapoid;    /* trap OID (snmpV2 notation) */
  char           *s_community;  /* trap community */
  char           *s_enterprise; /* trap enterprise */
  int             n_var;        /* number of trap variables in the array */
  t_var          *a_var;        /* array of trap variables */
}
t_trap;

/* --- local variables --- */
int             o_loglev = 0;   /* log level */
char           *o_cfgname = CFGNAME;  /* configuration file name */
FILE           *o_logfile = NULL; /* log file handle */
long            pid;            /* value of already running process */

/* --- logfile configuration section --- */

/* logfile configuration constants */
#define OIDFMT_OID   0          /* print OIDs numerical */
#define OIDFMT_TEXT  1          /* print OIDs symbolically */
#define NODEFMT_IP   0          /* print nodenames as IP address */
#define NODEFMT_FQDN 1          /* print nodenames as FQDN */
#define NODEFMT_NAME 2          /* print short nodenames */

/* logfile configuration tokens */
#define TOK_SUBST   "SUBST"
#define TOK_OIDFMT  "OIDFMT"
#define TOK_NODEFMT "NODEFMT"
#define TOK_VARFMT  "VARFMT"
#define TOK_LOGFMT  "LOGFMT"
#define TOK_LOGFILE "LOGFILE"
#define TOK_CMUSNMP "CMUSNMP"

/* logfile configuration variables */
char            cfg_subst1 = ';'; /* subst this char in var values */
char            cfg_subst2 = ' '; /* by this char */
int             cfg_oidfmt = OIDFMT_OID;  /* format for OID's */
int             cfg_nodefmt = NODEFMT_FQDN; /* format for nodenames */
char           *cfg_varfmt = ";[%s] %n (%t) : %v";  /* format string for vars in '$*' */
char           *cfg_logfmt = "$x;$A;$e;$G;$S$*";  /* format for the logfile entry */
char           *cfg_logname = NULL;

/* --- local functions --- */
static void     lg_print_config();
static FILE    *lg_parse_config(char *cfgname);
static char    *lg_format_buffer(t_trap * p_trap, time_t trap_time);
static void     lg_sprint_node(char *name, int nodeFmt, char **cPPtr, int *bRemP);
static void     lg_sprint_oid(char *oidP, int oidFmt, char **cPPtr, int *bRemP);
static void     lg_sprint_int(int ival, char *iFmt, char **cPPtr, int *bRemP);
static void     lg_sprint_ulong(unsigned long ival, char *iFmt, char **cPPtr, int *bRemP);
static void     lg_sprint_ASNtype(u_char asntype, char **cPPtr, int *bRemP);
static void     lg_sprint_var(t_var *var, char *vFmt, int seqno, char **cPPtr, int *bRemP);
static void     lg_sprint_string(char *stringP, char **cPPtr, int *bRemP);

static void     free_trap(t_trap * p_trap);
static void     process_trapdata(FILE * f);
static int      read_trapdata(FILE * f, t_trap * p_trap);
static char    *copy_string(char *buf);
static int      read_oidval(FILE * f, char **pp_oid, char **pp_val,
                            char *msg);
static char    *get_generic_id(char *trapoid);
static char    *get_specific_id(char *trapoid);

static u_long   uptime_ticks(char *uptime);

static long     create_pidfile(void);

/* ------------------------------------------------------------------------- */

char           *
trap_description(trap)
     int             trap;
{
  switch (trap)
  {
    case 0:
      return "Cold Start";
    case 1:
      return "Warm Start";
    case 2:
      return "Link Down";
    case 3:
      return "Link Up";
    case 4:
      return "Authentication Failure";
    case 5:
      return "EGP Neighbor Loss";
    case 6:
      return "Enterprise Specific";
    default:
      return "Unknown Type";
  }
}

/* ------------------------------------------------------------------------- */

static          u_long
uptime_ticks(char *uptime)
{
  int             days;
  int             hours;
  int             mins;
  int             secs;
  int             csecs;
  u_long          ticks = 0;

  if (sscanf(uptime, "%d:%d:%d:%d.%d",
             &days, &hours, &mins, &secs, &csecs) == 5)
  {
    ticks = (60 * 60 * 24 * days +
             60 * 60 * hours + 60 * mins + secs) * 100 + csecs;
  }

  return ticks;
}

/* ------------------------------------------------------------------------- */

static long
create_pidfile(void)
{
  long            retval = -1;
  int             pidfile;

  /* create new pidfile - or open existing one without destroying it */
  if ((pidfile = open(PIDFILE, O_WRONLY | O_CREAT, 0644)) != -1)
  {
    /* File created or opened, now try to lock */
    if (flock(pidfile, LOCK_EX | LOCK_NB) == 0)
    {
      char            pid[11];

      /* we have been too nice when opening file - now start at beginning */
      ftruncate(pidfile, 0);
      lseek(pidfile, 0, SEEK_SET);

      sprintf(pid, "%d", getpid());
      write(pidfile, pid, strlen(pid));

      /* we don't close the file - so try to get output to file */
      fsync(pidfile);

      retval = 0;
    }
    else
    {
      /* file is locked by other process */
    }
  }
  else
  {
    retval = errno;
  }

  return retval;
}

/* ------------------------------------------------------------------------- */

int
main(argc, argv)
     int             argc;
     char           *argv[];
{
  int             fd_pipe;
  FILE           *f_pipe;
  fd_set          fdset;
  struct timeval  timeout;
  int             numfds;
  char            is_daemon = FALSE;
  int             c;

  /* Check the arguments */
  while (1)
  {
    int             option_index = 0;
    static struct option long_options[] = {
      {"D", 0, 0, 0},
      {"d", 1, 0, 0},
      {"f", 1, 0, 0},
      {0, 0, 0, 0}
    };

    c = getopt_long(argc, argv, "Dd:f:", long_options, &option_index);
    if (c == -1)
      break;

    switch (c)
    {
      case 'd':
        o_loglev = atoi(optarg);
        break;
      case 'D':
        is_daemon = TRUE;
        break;
      case 'f':
        o_cfgname = optarg;
        break;
      default:
        printf("Unknown argument %c", c);
    }
  }

  /* now go into daemon mode if commandline parameter is set */
  if (is_daemon)
  {
    if (daemon(0, 1) != 0)
    {
      /* error occurred while going into daemon mode */
      fprintf(stderr, "Error while daemonizing (%s)\n", strerror(errno));
      fprintf(stderr, "Aborting ...\n");
      exit(1);
    }
  }

  /* check for existing process - allocate PID file */
  if (create_pidfile() != 0)
  {
    fprintf(stderr, "Error occurred while creating pid file\n");
    fprintf(stderr,
            "      not running as root or other snmptrapfmt running?\n");
    fprintf(stderr, "Aborting ...\n");

    /* that's it - drop off now */
    exit(1);
  }

  /* In daemon mode, now redirect std* to /dev/null */
  if (is_daemon)
  {
    freopen("/dev/null", "r", stdin);
    freopen("/dev/null", "w", stdout);
    freopen("/dev/null", "w", stderr);
  }

  /* Init the logfile, non append mode, i.e. create a new one */
  loginit(PNAME, LOGFILE, o_loglev, 0);
  logging(1, "Starting ...");

  /* Parse the configuration file */
  o_logfile = lg_parse_config(o_cfgname);

  /* Print the logfile output specification */
  if (o_loglev > 0)
  {
    lg_print_config();
  }

  /* Create and open the pipe */
  logging(1, "Create the pipe '%s' ...", PIPENAME);
  if ((mkfifo(PIPENAME, S_IWUSR | S_IRUSR) == -1) && (errno != EEXIST))
  {
    logging(0, "Cannot create the pipe '%s' [%s]", PIPENAME, strerror(errno));

    exit(1);
  }

  fd_pipe = open(PIPENAME, O_RDWR, S_IWUSR | S_IRUSR);
  if (fd_pipe < 0)
  {
    logging(0, "Cannot open the pipe '%s' [%s]", PIPENAME, strerror(errno));

    exit(1);
  }

  f_pipe = fdopen(fd_pipe, "w+");
  if (f_pipe == NULL)
  {
    logging(0, "Cannot associate stream with file handle for pipe '%s' [%s]",
        PIPENAME, strerror(errno));

    exit(1);
  }
  logging(1, "Pipe opened for reading");

  /* Main loop: sit and wait until data arrives on the pipe */
  while (1)
  {
    FD_ZERO(&fdset);            /* wait for data on the pipe handle */
    FD_SET(fd_pipe, &fdset);
    timeout.tv_sec = 5;         /* wait 5 seconds for data */
    timeout.tv_usec = 0;

    numfds = select(fd_pipe + 1, &fdset, 0, 0, &timeout);
    switch (numfds)
    {
      case 0:
        logging(1, "Timeout occurred ...");
        break;
      case -1:
        if (errno == EINTR)
        {
          logging(1, "Interrupted select() - continue");
          continue;
        }
        else
        {
          logging(0, "Error from select() [%s]", strerror(errno));
          exit(1);
        }
        break;
      default:
        logging(1, "Data available ...");
        process_trapdata(f_pipe);
        break;
    }
  }

  /* not reached */
}

/* ------------------------------------------------------------------------- */

/* Parse the configuration file:
 * - check for the tokens and set the config variables
 * - open the logfile and return the file pointer (or NULL if no logfile)
 * - syntax of configuration file (fixed text in '')
 *   comment lines begin with '#'
 *     file    ::= line | file line
 *     line    ::= 'SUBST'   '=' '\'char'\'char'\'
 *               | 'OIDFMT'  '=' ( 'text' | 'oid' )
 *               | 'NODEFMT' '=' ( 'ip' | 'fqdn' | 'name' )
 *               | 'VARFMT'  '=' stringV
 *               | 'LOGFMT'  '=' stringL
 *               | 'LOGFILE' '=' string
 *               | 'CMUSNMP' '=' string                 >>>OBSOLETE<<<
 *     string  ::= '"' { char | '\"' } '"'
 *     stringV ::= '"' { char | '%s' | '%n' | '%t' | '%v' | '%%' } '"'
 *     stringL ::= '"' { char | '$#' | '$*' | '$x' | '$r' | '$R'
 *                            | '$e' | '$A' | '$G' | '$S' | '$T'
 *                            | '$$'
 *                            | '\n' | '\r' | '\t' | '\\' } '"'
 *
 * - Tokens and associated config variables are:
 *     SUBST       ... cfg_subst1, cfg_subst2   (both char)
 *     OIDFMT      ... cfg_oidfmt               (OIDFMT_TEXT,_OID)
 *     NODEFMT     ... cfg_nodefmt              (NODEFMT_IP, _FQDN, _NAME)
 *     VARFMT      ... cfg_varfmt               (char*)
 *     LOGFMT      ... cfg_logfmt               (char*)
 *     LOGFILE     ... cfg_logname              (char*)
 *     CMUSNMP     ... cfg_cmusnmp              (char*)    >>>OBSOLETE<<<
 *     
 */
static FILE    *
lg_parse_config(char *cfgname)
{
  FILE           *cfg;
  FILE           *f_log = NULL;
  char            lbuf[1024];
  int             lno = 0;


  logging(1, "Parsing config file '%s'", cfgname);

  if (!(cfg = fopen(cfgname, "r")))
  {
    logging(0, "Cannot open config file '%s' - %s\n", cfgname, strerror(errno));

    return NULL;
  }

  while (fgets(lbuf, sizeof(lbuf), cfg))
  {
    char           *p;

    logging(1, "Read line '%s'", lbuf);

    p = strtok(lbuf, "=\n");

    /* check for comment or empty lines */
    lno++;
    if (!p || (*p == '#'))
    {
      continue;
    }

    /* check for tokens */
    if (strcasecmp(TOK_SUBST, p) == 0)
    {
      char           *p1 = strtok(NULL, "\n");  /* the substitution */
      int             ok = 1;

      if (!p1 || !*p1 || (*p1 != '\\'))
      {
        ok = 0;
      }
      else
      {
        p1++;
        cfg_subst1 = *p1++;

        if (*p1++ == '\\' && *p1)
        {
          cfg_subst2 = *p1;
        }
        else
        {
          ok = 0;
        }
      }
      if (!ok)
      {
        logging(0, "Expected: %s=\\<char>\\<char>\\ in file '%s',%d",
            TOK_SUBST, cfgname, lno);
      }
    }
    else if (strcasecmp(TOK_OIDFMT, p) == 0)
    {
      char           *p1 = strtok(NULL, " \n");
      int             ok = 1;

      if (!p1 || !*p1)
      {
        ok = 0;
      }
      else if (strcasecmp("text", p1) == 0)
      {
#if 0
        cfg_oidfmt = OIDFMT_TEXT;
#else
        logging(0, "Error: Format for OID must be set in /etc/snmp/snmp.conf");

        cfg_oidfmt = OIDFMT_OID;
#endif
      }
      else if (strcasecmp("oid", p1) == 0)
      {
        cfg_oidfmt = OIDFMT_OID;
      }
      else
      {
        ok = 0;
      }
      if (!ok)
      {
        logging(0, "Expected: %s='text' | 'oid' in file '%s',%d",
            TOK_OIDFMT, cfgname, lno);
      }
    }
    else if (strcasecmp(TOK_NODEFMT, p) == 0)
    {
      char           *p1 = strtok(NULL, " \n");
      int             ok = 1;

      if (!p1)
      {
        ok = 0;
      }
      else if (strcasecmp("ip", p1) == 0)
      {
        cfg_nodefmt = NODEFMT_IP;
      }
      else if (strcasecmp("fqdn", p1) == 0)
      {
        cfg_nodefmt = NODEFMT_FQDN;
      }
      else if (strcasecmp("name", p1) == 0)
      {
        cfg_nodefmt = NODEFMT_NAME;
      }
      else
      {
        ok = 0;
      }
      if (!ok)
      {
        logging(0, "Expected: %s='ip' | 'fqdn' | 'name' in file '%s',%d",
            TOK_NODEFMT, cfgname, lno);
      }
    }
    else if ((strcasecmp(TOK_VARFMT, p) == 0) ||
             (strcasecmp(TOK_LOGFMT, p) == 0) ||
             (strcasecmp(TOK_LOGFILE, p) == 0) ||
             (strcasecmp(TOK_CMUSNMP, p) == 0))
    {
      char           *p1 = strtok(NULL, "\n");
      int             ok = 1;

      if (!p1)
      {
        ok = 0;
      }
      else if (*p1 == '\"')
      {
        char           *p2 = strrchr(++p1, '\"');

        if (p2)
        {
          char           *pval;

          *p2 = '\0';
          pval = strdup(p1);

          if (strcasecmp(TOK_VARFMT, p) == 0)
          {
            cfg_varfmt = pval;
          }
          else if (strcasecmp(TOK_LOGFMT, p) == 0)
          {
            cfg_logfmt = pval;
          }
          else if (strcasecmp(TOK_LOGFILE, p) == 0)
          {
            cfg_logname = pval;
          }
          else if (strcasecmp(TOK_CMUSNMP, p) == 0)
          {
            logging(0, "The option 'CMUSNMP' is obsolete");
          }
        }
        else
        {
          ok = 0;
        }
      }
      else
      {
        ok = 0;
      }
      if (!ok)
      {
        logging(0, "Expected: %s=\"<string>\" in file '%s',%d", p, cfgname, lno);
      }
    }
    else
    {
      logging(0, "Missing token in file '%s',%d", cfgname, lno);
    }
  }

  fclose(cfg);

  /* now open the log file (if any) */
  if (cfg_logname && *cfg_logname)
  {
    f_log = fopen(cfg_logname, "a");

    if (!f_log)
    {
      logging(0, "Cannot append to logfile '%s' [%s]",
          cfg_logname, strerror(errno));
    }
  }

  return f_log;
}

/* ------------------------------------------------------------------------- */

/* print the logfile configuration values */
static void
lg_print_config()
{

  char           *oidfmt[2];
  char           *nodefmt[3];

  oidfmt[OIDFMT_OID] = "oid";
  oidfmt[OIDFMT_TEXT] = "text";
  nodefmt[NODEFMT_IP] = "ip";
  nodefmt[NODEFMT_FQDN] = "fqdn";
  nodefmt[NODEFMT_NAME] = "name";

  logging(1, "Configuration variables:");
  logging(1, " cfg_subst1  = '%c'", cfg_subst1);
  logging(1, " cfg_subst2  = '%c'", cfg_subst2);
  logging(1, " cfg_oidfmt  = %s", oidfmt[cfg_oidfmt]);
  logging(1, " cfg_nodefmt = %s", nodefmt[cfg_nodefmt]);
  logging(1, " cfg_varfmt  = \"%s\"", cfg_varfmt);
  logging(1, " cfg_logfmt  = \"%s\"", cfg_logfmt);
  logging(1, " cfg_logname = \"%s\"",
      (cfg_logname && *cfg_logname ? cfg_logname : "<syslog>"));
}

/* ------------------------------------------------------------------------- */

/* Allocate and format the output buffer.
 * Return the pointer to the allocated area or NULL if an error occurred.
 */
static char    *
lg_format_buffer(t_trap * p_trap, time_t trap_time)
{
  static char     buf[65535];   /* the output buffer */
  char           *cPtr;         /* points to next character in output buf */
  int             bRem;         /* number of remaining chars in output buf */
  /* (starting with cPtr) */
  char           *lPtr;         /* points to next char in log format */
  int             seqno;        /* sequence number of variable */


  logging(1, "Formatting the trap data with '%s' ...", cfg_logfmt);

  /* init */
  bRem = sizeof(buf) - 1;       /* leave space for EOS */
  cPtr = buf;

  /* process the log format string */
  for (lPtr = cfg_logfmt; *lPtr; lPtr++)
  {
    int             l;          /* local */

    /* Assertion: bRem > 0 */
    switch (*lPtr)
    {
      case '\\':
        switch (*++lPtr)
        {
          case 'n':
            *cPtr++ = '\n';
            break;
          case 'r':
            *cPtr++ = '\r';
            break;
          case 't':
            *cPtr++ = '\t';
            break;
          default:
            *cPtr++ = *lPtr;
            break;
        }
        bRem--;
        break;
      case '$':
        switch (*++lPtr)
        {
          case 'x':            /* time trap was received */
            l = strftime(cPtr, bRem, "%Y%m%d.%H%M%S", localtime(&trap_time));
            cPtr += l;
            bRem -= l;
            break;
          case 'A':            /* agents address */
            if (p_trap->s_agentaddr == NULL)
              lg_sprint_node(p_trap->s_agentname, cfg_nodefmt, &cPtr, &bRem);
            else
              lg_sprint_node(p_trap->s_agentaddr, cfg_nodefmt, &cPtr, &bRem);
            break;
          case 'r':            /* implied source (agent address) */
            lg_sprint_node(p_trap->s_agentname, cfg_nodefmt, &cPtr, &bRem);
            break;
          case 'R':            /* true source (peer address) */
            lg_sprint_node(p_trap->s_senderaddr, cfg_nodefmt, &cPtr, &bRem);
            break;
          case 'e':            /* enterprise */
            lg_sprint_oid(p_trap->s_enterprise, cfg_oidfmt, &cPtr, &bRem);
            break;
          case 'G':            /* generic trap number */
            lg_sprint_string(get_generic_id(p_trap->s_trapoid), &cPtr, &bRem);
            break;
          case 'S':            /* specific trap number */
            lg_sprint_string(get_specific_id(p_trap->s_trapoid),
                             &cPtr, &bRem);
            break;
          case 'T':            /* agent's sysUpTime in 1/100 seconds */
            lg_sprint_ulong(uptime_ticks(p_trap->s_uptime),
                            "%lu", &cPtr, &bRem);
            break;
          case '#':            /* number of variables in trap */
            lg_sprint_int(p_trap->n_var, "%d", &cPtr, &bRem);
            break;
          case '*':            /* all variables in trap */
            for (seqno = 1; seqno <= p_trap->n_var; seqno++)
            {
              lg_sprint_var(&p_trap->a_var[seqno - 1],
                            cfg_varfmt, seqno, &cPtr, &bRem);
            }
            break;
          case '$':            /* insert '$' */
            *cPtr++ = '$';
            bRem--;
            break;
          default:             /* insert the characters verbatim */
            *cPtr++ = '$';
            *cPtr++ = *lPtr;
            bRem -= 2;
        }
        break;
      default:
        *cPtr++ = *lPtr;
        bRem--;
        break;
    }

    /* leave if no more space is left */
    if (bRem == 0)
    {
      logging(0, "No more internal space left for remaining format '%s'", lPtr);
      break;
    }
  }
  *cPtr = '\0';

  /* Debug output  */
  logging(1, "Output buffer: '%s'", buf);

  /* this is the result */
  return buf;
}

/* ------------------------------------------------------------------------- */

/* print a nodes ip-address, fully qualified domain name or
 * short hostname according to the specified format into the
 * output buffer
 */
static void
lg_sprint_node(char           *name,      /* node name (or ip) */
               int             nodeFmt,   /* NODEFMT_IP/_FQDN/_NAME */
               char          **cPPtr,     /* address of pointer to current outchar */
               int            *bRemP     /* address of counter of remaining chars */)
{
  char            lbuf[80];     /* local buffer for result */
  int             l;
  struct hostent *hent = gethostbyname(name);

  logging(1, "lg_sprint_node(%s, ...)", name);

  switch (nodeFmt)
  {
    case NODEFMT_FQDN:         /* use FQDN (resolver) */
    case NODEFMT_NAME:         /* use the short name (hostname) */
      if (hent)
      {
        sprintf(lbuf, "%s", hent->h_name);
      }
      else
      {
        /* no result, use the passed name instead */
        sprintf(lbuf, "%s", name);
      }

      if (nodeFmt == NODEFMT_NAME)
      {
        /* strip the domain part */
        char           *p = strchr(lbuf, '.');

        if (p)
        {
          *p = '\0';
        }
      }
      break;
    case NODEFMT_IP:           /* use ip address */
    default:                   /* shouldn't happen */
      if (hent)
      {
        struct in_addr  in;

        memcpy(&in.s_addr, hent->h_addr, sizeof(in.s_addr));
        sprintf(lbuf, "%s", inet_ntoa(in));
      }
      else
      {
        sprintf(lbuf, "%s", name);
      }
      break;
  }

  /* insert the local buffer into the output buffer */
  l = strlen(lbuf);
  if (l <= *bRemP)
  {
    strncpy(*cPPtr, lbuf, l);
    (*cPPtr) += l;
    (*bRemP) -= l;
  }
  else
  {
    logging(0, "No more internal space left for '%s'", lbuf);
  }
}

/* ------------------------------------------------------------------------- */

/* print an oid according to the specified format into the output buffer 
 */
static void
lg_sprint_oid(char           *oidP,      /* the OID */
              int             oidFmt,    /* OIDFMT_TEXT/_OID */
              char          **cPPtr,     /* address of pointer to current outchar */
              int            *bRemP     /* address of counter of remaining chars */)
{
  char            lbuf[1024];   /* local buffer */
  int             l;

  logging(1, "lg_sprint_oid(%s, ...)", oidP);

  switch (oidFmt)
  {
    case OIDFMT_TEXT:          /* use textual format for the oid */
      sprintf(lbuf, "%s", oidP ? oidP : "(null)");
      break;
    case OIDFMT_OID:           /* usenumerical format for the oid */
    default:                   /* shouldn't happen */
      sprintf(lbuf, "%s", oidP ? oidP : "(null)");
      break;
  }

  /* insert the local buffer into the output buffer */
  l = strlen(lbuf);
  if (l <= *bRemP)
  {
    strncpy(*cPPtr, lbuf, l);
    (*cPPtr) += l;
    (*bRemP) -= l;
  }
  else
  {
    logging(0, "No more internal space left for '%s'", lbuf);
  }
}

/* ------------------------------------------------------------------------- */

/* print a string according to the specified format into the output buffer 
 */
static void
lg_sprint_string(char           *stringP,   /* the string */
                 char          **cPPtr,     /* address of pointer to current outchar */
                 int            *bRemP     /* address of counter of remaining chars */)
{
  int             l;

  logging(1, "lg_sprint_string(%s, ...)", stringP);

  /* insert the string into the output buffer */
  l = strlen(stringP);
  if (l <= *bRemP)
  {
    strncpy(*cPPtr, stringP, l);
    (*cPPtr) += l;
    (*bRemP) -= l;
  }
  else
  {
    logging(0, "No more internal space left for '%s'", stringP);
  }
}

/* ------------------------------------------------------------------------- */

/* print an integer according to the specified format into the output buffer
 */
static void
lg_sprint_int(int             ival,      /* the integer value */
              char           *iFmt,      /* the format string */
              char          **cPPtr,     /* address of pointer to current outchar */
              int            *bRemP     /* address of counter of remaining chars */)
{
  char            lbuf[20];     /* local buffer */
  int             l;

  logging(1, "lg_spring_int(%d, ...)", ival);

  /* fill the local buffer */
  sprintf(lbuf, iFmt, ival);

  /* insert the local buffer into the output buffer */
  l = strlen(lbuf);
  if (l <= *bRemP)
  {
    strncpy(*cPPtr, lbuf, l);
    (*cPPtr) += l;
    (*bRemP) -= l;
  }
  else
  {
    logging(0, "No more internal space left for '%s'", lbuf);
  }
}

/* ------------------------------------------------------------------------- */

/* print an u_long according to the specified format into the output buffer
 */
static void
lg_sprint_ulong(unsigned long   uval,      /* the integer value */
                char           *uFmt,      /* the format string */
                char          **cPPtr,     /* address of pointer to current outchar */
                int            *bRemP     /* address of counter of remaining chars */)
{
  char            lbuf[20];     /* local buffer */
  int             l;

  logging(1, "lg_sprint_ulong(%lu, ...)", uval);

  /* fill the local buffer */
  sprintf(lbuf, uFmt, uval);

  /* insert the local buffer into the output buffer */
  l = strlen(lbuf);
  if (l <= *bRemP)
  {
    strncpy(*cPPtr, lbuf, l);
    (*cPPtr) += l;
    (*bRemP) -= l;
  }
  else
  {
    logging(0, "No more internal space left for '%s'", lbuf);
  }
}

/* ------------------------------------------------------------------------- */

/* print an ASN.1 type ito the output buffer
 */
static void
lg_sprint_ASNtype(u_char          asntype,   /* ASN.1 type */
                  char          **cPPtr,     /* address of pointer to current outchar */
                  int            *bRemP     /* address of counter of remaining chars */)
{
  char           *p;
  int             l;

  logging(1, "lg_sprint_ASNtype(%c, ...)", asntype);

  switch (asntype)
  {
    case ASN_BOOLEAN:
      p = "Boolean";
      break;
    case ASN_INTEGER:
      p = "Integer";
      break;
    case ASN_BIT_STR:
      p = "BitString";
      break;
    case ASN_OCTET_STR:
      p = "OctetString";
      break;
    case ASN_NULL:
      p = "Null";
      break;
    case ASN_OBJECT_ID:
      p = "ObjectIdentifier";
      break;
    case ASN_OPAQUE:
      p = "Opaque";
      break;
    case ASN_TIMETICKS:
      p = "Timeticks";
      break;
    case ASN_GAUGE:
      p = "Gauge";
      break;
    case ASN_COUNTER:
      p = "Counter";
      break;
    case ASN_IPADDRESS:
      p = "IpAddress";
      break;
    case ASN_UINTEGER:
      p = "UnsignedInteger32";
      break;
    default:
      p = "BadType";
      break;
  }

  /* insert the local buffer into the output buffer */
  l = strlen(p);
  if (l <= *bRemP)
  {
    strncpy(*cPPtr, p, l);
    (*cPPtr) += l;
    (*bRemP) -= l;
  }
  else
  {
    logging(0, "No more internal space left for '%s'", p);
  }

  /* temporary close the string  */
  **cPPtr = '\0';
}

/* ------------------------------------------------------------------------- */

/* print a snmp variable according to the specified format into the 
 * output buffer
 */
static void
lg_sprint_var(t_var          *var,       /* the snmp variable */
              char           *vFmt,      /* the output format string */
              int             seqno,     /* current sequence number */
              char          **cPPtr,     /* address of pointer to current outchar */
              int            *bRemP     /* address of counter of remaining chars */ )
{
  char           *vPtr;         /* current varfmt character */

  logging(1, "lg_sprint_var(%s/%s, %s, %d, ...)",
      var->v_oid, var->v_val, vFmt, seqno);

  /* process the variable format */
  for (vPtr = vFmt; *vPtr; vPtr++)
  {
    switch (*vPtr)
    {
      case '\\':
        if (*bRemP > 0)
        {
          switch (*++vPtr)
          {
            case 'n':
              *(*cPPtr)++ = '\n';
              (*bRemP)--;
              break;
            case 'r':
              *(*cPPtr)++ = '\r';
              (*bRemP)--;
              break;
            case 't':
              *(*cPPtr)++ = '\t';
              (*bRemP)--;
              break;
            default:
              *(*cPPtr)++ = *vPtr;
              (*bRemP)--;
          }
        }
        break;
      case '%':                /* special char follows */
        switch (*++vPtr)
        {
          case 's':            /* the sequence number */
            lg_sprint_int(seqno, "%d", cPPtr, bRemP);
            break;
          case 'n':            /* the name */
            lg_sprint_oid(var->v_oid, cfg_oidfmt, cPPtr, bRemP);
            break;
          case 't':            /* the type */
            logging(1, "Type info not available - using ASN_OCTET_STR");
            lg_sprint_ASNtype(ASN_OCTET_STR, cPPtr, bRemP);
            break;
          case 'v':            /* the value */
            /* special handling for some (distinguishable) types */
            if (var->v_val[0] == '"')
            {
              /* we got a string: strip delims and substitute characters */
              int             l = strlen(var->v_val);
              char           *p;

              if ((l > 0) && (var->v_val[l - 1] == '"'))
              {
                var->v_val[l - 1] = '\0';
                l--;
              }

              if (l > 0)
              {
                for (p = var->v_val + 1; *p; p++)
                {
                  if (*p == cfg_subst1)
                  {
                    *p = cfg_subst2;
                  }
                }
              }

              lg_sprint_string(var->v_val + 1, cPPtr, bRemP);
            }
            else
            {
              /* Standard */
              lg_sprint_string(var->v_val, cPPtr, bRemP);
            }
            break;
          case '%':            /* insert '%' */
            if (*bRemP > 0)
            {
              *(*cPPtr)++ = '%';
              (*bRemP)--;
            }
            break;
          default:             /* insert the two chars verbatim */
            if (*bRemP > 1)
            {
              *(*cPPtr)++ = '%';
              *(*cPPtr)++ = *vPtr;
              (*bRemP) -= 2;
            }
            else
            {
              *bRemP = 0;
            }
            break;
        }
        break;
      default:                 /* insert char verbatim */
        if (*bRemP > 0)
        {
          *(*cPPtr)++ = *vPtr;
          (*bRemP)--;
        }
    }

    if (*bRemP <= 0)
    {
      logging(0, "No more internal space left for variable %d", seqno);
      *bRemP = 0;
      break;
    }
  }
}

/* ------------------------------------------------------------------------- */

/* Read the trap data from the pipe and store the data
 * - Returns 0 if ok, -1 if error
 */
static int
read_trapdata(FILE * f, t_trap * p_trap)
{
  char           *oid;
  char           *val;

  /* Read the constant header */
  if (read_oidval(f, &p_trap->s_agentname, NULL,
                  "Missing AGENTNAME from handler") == -1)
  {
    return -1;
  }
  logging(1, "Store: AGENTNAME := '%s'", p_trap->s_agentname);

  if (read_oidval(f, &p_trap->s_senderaddr, NULL,
                  "Missing SENDERIP from handler") == -1)
  {
    return -1;
  }
  logging(1, "Store: SENDERADDR := '%s'", p_trap->s_senderaddr);

  if (read_oidval(f, NULL, &p_trap->s_uptime,
                  "Missing UPTIME from handler") == -1)
  {
    return -1;
  }
  logging(1, "Store: UPTIME := '%s'", p_trap->s_uptime);

  if (read_oidval(f, NULL, &p_trap->s_trapoid,
                  "Missing TRAPOID from handler") == -1)
  {
    return -1;
  }
  logging(1, "Store: TRAPOID := '%s'", p_trap->s_trapoid);

  /* Now read all remaining OID/VAL pairs */
  while (read_oidval(f, &oid, &val, NULL) == 0)
  {
    if (oid[0] == '\0')
    {
      /* End of data from handler */
      logging(1, "End of handler data reached");
      free(oid);
      free(val);
      break;
    }
    else if ((strcmp(oid, OID_SYM_SNMPTRAPADDRESS) == 0) ||
             (strcmp(oid, OID_NUM_SNMPTRAPADDRESS) == 0))
    {
      free(oid);
      p_trap->s_agentaddr = val;
      logging(1, "Store: SNMPTRAPADDRESS := '%s'", p_trap->s_agentaddr);
    }
    else if ((strcmp(oid, OID_SYM_SNMPTRAPCOMMUNITY) == 0) ||
             (strcmp(oid, OID_NUM_SNMPTRAPCOMMUNITY) == 0))
    {
      free(oid);
      p_trap->s_community = val;
      logging(1, "Store: SNMPTRAPCOMMUNITY := '%s'", p_trap->s_community);
    }
    else if ((strcmp(oid, OID_SYM_SNMPTRAPENTERPRISE) == 0) ||
             (strcmp(oid, OID_NUM_SNMPTRAPENTERPRISE) == 0))
    {
      free(oid);
      p_trap->s_enterprise = val;
      logging(1, "Store: SNMPTRAPENTERPRISE := '%s'", p_trap->s_enterprise);
    }
    else
    {
      /* store as a variable */
      void           *p;

      p_trap->n_var++;
      p = realloc(p_trap->a_var, p_trap->n_var * sizeof(t_var));
      if (p == NULL)
      {
        logging(0, "Out of memory - aborting");
        exit(1);
      }
      p_trap->a_var = p;

      p_trap->a_var[p_trap->n_var - 1].v_oid = oid;
      p_trap->a_var[p_trap->n_var - 1].v_val = val;

      logging(1, "Store var %d: '%s' := '%s'", p_trap->n_var, oid, val);
    }
  }

  return 0;
}

/* ------------------------------------------------------------------------- */

/* Read the trap data from the handlers pipe and format the output buffer
 */
void
process_trapdata(FILE * f)
{
  char           *buf;
  t_trap          trapdata;


  /* Fetch the trap data  */
  memset(&trapdata, '\0', sizeof(trapdata));

  if (read_trapdata(f, &trapdata) == -1)
  {
    logging(0, "Error reading trap data - skip formatting");
    free_trap(&trapdata);

    return;
  }

  /* Format the trap data */
  buf = lg_format_buffer(&trapdata, time(NULL));

  /* And now log the data according to the configuration */
  if (!buf)
  {
    logging(0, "Error: Cannot allocate/format output buffer");
  }
  else if (o_logfile)
  {
    logging(1, "Logging to file '%s'", buf);

    fprintf(o_logfile, "%s\n", buf);
    fflush(o_logfile);
  }
  else
  {
    logging(1, "Logging to syslog 'LOG_WARNING:%s'", buf);

    syslog(LOG_WARNING, "%s\n", buf);
  }

  free_trap(&trapdata);
}

/* ------------------------------------------------------------------------- */

/* Read a OID/VAL pair from the pipe, allocate memory and store the pointers
 * (if specified). If an error occurs, emit msg (if any) and return -1, else
 * return 0.
 */
static int
read_oidval(FILE * f, char **pp_oid, char **pp_val, char *msg)
{
  char            rbuf[1024];

  if (fgets(rbuf, sizeof(rbuf), f) == NULL)
  {
    if (msg)
    {
      logging(0, msg);
    }

    return -1;
  }
  else
  {
    /* look for a delimiting blank */
    char           *p_del;
    int             l;

    /* strip the trailing EOL */
    l = strlen(rbuf);
    if ((l > 0) && (rbuf[l - 1] == '\n'))
    {
      rbuf[l - 1] = '\0';
    }

    logging(1, "Read from handler: '%s'", rbuf);

    /* split the line (if two components are on the line) */
    p_del = strchr(rbuf, ' ');
    if (p_del)
    {
      *p_del = '\0';
    }

    /* fetch and store the oid */
    if (pp_oid)
    {
      *pp_oid = copy_string(rbuf);
    }

    /* fetch and store the value */
    if (pp_val)
    {
      *pp_val = copy_string(p_del ? p_del + 1 : rbuf);
    }

    logging(1, " Split: OID = '%s', VAL = '%s'", rbuf,
        (p_del ? p_del + 1 : rbuf));
  }

  return 0;
}

/* ------------------------------------------------------------------------- */

/* Copy a string into allocated memory (but do not copy the trailing EOL)
 */
static char    *
copy_string(char *buf)
{
  char           *s;
  int             l = strlen(buf);

  if ((l > 0) && (buf[l - 1] == '\n'))
  {
    buf[--l] = '\0';
  }

  s = strdup(buf);
  if (s == NULL)
  {
    logging(0, "Out of memory - aborting");
    exit(1);
  }

  return s;
}

/* ------------------------------------------------------------------------- */

/* Free a trap data structure
 */
static void
free_trap(t_trap * p_trap)
{
  if (p_trap)
  {
    int             i;

    FREEMEM(p_trap->s_agentname);
    FREEMEM(p_trap->s_agentaddr);
    FREEMEM(p_trap->s_senderaddr);
    FREEMEM(p_trap->s_uptime);
    FREEMEM(p_trap->s_trapoid);
    FREEMEM(p_trap->s_community);
    FREEMEM(p_trap->s_enterprise);

    for (i = 0; i < p_trap->n_var; i++)
    {
      FREEMEM(p_trap->a_var[i].v_oid);
      FREEMEM(p_trap->a_var[i].v_val);
    }

    if (p_trap->n_var > 0)
    {
      FREEMEM(p_trap->a_var);
    }
  }
}

/* ------------------------------------------------------------------------- */

/* extract the Generid ID from the Trap OID by checking the second to last
 * component of the Trap OID
 */
static char    *
get_generic_id(char *trapoidP)
{
  char           *p_delim;
  char            trapoid[2048];
  static char     buf[80];


  /* Save the trap OID */
  strcpy(trapoid, trapoidP);

  /* look for the last period */
  p_delim = strrchr(trapoid, '.');
  if (p_delim)
  {
    char           *p_delim0;

    *p_delim = '\0';

    /* now look for the previous delim */
    p_delim0 = strrchr(trapoid, '.');
    if (p_delim0)
    {
      /* inspect the second to last component */
      if (strcmp(p_delim0 + 1, "0") == 0)
      {
        /* this is a specific trap, thus the GID is 6 */
        sprintf(buf, "%d", SNMP_TRAP_ENTERPRISESPECIFIC);
      }
      else
      {
        /* this is a generic trap, return the last component
         * (but decrement if numeric) 
         */
        if (isdigit(p_delim[1]))
        {
          int             gid;

          sscanf(p_delim + 1, "%d", &gid);
          sprintf(buf, "%d", gid - 1);
        }
        else
        {
          strcpy(buf, p_delim + 1);
        }
      }
    }
    else
    {
      /* only one delimiter in this trap OID, must be generic */
      if (isdigit(p_delim[1]))
      {
        int             gid;

        sscanf(p_delim + 1, "%d", &gid);
        sprintf(buf, "%d", gid - 1);
      }
      else
      {
        strcpy(buf, p_delim + 1);
      }
    }
  }
  else
  {
    /* no delimiter in this trap, must be generic */
    if (isdigit(trapoid[0]))
    {
      int             gid;

      sscanf(trapoid, "%d", &gid);
      sprintf(buf, "%d", gid - 1);
    }
    else
    {
      strcpy(buf, trapoid);
    }
  }

  return buf;

}

/* ------------------------------------------------------------------------- */

/* extract the Specific ID from the Trap OID 
 */
static char    *
get_specific_id(char *trapoidP)
{
  char           *p_delim;
  char            trapoid[2048];
  static char     buf[80];


  /* Save the trap OID */
  strcpy(trapoid, trapoidP);

  /* look for the last period */
  p_delim = strrchr(trapoid, '.');
  if (p_delim)
  {
    char           *p_delim0;

    *p_delim = '\0';

    /* now look for the previous delim */
    p_delim0 = strrchr(trapoid, '.');
    if (p_delim0)
    {
      /* inspect the second to last component */
      if (strcmp(p_delim0 + 1, "0") == 0)
      {
        /* this is a specific trap */
        strcpy(buf, p_delim + 1);
      }
      else
      {
        /* this is a generic trap */
        strcpy(buf, "0");
      }
    }
    else
    {
      /* only one delimiter in this trap OID, must be generic */
      strcpy(buf, "0");
    }
  }
  else
  {
    /* no delimiter in this trap, must be generic */
    strcpy(buf, "0");
  }

  return buf;
}

/* ------------------------------------------------------------------------- */