1 /* u_error.c
2  *
3  * Copyright (c) 1996-2005 Mike Gleason, NcFTP Software.
4  * All rights reserved.
5  *
6  */
7 
8 #include "syshdrs.h"
9 #ifdef PRAGMA_HDRSTOP
10 #	pragma hdrstop
11 #endif
12 
13 #if (defined(WIN32) || defined(_WINDOWS)) && !defined(__CYGWIN__)
14 #define _CRT_SECURE_NO_WARNINGS 1
15 #endif
16 
17 /*VARARGS*/
18 void
FTPLogError(const FTPCIPtr cip,const int pError,const char * const fmt,...)19 FTPLogError(const FTPCIPtr cip, const int pError, const char *const fmt, ...)
20 {
21 	va_list ap;
22 	int errnum;
23 	size_t len;
24 	char buf[256];
25 	int endsinperiod;
26 	int endsinnewline;
27 #ifndef HAVE_STRERROR
28 	char errnostr[16];
29 #endif
30 	size_t buflen = 0;
31 	int x;
32 	time_t t;
33 	struct tm lt, *ltp;
34 
35 	buf[0] = '\0';
36 	if ((x = cip->debugTimestamping) != 0) {
37 		ltp = Localtime(time(&t), &lt);
38 		if (x == 1) {
39 			buflen = strftime(buf, sizeof(buf), "%H:%M:%S  ", ltp);
40 		} else {
41 			buflen = strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S  ", ltp);
42 		}
43 	}
44 
45 	errnum = errno;
46 	va_start(ap, fmt);
47 #ifdef HAVE_VSNPRINTF
48 	vsnprintf(buf + buflen, sizeof(buf) - 1 - buflen, fmt, ap);
49 	buf[sizeof(buf) - 1] = '\0';
50 #else
51 	(void) vsprintf(buf + buflen, fmt, ap);
52 #endif
53 	va_end(ap);
54 
55 	if (pError != 0) {
56 		len = strlen(buf);
57 		endsinperiod = 0;
58 		endsinnewline = 0;
59 		if (len > 2) {
60 			if (buf[len - 1] == '\n') {
61 				endsinnewline = 1;
62 				buf[len - 1] = '\0';
63 				if (buf[len - 2] == '.') {
64 					endsinperiod = 1;
65 					buf[len - 2] = '\0';
66 				}
67 			} else if (buf[len - 1] == '.') {
68 				endsinperiod = 1;
69 				buf[len - 1] = '\0';
70 			}
71 		}
72 #ifdef HAVE_STRERROR
73 		(void) STRNCAT(buf, ": ");
74 		(void) STRNCAT(buf, strerror(errnum));
75 #else
76 #	ifdef HAVE_SNPRINTF
77 		snprintf(errnostr, sizeof(errnostr) - 1, " (errno = %d)", errnum);
78 		errnostr[sizeof(errnostr) - 1] = '\0';
79 #	else
80 		sprintf(errnostr, " (errno = %d)", errnum);
81 #	endif
82 		STRNCAT(buf, errnostr);
83 #endif
84 		if (endsinperiod != 0)
85 			(void) STRNCAT(buf, ".");
86 		if (endsinnewline != 0)
87 			(void) STRNCAT(buf, "\n");
88 	}
89 
90 	if (cip->errLog != NULL) {
91 		(void) fprintf(cip->errLog, "%s", buf);
92 		(void) fflush(cip->errLog);
93 	}
94 	if ((cip->debugLog != NULL) && (cip->debugLog != cip->errLog)) {
95 		if ((cip->errLog != stderr) || (cip->debugLog != stdout)) {
96 			(void) fprintf(cip->debugLog, "%s", buf);
97 			(void) fflush(cip->debugLog);
98 		}
99 	}
100 	if (cip->errLogProc != NULL) {
101 		(*cip->errLogProc)(cip, buf);
102 	}
103 	if ((cip->debugLogProc != NULL) && (cip->debugLogProc != cip->errLogProc)) {
104 		(*cip->debugLogProc)(cip, buf);
105 	}
106 }	/* FTPLogError */
107