main.c revision 102843
1/*
2 *    Copyright (c) 1992, Brian Berliner and Jeff Polk
3 *    Copyright (c) 1989-1992, Brian Berliner
4 *
5 *    You may distribute under the terms of the GNU General Public License
6 *    as specified in the README file that comes with the CVS source distribution.
7 *
8 * This is the main C driver for the CVS system.
9 *
10 * Credit to Dick Grune, Vrije Universiteit, Amsterdam, for writing
11 * the shell-script CVS system that this is based on.
12 *
13 * $FreeBSD: head/contrib/cvs/src/main.c 102843 2002-09-02 05:57:14Z peter $
14 */
15
16#include <assert.h>
17#include "cvs.h"
18#include "prepend_args.h"
19
20#ifdef HAVE_WINSOCK_H
21#include <winsock.h>
22#else
23extern int gethostname ();
24#endif
25
26char *program_name;
27char *program_path;
28char *command_name;
29
30/* I'd dynamically allocate this, but it seems like gethostname
31   requires a fixed size array.  If I'm remembering the RFCs right,
32   256 should be enough.  */
33#ifndef MAXHOSTNAMELEN
34#define MAXHOSTNAMELEN  256
35#endif
36
37char hostname[MAXHOSTNAMELEN];
38
39int use_editor = 1;
40int use_cvsrc = 1;
41int cvswrite = !CVSREAD_DFLT;
42int really_quiet = 0;
43int quiet = 0;
44int trace = 0;
45int noexec = 0;
46int readonlyfs = 0;
47int require_real_user = 0;
48int logoff = 0;
49
50/* Set if we should be writing CVSADM directories at top level.  At
51   least for now we'll make the default be off (the CVS 1.9, not CVS
52   1.9.2, behavior). */
53int top_level_admin = 0;
54
55mode_t cvsumask = UMASK_DFLT;
56
57char *CurDir;
58
59/*
60 * Defaults, for the environment variables that are not set
61 */
62char *Tmpdir = TMPDIR_DFLT;
63char *Editor = EDITOR_DFLT;
64
65
66/* When our working directory contains subdirectories with different
67   values in CVS/Root files, we maintain a list of them.  */
68List *root_directories = NULL;
69
70/* We step through the above values.  This variable is set to reflect
71 * the currently active value.
72 *
73 * Now static.  FIXME - this variable should be removable (well, localizable)
74 * with a little more work.
75 */
76static char *current_root = NULL;
77
78
79static const struct cmd
80{
81    char *fullname;		/* Full name of the function (e.g. "commit") */
82
83    /* Synonyms for the command, nick1 and nick2.  We supply them
84       mostly for two reasons: (1) CVS has always supported them, and
85       we need to maintain compatibility, (2) if there is a need for a
86       version which is shorter than the fullname, for ease in typing.
87       Synonyms have the disadvantage that people will see "new" and
88       then have to think about it, or look it up, to realize that is
89       the operation they know as "add".  Also, this means that one
90       cannot create a command "cvs new" with a different meaning.  So
91       new synonyms are probably best used sparingly, and where used
92       should be abbreviations of the fullname (preferably consisting
93       of the first 2 or 3 or so letters).
94
95       One thing that some systems do is to recognize any unique
96       abbreviation, for example "annotat" "annota", etc., for
97       "annotate".  The problem with this is that scripts and user
98       habits will expect a certain abbreviation to be unique, and in
99       a future release of CVS it may not be.  So it is better to
100       accept only an explicit list of abbreviations and plan on
101       supporting them in the future as well as now.  */
102
103    char *nick1;
104    char *nick2;
105
106    int (*func) ();		/* Function takes (argc, argv) arguments. */
107    unsigned long attr;		/* Attributes. */
108} cmds[] =
109
110{
111    { "add",      "ad",       "new",       add,       CVS_CMD_MODIFIES_REPOSITORY | CVS_CMD_USES_WORK_DIR },
112    { "admin",    "adm",      "rcs",       admin,     CVS_CMD_MODIFIES_REPOSITORY | CVS_CMD_USES_WORK_DIR },
113    { "annotate", "ann",      NULL,        annotate,  CVS_CMD_USES_WORK_DIR },
114    { "checkout", "co",       "get",       checkout,  0 },
115    { "commit",   "ci",       "com",       commit,    CVS_CMD_MODIFIES_REPOSITORY | CVS_CMD_USES_WORK_DIR },
116    { "diff",     "di",       "dif",       diff,      CVS_CMD_USES_WORK_DIR },
117    { "edit",     NULL,       NULL,        edit,      CVS_CMD_MODIFIES_REPOSITORY | CVS_CMD_USES_WORK_DIR },
118    { "editors",  NULL,       NULL,        editors,   CVS_CMD_USES_WORK_DIR },
119    { "export",   "exp",      "ex",        checkout,  CVS_CMD_USES_WORK_DIR },
120    { "history",  "hi",       "his",       history,   CVS_CMD_USES_WORK_DIR },
121    { "import",   "im",       "imp",       import,    CVS_CMD_MODIFIES_REPOSITORY | CVS_CMD_USES_WORK_DIR | CVS_CMD_IGNORE_ADMROOT},
122    { "init",     NULL,       NULL,        init,      CVS_CMD_MODIFIES_REPOSITORY },
123#if defined (HAVE_KERBEROS) && defined (SERVER_SUPPORT)
124    { "kserver",  NULL,       NULL,        server,    CVS_CMD_MODIFIES_REPOSITORY | CVS_CMD_USES_WORK_DIR }, /* placeholder */
125#endif
126    { "log",      "lo",       NULL,        cvslog,    CVS_CMD_USES_WORK_DIR },
127#ifdef AUTH_CLIENT_SUPPORT
128    { "login",    "logon",    "lgn",       login,     0 },
129    { "logout",   NULL,       NULL,        logout,    0 },
130#endif /* AUTH_CLIENT_SUPPORT */
131#if (defined(AUTH_SERVER_SUPPORT) || defined (HAVE_GSSAPI)) && defined(SERVER_SUPPORT)
132    { "pserver",  NULL,       NULL,        server,    CVS_CMD_MODIFIES_REPOSITORY | CVS_CMD_USES_WORK_DIR }, /* placeholder */
133#endif
134    { "rannotate","rann",     "ra",        annotate,  0 },
135    { "rdiff",    "patch",    "pa",        patch,     0 },
136    { "release",  "re",       "rel",       release,   0 },
137    { "remove",   "rm",       "delete",    cvsremove, CVS_CMD_MODIFIES_REPOSITORY | CVS_CMD_USES_WORK_DIR },
138    { "rlog",     "rl",       NULL,        cvslog,    0 },
139    { "rtag",     "rt",       "rfreeze",   cvstag,    CVS_CMD_MODIFIES_REPOSITORY },
140#ifdef SERVER_SUPPORT
141    { "server",   NULL,       NULL,        server,    CVS_CMD_MODIFIES_REPOSITORY | CVS_CMD_USES_WORK_DIR },
142#endif
143    { "status",   "st",       "stat",      cvsstatus, CVS_CMD_USES_WORK_DIR },
144    { "tag",      "ta",       "freeze",    cvstag,    CVS_CMD_MODIFIES_REPOSITORY | CVS_CMD_USES_WORK_DIR },
145    { "unedit",   NULL,       NULL,        unedit,    CVS_CMD_MODIFIES_REPOSITORY | CVS_CMD_USES_WORK_DIR },
146    { "update",   "up",       "upd",       update,    CVS_CMD_USES_WORK_DIR },
147    { "version",  "ve",       "ver",       version,   0 },
148    { "watch",    NULL,       NULL,        watch,     CVS_CMD_MODIFIES_REPOSITORY | CVS_CMD_USES_WORK_DIR },
149    { "watchers", NULL,       NULL,        watchers,  CVS_CMD_USES_WORK_DIR },
150    { NULL, NULL, NULL, NULL, 0 },
151};
152
153static const char *const usg[] =
154{
155    /* CVS usage messages never have followed the GNU convention of
156       putting metavariables in uppercase.  I don't know whether that
157       is a good convention or not, but if it changes it would have to
158       change in all the usage messages.  For now, they consistently
159       use lowercase, as far as I know.  Punctuation is pretty funky,
160       though.  Sometimes they use none, as here.  Sometimes they use
161       single quotes (not the TeX-ish `' stuff), as in --help-options.
162       Sometimes they use double quotes, as in cvs -H add.
163
164       Most (not all) of the usage messages seem to have periods at
165       the end of each line.  I haven't tried to duplicate this style
166       in --help as it is a rather different format from the rest.  */
167
168    "Usage: %s [cvs-options] command [command-options-and-arguments]\n",
169    "  where cvs-options are -q, -n, etc.\n",
170    "    (specify --help-options for a list of options)\n",
171    "  where command is add, admin, etc.\n",
172    "    (specify --help-commands for a list of commands\n",
173    "     or --help-synonyms for a list of command synonyms)\n",
174    "  where command-options-and-arguments depend on the specific command\n",
175    "    (specify -H followed by a command name for command-specific help)\n",
176    "  Specify --help to receive this message\n",
177    "\n",
178
179    /* Some people think that a bug-reporting address should go here.  IMHO,
180       the web sites are better because anything else is very likely to go
181       obsolete in the years between a release and when someone might be
182       reading this help.  Besides, we could never adequately discuss
183       bug reporting in a concise enough way to put in a help message.  */
184
185    /* I was going to put this at the top, but usage() wants the %s to
186       be in the first line.  */
187    "The Concurrent Versions System (CVS) is a tool for version control.\n",
188    /* I really don't think I want to try to define "version control"
189       in one line.  I'm not sure one can get more concise than the
190       paragraph in ../cvs.spec without assuming the reader knows what
191       version control means.  */
192
193    "For CVS updates and additional information, see\n",
194    "    the CVS home page at http://www.cvshome.org/ or\n",
195    "    Pascal Molli's CVS site at http://www.loria.fr/~molli/cvs-index.html\n",
196    NULL,
197};
198
199static const char *const cmd_usage[] =
200{
201    "CVS commands are:\n",
202    "        add          Add a new file/directory to the repository\n",
203    "        admin        Administration front end for rcs\n",
204    "        annotate     Show last revision where each line was modified\n",
205    "        checkout     Checkout sources for editing\n",
206    "        commit       Check files into the repository\n",
207    "        diff         Show differences between revisions\n",
208    "        edit         Get ready to edit a watched file\n",
209    "        editors      See who is editing a watched file\n",
210    "        export       Export sources from CVS, similar to checkout\n",
211    "        history      Show repository access history\n",
212    "        import       Import sources into CVS, using vendor branches\n",
213    "        init         Create a CVS repository if it doesn't exist\n",
214#if defined (HAVE_KERBEROS) && defined (SERVER_SUPPORT)
215    "        kserver      Kerberos server mode\n",
216#endif
217    "        log          Print out history information for files\n",
218#ifdef AUTH_CLIENT_SUPPORT
219    "        login        Prompt for password for authenticating server\n",
220    "        logout       Removes entry in .cvspass for remote repository\n",
221#endif /* AUTH_CLIENT_SUPPORT */
222#if (defined(AUTH_SERVER_SUPPORT) || defined (HAVE_GSSAPI)) && defined(SERVER_SUPPORT)
223    "        pserver      Password server mode\n",
224#endif
225    "        rannotate    Show last revision where each line of module was modified\n",
226    "        rdiff        Create 'patch' format diffs between releases\n",
227    "        release      Indicate that a Module is no longer in use\n",
228    "        remove       Remove an entry from the repository\n",
229    "        rlog         Print out history information for a module\n",
230    "        rtag         Add a symbolic tag to a module\n",
231#ifdef SERVER_SUPPORT
232    "        server       Server mode\n",
233#endif
234    "        status       Display status information on checked out files\n",
235    "        tag          Add a symbolic tag to checked out version of files\n",
236    "        unedit       Undo an edit command\n",
237    "        update       Bring work tree in sync with repository\n",
238    "        version      Show current CVS version(s)\n",
239    "        watch        Set watches\n",
240    "        watchers     See who is watching a file\n",
241    "(Specify the --help option for a list of other help options)\n",
242    NULL,
243};
244
245static const char *const opt_usage[] =
246{
247    /* Omit -b because it is just for compatibility.  */
248    "CVS global options (specified before the command name) are:\n",
249    "    -H           Displays usage information for command.\n",
250    "    -Q           Cause CVS to be really quiet.\n",
251    "    -q           Cause CVS to be somewhat quiet.\n",
252    "    -r           Make checked-out files read-only.\n",
253    "    -w           Make checked-out files read-write (default).\n",
254    "    -g           Force group-write perms on checked-out files.\n",
255    "    -l           Turn history logging off.\n",
256    "    -n           Do not execute anything that will change the disk.\n",
257    "    -t           Show trace of program execution -- try with -n.\n",
258    "    -R           Assume repository is read-only, such as CDROM\n",
259    "    -v           CVS version and copyright.\n",
260    "    -T tmpdir    Use 'tmpdir' for temporary files.\n",
261    "    -e editor    Use 'editor' for editing log information.\n",
262    "    -d CVS_root  Overrides $CVSROOT as the root of the CVS tree.\n",
263    "    -f           Do not use the ~/.cvsrc file.\n",
264#ifdef CLIENT_SUPPORT
265    "    -z #         Use compression level '#' for net traffic.\n",
266#ifdef ENCRYPTION
267    "    -x           Encrypt all net traffic.\n",
268#endif
269    "    -a           Authenticate all net traffic.\n",
270#endif
271    "    -s VAR=VAL   Set CVS user variable.\n",
272    "(Specify the --help option for a list of other help options)\n",
273    NULL
274};
275
276
277static int
278set_root_directory (p, ignored)
279    Node *p;
280    void *ignored;
281{
282    if (current_root == NULL && p->data == NULL)
283    {
284	current_root = p->key;
285	return 1;
286    }
287    return 0;
288}
289
290
291static const char * const*
292cmd_synonyms ()
293{
294    char ** synonyms;
295    char ** line;
296    const struct cmd *c = &cmds[0];
297    /* Three more for title, "specify --help" line, and NULL.  */
298    int numcmds = 3;
299
300    while (c->fullname != NULL)
301    {
302	numcmds++;
303	c++;
304    }
305
306    synonyms = (char **) xmalloc(numcmds * sizeof(char *));
307    line = synonyms;
308    *line++ = "CVS command synonyms are:\n";
309    for (c = &cmds[0]; c->fullname != NULL; c++)
310    {
311	if (c->nick1 || c->nick2)
312	{
313	    *line = xmalloc (strlen (c->fullname)
314			     + (c->nick1 != NULL ? strlen (c->nick1) : 0)
315			     + (c->nick2 != NULL ? strlen (c->nick2) : 0)
316			     + 40);
317	    sprintf(*line, "        %-12s %s %s\n", c->fullname,
318		    c->nick1 ? c->nick1 : "",
319		    c->nick2 ? c->nick2 : "");
320	    line++;
321	}
322    }
323    *line++ = "(Specify the --help option for a list of other help options)\n";
324    *line = NULL;
325
326    return (const char * const*) synonyms; /* will never be freed */
327}
328
329
330unsigned long int
331lookup_command_attribute (cmd_name)
332     char *cmd_name;
333{
334    const struct cmd *cm;
335
336    for (cm = cmds; cm->fullname; cm++)
337    {
338	if (strcmp (cmd_name, cm->fullname) == 0)
339	    break;
340    }
341    if (!cm->fullname)
342	error (1, 0, "unknown command: %s", cmd_name);
343    return cm->attr;
344}
345
346
347static RETSIGTYPE
348main_cleanup (sig)
349    int sig;
350{
351#ifndef DONT_USE_SIGNALS
352    const char *name;
353    char temp[10];
354
355    switch (sig)
356    {
357#ifdef SIGABRT
358    case SIGABRT:
359	name = "abort";
360	break;
361#endif
362#ifdef SIGHUP
363    case SIGHUP:
364	name = "hangup";
365	break;
366#endif
367#ifdef SIGINT
368    case SIGINT:
369	name = "interrupt";
370	break;
371#endif
372#ifdef SIGQUIT
373    case SIGQUIT:
374	name = "quit";
375	break;
376#endif
377#ifdef SIGPIPE
378    case SIGPIPE:
379	name = "broken pipe";
380	break;
381#endif
382#ifdef SIGTERM
383    case SIGTERM:
384	name = "termination";
385	break;
386#endif
387    default:
388	/* This case should never be reached, because we list above all
389	   the signals for which we actually establish a signal handler.  */
390	sprintf (temp, "%d", sig);
391	name = temp;
392	break;
393    }
394
395    error (1, 0, "received %s signal", name);
396#endif /* !DONT_USE_SIGNALS */
397}
398
399int
400main (argc, argv)
401    int argc;
402    char **argv;
403{
404    char *CVSroot = CVSROOT_DFLT;
405    char *cp, *end;
406    const struct cmd *cm;
407    int c, err = 0;
408    int tmpdir_update_env, cvs_update_env;
409    int free_CVSroot = 0;
410    int free_Editor = 0;
411    int free_Tmpdir = 0;
412
413    int help = 0;		/* Has the user asked for help?  This
414				   lets us support the `cvs -H cmd'
415				   convention to give help for cmd. */
416    static const char short_options[] = "+QqgrwtnRlvb:T:e:d:Hfz:s:xaU";
417    static struct option long_options[] =
418    {
419        {"help", 0, NULL, 'H'},
420        {"version", 0, NULL, 'v'},
421	{"help-commands", 0, NULL, 1},
422	{"help-synonyms", 0, NULL, 2},
423	{"help-options", 0, NULL, 4},
424	{"allow-root", required_argument, NULL, 3},
425        {0, 0, 0, 0}
426    };
427    /* `getopt_long' stores the option index here, but right now we
428        don't use it. */
429    int option_index = 0;
430
431#ifdef SYSTEM_INITIALIZE
432    /* Hook for OS-specific behavior, for example socket subsystems on
433       NT and OS2 or dealing with windows and arguments on Mac.  */
434    SYSTEM_INITIALIZE (&argc, &argv);
435#endif
436
437#ifdef HAVE_TZSET
438    /* On systems that have tzset (which is almost all the ones I know
439       of), it's a good idea to call it.  */
440    tzset ();
441#endif
442
443    /*
444     * Just save the last component of the path for error messages
445     */
446    program_path = xstrdup (argv[0]);
447#ifdef ARGV0_NOT_PROGRAM_NAME
448    /* On some systems, e.g. VMS, argv[0] is not the name of the command
449       which the user types to invoke the program.  */
450    program_name = "cvs";
451#else
452    program_name = last_component (argv[0]);
453#endif
454
455    /*
456     * Query the environment variables up-front, so that
457     * they can be overridden by command line arguments
458     */
459    cvs_update_env = 0;
460    tmpdir_update_env = *Tmpdir;	/* TMPDIR_DFLT must be set */
461    if ((cp = getenv (TMPDIR_ENV)) != NULL)
462    {
463	Tmpdir = cp;
464	tmpdir_update_env = 0;		/* it's already there */
465    }
466    if ((cp = getenv (EDITOR1_ENV)) != NULL)
467 	Editor = cp;
468    else if ((cp = getenv (EDITOR2_ENV)) != NULL)
469	Editor = cp;
470    else if ((cp = getenv (EDITOR3_ENV)) != NULL)
471	Editor = cp;
472    if ((cp = getenv (CVSROOT_ENV)) != NULL)
473    {
474	CVSroot = cp;
475	cvs_update_env = 0;		/* it's already there */
476    }
477    if (getenv (CVSREAD_ENV) != NULL)
478	cvswrite = 0;
479    if (getenv (CVSREADONLYFS_ENV) != NULL) {
480	readonlyfs = 1;
481	logoff = 1;
482    }
483
484    prepend_default_options (getenv ("CVS_OPTIONS"), &argc, &argv);
485
486    /* Set this to 0 to force getopt initialization.  getopt() sets
487       this to 1 internally.  */
488    optind = 0;
489
490    /* We have to parse the options twice because else there is no
491       chance to avoid reading the global options from ".cvsrc".  Set
492       opterr to 0 for avoiding error messages about invalid options.
493       */
494    opterr = 0;
495
496    while ((c = getopt_long
497            (argc, argv, short_options, long_options, &option_index))
498           != EOF)
499    {
500	if (c == 'f')
501	    use_cvsrc = 0;
502    }
503
504    /*
505     * Scan cvsrc file for global options.
506     */
507    if (use_cvsrc)
508	read_cvsrc (&argc, &argv, "cvs");
509
510    optind = 0;
511    opterr = 1;
512
513    while ((c = getopt_long
514            (argc, argv, short_options, long_options, &option_index))
515           != EOF)
516    {
517	switch (c)
518	{
519            case 1:
520	        /* --help-commands */
521                usage (cmd_usage);
522                break;
523            case 2:
524	        /* --help-synonyms */
525                usage (cmd_synonyms());
526                break;
527	    case 4:
528		/* --help-options */
529		usage (opt_usage);
530		break;
531	    case 3:
532		/* --allow-root */
533		root_allow_add (optarg);
534		break;
535	    case 'Q':
536		really_quiet = 1;
537		/* FALL THROUGH */
538	    case 'q':
539		quiet = 1;
540		break;
541	    case 'r':
542		cvswrite = 0;
543		break;
544	    case 'w':
545		cvswrite = 1;
546		break;
547	    case 'g':
548		/*
549		 * force full group write perms (used for shared checked-out
550		 * source trees, see manual page)
551		 */
552		umask(umask(077) & 007);
553		break;
554	    case 't':
555		trace = 1;
556		break;
557	    case 'R':
558		readonlyfs = 1;
559		logoff = 1;
560		break;
561	    case 'n':
562		noexec = 1;
563	    case 'l':			/* Fall through */
564		logoff = 1;
565		break;
566	    case 'v':
567		(void) fputs ("\n", stdout);
568		version (0, (char **) NULL);
569		(void) fputs ("\n", stdout);
570		(void) fputs ("\
571Copyright (c) 1989-2001 Brian Berliner, david d `zoo' zuhn, \n\
572                        Jeff Polk, and other authors\n", stdout);
573		(void) fputs ("\n", stdout);
574		(void) fputs ("CVS may be copied only under the terms of the GNU General Public License,\n", stdout);
575		(void) fputs ("a copy of which can be found with the CVS distribution kit.\n", stdout);
576		(void) fputs ("\n", stdout);
577
578		(void) fputs ("Specify the --help option for further information about CVS\n", stdout);
579
580		exit (0);
581		break;
582	    case 'b':
583		/* This option used to specify the directory for RCS
584		   executables.  But since we don't run them any more,
585		   this is a noop.  Silently ignore it so that .cvsrc
586		   and scripts and inetd.conf and such can work with
587		   either new or old CVS.  */
588		break;
589	    case 'T':
590		Tmpdir = xstrdup (optarg);
591		free_Tmpdir = 1;
592		tmpdir_update_env = 1;	/* need to update environment */
593		break;
594	    case 'e':
595		Editor = xstrdup (optarg);
596		free_Editor = 1;
597		break;
598	    case 'd':
599		if (CVSroot_cmdline != NULL)
600		    free (CVSroot_cmdline);
601		CVSroot_cmdline = xstrdup (optarg);
602		if (free_CVSroot)
603		    free (CVSroot);
604		CVSroot = xstrdup (optarg);
605		free_CVSroot = 1;
606		cvs_update_env = 1;	/* need to update environment */
607		break;
608	    case 'H':
609	        help = 1;
610		break;
611            case 'f':
612		use_cvsrc = 0; /* unnecessary, since we've done it above */
613		break;
614	    case 'z':
615#ifdef CLIENT_SUPPORT
616		gzip_level = atoi (optarg);
617		if (gzip_level < 0 || gzip_level > 9)
618		  error (1, 0,
619			 "gzip compression level must be between 0 and 9");
620#endif
621		/* If no CLIENT_SUPPORT, we just silently ignore the gzip
622		   level, so that users can have it in their .cvsrc and not
623		   cause any trouble.  */
624		break;
625	    case 's':
626		variable_set (optarg);
627		break;
628	    case 'x':
629#ifdef CLIENT_SUPPORT
630	        cvsencrypt = 1;
631#endif /* CLIENT_SUPPORT */
632		/* If no CLIENT_SUPPORT, ignore -x, so that users can
633                   have it in their .cvsrc and not cause any trouble.
634                   If no ENCRYPTION, we still accept -x, but issue an
635                   error if we are being run as a client.  */
636		break;
637	    case 'a':
638#ifdef CLIENT_SUPPORT
639		cvsauthenticate = 1;
640#endif
641		/* If no CLIENT_SUPPORT, ignore -a, so that users can
642                   have it in their .cvsrc and not cause any trouble.
643                   We will issue an error later if stream
644                   authentication is not supported.  */
645		break;
646	    case 'U':
647#ifdef SERVER_SUPPORT
648		require_real_user = 1;
649#endif
650		break;
651	    case '?':
652	    default:
653                usage (usg);
654	}
655    }
656
657    argc -= optind;
658    argv += optind;
659    if (argc < 1)
660	usage (usg);
661
662
663    /* Look up the command name. */
664
665    command_name = argv[0];
666    for (cm = cmds; cm->fullname; cm++)
667    {
668	if (cm->nick1 && !strcmp (command_name, cm->nick1))
669	    break;
670	if (cm->nick2 && !strcmp (command_name, cm->nick2))
671	    break;
672	if (!strcmp (command_name, cm->fullname))
673	    break;
674    }
675
676    if (!cm->fullname)
677    {
678	fprintf (stderr, "Unknown command: `%s'\n\n", command_name);
679	usage (cmd_usage);
680    }
681    else
682	command_name = cm->fullname;	/* Global pointer for later use */
683
684    if (help)
685    {
686	argc = -1;		/* some functions only check for this */
687	err = (*(cm->func)) (argc, argv);
688    }
689    else
690    {
691	/* The user didn't ask for help, so go ahead and authenticate,
692           set up CVSROOT, and the rest of it. */
693
694	/* The UMASK environment variable isn't handled with the
695	   others above, since we don't want to signal errors if the
696	   user has asked for help.  This won't work if somebody adds
697	   a command-line flag to set the umask, since we'll have to
698	   parse it before we get here. */
699
700	if ((cp = getenv (CVSUMASK_ENV)) != NULL)
701	{
702	    /* FIXME: Should be accepting symbolic as well as numeric mask.  */
703	    cvsumask = strtol (cp, &end, 8) & 0777;
704	    if (*end != '\0')
705		error (1, errno, "invalid umask value in %s (%s)",
706		       CVSUMASK_ENV, cp);
707	}
708
709#if defined (HAVE_KERBEROS) && defined (SERVER_SUPPORT)
710	/* If we are invoked with a single argument "kserver", then we are
711	   running as Kerberos server as root.  Do the authentication as
712	   the very first thing, to minimize the amount of time we are
713	   running as root.  */
714	if (strcmp (command_name, "kserver") == 0)
715	{
716	    kserver_authenticate_connection ();
717
718	    /* Pretend we were invoked as a plain server.  */
719	    command_name = "server";
720	}
721#endif /* HAVE_KERBEROS */
722
723
724#if (defined(AUTH_SERVER_SUPPORT) || defined (HAVE_GSSAPI)) && defined(SERVER_SUPPORT)
725	if (strcmp (command_name, "pserver") == 0)
726	{
727	    /* The reason that --allow-root is not a command option
728	       is mainly the comment in server() about how argc,argv
729	       might be from .cvsrc.  I'm not sure about that, and
730	       I'm not sure it is only true of command options, but
731	       it seems easier to make it a global option.  */
732
733	    /* Gets username and password from client, authenticates, then
734	       switches to run as that user and sends an ACK back to the
735	       client. */
736	    pserver_authenticate_connection ();
737
738	    /* Pretend we were invoked as a plain server.  */
739	    command_name = "server";
740	}
741#endif /* (AUTH_SERVER_SUPPORT || HAVE_GSSAPI) && SERVER_SUPPORT */
742
743#ifdef SERVER_SUPPORT
744	server_active = strcmp (command_name, "server") == 0;
745#endif
746
747	/* This is only used for writing into the history file.  For
748	   remote connections, it might be nice to have hostname
749	   and/or remote path, on the other hand I'm not sure whether
750	   it is worth the trouble.  */
751
752#ifdef SERVER_SUPPORT
753	if (server_active)
754	    CurDir = xstrdup ("<remote>");
755	else
756#endif
757	{
758	    CurDir = xgetwd ();
759            if (CurDir == NULL)
760		error (1, errno, "cannot get working directory");
761	}
762
763	if (Tmpdir == NULL || Tmpdir[0] == '\0')
764	    Tmpdir = "/tmp";
765
766#ifdef HAVE_PUTENV
767	if (tmpdir_update_env)
768	{
769	    char *env;
770	    env = xmalloc (strlen (TMPDIR_ENV) + strlen (Tmpdir) + 1 + 1);
771	    (void) sprintf (env, "%s=%s", TMPDIR_ENV, Tmpdir);
772	    (void) putenv (env);
773	    /* do not free env, as putenv has control of it */
774	}
775	{
776	    char *env;
777	    env = xmalloc (sizeof "CVS_PID=" + 32); /* XXX pid < 10^32 */
778	    (void) sprintf (env, "CVS_PID=%ld", (long) getpid ());
779	    (void) putenv (env);
780	}
781#endif
782
783#ifndef DONT_USE_SIGNALS
784	/* make sure we clean up on error */
785#ifdef SIGABRT
786	(void) SIG_register (SIGABRT, main_cleanup);
787#endif
788#ifdef SIGHUP
789	(void) SIG_register (SIGHUP, main_cleanup);
790#endif
791#ifdef SIGINT
792	(void) SIG_register (SIGINT, main_cleanup);
793#endif
794#ifdef SIGQUIT
795	(void) SIG_register (SIGQUIT, main_cleanup);
796#endif
797#ifdef SIGPIPE
798	(void) SIG_register (SIGPIPE, main_cleanup);
799#endif
800#ifdef SIGTERM
801	(void) SIG_register (SIGTERM, main_cleanup);
802#endif
803#endif /* !DONT_USE_SIGNALS */
804
805	gethostname(hostname, sizeof (hostname));
806
807#ifdef KLUDGE_FOR_WNT_TESTSUITE
808	/* Probably the need for this will go away at some point once
809	   we call fflush enough places (e.g. fflush (stdout) in
810	   cvs_outerr).  */
811	(void) setvbuf (stdout, (char *) NULL, _IONBF, 0);
812	(void) setvbuf (stderr, (char *) NULL, _IONBF, 0);
813#endif /* KLUDGE_FOR_WNT_TESTSUITE */
814
815	if (use_cvsrc)
816	    read_cvsrc (&argc, &argv, command_name);
817
818#ifdef SERVER_SUPPORT
819	/* Fiddling with CVSROOT doesn't make sense if we're running
820	       in server mode, since the client will send the repository
821	       directory after the connection is made. */
822
823	if (!server_active)
824#endif
825	{
826	    char *CVSADM_Root;
827
828	    /* See if we are able to find a 'better' value for CVSroot
829	       in the CVSADM_ROOT directory. */
830
831	    CVSADM_Root = NULL;
832
833	    /* "cvs import" shouldn't check CVS/Root; in general it
834	       ignores CVS directories and CVS/Root is likely to
835	       specify a different repository than the one we are
836	       importing to.  */
837
838	    if (!(cm->attr & CVS_CMD_IGNORE_ADMROOT)
839
840		/* -d overrides CVS/Root, so don't give an error if the
841		   latter points to a nonexistent repository.  */
842		&& CVSroot_cmdline == NULL)
843	    {
844		CVSADM_Root = Name_Root((char *) NULL, (char *) NULL);
845	    }
846
847	    if (CVSADM_Root != NULL)
848	    {
849		if (CVSroot == NULL || !cvs_update_env)
850		{
851		    CVSroot = CVSADM_Root;
852		    cvs_update_env = 1;	/* need to update environment */
853		}
854	    }
855
856	    /* Now we've reconciled CVSROOT from the command line, the
857	       CVS/Root file, and the environment variable.  Do the
858	       last sanity checks on the variable. */
859
860	    if (! CVSroot)
861	    {
862		error (0, 0,
863		       "No CVSROOT specified!  Please use the `-d' option");
864		error (1, 0,
865		       "or set the %s environment variable.", CVSROOT_ENV);
866	    }
867
868	    if (! *CVSroot)
869	    {
870		error (0, 0,
871		       "CVSROOT is set but empty!  Make sure that the");
872		error (0, 0,
873		       "specification of CVSROOT is valid, either via the");
874		error (0, 0,
875		       "`-d' option, the %s environment variable, or the",
876		       CVSROOT_ENV);
877		error (1, 0,
878		       "CVS/Root file (if any).");
879	    }
880	}
881
882	/* Here begins the big loop over unique cvsroot values.  We
883           need to call do_recursion once for each unique value found
884           in CVS/Root.  Prime the list with the current value. */
885
886	/* Create the list. */
887	assert (root_directories == NULL);
888	root_directories = getlist ();
889
890	/* Prime it. */
891	if (CVSroot != NULL)
892	{
893	    Node *n;
894	    n = getnode ();
895	    n->type = NT_UNKNOWN;
896	    n->key = xstrdup (CVSroot);
897	    n->data = NULL;
898
899	    if (addnode (root_directories, n))
900		error (1, 0, "cannot add initial CVSROOT %s", n->key);
901	}
902
903	assert (current_root == NULL);
904
905	/* If we're running the server, we want to execute this main
906	   loop once and only once (we won't be serving multiple roots
907	   from this connection, so there's no need to do it more than
908	   once).  To get out of the loop, we perform a "break" at the
909	   end of things.  */
910
911	while (
912#ifdef SERVER_SUPPORT
913	       server_active ||
914#endif
915	       walklist (root_directories, set_root_directory, NULL)
916	       )
917	{
918#ifdef SERVER_SUPPORT
919	    /* Fiddling with CVSROOT doesn't make sense if we're running
920	       in server mode, since the client will send the repository
921	       directory after the connection is made. */
922
923	    if (!server_active)
924#endif
925	    {
926		/* Now we're 100% sure that we have a valid CVSROOT
927		   variable.  Parse it to see if we're supposed to do
928		   remote accesses or use a special access method. */
929
930		if (current_parsed_root != NULL)
931		    free_cvsroot_t (current_parsed_root);
932		if ((current_parsed_root = parse_cvsroot (current_root)) == NULL)
933		    error (1, 0, "Bad CVSROOT: `%s'.", current_root);
934
935		if (trace)
936		    fprintf (stderr, "%s-> main loop with CVSROOT=%s\n",
937			   CLIENT_SERVER_STR, current_root);
938
939		/*
940		 * Check to see if the repository exists.
941		 */
942#ifdef CLIENT_SUPPORT
943		if (!current_parsed_root->isremote)
944#endif	/* CLIENT_SUPPORT */
945		{
946		    char *path;
947		    int save_errno;
948
949		    path = xmalloc (strlen (current_parsed_root->directory)
950				    + sizeof (CVSROOTADM)
951				    + 2);
952		    (void) sprintf (path, "%s/%s", current_parsed_root->directory, CVSROOTADM);
953		    if (!isaccessible (path, R_OK | X_OK))
954		    {
955			save_errno = errno;
956			/* If this is "cvs init", the root need not exist yet.  */
957			if (strcmp (command_name, "init") != 0)
958			{
959			    error (1, save_errno, "%s", path);
960			}
961		    }
962		    free (path);
963		}
964
965#ifdef HAVE_PUTENV
966		/* Update the CVSROOT environment variable if necessary. */
967		/* FIXME (njc): should we always set this with the CVSROOT from the command line? */
968		if (cvs_update_env)
969		{
970		    static char *prev;
971		    char *env;
972		    env = xmalloc (strlen (CVSROOT_ENV) + strlen (CVSroot)
973				   + 1 + 1);
974		    (void) sprintf (env, "%s=%s", CVSROOT_ENV, CVSroot);
975		    (void) putenv (env);
976		    /* do not free env yet, as putenv has control of it */
977		    /* but do free the previous value, if any */
978		    if (prev != NULL)
979			free (prev);
980		    prev = env;
981		}
982#endif
983	    }
984
985	    /* Parse the CVSROOT/config file, but only for local.  For the
986	       server, we parse it after we know $CVSROOT.  For the
987	       client, it doesn't get parsed at all, obviously.  The
988	       presence of the parse_config call here is not mean to
989	       predetermine whether CVSROOT/config overrides things from
990	       read_cvsrc and other such places or vice versa.  That sort
991	       of thing probably needs more thought.  */
992	    if (1
993#ifdef SERVER_SUPPORT
994		&& !server_active
995#endif
996#ifdef CLIENT_SUPPORT
997		&& !current_parsed_root->isremote
998#endif
999		)
1000	    {
1001		/* If there was an error parsing the config file, parse_config
1002		   already printed an error.  We keep going.  Why?  Because
1003		   if we didn't, then there would be no way to check in a new
1004		   CVSROOT/config file to fix the broken one!  */
1005		parse_config (current_parsed_root->directory);
1006
1007		/* Now is a convenient time to read CVSROOT/options */
1008		parseopts(current_parsed_root->directory);
1009	    }
1010
1011#ifdef CLIENT_SUPPORT
1012	    /* Need to check for current_parsed_root != NULL here since
1013	     * we could still be in server mode before the server function
1014	     * gets called below and sets the root
1015	     */
1016	    if (current_parsed_root != NULL && current_parsed_root->isremote)
1017	    {
1018		/* Create a new list for directory names that we've
1019		   sent to the server. */
1020		if (dirs_sent_to_server != NULL)
1021		    dellist (&dirs_sent_to_server);
1022		dirs_sent_to_server = getlist ();
1023	    }
1024#endif
1025
1026	    err = (*(cm->func)) (argc, argv);
1027
1028	    /* Mark this root directory as done.  When the server is
1029               active, current_root will be NULL -- don't try and
1030               remove it from the list. */
1031
1032	    if (current_root != NULL)
1033	    {
1034		Node *n = findnode (root_directories, current_root);
1035		assert (n != NULL);
1036		n->data = (void *) 1;
1037		current_root = NULL;
1038	    }
1039
1040#if 0
1041	    /* This will not work yet, since it tries to free (void *) 1. */
1042	    dellist (&root_directories);
1043#endif
1044
1045#ifdef SERVER_SUPPORT
1046	    if (server_active)
1047	      break;
1048#endif
1049	} /* end of loop for cvsroot values */
1050
1051    } /* end of stuff that gets done if the user DOESN'T ask for help */
1052
1053    Lock_Cleanup ();
1054
1055    free (program_path);
1056    if (CVSroot_cmdline != NULL)
1057	free (CVSroot_cmdline);
1058    if (free_CVSroot)
1059	free (CVSroot);
1060    if (free_Editor)
1061	free (Editor);
1062    if (free_Tmpdir)
1063	free (Tmpdir);
1064    root_allow_free ();
1065
1066#ifdef SYSTEM_CLEANUP
1067    /* Hook for OS-specific behavior, for example socket subsystems on
1068       NT and OS2 or dealing with windows and arguments on Mac.  */
1069    SYSTEM_CLEANUP ();
1070#endif
1071
1072    /* This is exit rather than return because apparently that keeps
1073       some tools which check for memory leaks happier.  */
1074    exit (err ? EXIT_FAILURE : 0);
1075	/* Keep picky/stupid compilers (e.g. Visual C++ 5.0) happy.  */
1076	return 0;
1077}
1078
1079char *
1080Make_Date (rawdate)
1081    char *rawdate;
1082{
1083    time_t unixtime;
1084
1085    unixtime = get_date (rawdate, (struct timeb *) NULL);
1086    if (unixtime == (time_t) - 1)
1087	error (1, 0, "Can't parse date/time: %s", rawdate);
1088    return date_from_time_t (unixtime);
1089}
1090
1091/* Convert a time_t to an RCS format date.  This is mainly for the
1092   use of "cvs history", because the CVSROOT/history file contains
1093   time_t format dates; most parts of CVS will want to avoid using
1094   time_t's directly, and instead use RCS_datecmp, Make_Date, &c.
1095   Assuming that the time_t is in GMT (as it generally should be),
1096   then the result will be in GMT too.
1097
1098   Returns a newly malloc'd string.  */
1099
1100char *
1101date_from_time_t (unixtime)
1102    time_t unixtime;
1103{
1104    struct tm *ftm;
1105    char date[MAXDATELEN];
1106    char *ret;
1107
1108    ftm = gmtime (&unixtime);
1109    if (ftm == NULL)
1110	/* This is a system, like VMS, where the system clock is in local
1111	   time.  Hopefully using localtime here matches the "zero timezone"
1112	   hack I added to get_date (get_date of course being the relevant
1113	   issue for Make_Date, and for history.c too I think).  */
1114	ftm = localtime (&unixtime);
1115
1116    (void) sprintf (date, DATEFORM,
1117		    ftm->tm_year + (ftm->tm_year < 100 ? 0 : 1900),
1118		    ftm->tm_mon + 1, ftm->tm_mday, ftm->tm_hour,
1119		    ftm->tm_min, ftm->tm_sec);
1120    ret = xstrdup (date);
1121    return (ret);
1122}
1123
1124/* Convert a date to RFC822/1123 format.  This is used in contexts like
1125   dates to send in the protocol; it should not vary based on locale or
1126   other such conventions for users.  We should have another routine which
1127   does that kind of thing.
1128
1129   The SOURCE date is in our internal RCS format.  DEST should point to
1130   storage managed by the caller, at least MAXDATELEN characters.  */
1131void
1132date_to_internet (dest, source)
1133    char *dest;
1134    const char *source;
1135{
1136    struct tm date;
1137
1138    date_to_tm (&date, source);
1139    tm_to_internet (dest, &date);
1140}
1141
1142void
1143date_to_tm (dest, source)
1144    struct tm *dest;
1145    const char *source;
1146{
1147    if (sscanf (source, SDATEFORM,
1148		&dest->tm_year, &dest->tm_mon, &dest->tm_mday,
1149		&dest->tm_hour, &dest->tm_min, &dest->tm_sec)
1150	    != 6)
1151	/* Is there a better way to handle errors here?  I made this
1152	   non-fatal in case we are called from the code which can't
1153	   deal with fatal errors.  */
1154	error (0, 0, "internal error: bad date %s", source);
1155
1156    if (dest->tm_year > 100)
1157	dest->tm_year -= 1900;
1158
1159    dest->tm_mon -= 1;
1160}
1161
1162/* Convert a date to RFC822/1123 format.  This is used in contexts like
1163   dates to send in the protocol; it should not vary based on locale or
1164   other such conventions for users.  We should have another routine which
1165   does that kind of thing.
1166
1167   The SOURCE date is a pointer to a struct tm.  DEST should point to
1168   storage managed by the caller, at least MAXDATELEN characters.  */
1169void
1170tm_to_internet (dest, source)
1171    char *dest;
1172    const struct tm *source;
1173{
1174    /* Just to reiterate, these strings are from RFC822 and do not vary
1175       according to locale.  */
1176    static const char *const month_names[] =
1177      {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
1178	 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
1179
1180    sprintf (dest, "%d %s %d %02d:%02d:%02d -0000", source->tm_mday,
1181	     source->tm_mon < 0 || source->tm_mon > 11 ? "???" : month_names[source->tm_mon],
1182	     source->tm_year + 1900, source->tm_hour, source->tm_min, source->tm_sec);
1183}
1184
1185void
1186usage (cpp)
1187    register const char *const *cpp;
1188{
1189    (void) fprintf (stderr, *cpp++, program_name, command_name);
1190    for (; *cpp; cpp++)
1191	(void) fprintf (stderr, *cpp);
1192    error_exit ();
1193}
1194
1195void
1196parseopts(root)
1197    const char *root;
1198{
1199    char path[PATH_MAX];
1200    int save_errno;
1201    char buf[1024];
1202    const char *p;
1203    char *q;
1204    FILE *fp;
1205
1206    if (root == NULL) {
1207	printf("no CVSROOT in parseopts\n");
1208	return;
1209    }
1210    p = strchr (root, ':');
1211    if (p)
1212	p++;
1213    else
1214	p = root;
1215    if (p == NULL) {
1216	printf("mangled CVSROOT in parseopts\n");
1217	return;
1218    }
1219    (void) sprintf (path, "%s/%s/%s", p, CVSROOTADM, CVSROOTADM_OPTIONS);
1220    if ((fp = fopen(path, "r")) != NULL) {
1221	while (fgets(buf, sizeof buf, fp) != NULL) {
1222	    if (buf[0] == '#')
1223		continue;
1224	    q = strrchr(buf, '\n');
1225	    if (q)
1226		*q = '\0';
1227
1228	    if (!strncmp(buf, "tag=", 4)) {
1229		char *what;
1230		char *rcs_localid;
1231
1232		rcs_localid = buf + 4;
1233		RCS_setlocalid(rcs_localid);
1234	    }
1235	    if (!strncmp(buf, "tagexpand=", 10)) {
1236		char *what;
1237		char *rcs_incexc;
1238
1239		rcs_incexc = buf + 10;
1240		RCS_setincexc(rcs_incexc);
1241	    }
1242	    /*
1243	     * OpenBSD has a "umask=" and "dlimit=" command, we silently
1244	     * ignore them here since they are not much use to us.  cvsumask
1245	     * defaults to 002 already, and the dlimit (data size limit)
1246	     * should really be handled elsewhere (eg: login.conf).
1247	     */
1248	}
1249	fclose(fp);
1250    }
1251}
1252