xref: /freebsd/usr.bin/rpcgen/rpc_main.c (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
1 /*
2  * Sun RPC is a product of Sun Microsystems, Inc. and is provided for
3  * unrestricted use provided that this legend is included on all tape
4  * media and as a part of the software program in whole or part.  Users
5  * may copy or modify Sun RPC without charge, but are not authorized
6  * to license or distribute it to anyone else except as part of a product or
7  * program developed by the user.
8  *
9  * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE
10  * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
11  * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE.
12  *
13  * Sun RPC is provided with no support and without any obligation on the
14  * part of Sun Microsystems, Inc. to assist in its use, correction,
15  * modification or enhancement.
16  *
17  * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE
18  * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC
19  * OR ANY PART THEREOF.
20  *
21  * In no event will Sun Microsystems, Inc. be liable for any lost revenue
22  * or profits or other special, indirect and consequential damages, even if
23  * Sun has been advised of the possibility of such damages.
24  *
25  * Sun Microsystems, Inc.
26  * 2550 Garcia Avenue
27  * Mountain View, California  94043
28  */
29 
30 
31 #if 0
32 #ifndef lint
33 #ident	"@(#)rpc_main.c	1.21	94/04/25 SMI"
34 static char sccsid[] = "@(#)rpc_main.c 1.30 89/03/30 (C) 1987 SMI";
35 #endif
36 #endif
37 
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 /*
42  * rpc_main.c, Top level of the RPC protocol compiler.
43  * Copyright (C) 1987, Sun Microsystems, Inc.
44  */
45 
46 #include <err.h>
47 #include <ctype.h>
48 #include <stdbool.h>
49 #include <stdio.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <sys/types.h>
53 #include <sys/param.h>
54 #include <sys/file.h>
55 #include <sys/stat.h>
56 #include "rpc_parse.h"
57 #include "rpc_scan.h"
58 #include "rpc_util.h"
59 
60 static void c_output(const char *, const char *, int, const char *);
61 static void h_output(const char *, const char *, int, const char *, int);
62 static void l_output(const char *, const char *, int, const char *);
63 static void t_output(const char *, const char *, int, const char *);
64 static void clnt_output(const char *, const char *, int, const char * );
65 static char *generate_guard(const char *);
66 static void c_initialize(void);
67 
68 static void usage(void) __dead2;
69 static void options_usage(void);
70 static int do_registers(int, const char **);
71 static int parseargs(int, const char **, struct commandline *);
72 static void svc_output(const char *, const char *, int, const char *);
73 static void mkfile_output(struct commandline *);
74 static void s_output(int, const char **, const char *, const char *, int, const char *, int, int);
75 
76 #define	EXTEND	1		/* alias for TRUE */
77 #define	DONT_EXTEND	0		/* alias for FALSE */
78 
79 static const char *svcclosetime = "120";
80 static const char *CPP = NULL;
81 static const char CPPFLAGS[] = "-C";
82 static char pathbuf[MAXPATHLEN + 1];
83 static const char *allv[] = {
84 	"rpcgen", "-s", "udp", "-s", "tcp",
85 };
86 static int allc = nitems(allv);
87 static const char *allnv[] = {
88 	"rpcgen", "-s", "netpath",
89 };
90 static int allnc = nitems(allnv);
91 
92 /*
93  * machinations for handling expanding argument list
94  */
95 static void addarg(const char *);	/* add another argument to the list */
96 static void insarg(int, const char *);	/* insert arg at specified location */
97 static void checkfiles(const char *, const char *);
98 					/* check if out file already exists */
99 
100 static char **arglist;
101 static int argcount = 0;
102 static int argmax = 0;
103 
104 int nonfatalerrors;	/* errors */
105 int inetdflag = 0;	/* Support for inetd is disabled by default, use -I */
106 int pmflag = 0;		/* Support for port monitors is disabled by default */
107 int tirpc_socket = 1;	/* TI-RPC on socket, no TLI library */
108 int logflag;		/* Use syslog instead of fprintf for errors */
109 int tblflag;		/* Support for dispatch table file */
110 int mtflag = 0;		/* Support for MT */
111 
112 #define INLINE 0
113 /* length at which to start doing an inline */
114 
115 int inline_size = INLINE;
116 /*
117  * Length at which to start doing an inline. INLINE = default
118  * if 0, no xdr_inline code
119  */
120 
121 int indefinitewait;	/* If started by port monitors, hang till it wants */
122 int exitnow;		/* If started by port monitors, exit after the call */
123 int timerflag;		/* TRUE if !indefinite && !exitnow */
124 int newstyle;		/* newstyle of passing arguments (by value) */
125 int CCflag = 0;		/* C++ files */
126 static int allfiles;   /* generate all files */
127 int tirpcflag = 1;    /* generating code for tirpc, by default */
128 xdrfunc *xdrfunc_head = NULL; /* xdr function list */
129 xdrfunc *xdrfunc_tail = NULL; /* xdr function list */
130 pid_t childpid;
131 
132 
133 int
134 main(int argc, const char *argv[])
135 {
136 	struct commandline cmd;
137 
138 	(void) memset((char *)&cmd, 0, sizeof (struct commandline));
139 	if (!parseargs(argc, argv, &cmd))
140 		usage();
141 	/*
142 	 * Only the client and server side stubs are likely to be customized,
143 	 *  so in that case only, check if the outfile exists, and if so,
144 	 *  print an error message and exit.
145 	 */
146 	if (cmd.Ssflag || cmd.Scflag || cmd.makefileflag) {
147 		checkfiles(cmd.infile, cmd.outfile);
148 	}
149 	else
150 		checkfiles(cmd.infile, NULL);
151 
152 	if (cmd.cflag) {
153 		c_output(cmd.infile, "-DRPC_XDR", DONT_EXTEND, cmd.outfile);
154 	} else if (cmd.hflag) {
155 		h_output(cmd.infile, "-DRPC_HDR", DONT_EXTEND, cmd.outfile,
156 		    cmd.hflag);
157 	} else if (cmd.lflag) {
158 		l_output(cmd.infile, "-DRPC_CLNT", DONT_EXTEND, cmd.outfile);
159 	} else if (cmd.sflag || cmd.mflag || (cmd.nflag)) {
160 		s_output(argc, argv, cmd.infile, "-DRPC_SVC", DONT_EXTEND,
161 			cmd.outfile, cmd.mflag, cmd.nflag);
162 	} else if (cmd.tflag) {
163 		t_output(cmd.infile, "-DRPC_TBL", DONT_EXTEND, cmd.outfile);
164 	} else if  (cmd.Ssflag) {
165 		svc_output(cmd.infile, "-DRPC_SERVER", DONT_EXTEND,
166 			cmd.outfile);
167 	} else if (cmd.Scflag) {
168 		clnt_output(cmd.infile, "-DRPC_CLIENT", DONT_EXTEND,
169 			    cmd.outfile);
170 	} else if (cmd.makefileflag) {
171 		mkfile_output(&cmd);
172 	} else {
173 		/* the rescans are required, since cpp may effect input */
174 		c_output(cmd.infile, "-DRPC_XDR", EXTEND, "_xdr.c");
175 		reinitialize();
176 		h_output(cmd.infile, "-DRPC_HDR", EXTEND, ".h", cmd.hflag);
177 		reinitialize();
178 		l_output(cmd.infile, "-DRPC_CLNT", EXTEND, "_clnt.c");
179 		reinitialize();
180 		if (inetdflag || !tirpcflag)
181 			s_output(allc, allv, cmd.infile, "-DRPC_SVC", EXTEND,
182 			"_svc.c", cmd.mflag, cmd.nflag);
183 		else
184 			s_output(allnc, allnv, cmd.infile, "-DRPC_SVC",
185 				EXTEND, "_svc.c", cmd.mflag, cmd.nflag);
186 		if (tblflag) {
187 			reinitialize();
188 			t_output(cmd.infile, "-DRPC_TBL", EXTEND, "_tbl.i");
189 		}
190 
191 		if (allfiles) {
192 			reinitialize();
193 			svc_output(cmd.infile, "-DRPC_SERVER", EXTEND,
194 				"_server.c");
195 			reinitialize();
196 			clnt_output(cmd.infile, "-DRPC_CLIENT", EXTEND,
197 				"_client.c");
198 
199 		}
200 		if (allfiles || (cmd.makefileflag == 1)){
201 			reinitialize();
202 			mkfile_output(&cmd);
203 		}
204 
205 	}
206 	exit(nonfatalerrors);
207 	/* NOTREACHED */
208 }
209 
210 
211 /*
212  * add extension to filename
213  */
214 static char *
215 extendfile(const char *path, const char *ext)
216 {
217 	char *res;
218 	const char *p;
219 	const char *file;
220 
221 	if ((file = strrchr(path, '/')) == NULL)
222 		file = path;
223 	else
224 		file++;
225 	res = xmalloc(strlen(file) + strlen(ext) + 1);
226 	p = strrchr(file, '.');
227 	if (p == NULL) {
228 		p = file + strlen(file);
229 	}
230 	(void) strcpy(res, file);
231 	(void) strcpy(res + (p - file), ext);
232 	return (res);
233 }
234 
235 /*
236  * Open output file with given extension
237  */
238 static void
239 open_output(const char *infile, const char *outfile)
240 {
241 
242 	if (outfile == NULL) {
243 		fout = stdout;
244 		return;
245 	}
246 
247 	if (infile != NULL && streq(outfile, infile)) {
248 		warnx("%s already exists. No output generated", infile);
249 		crash();
250 	}
251 	fout = fopen(outfile, "w");
252 	if (fout == NULL) {
253 		warn("unable to open %s", outfile);
254 		crash();
255 	}
256 	record_open(outfile);
257 
258 	return;
259 }
260 
261 static void
262 add_warning(void)
263 {
264 	f_print(fout, "/*\n");
265 	f_print(fout, " * Please do not edit this file.\n");
266 	f_print(fout, " * It was generated using rpcgen.\n");
267 	f_print(fout, " */\n\n");
268 }
269 
270 /* prepend C-preprocessor and flags before arguments */
271 static void
272 prepend_cpp(void)
273 {
274 	int idx = 0, quoted;
275 	const char *var, *s;
276 	char *dupvar, *t, *word;
277 
278 	if (CPP != NULL)
279 		insarg(idx++, CPP);
280 	else if ((var = getenv("RPCGEN_CPP")) == NULL)
281 		insarg(idx++, "/usr/bin/cpp");
282 	else {
283 		/*
284 		 * Parse command line like a shell (but only handle whitespace,
285 		 * quotes and backslash).
286 		 */
287 		dupvar = malloc(strlen(var) + 1);
288 		quoted = 0;
289 		word = NULL;
290 		for (s = var, t = dupvar; *s; ++s) {
291 			switch (quoted) {
292 			/* Unquoted */
293 			case 0:
294 				switch (*s) {
295 				case ' ':
296 				case '\t':
297 				case '\n':
298 					if (word != NULL) {
299 						*t++ = '\0';
300 						insarg(idx++, word);
301 						word = NULL;
302 					}
303 					break;
304 				case '\'':
305 					if (word == NULL)
306 						word = t;
307 					quoted = 1;
308 					break;
309 				case '"':
310 					if (word == NULL)
311 						word = t;
312 					quoted = 2;
313 					break;
314 				case '\\':
315 					switch (*(s + 1)) {
316 					case '\0':
317 						break;
318 					case '\n':
319 						++s;
320 						continue;
321 					default:
322 						++s;
323 						break;
324 					}
325 					/* FALLTHROUGH */
326 				default:
327 					if (word == NULL)
328 						word = t;
329 					*t++ = *s;
330 					break;
331 				}
332 				break;
333 
334 			/* Single-quoted */
335 			case 1:
336 				switch (*s) {
337 				case '\'':
338 					quoted = 0;
339 					break;
340 				default:
341 					*t++ = *s;
342 					break;
343 				}
344 				break;
345 
346 			/* Double-quoted */
347 			case 2:
348 				switch (*s) {
349 				case '"':
350 					quoted = 0;
351 					break;
352 				case '\\':
353 					switch (*(s + 1)) {
354 					case '\0':
355 						break;
356 					case '$':
357 					case '`':
358 					case '"':
359 					case '\\':
360 						++s;
361 						break;
362 					case '\n':
363 						++s;
364 						continue;
365 					default:
366 						break;
367 					}
368 					/* FALLTHROUGH */
369 				default:
370 					*t++ = *s;
371 					break;
372 				}
373 				break;
374 			}
375 		}
376 		if (quoted)
377 			errx(1, "RPCGEN_CPP: unterminated %c",
378 			    quoted == 1 ? '\'' : '"');
379 		if (word != NULL) {
380 			*t++ = '\0';
381 			insarg(idx++, word);
382 		}
383 		free(dupvar);
384 	}
385 
386 	insarg(idx, CPPFLAGS);
387 }
388 
389 /*
390  * Open input file with given define for C-preprocessor
391  */
392 static void
393 open_input(const char *infile, const char *define)
394 {
395 	int pd[2];
396 
397 	infilename = (infile == NULL) ? "<stdin>" : infile;
398 	(void) pipe(pd);
399 	switch (childpid = fork()) {
400 	case 0:
401 		prepend_cpp();
402 		addarg(define);
403 		if (infile)
404 			addarg(infile);
405 		addarg((char *)NULL);
406 		(void) close(1);
407 		(void) dup2(pd[1], 1);
408 		(void) close(pd[0]);
409 		execvp(arglist[0], arglist);
410 		err(1, "execvp %s", arglist[0]);
411 	case -1:
412 		err(1, "fork");
413 	}
414 	(void) close(pd[1]);
415 	fin = fdopen(pd[0], "r");
416 	if (fin == NULL) {
417 		warn("%s", infilename);
418 		crash();
419 	}
420 }
421 
422 /* valid tirpc nettypes */
423 static const char *valid_ti_nettypes[] =
424 {
425 	"netpath",
426 	"visible",
427 	"circuit_v",
428 	"datagram_v",
429 	"circuit_n",
430 	"datagram_n",
431 	"udp",
432 	"tcp",
433 	"raw",
434 	NULL
435 	};
436 
437 /* valid inetd nettypes */
438 static const char *valid_i_nettypes[] =
439 {
440 	"udp",
441 	"tcp",
442 	NULL
443 	};
444 
445 static int
446 check_nettype(const char *name, const char *list_to_check[])
447 {
448 	int i;
449 	for (i = 0; list_to_check[i] != NULL; i++) {
450 		if (strcmp(name, list_to_check[i]) == 0) {
451 			return (1);
452 		}
453 	}
454 	warnx("illegal nettype :\'%s\'", name);
455 	return (0);
456 }
457 
458 static const char *
459 file_name(const char *file, const char *ext)
460 {
461 	char *temp;
462 	temp = extendfile(file, ext);
463 
464 	if (access(temp, F_OK) != -1)
465 		return (temp);
466 	else
467 		return (" ");
468 
469 }
470 
471 
472 static void
473 c_output(const char *infile, const char *define, int extend, const char *outfile)
474 {
475 	definition *def;
476 	char *include;
477 	const char *outfilename;
478 	long tell;
479 
480 	c_initialize();
481 	open_input(infile, define);
482 	outfilename = extend ? extendfile(infile, outfile) : outfile;
483 	open_output(infile, outfilename);
484 	add_warning();
485 	if (infile && (include = extendfile(infile, ".h"))) {
486 		f_print(fout, "#include \"%s\"\n", include);
487 		free(include);
488 		/* .h file already contains rpc/rpc.h */
489 	} else
490 		f_print(fout, "#include <rpc/rpc.h>\n");
491 	tell = ftell(fout);
492 	while ( (def = get_definition()) ) {
493 		emit(def);
494 	}
495 	if (extend && tell == ftell(fout)) {
496 		(void) unlink(outfilename);
497 	}
498 }
499 
500 
501 void
502 c_initialize(void)
503 {
504 
505 	/* add all the starting basic types */
506 	add_type(1, "int");
507 	add_type(1, "long");
508 	add_type(1, "short");
509 	add_type(1, "bool");
510 	add_type(1, "u_int");
511 	add_type(1, "u_long");
512 	add_type(1, "u_short");
513 
514 }
515 
516 static const char rpcgen_table_dcl[] = "struct rpcgen_table {\n\
517 	char	*(*proc)(); \n\
518 	xdrproc_t	xdr_arg; \n\
519 	unsigned	len_arg; \n\
520 	xdrproc_t	xdr_res; \n\
521 	unsigned	len_res; \n\
522 }; \n";
523 
524 
525 char *
526 generate_guard(const char *pathname)
527 {
528 	const char *filename;
529 	char *guard, *tmp, *stopat;
530 
531 	filename = strrchr(pathname, '/');  /* find last component */
532 	filename = ((filename == NULL) ? pathname : filename+1);
533 	guard = xstrdup(filename);
534 	stopat = strrchr(guard, '.');
535 
536 	/*
537 	 * Convert to a valid C macro name and make it upper case.
538 	 * Map macro unfriendly characterss to '_'.
539 	 */
540 	for (tmp = guard; *tmp != '\000'; ++tmp) {
541 		if (islower(*tmp))
542 			*tmp = toupper(*tmp);
543 		else if (isupper(*tmp) || *tmp == '_')
544 			/* OK for C */;
545 		else if (tmp == guard)
546 			*tmp = '_';
547 		else if (isdigit(*tmp))
548 			/* OK for all but first character */;
549 		else if (tmp == stopat) {
550 			*tmp = '\0';
551 			break;
552 		} else
553 			*tmp = '_';
554 	}
555 	/*
556 	 * Can't have a '_' in front, because it'll end up being "__".
557 	 * "__" macros shoudln't be used. So, remove all of the
558 	 * '_' characters from the front.
559 	 */
560 	if (*guard == '_') {
561 		for (tmp = guard; *tmp == '_'; ++tmp)
562 			;
563 		strcpy(guard, tmp);
564 	}
565 	tmp = guard;
566 	guard = extendfile(guard, "_H_RPCGEN");
567 	free(tmp);
568 	return (guard);
569 }
570 
571 /*
572  * Compile into an XDR header file
573  */
574 
575 
576 static void
577 h_output(const char *infile, const char *define, int extend, const char *outfile, int headeronly)
578 {
579 	definition *def;
580 	const char *outfilename;
581 	long tell;
582 	const char *guard;
583 	list *l;
584 	xdrfunc *xdrfuncp;
585 	void *tmp = NULL;
586 
587 	open_input(infile, define);
588 	outfilename =  extend ? extendfile(infile, outfile) : outfile;
589 	open_output(infile, outfilename);
590 	add_warning();
591 	if (outfilename || infile){
592 		guard = tmp = generate_guard(outfilename ? outfilename: infile);
593 	} else
594 		guard = "STDIN_";
595 
596 	f_print(fout, "#ifndef _%s\n#define	_%s\n\n", guard,
597 		guard);
598 
599 	f_print(fout, "#include <rpc/rpc.h>\n");
600 
601 	if (mtflag)
602 		f_print(fout, "#include <pthread.h>\n");
603 
604 	/* put the C++ support */
605 	if (!CCflag) {
606 		f_print(fout, "\n#ifdef __cplusplus\n");
607 		f_print(fout, "extern \"C\" {\n");
608 		f_print(fout, "#endif\n\n");
609 	}
610 
611 	/* put in a typedef for quadprecision. Only with Cflag */
612 
613 	tell = ftell(fout);
614 
615 	/* print data definitions */
616 	while ( (def = get_definition()) ) {
617 		print_datadef(def, headeronly);
618 	}
619 
620 	/*
621 	 * print function declarations.
622 	 *  Do this after data definitions because they might be used as
623 	 *  arguments for functions
624 	 */
625 	for (l = defined; l != NULL; l = l->next) {
626 		print_funcdef(l->val, headeronly);
627 	}
628 	/* Now  print all xdr func declarations */
629 	if (xdrfunc_head != NULL){
630 
631 		f_print(fout,
632 			"\n/* the xdr functions */\n");
633 
634 		if (CCflag){
635 			f_print(fout, "\n#ifdef __cplusplus\n");
636 			f_print(fout, "extern \"C\" {\n");
637 			f_print(fout, "#endif\n");
638 		}
639 
640 		xdrfuncp = xdrfunc_head;
641 		while (xdrfuncp != NULL){
642 			print_xdr_func_def(xdrfuncp->name, xdrfuncp->pointerp);
643 			xdrfuncp = xdrfuncp->next;
644 		}
645 	}
646 
647 	if (extend && tell == ftell(fout)) {
648 		(void) unlink(outfilename);
649 	} else if (tblflag) {
650 		f_print(fout, rpcgen_table_dcl);
651 	}
652 
653 	f_print(fout, "\n#ifdef __cplusplus\n");
654 	f_print(fout, "}\n");
655 	f_print(fout, "#endif\n");
656 
657 	f_print(fout, "\n#endif /* !_%s */\n", guard);
658 	free(tmp);
659 }
660 
661 /*
662  * Compile into an RPC service
663  */
664 static void
665 s_output(int argc, const char *argv[], const char *infile, const char *define,
666     int extend, const char *outfile, int nomain, int netflag)
667 {
668 	char *include;
669 	definition *def;
670 	int foundprogram = 0;
671 	const char *outfilename;
672 
673 	open_input(infile, define);
674 	outfilename = extend ? extendfile(infile, outfile) : outfile;
675 	open_output(infile, outfilename);
676 	add_warning();
677 	if (infile && (include = extendfile(infile, ".h"))) {
678 		f_print(fout, "#include \"%s\"\n", include);
679 		free(include);
680 	} else
681 		f_print(fout, "#include <rpc/rpc.h>\n");
682 
683 	f_print(fout, "#include <stdio.h>\n");
684 	f_print(fout, "#include <stdlib.h> /* getenv, exit */\n");
685 	f_print (fout, "#include <rpc/pmap_clnt.h> /* for pmap_unset */\n");
686 	f_print (fout, "#include <string.h> /* strcmp */\n");
687 	if (tirpcflag)
688 		f_print(fout, "#include <rpc/rpc_com.h>\n");
689 	if (strcmp(svcclosetime, "-1") == 0)
690 		indefinitewait = 1;
691 	else if (strcmp(svcclosetime, "0") == 0)
692 		exitnow = 1;
693 	else if (inetdflag || pmflag) {
694 		f_print(fout, "#include <signal.h>\n");
695 		timerflag = 1;
696 	}
697 
698 	if (!tirpcflag && inetdflag)
699 		f_print(fout, "#include <sys/ttycom.h> /* TIOCNOTTY */\n");
700 	if (inetdflag || pmflag) {
701 		f_print(fout, "#ifdef __cplusplus\n");
702 		f_print(fout,
703 			"#include <sys/sysent.h> /* getdtablesize, open */\n");
704 		f_print(fout, "#endif /* __cplusplus */\n");
705 	}
706 	if (tirpcflag) {
707 		f_print(fout, "#include <fcntl.h> /* open */\n");
708 		f_print(fout, "#include <unistd.h> /* fork / setsid */\n");
709 		f_print(fout, "#include <sys/types.h>\n");
710 	}
711 
712 	f_print(fout, "#include <string.h>\n");
713 	if (inetdflag || !tirpcflag) {
714 		f_print(fout, "#include <sys/socket.h>\n");
715 		f_print(fout, "#include <netinet/in.h>\n");
716 	}
717 
718 	if ((netflag || pmflag) && tirpcflag && !nomain) {
719 		f_print(fout, "#include <netconfig.h>\n");
720 	}
721 	if (tirpcflag)
722 		f_print(fout, "#include <sys/resource.h> /* rlimit */\n");
723 	if (logflag || inetdflag || pmflag || tirpcflag)
724 		f_print(fout, "#include <syslog.h>\n");
725 
726 	f_print(fout, "\n#ifdef DEBUG\n#define	RPC_SVC_FG\n#endif\n");
727 	if (timerflag)
728 		f_print(fout, "\n#define	_RPCSVC_CLOSEDOWN %s\n",
729 			svcclosetime);
730 	while ( (def = get_definition()) ) {
731 		foundprogram |= (def->def_kind == DEF_PROGRAM);
732 	}
733 	if (extend && !foundprogram) {
734 		(void) unlink(outfilename);
735 		return;
736 	}
737 	write_most(infile, netflag, nomain);
738 	if (!nomain) {
739 		if (!do_registers(argc, argv)) {
740 			if (outfilename)
741 				(void) unlink(outfilename);
742 			usage();
743 		}
744 		write_rest();
745 	}
746 }
747 
748 /*
749  * generate client side stubs
750  */
751 static void
752 l_output(const char *infile, const char *define, int extend, const char *outfile)
753 {
754 	char *include;
755 	definition *def;
756 	int foundprogram = 0;
757 	const char *outfilename;
758 
759 	open_input(infile, define);
760 	outfilename = extend ? extendfile(infile, outfile) : outfile;
761 	open_output(infile, outfilename);
762 	add_warning();
763 	f_print (fout, "#include <string.h> /* for memset */\n");
764 	if (infile && (include = extendfile(infile, ".h"))) {
765 		f_print(fout, "#include \"%s\"\n", include);
766 		free(include);
767 	} else
768 		f_print(fout, "#include <rpc/rpc.h>\n");
769 	while ( (def = get_definition()) ) {
770 		foundprogram |= (def->def_kind == DEF_PROGRAM);
771 	}
772 	if (extend && !foundprogram) {
773 		(void) unlink(outfilename);
774 		return;
775 	}
776 	write_stubs();
777 }
778 
779 /*
780  * generate the dispatch table
781  */
782 static void
783 t_output(const char *infile, const char *define, int extend, const char *outfile)
784 {
785 	definition *def;
786 	int foundprogram = 0;
787 	const char *outfilename;
788 
789 	open_input(infile, define);
790 	outfilename = extend ? extendfile(infile, outfile) : outfile;
791 	open_output(infile, outfilename);
792 	add_warning();
793 	while ( (def = get_definition()) ) {
794 		foundprogram |= (def->def_kind == DEF_PROGRAM);
795 	}
796 	if (extend && !foundprogram) {
797 		(void) unlink(outfilename);
798 		return;
799 	}
800 	write_tables();
801 }
802 
803 /* sample routine for the server template */
804 static void
805 svc_output(const char *infile, const char *define, int extend, const char *outfile)
806 {
807 	definition *def;
808 	char *include;
809 	const char *outfilename;
810 	long tell;
811 	open_input(infile, define);
812 	outfilename = extend ? extendfile(infile, outfile) : outfile;
813 	checkfiles(infile, outfilename);
814 	/*
815 	 * Check if outfile already exists.
816 	 * if so, print an error message and exit
817 	 */
818 	open_output(infile, outfilename);
819 	add_sample_msg();
820 
821 	if (infile && (include = extendfile(infile, ".h"))) {
822 		f_print(fout, "#include \"%s\"\n", include);
823 		free(include);
824 	} else
825 		f_print(fout, "#include <rpc/rpc.h>\n");
826 
827 	tell = ftell(fout);
828 	while ( (def = get_definition()) ) {
829 		write_sample_svc(def);
830 	}
831 	if (extend && tell == ftell(fout)) {
832 		(void) unlink(outfilename);
833 	}
834 }
835 
836 /* sample main routine for client */
837 static void
838 clnt_output(const char *infile, const char *define, int extend, const char *outfile)
839 {
840 	definition *def;
841 	char *include;
842 	const char *outfilename;
843 	long tell;
844 	int has_program = 0;
845 
846 	open_input(infile, define);
847 	outfilename = extend ? extendfile(infile, outfile) : outfile;
848 	checkfiles(infile, outfilename);
849 	/*
850 	 * Check if outfile already exists.
851 	 * if so, print an error message and exit
852 	 */
853 
854 	open_output(infile, outfilename);
855 	add_sample_msg();
856 	if (infile && (include = extendfile(infile, ".h"))) {
857 		f_print(fout, "#include \"%s\"\n", include);
858 		free(include);
859 	} else
860 		f_print(fout, "#include <rpc/rpc.h>\n");
861 	f_print(fout, "#include <stdio.h>\n");
862 	f_print(fout, "#include <stdlib.h>\n");
863 	tell = ftell(fout);
864 	while ( (def = get_definition()) ) {
865 		has_program += write_sample_clnt(def);
866 	}
867 
868 	if (has_program)
869 		write_sample_clnt_main();
870 
871 	if (extend && tell == ftell(fout)) {
872 		(void) unlink(outfilename);
873 	}
874 }
875 
876 
877 static void mkfile_output(struct commandline *cmd)
878 {
879 	const char *mkfilename, *clientname, *clntname, *xdrname, *hdrname;
880 	const char *servername, *svcname, *servprogname, *clntprogname;
881 	char *temp, *mkftemp;
882 
883 	svcname = file_name(cmd->infile, "_svc.c");
884 	clntname = file_name(cmd->infile, "_clnt.c");
885 	xdrname = file_name(cmd->infile, "_xdr.c");
886 	hdrname = file_name(cmd->infile, ".h");
887 
888 
889 	if (allfiles){
890 		servername = extendfile(cmd->infile, "_server.c");
891 		clientname = extendfile(cmd->infile, "_client.c");
892 	}else{
893 		servername = " ";
894 		clientname = " ";
895 	}
896 	servprogname = extendfile(cmd->infile, "_server");
897 	clntprogname = extendfile(cmd->infile, "_client");
898 
899 	if (allfiles){
900 		mkftemp = xmalloc(strlen("makefile.") +
901 		                     strlen(cmd->infile) + 1);
902 		temp = strrchr(cmd->infile, '.');
903 		strcpy(mkftemp, "makefile.");
904 		(void) strncat(mkftemp, cmd->infile,
905 			(temp - cmd->infile));
906 		mkfilename = mkftemp;
907 	} else
908 		mkfilename = cmd->outfile;
909 
910 
911 	checkfiles(NULL, mkfilename);
912 	open_output(NULL, mkfilename);
913 
914 	f_print(fout, "\n# This is a template makefile generated\
915 		by rpcgen \n");
916 
917 	f_print(fout, "\n# Parameters \n\n");
918 
919 	f_print(fout, "CLIENT = %s\nSERVER = %s\n\n",
920 		clntprogname, servprogname);
921 	f_print(fout, "SOURCES_CLNT.c = \nSOURCES_CLNT.h = \n");
922 	f_print(fout, "SOURCES_SVC.c = \nSOURCES_SVC.h = \n");
923 	f_print(fout, "SOURCES.x = %s\n\n", cmd->infile);
924 	f_print(fout, "TARGETS_SVC.c = %s %s %s \n",
925 		svcname, servername, xdrname);
926 	f_print(fout, "TARGETS_CLNT.c = %s %s %s \n",
927 		clntname, clientname, xdrname);
928 	f_print(fout, "TARGETS = %s %s %s %s %s %s\n\n",
929 		hdrname, xdrname, clntname,
930 		svcname, clientname, servername);
931 
932 	f_print(fout, "OBJECTS_CLNT = $(SOURCES_CLNT.c:%%.c=%%.o) \
933 $(TARGETS_CLNT.c:%%.c=%%.o) ");
934 
935 	f_print(fout, "\nOBJECTS_SVC = $(SOURCES_SVC.c:%%.c=%%.o) \
936 $(TARGETS_SVC.c:%%.c=%%.o) ");
937 
938 
939 	f_print(fout, "\n# Compiler flags \n");
940 	if (mtflag)
941 		f_print(fout, "\nCFLAGS += -D_REENTRANT -D_THEAD_SAFE \nLDLIBS += -pthread\n");
942 
943 	f_print(fout, "RPCGENFLAGS = \n");
944 
945 	f_print(fout, "\n# Targets \n\n");
946 
947 	f_print(fout, "all : $(CLIENT) $(SERVER)\n\n");
948 	f_print(fout, "$(TARGETS) : $(SOURCES.x) \n");
949 	f_print(fout, "\trpcgen $(RPCGENFLAGS) $(SOURCES.x)\n\n");
950 	if (allfiles) {
951 		f_print(fout, "\trpcgen -Sc $(RPCGENFLAGS) $(SOURCES.x) -o %s\n\n", clientname);
952 		f_print(fout, "\trpcgen -Ss $(RPCGENFLAGS) $(SOURCES.x) -o %s\n\n", servername);
953 	}
954 	f_print(fout, "$(OBJECTS_CLNT) : $(SOURCES_CLNT.c) $(SOURCES_CLNT.h) \
955 $(TARGETS_CLNT.c) \n\n");
956 
957 	f_print(fout, "$(OBJECTS_SVC) : $(SOURCES_SVC.c) $(SOURCES_SVC.h) \
958 $(TARGETS_SVC.c) \n\n");
959 	f_print(fout, "$(CLIENT) : $(OBJECTS_CLNT) \n");
960 	f_print(fout, "\t$(CC) -o $(CLIENT) $(OBJECTS_CLNT) \
961 $(LDLIBS) \n\n");
962 	f_print(fout, "$(SERVER) : $(OBJECTS_SVC) \n");
963 	f_print(fout, "\t$(CC) -o $(SERVER) $(OBJECTS_SVC) $(LDLIBS)\n\n");
964 	f_print(fout, "clean:\n\t rm -f core $(TARGETS) $(OBJECTS_CLNT) \
965 $(OBJECTS_SVC) $(CLIENT) $(SERVER)\n\n");
966 }
967 
968 
969 
970 /*
971  * Perform registrations for service output
972  * Return 0 if failed; 1 otherwise.
973  */
974 static int
975 do_registers(int argc, const char *argv[])
976 {
977 	int i;
978 
979 	if (inetdflag || !tirpcflag) {
980 		for (i = 1; i < argc; i++) {
981 			if (streq(argv[i], "-s")) {
982 				if (!check_nettype(argv[i + 1],
983 						    valid_i_nettypes))
984 					return (0);
985 				write_inetd_register(argv[i + 1]);
986 				i++;
987 			}
988 		}
989 	} else {
990 		for (i = 1; i < argc; i++)
991 			if (streq(argv[i], "-s")) {
992 				if (!check_nettype(argv[i + 1],
993 						    valid_ti_nettypes))
994 					return (0);
995 				write_nettype_register(argv[i + 1]);
996 				i++;
997 			} else if (streq(argv[i], "-n")) {
998 				write_netid_register(argv[i + 1]);
999 				i++;
1000 			}
1001 	}
1002 	return (1);
1003 }
1004 
1005 /*
1006  * Extend the argument list
1007  */
1008 static void
1009 moreargs(void)
1010 {
1011 	char **newarglist;
1012 
1013 	argmax = argmax == 0 ? 32 : argmax << 1;
1014 	if (argmax > INT_MAX / 4) {
1015 		warnx("refusing to allocate too many arguments");
1016 		crash();
1017 	}
1018 	newarglist = realloc(arglist, argmax * sizeof(*arglist));
1019 	if (newarglist == NULL) {
1020 		warnx("unable to allocate arglist");
1021 		crash();
1022 	}
1023 	arglist = newarglist;
1024 }
1025 
1026 /*
1027  * Add another argument to the arg list
1028  */
1029 static void
1030 addarg(const char *cp)
1031 {
1032 	if (argcount >= argmax)
1033 		moreargs();
1034 
1035 	if (cp != NULL)
1036 		arglist[argcount++] = xstrdup(cp);
1037 	else
1038 		arglist[argcount++] = NULL;
1039 }
1040 
1041 /*
1042  * Insert an argument at the specified location
1043  */
1044 static void
1045 insarg(int place, const char *cp)
1046 {
1047 	int i;
1048 
1049 	if (argcount >= argmax)
1050 		moreargs();
1051 
1052 	/* Move up existing arguments */
1053 	for (i = argcount - 1; i >= place; i--)
1054 		arglist[i + 1] = arglist[i];
1055 
1056 	arglist[place] = xstrdup(cp);
1057 	argcount++;
1058 }
1059 
1060 /*
1061  * if input file is stdin and an output file is specified then complain
1062  * if the file already exists. Otherwise the file may get overwritten
1063  * If input file does not exist, exit with an error
1064  */
1065 
1066 static void
1067 checkfiles(const char *infile, const char *outfile)
1068 {
1069 
1070 	struct stat buf;
1071 
1072 	if (infile)		/* infile ! = NULL */
1073 		if (stat(infile, &buf) < 0)
1074 		{
1075 			warn("%s", infile);
1076 			crash();
1077 		}
1078 	if (outfile) {
1079 		if (stat(outfile, &buf) < 0)
1080 			return;	/* file does not exist */
1081 		else {
1082 			warnx("file '%s' already exists and may be overwritten", outfile);
1083 			crash();
1084 		}
1085 	}
1086 }
1087 
1088 /*
1089  * Parse command line arguments
1090  */
1091 static int
1092 parseargs(int argc, const char *argv[], struct commandline *cmd)
1093 {
1094 	int i;
1095 	int j;
1096 	char c, ch;
1097 	char flag[(1 << 8 * sizeof (char))];
1098 	int nflags;
1099 
1100 	cmd->infile = cmd->outfile = NULL;
1101 	if (argc < 2) {
1102 		return (0);
1103 	}
1104 	allfiles = 0;
1105 	flag['c'] = 0;
1106 	flag['h'] = 0;
1107 	flag['l'] = 0;
1108 	flag['m'] = 0;
1109 	flag['o'] = 0;
1110 	flag['s'] = 0;
1111 	flag['n'] = 0;
1112 	flag['t'] = 0;
1113 	flag['S'] = 0;
1114 	flag['C'] = 0;
1115 	flag['M'] = 0;
1116 
1117 	for (i = 1; i < argc; i++) {
1118 		if (argv[i][0] != '-') {
1119 			if (cmd->infile) {
1120 				warnx("cannot specify more than one input file");
1121 				return (0);
1122 			}
1123 			cmd->infile = argv[i];
1124 		} else {
1125 			for (j = 1; argv[i][j] != 0; j++) {
1126 				c = argv[i][j];
1127 				switch (c) {
1128 				case 'a':
1129 					allfiles = 1;
1130 					break;
1131 				case 'c':
1132 				case 'h':
1133 				case 'l':
1134 				case 'm':
1135 				case 't':
1136 					if (flag[(int)c]) {
1137 						return (0);
1138 					}
1139 					flag[(int)c] = 1;
1140 					break;
1141 				case 'S':
1142 					/*
1143 					 * sample flag: Ss or Sc.
1144 					 *  Ss means set flag['S'];
1145 					 *  Sc means set flag['C'];
1146 					 *  Sm means set flag['M'];
1147 					 */
1148 					ch = argv[i][++j]; /* get next char */
1149 					if (ch == 's')
1150 						ch = 'S';
1151 					else if (ch == 'c')
1152 						ch = 'C';
1153 					else if (ch == 'm')
1154 						ch = 'M';
1155 					else
1156 						return (0);
1157 
1158 					if (flag[(int)ch]) {
1159 						return (0);
1160 					}
1161 					flag[(int)ch] = 1;
1162 					break;
1163 				case 'C': /* ANSI C syntax */
1164 					ch = argv[i][j+1]; /* get next char */
1165 
1166 					if (ch != 'C')
1167 						break;
1168 					CCflag = 1;
1169 					break;
1170 				case 'b':
1171 					/*
1172 					 *  Turn TIRPC flag off for
1173 					 *  generating backward compatible
1174 					 *  code
1175 					 */
1176 					tirpcflag = 0;
1177 					break;
1178 
1179 				case 'I':
1180 					inetdflag = 1;
1181 					break;
1182 				case 'N':
1183 					newstyle = 1;
1184 					break;
1185 				case 'L':
1186 					logflag = 1;
1187 					break;
1188 				case 'P':
1189 					pmflag = 1;
1190 					break;
1191 				case 'K':
1192 					if (++i == argc) {
1193 						return (0);
1194 					}
1195 					svcclosetime = argv[i];
1196 					goto nextarg;
1197 				case 'T':
1198 					tblflag = 1;
1199 					break;
1200 				case 'M':
1201 					mtflag = 1;
1202 					break;
1203 				case 'i' :
1204 					if (++i == argc) {
1205 						return (0);
1206 					}
1207 					inline_size = atoi(argv[i]);
1208 					goto nextarg;
1209 				case 'n':
1210 				case 'o':
1211 				case 's':
1212 					if (argv[i][j - 1] != '-' ||
1213 					    argv[i][j + 1] != 0) {
1214 						return (0);
1215 					}
1216 					flag[(int)c] = 1;
1217 					if (++i == argc) {
1218 						return (0);
1219 					}
1220 					if (c == 'o') {
1221 						if (cmd->outfile) {
1222 							return (0);
1223 						}
1224 						cmd->outfile = argv[i];
1225 					}
1226 					goto nextarg;
1227 				case 'D':
1228 					if (argv[i][j - 1] != '-') {
1229 						return (0);
1230 					}
1231 					(void) addarg(argv[i]);
1232 					goto nextarg;
1233 				case 'Y':
1234 					if (++i == argc) {
1235 						return (0);
1236 					}
1237 					if (strlcpy(pathbuf, argv[i],
1238 					    sizeof(pathbuf)) >= sizeof(pathbuf)
1239 					    || strlcat(pathbuf, "/cpp",
1240 					    sizeof(pathbuf)) >=
1241 					    sizeof(pathbuf)) {
1242 						warnx("argument too long");
1243 						return (0);
1244 					}
1245 					CPP = pathbuf;
1246 					goto nextarg;
1247 
1248 
1249 
1250 				default:
1251 					return (0);
1252 				}
1253 			}
1254 		nextarg:
1255 			;
1256 		}
1257 	}
1258 
1259 	cmd->cflag = flag['c'];
1260 	cmd->hflag = flag['h'];
1261 	cmd->lflag = flag['l'];
1262 	cmd->mflag = flag['m'];
1263 	cmd->nflag = flag['n'];
1264 	cmd->sflag = flag['s'];
1265 	cmd->tflag = flag['t'];
1266 	cmd->Ssflag = flag['S'];
1267 	cmd->Scflag = flag['C'];
1268 	cmd->makefileflag = flag['M'];
1269 
1270 	if (tirpcflag) {
1271 		if (inetdflag)
1272 			pmflag = 0;
1273 		if ((inetdflag && cmd->nflag)) {
1274 			/* netid not allowed with inetdflag */
1275 			warnx("cannot use netid flag with inetd flag");
1276 			return (0);
1277 		}
1278 	} else {		/* 4.1 mode */
1279 		pmflag = 0;	/* set pmflag only in tirpcmode */
1280 		if (cmd->nflag) { /* netid needs TIRPC */
1281 			warnx("cannot use netid flag without TIRPC");
1282 			return (0);
1283 		}
1284 	}
1285 
1286 	if (newstyle && (tblflag || cmd->tflag)) {
1287 		warnx("cannot use table flags with newstyle");
1288 		return (0);
1289 	}
1290 
1291 	/* check no conflicts with file generation flags */
1292 	nflags = cmd->cflag + cmd->hflag + cmd->lflag + cmd->mflag +
1293 		cmd->sflag + cmd->nflag + cmd->tflag + cmd->Ssflag +
1294 			cmd->Scflag + cmd->makefileflag;
1295 
1296 	if (nflags == 0) {
1297 		if (cmd->outfile != NULL || cmd->infile == NULL) {
1298 			return (0);
1299 		}
1300 	} else if (cmd->infile == NULL &&
1301 	    (cmd->Ssflag || cmd->Scflag || cmd->makefileflag)) {
1302 		warnx("\"infile\" is required for template generation flags");
1303 		return (0);
1304 	} if (nflags > 1) {
1305 		warnx("cannot have more than one file generation flag");
1306 		return (0);
1307 	}
1308 	return (1);
1309 }
1310 
1311 static void
1312 usage(void)
1313 {
1314 	f_print(stderr, "%s\n%s\n%s\n%s\n%s\n",
1315 		"usage: rpcgen infile",
1316 		"       rpcgen [-abCLNTM] [-Dname[=value]] [-i size]\
1317 [-I -P [-K seconds]] [-Y path] infile",
1318 		"       rpcgen [-c | -h | -l | -m | -t | -Sc | -Ss | -Sm]\
1319 [-o outfile] [infile]",
1320 		"       rpcgen [-s nettype]* [-o outfile] [infile]",
1321 		"       rpcgen [-n netid]* [-o outfile] [infile]");
1322 	options_usage();
1323 	exit(1);
1324 }
1325 
1326 static void
1327 options_usage(void)
1328 {
1329 	f_print(stderr, "options:\n");
1330 	f_print(stderr, "-a\t\tgenerate all files, including samples\n");
1331 	f_print(stderr, "-b\t\tbackward compatibility mode (generates code \
1332 for FreeBSD 4.X)\n");
1333 	f_print(stderr, "-c\t\tgenerate XDR routines\n");
1334 	f_print(stderr, "-C\t\tANSI C mode\n");
1335 	f_print(stderr, "-Dname[=value]\tdefine a symbol (same as #define)\n");
1336 	f_print(stderr, "-h\t\tgenerate header file\n");
1337 	f_print(stderr, "-i size\t\tsize at which to start generating\
1338 inline code\n");
1339 	f_print(stderr, "-I\t\tgenerate code for inetd support in server\n");
1340 	f_print(stderr, "-K seconds\tserver exits after K seconds of\
1341 inactivity\n");
1342 	f_print(stderr, "-l\t\tgenerate client side stubs\n");
1343 	f_print(stderr, "-L\t\tserver errors will be printed to syslog\n");
1344 	f_print(stderr, "-m\t\tgenerate server side stubs\n");
1345 	f_print(stderr, "-M\t\tgenerate MT-safe code\n");
1346 	f_print(stderr, "-n netid\tgenerate server code that supports\
1347 named netid\n");
1348 	f_print(stderr, "-N\t\tsupports multiple arguments and\
1349 call-by-value\n");
1350 	f_print(stderr, "-o outfile\tname of the output file\n");
1351 	f_print(stderr, "-P\t\tgenerate code for port monitoring support in server\n");
1352 	f_print(stderr, "-s nettype\tgenerate server code that supports named\
1353 nettype\n");
1354 	f_print(stderr, "-Sc\t\tgenerate sample client code that uses remote\
1355 procedures\n");
1356 	f_print(stderr, "-Ss\t\tgenerate sample server code that defines\
1357 remote procedures\n");
1358 	f_print(stderr, "-Sm \t\tgenerate makefile template \n");
1359 
1360 	f_print(stderr, "-t\t\tgenerate RPC dispatch table\n");
1361 	f_print(stderr, "-T\t\tgenerate code to support RPC dispatch tables\n");
1362 	f_print(stderr, "-Y path\t\tpath where cpp is found\n");
1363 	exit(1);
1364 }
1365