dpkg (1.18.25) stretch; urgency=medium
[dpkg] / lib / dpkg / log.c
1 /*
2 * libdpkg - Debian packaging suite library routines
3 * log.c - logging related functions
4 *
5 * Copyright © 2005 Scott James Remnant <scott@netsplit.com>
6 *
7 * This is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21 #include <config.h>
22 #include <compat.h>
23
24 #include <errno.h>
25 #include <time.h>
26 #include <unistd.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29
30 #include <dpkg/i18n.h>
31 #include <dpkg/dpkg.h>
32 #include <dpkg/dpkg-db.h>
33 #include <dpkg/fdio.h>
34
35 const char *log_file = NULL;
36
37 void
38 log_message(const char *fmt, ...)
39 {
40 static struct varbuf log;
41 static FILE *logfd = NULL;
42 char time_str[20];
43 time_t now;
44 va_list args;
45
46 if (!log_file)
47 return;
48
49 if (!logfd) {
50 logfd = fopen(log_file, "a");
51 if (!logfd) {
52 notice(_("could not open log '%s': %s"),
53 log_file, strerror(errno));
54 log_file = NULL;
55 return;
56 }
57 setlinebuf(logfd);
58 setcloexec(fileno(logfd), log_file);
59 }
60
61 va_start(args, fmt);
62 varbuf_reset(&log);
63 varbuf_vprintf(&log, fmt, args);
64 va_end(args);
65
66 time(&now);
67 strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S",
68 localtime(&now));
69 fprintf(logfd, "%s %s\n", time_str, log.buf);
70 }
71
72 struct pipef {
73 struct pipef *next;
74 int fd;
75 };
76
77 static struct pipef *status_pipes = NULL;
78
79 void
80 statusfd_add(int fd)
81 {
82 struct pipef *pipe_new;
83
84 setcloexec(fd, _("<package status and progress file descriptor>"));
85
86 pipe_new = nfmalloc(sizeof(struct pipef));
87 pipe_new->fd = fd;
88 pipe_new->next = status_pipes;
89 status_pipes = pipe_new;
90 }
91
92 void
93 statusfd_send(const char *fmt, ...)
94 {
95 static struct varbuf vb;
96 struct pipef *pipef;
97 va_list args;
98
99 if (!status_pipes)
100 return;
101
102 va_start(args, fmt);
103 varbuf_reset(&vb);
104 varbuf_vprintf(&vb, fmt, args);
105 /* Sanitize string to not include new lines, as front-ends should be
106 * doing their own word-wrapping. */
107 varbuf_map_char(&vb, '\n', ' ');
108 varbuf_add_char(&vb, '\n');
109 va_end(args);
110
111 for (pipef = status_pipes; pipef; pipef = pipef->next) {
112 if (fd_write(pipef->fd, vb.buf, vb.used) < 0)
113 ohshite(_("unable to write to status fd %d"),
114 pipef->fd);
115 }
116 }