+static void logfile_open(void)
+{
+ mode_t old_umask = umask(022 | orig_umask);
+ logfile_fp = fopen(logfile_name, "a");
+ umask(old_umask);
+ if (!logfile_fp) {
+ int fopen_errno = errno;
+ /* Rsync falls back to using syslog on failure. */
+ syslog_init();
+ rsyserr(FERROR, fopen_errno,
+ "failed to open log-file %s", logfile_name);
+ rprintf(FINFO, "Ignoring \"log file\" setting.\n");
+ }
+}
+
+void log_init(int restart)
+{
+ if (log_initialised) {
+ if (!restart)
+ return;
+ if (strcmp(logfile_name, lp_log_file(module_id)) != 0) {
+ if (logfile_fp) {
+ fclose(logfile_fp);
+ logfile_fp = NULL;
+ } else
+ closelog();
+ logfile_name = NULL;
+ } else if (*logfile_name)
+ return; /* unchanged, non-empty "log file" names */
+ else if (lp_syslog_facility(-1) != lp_syslog_facility(module_id))
+ closelog();
+ else
+ return; /* unchanged syslog settings */
+ } else
+ log_initialised = 1;
+
+ /* This looks pointless, but it is needed in order for the
+ * C library on some systems to fetch the timezone info
+ * before the chroot. */
+ timestring(time(NULL));
+
+ /* Optionally use a log file instead of syslog. (Non-daemon
+ * rsyncs will have already set logfile_name, as needed.) */
+ if (am_daemon && !logfile_name)
+ logfile_name = lp_log_file(module_id);
+ if (logfile_name && *logfile_name)
+ logfile_open();
+ else
+ syslog_init();
+}
+
+void logfile_close(void)
+{
+ if (logfile_fp) {
+ logfile_was_closed = 1;
+ fclose(logfile_fp);
+ logfile_fp = NULL;
+ }
+}
+
+void logfile_reopen(void)
+{
+ if (logfile_was_closed) {
+ logfile_was_closed = 0;
+ logfile_open();
+ }
+}
+
+static void filtered_fwrite(FILE *f, const char *buf, int len, int use_isprint)
+{
+ const char *s, *end = buf + len;
+ for (s = buf; s < end; s++) {
+ if ((s < end - 4
+ && *s == '\\' && s[1] == '#'
+ && isdigit(*(uchar*)(s+2))
+ && isdigit(*(uchar*)(s+3))
+ && isdigit(*(uchar*)(s+4)))
+ || (*s != '\t'
+ && ((use_isprint && !isprint(*(uchar*)s))
+ || *(uchar*)s < ' '))) {
+ if (s != buf && fwrite(buf, s - buf, 1, f) != 1)
+ EXIT_OR_RETURN(RERR_MESSAGEIO);
+ fprintf(f, "\\#%03o", *(uchar*)s);
+ buf = s + 1;
+ }
+ }
+ if (buf != end && fwrite(buf, end - buf, 1, f) != 1)
+ EXIT_OR_RETURN(RERR_MESSAGEIO);
+}
+