nmsg  0.9.0
chalias.c
1 /*
2  * Copyright (c) 2009, 2012 by Farsight Security, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 /* Import. */
18 
19 #include "private.h"
20 
21 /* Macros. */
22 
23 #define CHALIAS_FILE NMSG_ETCDIR "/nmsg.chalias"
24 #define CHALIAS_FILE2 NMSG_ETCDIR "/nmsgtool.chalias"
25 
26 #define MAX_LINE_SZ 1024
27 
28 /* Functions. */
29 
30 int
31 nmsg_chalias_lookup(const char *ch, char ***alias) {
32  FILE *fp;
33  char line[1024];
34  char *saveptr, *tmp;
35  int num_aliases;
36 
37  *alias = NULL;
38  num_aliases = 0;
39 
40  fp = fopen(CHALIAS_FILE, "r");
41  if (fp == NULL) {
42  fp = fopen(CHALIAS_FILE2, "r");
43  if (fp == NULL)
44  return (-1);
45  }
46 
47  while (fgets(line, sizeof(line), fp) != NULL) {
48  tmp = strtok_r(line, " \t", &saveptr);
49  if (tmp != NULL && strcmp(tmp, ch) == 0) {
50  while ((tmp = strtok_r(NULL, " \t\n", &saveptr))
51  != NULL)
52  {
53  num_aliases += 1;
54  *alias = realloc(*alias,
55  sizeof(*alias) * num_aliases);
56  (*alias)[num_aliases - 1] = strdup(tmp);
57  }
58  }
59  }
60 
61  fclose(fp);
62 
63  /* append NULL sentinel */
64  *alias = realloc(*alias, sizeof(*alias) * (num_aliases + 1));
65  (*alias)[num_aliases] = NULL;
66 
67  return (num_aliases);
68 }
69 
70 void
71 nmsg_chalias_free(char ***alias) {
72  for (char **a = *alias; *a != NULL; a++)
73  free(*a);
74  free(*alias);
75  *alias = NULL;
76 }
void nmsg_chalias_free(char ***alias)
Free the memory allocated by nmsg_chalias_lookup().
Definition: chalias.c:71
int nmsg_chalias_lookup(const char *ch, char ***alias)
Lookup a channel alias.
Definition: chalias.c:31