-
Notifications
You must be signed in to change notification settings - Fork 1
/
Configuration.C
745 lines (637 loc) · 18.5 KB
/
Configuration.C
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
//
// Configuration.C -- News configuration class
//
// Copyright 2003-2004 Michael Sweet
// Copyright 2002 Greg Ercolano
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public Licensse as published by
// the Free Software Foundation; either version 2 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 for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "everything.H"
#include <stdarg.h>
#include <syslog.h>
#include "limits.h"
// Initialize default configuration values...
Configuration::Configuration()
{
char name[1024]; // Hostname string
// Set defaults...
HostnameLookups(0);
Listen(119);
log = stderr;
errorlog = "stderr";
log_ino = 0;
LogLevel(L_INFO);
MaxClients(0);
MaxLogSize("1m");
gethostname(name, sizeof(name));
ServerName(name);
SendMail(SENDMAIL " -t");
SpamFilter("");
SpoolDir(SPOOL_DIR);
Timeout(12 * 3600);
User("news");
}
// Listen on a specific address and port...
void Configuration::Listen(const char *l)
{
char hostname[256]; // Hostname or IP
char portname[256]; // Port number or name
char *ptr; // Pointer into port
struct hostent *host; // Host address
struct servent *port; // Service data
long p; // Port number
// Initialize the listen address to "nntp"...
listen.sin_family = AF_INET;
listen.sin_addr.s_addr = INADDR_ANY;
listen.sin_port = htons(119);
// Try to grab a hostname and port number...
switch (sscanf(l, "%255[^:]:%255s", hostname, portname))
{
case 1 :
/*
* Hostname is a port number...
*/
strcpy(portname, hostname);
strcpy(hostname, "*");
break;
case 2 :
break;
default :
fprintf(stderr, "news: Unable to decode address \"%s\"!\n", l);
return;
}
/*
* Decode the hostname and port number as needed...
*/
if (hostname[0] && strcmp(hostname, "*"))
{
if ((host = gethostbyname(hostname)) == NULL)
{
fprintf(stderr, "newsd: gethostbyname(\"%s\") failed - %s!\n",
hostname, hstrerror(h_errno));
fputs("newsd: Using address 127.0.0.1 (localhost)\n", stderr);
}
else if (host->h_length != 4 || host->h_addrtype != AF_INET)
{
fprintf(stderr, "newsd: gethostbyname(\"%s\") did not return an IPv4 address!\n",
hostname);
fputs("newsd: Using address 127.0.0.1 (localhost)\n", stderr);
}
else
memcpy(&(listen.sin_addr), host->h_addr, 4);
}
else if (!strcmp(hostname, "*"))
listen.sin_addr.s_addr = INADDR_ANY;
if (portname[0] != '\0')
{
if (isdigit(portname[0]))
{
p = strtol(portname, &ptr, 10);
if (p <= 0 || *ptr)
{
fprintf(stderr, "newsd: Bad port number \"%s\"!\n", portname);
fputs("newsd: Using port 119 (nntp)\n", stderr);
}
else
listen.sin_port = htons(p);
}
else
{
if ((port = getservbyname(portname, "tcp")) == NULL)
{
fprintf(stderr, "newsd: getservbyname(\"%s\", \"tcp\") failed!\n",
portname);
fputs("newsd: Using port 119 (nntp)\n", stderr);
}
else
listen.sin_port = port->s_port;
}
}
}
// Listen on a port...
void Configuration::Listen(int p)
{
// Listen on the "any" address with the specified port; needs to be
// updated for IPv6 at some point...
listen.sin_family = AF_INET;
listen.sin_addr.s_addr = INADDR_ANY;
listen.sin_port = htons(p);
}
// Load configuration values from a file...
void Configuration::Load(const char *conffile)
{
FILE *fp; // Config file
int linenum; // Line number
char line[1024], // Line from config file
*ptr, // Pointer into line
*name, // Config directive
*value; // Config value
long lvalue; // Integer value
if ((fp = fopen(conffile, "r")) == NULL)
{
fprintf(stderr, "newsd: Unable to open configuration file \"%s\" - %s!\n",
conffile, strerror(errno));
return;
}
linenum = 0;
while (fgets(line, sizeof(line), fp))
{
// Increment line counter...
linenum ++;
// Strip comments...
if ((ptr = strchr(line, '#')) != NULL)
*ptr = '\0';
// Strip trailing whitespace...
for (ptr = line + strlen(line) - 1; ptr >= line && isspace(*ptr); ptr --)
*ptr = '\0';
// Ignore blank lines...
if (!line[0])
continue;
// Find directive name...
for (name = line; isspace(*name); name ++);
// Separate directive from value...
for (value = name + 1; !isspace(*value) && *value; value ++);
while (isspace(*value))
*value++ = '\0';
if (!*value)
{
fprintf(stderr, "newsd: Missing value on line %d of \"%s\"!\n", linenum,
conffile);
continue;
}
// Decode configuration directive...
if (!strcasecmp(name, "HostnameLookups"))
{
if (!strcasecmp(value, "off") || !strcasecmp(value, "no"))
{
HostnameLookups(0);
}
else if (!strcasecmp(value, "on") || !strcasecmp(value, "yes"))
{
HostnameLookups(1);
}
else if (!strcasecmp(value, "double"))
{
HostnameLookups(2);
}
else
fprintf(stderr, "newsd: Bad HostnameLookups value \"%s\" on line %d of \"%s\"!\n",
value, linenum, conffile);
}
else if (!strcasecmp(name, "Listen"))
{
Listen(value);
}
else if (!strcasecmp(name, "LogFile"))
{
fprintf(stderr, "newsd: LogFile directive on line %d of "
"\"%s\" is deprecated; use ErrorLog instead!\n",
linenum, conffile);
ErrorLog(value);
}
else if (!strcasecmp(name, "ErrorLog"))
{
ErrorLog(value);
}
else if (!strcasecmp(name, "LogLevel"))
{
if (!strcasecmp(value, "error"))
LogLevel(L_ERROR);
else if (!strcasecmp(value, "info"))
LogLevel(L_INFO);
else if (!strcasecmp(value, "debug"))
LogLevel(L_DEBUG);
else
fprintf(stderr, "newsd: Bad LogLevel value \"%s\" on line %d of \"%s\"!\n",
value, linenum, conffile);
}
else if (!strcasecmp(name, "MaxClients"))
{
lvalue = strtol(value, &ptr, 10);
if (lvalue < 0 || *ptr)
fprintf(stderr, "newsd: Bad MaxClients value \"%s\" on line %d of \"%s\"!\n",
value, linenum, conffile);
else
MaxClients(lvalue);
}
else if (!strcasecmp(name, "MaxLogSize"))
{
if (value[0])
MaxLogSize(value);
else
fprintf(stderr, "newsd: MaxLogSize requires a value on line %d of \"%s\"!\n",
linenum, conffile);
}
else if (!strcasecmp(name, "NewsHostname"))
{
fprintf(stderr, "newsd: NewsHostname directive on line %d of "
"\"%s\" is deprecated; use ServerName instead!\n",
linenum, conffile);
ServerName(value);
}
else if (!strcasecmp(name, "ServerName"))
{
ServerName(value);
}
else if (!strcasecmp(name, "SendMail"))
{
SendMail(value);
}
else if (!strcasecmp(name, "SpamFilter"))
{
SpamFilter(value);
}
else if (!strcasecmp(name, "SpoolDir"))
{
SpoolDir(value);
}
else if (!strcasecmp(name, "Timeout"))
{
lvalue = strtol(value, &ptr, 10);
if (lvalue < 0 || *ptr)
fprintf(stderr, "newsd: Bad Timeout value \"%s\" on line %d of \"%s\"!\n",
value, linenum, conffile);
else
Timeout(lvalue);
}
else if (!strcasecmp(name, "User"))
{
User(value);
if (bad_user)
fprintf(stderr, "newsd: Bad User value \"%s\" on line %d of \"%s\"!\n",
value, linenum, conffile);
}
else
{
fprintf(stderr, "newsd: Unknown config file directive \"%s\" on line %d of \"%s\"!\n",
line, linenum, conffile);
}
}
// Close the config file and return...
fclose(fp);
}
// CREATE THE NEWS LOG DIRECTORY IF IT DOESNT EXIST
// Help zero admin for users using 'all defaults'.
// (If they change any of the defaults, then assume they know what they're doing)
// No return; all of this is optional.
// Assumes config file has already been loaded.
//
void Configuration::FixNewsLogDir(const char* newslogdir)
{
int statok = 1;
int domkdir = 0;
struct stat logdir_stat;
// Does log dir exist?
if ( stat(newslogdir, &logdir_stat) == 0 )
{
// Stat ok, is the newslogdir a file instead of a directory?
if ( ! S_ISDIR(logdir_stat.st_mode) )
{
// Rename away old news file, then create dir
// Rename /var/log/news -> /var/log/news.old
//
string oldfile;
oldfile = newslogdir;
oldfile += ".old";
if ( rename(newslogdir, oldfile.c_str()) < 0 )
{
fprintf(stderr, "newsd: Can't rename away old news file to make news log dir:\n"
"newsd: rename(%s,%s): %s\n",
newslogdir, oldfile.c_str(), strerror(errno));
}
domkdir = 1;
}
}
else
// Stat failed? Dir does not exist
{ domkdir = 1; }
// Need to create directory?
if ( domkdir )
{
// Logdir does not exist? Create it
if ( mkdir(newslogdir, 0755) )
{ fprintf(stderr, "newsd: mkdir(%s): %s\n", newslogdir, strerror(errno)); }
// Redo stat to get perms etc.
if ( stat(newslogdir, &logdir_stat) < 0 )
{ statok = 0; fprintf(stderr, "newsd: stat(%s): %s\n", newslogdir, strerror(errno)); }
}
// Now check perms on newslogdir
if ( statok )
{
// Dir owned by "news" user?
if ( UID() != logdir_stat.st_uid || GID() != logdir_stat.st_gid )
{
// No? change it
if ( chown(newslogdir, UID(), GID()) < 0 )
{
fprintf(stderr, "newsd: Can't change perms on log directory: "
"chown(%s,%lu,&lu): %s\n",
newslogdir, UID(), GID(), strerror(errno));
}
}
}
}
// INITIALIZE LOGGING
void Configuration::InitLog()
{
if (log)
{
if (log != stderr)
fclose(log);
log = 0;
}
if (errorlog == "syslog")
openlog("newsd", LOG_PID, LOG_NEWS);
else if (errorlog == "stderr")
log = stderr;
else if (errorlog.c_str()[0] == '|')
{
log = popen(errorlog.c_str() + 1, "w");
if (!log)
{
fprintf(stderr, "newsd: Unable to open log pipe to \"%s\" - %s.\n",
errorlog.c_str() + 1, strerror(errno));
log = stderr;
}
}
else
OpenLogAppend();
}
// OPEN LOG FILE FOR APPENDING
// o Closing existing log if open, new one is opened.
// o Any LogLock()s are automatically unlocked.
// o Log will be *UNLOCKED* on return.
// o This function does *nothing* if errorlog == "stderr" or "syslog"
//
// Returns -1 on error, error msgs are printed to stderr
//
int Configuration::OpenLogAppend()
{
// Non-logfile? skip
if ( errorlog == "stderr" || errorlog == "syslog" ||
errorlog.c_str()[0] == '|' )
return(0);
// Close log (if open)
if ( log )
{
if (log != stderr)
fclose(log); // (also clears Lock()s, if any)
log = 0;
}
// Open log for append, do NOT apply locks
log = fopen(errorlog.c_str(), "a");
if ( !log )
{
fprintf(stderr, "newsd: Unable to open log file \"%s\": %s.\n",
errorlog.c_str(), strerror(errno));
log = stderr;
return(-1);
}
setbuf(log, NULL);
// Save inode# for log rotation checks
{
struct stat buf;
log_ino = ( fstat(fileno(log), &buf) == 0 ) ? buf.st_ino : 0;
}
// This will fail when running as non-root, so don't bother checking
// the status here...
fchmod(fileno(log), 0600);
fchown(fileno(log), uid, gid);
return(0);
}
// LOCK THE LOG FILE FOR WRITING/ROTATING
// Returns -1 on error, error msg sent to stderr
//
int Configuration::LogLock()
{
if ( !log_ino ) return(0);
if ( flock(fileno(log), LOCK_EX) < 0 )
{
fprintf(stderr, "newsd: LogLock(): flock(LOCK_EX): %s", strerror(errno));
return(-1);
}
return(0);
}
// UNLOCK THE LOG FILE
// Returns -1 on error, error msg sent to stderr
//
int Configuration::LogUnlock()
{
if ( !log_ino ) return(0);
if ( flock(fileno(log), LOCK_UN) < 0 )
{
fprintf(stderr, "newsd: LogUnlock(): flock(LOCK_UN): %s", strerror(errno));
return(-1);
}
return(0);
}
// RETURN PATHNAME OF 'OLD' LOGFILE
string Configuration::OldLogFilename()
{
// Append .O
return(errorlog + ".O");
}
// PRINT MESSAGE TO LOG WITH DATE STAMP
// Appends crlf if none specified.
//
void Configuration::DateStampedMessage(FILE *fp, const char *msg)
{
time_t secs; // Current UNIX time
struct tm *date; // Current date/time
char datestr[1024]; // Date/time string
time(&secs);
date = localtime(&secs);
strftime(datestr, sizeof(datestr), "%c", date);
fprintf(fp, "%s newsd[%d]: %s%s",
datestr, getpid(), msg, ( msg[strlen(msg)-1] != '\n' ) ? "\n" : "");
fflush(fp);
}
// HANDLE LOG ROTATION
// Assumes Lock() already applied.
// On return, Lock() will be applied to new log.
//
// force:
// true = force log to be rotated (regardless of size)
// false = rotate only if logsize > maxlogsize
//
// Returns:
// 0 - no error, log not rotated
// 1 - no error, log rotated
// -1 - error occurred, error msg printed to log or stderr
//
int Configuration::Rotate(bool force)
{
// Don't rotate if we aren't logging to file...
if ( !log_ino ) return (0);
// Check size of log
if ( ! force && maxlogsize > 0)
{
struct stat buf;
if ( stat(errorlog.c_str(), &buf) < 0 )
{
string msg = "Log file size check failed: stat(" + errorlog + "): " + strerror(errno);
DateStampedMessage(log, msg.c_str());
return(-1);
}
// fprintf(stderr, "LOG SIZE CHECK: %lu <= %lu\n", (unsigned long)buf.st_size, (unsigned long)maxlogsize); // DEBUG
// Log too small? ignore
if ( buf.st_size <= maxlogsize )
{ return(0); }
}
// Rotate log (lock will follow renamed log)
string oerrorlog = OldLogFilename();
if ( rename(errorlog.c_str(), oerrorlog.c_str()) < 0 )
{
string msg = "Log file rotation failed: rename(" +
errorlog + "," + oerrorlog + "): " + strerror(errno);
// Include uid/euid info, incase error is permission related
{
char junk[256];
sprintf(junk, " (uid=%lu euid=%lu)", getuid(), geteuid());
msg += junk;
}
DateStampedMessage(log, msg.c_str());
return(-1);
}
// Indicate log rotated in old log
// Log file is still locked, even though renamed
//
DateStampedMessage(log, "*** Log file rotated. ***");
// Create new log
// This will close log (removing any locks)
//
if ( OpenLogAppend() < 0 )
return(-1);
// Leave with log locked
// Another process might sneak some msgs in before us.
//
LogLock();
// Indicate log rotated in new log
DateStampedMessage(log, "*** Log was rotated. ***");
return(0);
}
// WAS LOG RECENTLY ROTATED?
// Returns true if so, false if not.
// Checks to see if inode number changed.
//
bool Configuration::WasLogRotated()
{
if ( !log_ino ) return(false);
struct stat buf;
if ( stat(errorlog.c_str(), &buf) < 0 )
{
fprintf(stderr, "newsd: stat(%s): %s\n", errorlog.c_str(), strerror(errno));
return(false);
}
return(buf.st_ino != log_ino);
}
// Log a message...
void Configuration::LogMessage(int l, const char *m, ...)
{
// Only log messages as needed...
if (l > loglevel)
return;
// Format the message...
va_list ap; // Argument list pointer
char buffer[1024]; // Message buffer
unsigned int bytes; // Size of message
va_start(ap, m);
bytes = vsnprintf(buffer, sizeof(buffer), m, ap);
va_end(ap);
// Send it to the log file or syslog...
if (log)
{
LogLock();
{
// Was log recently rotated? Reopen to write to correct log
if ( WasLogRotated() )
{ OpenLogAppend(); LogLock(); }
// Automatic log rotation?
if ( maxlogsize > 0 )
Rotate(false); // Handle log rotations
DateStampedMessage(log, buffer); // Log message
}
LogUnlock();
}
else
syslog(loglevel == L_ERROR ? LOG_ERR :
loglevel == L_INFO ? LOG_INFO : LOG_DEBUG, "%s", buffer);
}
void Configuration::LogSelf(int loglevel)
{
LogMessage(loglevel, "ErrorLog %s", ErrorLog());
LogMessage(loglevel, "HostnameLookups %s",
HostnameLookups() == 0 ? "off" :
HostnameLookups() == 1 ? "on" : " double");
struct sockaddr_in *addr = Listen();
unsigned ipaddr = ntohl(addr->sin_addr.s_addr);
LogMessage(loglevel, "Listen %u.%u.%u.%u:%d",
(ipaddr >> 24) & 255, (ipaddr >> 16) & 255,
(ipaddr >> 8) & 255, ipaddr & 255,
ntohs(addr->sin_port));
LogMessage(loglevel, "LogLevel %s",
LogLevel() == L_ERROR ? "error" :
LogLevel() == L_INFO ? "info" : "debug");
LogMessage(loglevel, "MaxClients %u", MaxClients());
LogMessage(loglevel, "MaxLogSize %ld", MaxLogSize());
LogMessage(loglevel, "SendMail %s", SendMail());
LogMessage(loglevel, "ServerName %s", ServerName());
LogMessage(loglevel, "SpamFilter %s", SpamFilter());
LogMessage(loglevel, "SpoolDir %s", SpoolDir());
LogMessage(loglevel, "Timeout %u", Timeout());
LogMessage(loglevel, "User %s", User());
}
void
Configuration::MaxLogSize(const char *val)
{
double number; // Number
char units[255]; // Units
switch (sscanf(val, "%lf%254s", &number, units))
{
default :
fprintf(stderr, "newsd: Bad MaxLogSize value \"%s\"!\n", val);
maxlogsize = 0;
break;
case 1 :
maxlogsize = (long)number;
break;
case 2 :
if (!strcasecmp(units, "k"))
maxlogsize = (long)(number * 1024.0);
else if (!strcasecmp(units, "m"))
maxlogsize = (long)(number * 1024.0 * 1024.0);
else if (!strcasecmp(units, "g"))
maxlogsize = (long)(number * 1024.0 * 1024.0 * 1024.0);
else
maxlogsize = (long)number;
break;
}
}
int Configuration::lookup_user(const char *name)
{
struct passwd *pw = getpwnam(name);
if (pw == NULL )
{
uid = UINT_MAX;
gid = UINT_MAX;
bad_user = true;
return(-1);
}
uid = pw->pw_uid;
gid = pw->pw_gid;
bad_user = false;
endpwent();
return(0);
}