xref: /illumos-gate/usr/src/lib/libadm/common/puterror.c (revision 9164a50bf932130cbb5097a16f6986873ce0e6e5)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
24 /*	  All Rights Reserved  	*/
25 
26 
27 /*
28  * Copyright (c) 1997, by Sun Microsystems, Inc.
29  * All rights reserved.
30  */
31 
32 /*LINTLIBRARY*/
33 
34 #include <sys/types.h>
35 #include <stdio.h>
36 #include <string.h>
37 #include <stdlib.h>
38 #include "libadm.h"
39 
40 #define	DEFMSG	"ERROR: "
41 #define	MS	sizeof (DEFMSG)
42 #define	INVINP	"invalid input"
43 
44 void
45 puterror(FILE *fp, char *defmesg, char *error)
46 {
47 	char	*tmp;
48 	size_t	n;
49 
50 	if (error == NULL) {
51 		/* use default message since no error was provided */
52 		n = (defmesg ?  strlen(defmesg) : strlen(INVINP));
53 		tmp = calloc(MS+n+1, sizeof (char));
54 		(void) strcpy(tmp, DEFMSG);
55 		(void) strcat(tmp, defmesg ? defmesg : INVINP);
56 
57 	} else if (defmesg != NULL) {
58 		n = strlen(error);
59 		if (error[0] == '~') {
60 			/* prepend default message */
61 			tmp = calloc(MS+n+strlen(defmesg)+2, sizeof (char));
62 			(void) strcpy(tmp, DEFMSG);
63 			(void) strcat(tmp, defmesg);
64 			(void) strcat(tmp, "\n");
65 			++error;
66 			(void) strcat(tmp, error);
67 		} else if (n && (error[n-1] == '~')) {
68 			/* append default message */
69 			tmp = calloc(MS+n+strlen(defmesg)+2, sizeof (char));
70 			(void) strcpy(tmp, DEFMSG);
71 			(void) strcat(tmp, error);
72 			/* first -1 'cuz sizeof (DEFMSG) includes terminator */
73 			tmp[MS-1+n-1] = '\0';
74 			(void) strcat(tmp, "\n");
75 			(void) strcat(tmp, defmesg);
76 		} else {
77 			tmp = calloc(MS+n+1, sizeof (char));
78 			(void) strcpy(tmp, DEFMSG);
79 			(void) strcat(tmp, error);
80 		}
81 	} else {
82 		n = strlen(error);
83 		tmp = calloc(MS+n+1, sizeof (char));
84 		(void) strcpy(tmp, DEFMSG);
85 		(void) strcat(tmp, error);
86 	}
87 	(void) puttext(fp, tmp, ckindent, ckwidth);
88 	(void) fputc('\n', fp);
89 	free(tmp);
90 }
91