Windows: Use secure ctime and strncpy in afs_ctime
[openafs.git] / src / util / netutils.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11  * Network utility functions
12  * Parsing NetRestrict file and filtering IP addresses
13  */
14
15 #include <afsconfig.h>
16 #ifdef KERNEL
17 #include "afs/param.h"
18 #else
19 #include <afs/param.h>
20 #endif
21
22
23 #include <stdlib.h>
24 #include <stdio.h>
25 #include <string.h>
26 #include <ctype.h>
27 #ifdef KERNEL
28 #include "afs/sysincludes.h"
29 #include "afsincludes.h"
30 #else
31 #ifdef AFS_NT40_ENV
32 #include <winsock2.h>
33 #else 
34 #ifdef __FreeBSD__
35 #include <sys/types.h>
36 #endif
37 #include <netinet/in.h>
38 #include <sys/errno.h>
39 #endif
40 #include <errno.h>
41 #endif
42
43 #include <rx/rx.h>
44
45 #include "assert.h"
46 #include "afsutil.h"
47 #include "dirpath.h"
48
49 #define AFS_IPINVALID        0xffffffff /* invalid IP address */
50 #define AFS_IPINVALIDIGNORE  0xfffffffe /* no input given to extractAddr */
51 #define MAX_NETFILE_LINE       2048     /* length of a line in the netrestrict file */
52 #define MAXIPADDRS             1024     /* from afsd.c */
53
54 #ifndef INADDR_LOOPBACK
55 #define INADDR_LOOPBACK (afs_uint32)0x7f000001
56 #endif
57
58 int ParseNetInfoFile_int(afs_uint32 *, afs_uint32 *, afs_uint32 *,
59                          int, char reason[], const char *,
60                          int);
61 /* 
62  * The line parameter is a pointer to a buffer containing a string of 
63  * bytes of the form 
64 ** w.x.y.z      # machineName
65  * returns the network interface IP Address in NBO
66  */
67 afs_uint32
68 extract_Addr(char *line, int maxSize)
69 {
70     char bytes[4][32];
71     int i = 0, n = 0;
72     char *endPtr;
73     afs_uint32 val[4];
74     afs_uint32 retval = 0;
75
76     /* skip empty spaces */
77     while (isspace(*line) && maxSize) {
78         line++;
79         maxSize--;
80     }
81     /* skip empty lines */
82     if (!maxSize || !*line)
83         return AFS_IPINVALIDIGNORE;
84
85     for (n = 0; n < 4; n++) {
86         while ((*line != '.') && !isspace(*line) && maxSize) {  /* extract nth byte */
87             if (!isdigit(*line))
88                 return AFS_IPINVALID;
89             if (i > 31)
90                 return AFS_IPINVALID;   /* no space */
91             bytes[n][i++] = *line++;
92             maxSize--;
93         }                       /* while */
94         if (!maxSize)
95             return AFS_IPINVALID;
96         bytes[n][i] = 0;
97         i = 0, line++;
98         errno = 0;
99         val[n] = strtol(bytes[n], &endPtr, 10);
100         if ((val[n] == 0) && (errno != 0 || bytes[n] == endPtr))        /* no conversion */
101             return AFS_IPINVALID;
102     }                           /* for */
103
104     retval = (val[0] << 24) | (val[1] << 16) | (val[2] << 8) | val[3];
105     return htonl(retval);
106 }
107
108
109
110
111 /* parseNetRestrictFile()
112  * Get a list of IP addresses for this host removing any address found
113  * in the config file (fileName parameter): /usr/vice/etc/NetRestrict
114  * for clients and /usr/afs/local/NetRestrict for servers.  
115  *
116  * Returns the number of valid addresses in outAddrs[] and count in
117  * nAddrs.  Returns 0 on success; or 1 if the config file was not
118  * there or empty (we still return the host's IP addresses). Returns
119  * -1 on fatal failure with reason in the reason argument (so the
120  * caller can choose to ignore the entire file but should write
121  * something to a log file).
122  *
123  * All addresses should be in NBO (as returned by rx_getAllAddrMaskMtu() and
124  * parsed by extract_Addr().
125  */
126 /*
127   afs_uint32  outAddrs[];          * output address array *
128   afs_uint32  *mask, *mtu;         * optional mask and mtu *
129   afs_uint32 maxAddrs;             * max number of addresses *
130   afs_uint32 *nAddrs;              * number of Addresses in output array *
131   char       reason[];             * reason for failure *
132   const char *fileName;            * filename to parse *
133 */
134
135 int
136 parseNetRestrictFile_int(afs_uint32 outAddrs[], afs_uint32 * mask,
137                          afs_uint32 * mtu, afs_uint32 maxAddrs,
138                          afs_uint32 * nAddrs, char reason[], 
139                          const char *fileName, const char *fileName_ni)
140 {
141     FILE *fp;
142     char line[MAX_NETFILE_LINE];
143     int lineNo, usedfile = 0;
144     afs_uint32 i, neaddrs, nOutaddrs;
145     afs_uint32 addr, eAddrs[MAXIPADDRS], eMask[MAXIPADDRS], eMtu[MAXIPADDRS];
146
147     assert(outAddrs);
148     assert(reason);
149     assert(fileName);
150     assert(nAddrs);
151     if (mask)
152         assert(mtu);
153
154     /* Initialize */
155     *nAddrs = 0;
156     for (i = 0; i < maxAddrs; i++)
157         outAddrs[i] = 0;
158     strcpy(reason, "");
159
160     /* get all network interfaces from the kernel */
161     neaddrs = rx_getAllAddrMaskMtu(eAddrs, eMask, eMtu, MAXIPADDRS);
162     if (neaddrs <= 0) {
163         sprintf(reason, "No existing IP interfaces found");
164         return -1;
165     }
166     i = 0;
167     if ((neaddrs < MAXIPADDRS) && fileName_ni) 
168         i = ParseNetInfoFile_int(&(eAddrs[neaddrs]), &(eMask[neaddrs]), 
169                                  &(eMtu[neaddrs]), MAXIPADDRS-neaddrs, reason,
170                                  fileName_ni, 1);
171
172     if (i > 0)
173         neaddrs += i;
174
175     if ((fp = fopen(fileName, "r")) == 0) {
176         sprintf(reason, "Could not open file %s for reading:%s", fileName,
177                 strerror(errno));
178         goto done;
179     }
180
181     /* For each line in the NetRestrict file */
182     lineNo = 0;
183     usedfile = 0;
184     while (fgets(line, MAX_NETFILE_LINE, fp) != NULL) {
185         lineNo++;               /* input line number */
186         addr = extract_Addr(line, strlen(line));
187         if (addr == AFS_IPINVALID) {    /* syntactically invalid */
188             fprintf(stderr, "%s : line %d : parse error - invalid IP\n",
189                     fileName, lineNo);
190             continue;
191         }
192         if (addr == AFS_IPINVALIDIGNORE) {      /* ignore error */
193             fprintf(stderr, "%s : line %d : invalid address ... ignoring\n",
194                     fileName, lineNo);
195             continue;
196         }
197         usedfile = 1;
198
199         /* Check if we need to exclude this address */
200         for (i = 0; i < neaddrs; i++) {
201             if (eAddrs[i] && (eAddrs[i] == addr)) {
202                 eAddrs[i] = 0;  /* Yes - exclude it by zeroing it for now */
203             }
204         }
205     }                           /* while */
206
207     fclose(fp);
208
209     if (!usedfile) {
210         sprintf(reason, "No valid IP addresses in %s\n", fileName);
211         goto done;
212     }
213
214   done:
215     /* Collect the addresses we have left to return */
216     nOutaddrs = 0;
217     for (i = 0; i < neaddrs; i++) {
218         if (!eAddrs[i])
219             continue;
220         outAddrs[nOutaddrs] = eAddrs[i];
221         if (mask) {
222             mask[nOutaddrs] = eMask[i];
223             mtu[nOutaddrs] = eMtu[i];
224         }
225         if (++nOutaddrs >= maxAddrs)
226             break;
227     }
228     if (nOutaddrs == 0) {
229         sprintf(reason, "No addresses to use after parsing %s", fileName);
230         return -1;
231     }
232     *nAddrs = nOutaddrs;
233     return (usedfile ? 0 : 1);  /* 0=>used the file.  1=>didn't use file */
234 }
235
236 int
237 parseNetRestrictFile(afs_uint32 outAddrs[], afs_uint32 * mask,
238                          afs_uint32 * mtu, afs_uint32 maxAddrs,
239                          afs_uint32 * nAddrs, char reason[], 
240                          const char *fileName)
241 {
242     return parseNetRestrictFile_int(outAddrs, mask, mtu, maxAddrs, nAddrs, reason, fileName, NULL);
243 }
244
245 /*
246  * this function reads in stuff from InterfaceAddr file in
247  * /usr/vice/etc ( if it exists ) and verifies the addresses
248  * specified. 
249  * 'final' contains all those addresses that are found to 
250  * be valid. This function returns the number of valid
251  * interface addresses. Pulled out from afsd.c
252  */
253 int
254 ParseNetInfoFile_int(afs_uint32 * final, afs_uint32 * mask, afs_uint32 * mtu,
255                      int max, char reason[], const char *fileName, 
256                      int fakeonly)
257 {
258
259     afs_uint32 existingAddr[MAXIPADDRS], existingMask[MAXIPADDRS],
260         existingMtu[MAXIPADDRS];
261     char line[MAX_NETFILE_LINE];
262     FILE *fp;
263     int i, existNu, count = 0;
264     afs_uint32 addr;
265     int lineNo = 0;
266     int l;
267
268     assert(fileName);
269     assert(final);
270     assert(mask);
271     assert(mtu);
272     assert(reason);
273
274     /* get all network interfaces from the kernel */
275     existNu =
276         rx_getAllAddrMaskMtu(existingAddr, existingMask, existingMtu,
277                               MAXIPADDRS);
278     if (existNu < 0)
279         return existNu;
280
281     if ((fp = fopen(fileName, "r")) == 0) {
282         /* If file does not exist or is not readable, then
283          * use all interface addresses.
284          */
285         sprintf(reason,
286                 "Failed to open %s(%s)\nUsing all configured addresses\n",
287                 fileName, strerror(errno));
288         for (i = 0; i < existNu; i++) {
289             final[i] = existingAddr[i];
290             mask[i] = existingMask[i];
291             mtu[i] = existingMtu[i];
292         }
293         return existNu;
294     }
295
296     /* For each line in the NetInfo file */
297     while (fgets(line, MAX_NETFILE_LINE, fp) != NULL) {
298         int fake = 0;
299
300         /* See if first char is an 'F' for fake */
301         /* Added to allow the fileserver to advertise fake IPS for use with
302          * the translation tables for NAT-like firewalls - defect 12462 */
303         for (fake = 0; ((fake < strlen(line)) && isspace(line[fake]));
304              fake++);
305         if ((fake < strlen(line))
306             && ((line[fake] == 'f') || (line[fake] == 'F'))) {
307             fake++;
308         } else {
309             fake = 0;
310         }
311
312         lineNo++;               /* input line number */
313         addr = extract_Addr(&line[fake], strlen(&line[fake]));
314
315         if (addr == AFS_IPINVALID) {    /* syntactically invalid */
316             fprintf(stderr, "afs:%s : line %d : parse error\n", fileName,
317                     lineNo);
318             continue;
319         }
320         if (addr == AFS_IPINVALIDIGNORE) {      /* ignore error */
321             continue;
322         }
323
324         /* See if it is an address that really exists */
325         for (i = 0; i < existNu; i++) {
326             if (existingAddr[i] == addr)
327                 break;
328         }
329         if ((i >= existNu) && (!fake))
330             continue;           /* not found/fake - ignore */
331
332         /* Check if it is a duplicate address we alread have */
333         for (l = 0; l < count; l++) {
334             if (final[l] == addr)
335                 break;
336         }
337         if (l < count) {
338             fprintf(stderr, "afs:%x specified twice in NetInfo file\n",
339                     ntohl(addr));
340             continue;           /* duplicate addr - ignore */
341         }
342
343         if (count > max) {      /* no more space */
344             fprintf(stderr,
345                     "afs:Too many interfaces. The current kernel configuration supports a maximum of %d interfaces\n",
346                     max);
347         } else if (fake) {
348             if (!fake) 
349                 fprintf(stderr, "Client (2) also has address %s\n", line);
350             final[count] = addr;
351             mask[count] = 0xffffffff;
352             mtu[count] = htonl(1500);
353             count++;
354         } else if (!fakeonly) {
355             final[count] = existingAddr[i];
356             mask[count] = existingMask[i];
357             mtu[count] = existingMtu[i];
358             count++;
359         }
360     }                           /* while */
361
362     /* in case of any error, we use all the interfaces present */
363     if (count <= 0) {
364         sprintf(reason,
365                 "Error in reading/parsing Interface file\nUsing all configured interface addresses \n");
366         for (i = 0; i < existNu; i++) {
367             final[i] = existingAddr[i];
368             mask[i] = existingMask[i];
369             mtu[i] = existingMtu[i];
370         }
371         return existNu;
372     }
373     return count;
374 }
375
376 int
377 ParseNetInfoFile(afs_uint32 * final, afs_uint32 * mask, afs_uint32 * mtu,
378                  int max, char reason[], const char *fileName)
379 {
380     return ParseNetInfoFile_int(final, mask, mtu, max, reason, fileName, 0);
381 }
382
383 /*
384  * Given two arrays of addresses, masks and mtus find the common ones
385  * and return them in the first buffer. Return number of common
386  * entries.
387  */
388 int
389 filterAddrs(afs_uint32 addr1[], afs_uint32 addr2[], afs_uint32 mask1[],
390             afs_uint32 mask2[], afs_uint32 mtu1[], afs_uint32 mtu2[], int n1,
391             int n2)
392 {
393     afs_uint32 taddr[MAXIPADDRS];
394     afs_uint32 tmask[MAXIPADDRS];
395     afs_uint32 tmtu[MAXIPADDRS];
396     int count = 0, i = 0, j = 0, found = 0;
397
398     assert(addr1);
399     assert(addr2);
400     assert(mask1);
401     assert(mask2);
402     assert(mtu1);
403     assert(mtu2);
404
405     for (i = 0; i < n1; i++) {
406         found = 0;
407         for (j = 0; j < n2; j++) {
408             if (addr1[i] == addr2[j]) {
409                 found = 1;
410                 break;
411             }
412         }
413
414         /* Always mask loopback address */
415         if (found && addr1[i] == INADDR_LOOPBACK) 
416             found = 0;
417
418         if (found) {
419             taddr[count] = addr1[i];
420             tmask[count] = mask1[i];
421             tmtu[count] = mtu1[i];
422             count++;
423         }
424     }
425     /* copy everything into addr1, mask1 and mtu1 */
426     for (i = 0; i < count; i++) {
427         addr1[i] = taddr[i];
428         if (mask1) {
429             mask1[i] = tmask[i];
430             mtu1[i] = tmtu[i];
431         }
432     }
433     /* and zero out the rest */
434     for (i = count; i < n1; i++) {
435         addr1[i] = 0;
436         if (mask1) {
437             mask1[i] = 0;
438             mtu1[i] = 0;
439         }
440     }
441     return count;
442 }
443
444 /*
445  * parse both netinfo and netrerstrict files and return the final
446  * set of IP addresses to use
447  */
448 /* max - Entries in addrbuf, maskbuf and mtubuf */
449 int
450 parseNetFiles(afs_uint32 addrbuf[], afs_uint32 maskbuf[], afs_uint32 mtubuf[],
451               afs_uint32 max, char reason[], const char *niFileName,
452               const char *nrFileName)
453 {
454     afs_uint32 addrbuf1[MAXIPADDRS], maskbuf1[MAXIPADDRS],
455         mtubuf1[MAXIPADDRS];
456     afs_uint32 addrbuf2[MAXIPADDRS], maskbuf2[MAXIPADDRS],
457         mtubuf2[MAXIPADDRS];
458     int nAddrs1 = 0;
459     afs_uint32 nAddrs2 = 0;
460     int code, i;
461
462     nAddrs1 =
463         ParseNetInfoFile(addrbuf1, maskbuf1, mtubuf1, MAXIPADDRS, reason,
464                          niFileName);
465     code =
466         parseNetRestrictFile_int(addrbuf2, maskbuf2, mtubuf2, MAXIPADDRS,
467                              &nAddrs2, reason, nrFileName, niFileName);
468     if ((nAddrs1 < 0) && (code)) {
469         /* both failed */
470         return -1;
471     } else if ((nAddrs1 > 0) && (code)) {
472         /* netinfo succeeded and netrestrict failed */
473         for (i = 0; ((i < nAddrs1) && (i < max)); i++) {
474             addrbuf[i] = addrbuf1[i];
475             if (maskbuf) {
476                 maskbuf[i] = maskbuf1[i];
477                 mtubuf[i] = mtubuf1[i];
478             }
479         }
480         return i;
481     } else if ((!code) && (nAddrs1 < 0)) {
482         /* netrestrict succeeded and netinfo failed */
483         for (i = 0; ((i < nAddrs2) && (i < max)); i++) {
484             addrbuf[i] = addrbuf2[i];
485             if (maskbuf) {
486                 maskbuf[i] = maskbuf2[i];
487                 mtubuf[i] = mtubuf2[i];
488             }
489         }
490         return i;
491     } else if ((!code) && (nAddrs1 >= 0)) {
492         /* both succeeded */
493         /* take the intersection of addrbuf1 and addrbuf2 */
494         code =
495             filterAddrs(addrbuf1, addrbuf2, maskbuf1, maskbuf2, mtubuf1,
496                         mtubuf2, nAddrs1, nAddrs2);
497         for (i = 0; ((i < code) && (i < max)); i++) {
498             addrbuf[i] = addrbuf1[i];
499             if (maskbuf) {
500                 maskbuf[i] = maskbuf1[i];
501                 mtubuf[i] = mtubuf1[i];
502             }
503         }
504         return i;
505     }
506     return 0;
507 }