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