1 /* qmailn.c - qmail initialization routines
2  * Copyright (C) 2010  Bruce Guenter <bruce@untroubled.org>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23 
24 #include "qmail.h"
25 
26 const char* qmail_root = "/var/qmail";
27 const char* qmail_me = 0;
28 const char* qmail_envnoathost = 0;
29 
read_control(const char * control,const char ** s,str * path)30 static int read_control(const char* control,
31 			const char** s,
32 			str* path)
33 {
34   /* Hostnames are realistically limited to 256 bytes.  This is overkill. */
35   char buf[4096];
36   int fd;
37   long rd;
38   char* nl;
39   char* news;
40   long len;
41   if (!str_copy3s(path, qmail_root, "/control/", control))
42     return -1;
43   if ((fd = open(path->s, O_RDONLY)) == -1)
44     return (errno == ENOENT) ? 0 : -1;
45   rd = read(fd, buf, sizeof buf);
46   close(fd);
47   if (rd <= 0)
48     return rd;
49   if ((nl = memchr(buf, '\n', rd)) == 0)
50     nl = buf + rd;
51   len = nl - buf;
52   if ((news = malloc(len + 1)) == 0)
53     return -1;
54   memcpy(news, buf, len);
55   news[len] = 0;
56   *s = news;
57   return 0;
58 }
59 
qmail_init(void)60 int qmail_init(void)
61 {
62   str path = { 0,0,0 };
63   const char* tmp;
64   if ((tmp = getenv("QMAIL_ROOT")) != 0)
65     qmail_root = tmp;
66   if (read_control("envnoathost", &qmail_envnoathost, &path) != 0)
67     return -1;
68   if (read_control("me", &qmail_me, &path) != 0)
69     return -1;
70   if (qmail_envnoathost == 0)
71     qmail_envnoathost = (qmail_me == 0) ? "envnoathost" : qmail_me;
72   if (qmail_me == 0)
73     qmail_me = "me";
74   str_free(&path);
75   return 0;
76 }
77