xref: /dragonfly/contrib/cvs-1.12/src/root.c (revision 1847e88f)
1 /*
2  * Copyright (C) 1986-2005 The Free Software Foundation, Inc.
3  *
4  * Portions Copyright (C) 1998-2005 Derek Price, Ximbiot <http://ximbiot.com>,
5  *                                  and others.
6  *
7  * Poritons Copyright (c) 1992, Mark D. Baushke
8  *
9  * You may distribute under the terms of the GNU General Public License as
10  * specified in the README file that comes with the CVS source distribution.
11  *
12  * Name of Root
13  *
14  * Determine the path to the CVSROOT and set "Root" accordingly.
15  */
16 
17 #include "cvs.h"
18 #include <assert.h>
19 #include "getline.h"
20 
21 /* Printable names for things in the current_parsed_root->method enum variable.
22    Watch out if the enum is changed in cvs.h! */
23 
24 const char method_names[][16] = {
25     "undefined", "local", "server (rsh)", "pserver",
26     "kserver", "gserver", "ext", "fork"
27 };
28 
29 #ifndef DEBUG
30 
31 cvsroot_t *
32 Name_Root (const char *dir, const char *update_dir)
33 {
34     FILE *fpin;
35     cvsroot_t *ret;
36     const char *xupdate_dir;
37     char *root = NULL;
38     size_t root_allocated = 0;
39     char *tmp;
40     char *cvsadm;
41     char *cp;
42     int len;
43 
44     TRACE (TRACE_FLOW, "Name_Root (%s, %s)",
45 	   dir ? dir : "(null)",
46 	   update_dir ? update_dir : "(null)");
47 
48     if (update_dir && *update_dir)
49 	xupdate_dir = update_dir;
50     else
51 	xupdate_dir = ".";
52 
53     if (dir != NULL)
54     {
55 	cvsadm = Xasprintf ("%s/%s", dir, CVSADM);
56 	tmp = Xasprintf ("%s/%s", dir, CVSADM_ROOT);
57     }
58     else
59     {
60 	cvsadm = xstrdup (CVSADM);
61 	tmp = xstrdup (CVSADM_ROOT);
62     }
63 
64     /*
65      * Do not bother looking for a readable file if there is no cvsadm
66      * directory present.
67      *
68      * It is possible that not all repositories will have a CVS/Root
69      * file. This is ok, but the user will need to specify -d
70      * /path/name or have the environment variable CVSROOT set in
71      * order to continue.  */
72     if ((!isdir (cvsadm)) || (!isreadable (tmp)))
73     {
74 	ret = NULL;
75 	goto out;
76     }
77 
78     /*
79      * The assumption here is that the CVS Root is always contained in the
80      * first line of the "Root" file.
81      */
82     fpin = xfopen (tmp, "r");
83 
84     if ((len = getline (&root, &root_allocated, fpin)) < 0)
85     {
86 	int saved_errno = errno;
87 	/* FIXME: should be checking for end of file separately; errno
88 	   is not set in that case.  */
89 	error (0, 0, "in directory %s:", xupdate_dir);
90 	error (0, saved_errno, "cannot read %s", CVSADM_ROOT);
91 	error (0, 0, "please correct this problem");
92 	ret = NULL;
93 	goto out;
94     }
95     fclose (fpin);
96     cp = root + len - 1;
97     if (*cp == '\n')
98 	*cp = '\0';			/* strip the newline */
99 
100     /*
101      * root now contains a candidate for CVSroot. It must be an
102      * absolute pathname or specify a remote server.
103      */
104 
105     ret = parse_cvsroot (root);
106     if (ret == NULL)
107     {
108 	error (0, 0, "in directory %s:", xupdate_dir);
109 	error (0, 0,
110 	       "ignoring %s because it does not contain a valid root.",
111 	       CVSADM_ROOT);
112 	goto out;
113     }
114 
115     if (!ret->isremote && !isdir (ret->directory))
116     {
117 	error (0, 0, "in directory %s:", xupdate_dir);
118 	error (0, 0,
119 	       "ignoring %s because it specifies a non-existent repository %s",
120 	       CVSADM_ROOT, root);
121 	ret = NULL;
122 	goto out;
123     }
124 
125 
126  out:
127     free (cvsadm);
128     free (tmp);
129     if (root != NULL)
130 	free (root);
131     return ret;
132 }
133 
134 
135 
136 /*
137  * Write the CVS/Root file so that the environment variable CVSROOT
138  * and/or the -d option to cvs will be validated or not necessary for
139  * future work.
140  */
141 void
142 Create_Root (const char *dir, const char *rootdir)
143 {
144     FILE *fout;
145     char *tmp;
146 
147     if (noexec)
148 	return;
149 
150     /* record the current cvs root */
151 
152     if (rootdir != NULL)
153     {
154         if (dir != NULL)
155 	    tmp = Xasprintf ("%s/%s", dir, CVSADM_ROOT);
156         else
157 	    tmp = xstrdup (CVSADM_ROOT);
158 
159         fout = xfopen (tmp, "w+");
160         if (fprintf (fout, "%s\n", rootdir) < 0)
161 	    error (1, errno, "write to %s failed", tmp);
162         if (fclose (fout) == EOF)
163 	    error (1, errno, "cannot close %s", tmp);
164 	free (tmp);
165     }
166 }
167 
168 #endif /* ! DEBUG */
169 
170 
171 
172 /* Translate an absolute repository string for a primary server and return it.
173  *
174  * INPUTS
175  *   root_in	The root to be translated.
176  *
177  * RETURNS
178  *   A translated string this function owns, or a pointer to the original
179  *   string passed in if no translation was necessary.
180  *
181  *   If the returned string is the translated one, it may be overwritten
182  *   by the next call to this function.
183  */
184 const char *
185 primary_root_translate (const char *root_in)
186 {
187 #ifdef PROXY_SUPPORT
188     char *translated;
189     static char *previous = NULL;
190     static size_t len;
191 
192     /* This can happen, for instance, during `cvs init'.  */
193     if (!config) return root_in;
194 
195     if (config->PrimaryServer
196         && !strncmp (root_in, config->PrimaryServer->directory,
197 		     strlen (config->PrimaryServer->directory))
198         && (ISSLASH (root_in[strlen (config->PrimaryServer->directory)])
199             || root_in[strlen (config->PrimaryServer->directory)] == '\0')
200        )
201     {
202 	translated =
203 	    Xasnprintf (previous, &len,
204 		        "%s%s", current_parsed_root->directory,
205 	                root_in + strlen (config->PrimaryServer->directory));
206 	if (previous && previous != translated)
207 	    free (previous);
208 	return previous = translated;
209     }
210 #endif
211 
212     /* There is no primary root configured or it didn't match.  */
213     return root_in;
214 }
215 
216 
217 
218 /* Translate a primary root in reverse for PATHNAMEs in responses.
219  *
220  * INPUTS
221  *   root_in	The root to be translated.
222  *
223  * RETURNS
224  *   A translated string this function owns, or a pointer to the original
225  *   string passed in if no translation was necessary.
226  *
227  *   If the returned string is the translated one, it may be overwritten
228  *   by the next call to this function.
229  */
230 const char *
231 primary_root_inverse_translate (const char *root_in)
232 {
233 #ifdef PROXY_SUPPORT
234     char *translated;
235     static char *previous = NULL;
236     static size_t len;
237 
238     /* This can happen, for instance, during `cvs init'.  */
239     if (!config) return root_in;
240 
241     if (config->PrimaryServer
242         && !strncmp (root_in, current_parsed_root->directory,
243 		     strlen (current_parsed_root->directory))
244         && (ISSLASH (root_in[strlen (current_parsed_root->directory)])
245             || root_in[strlen (current_parsed_root->directory)] == '\0')
246        )
247     {
248 	translated =
249 	    Xasnprintf (previous, &len,
250 		        "%s%s", config->PrimaryServer->directory,
251 	                root_in + strlen (current_parsed_root->directory));
252 	if (previous && previous != translated)
253 	    free (previous);
254 	return previous = translated;
255     }
256 #endif
257 
258     /* There is no primary root configured or it didn't match.  */
259     return root_in;
260 }
261 
262 
263 
264 /* The root_allow_* stuff maintains a list of valid CVSROOT
265    directories.  Then we can check against them when a remote user
266    hands us a CVSROOT directory.  */
267 static List *root_allow;
268 
269 static void
270 delconfig (Node *n)
271 {
272     if (n->data) free_config (n->data);
273 }
274 
275 
276 
277 void
278 root_allow_add (const char *arg, const char *configPath)
279 {
280     Node *n;
281 
282     if (!root_allow) root_allow = getlist();
283     n = getnode();
284     n->key = xstrdup (arg);
285     n->data = parse_config (arg, configPath);
286     n->delproc = delconfig;
287     addnode (root_allow, n);
288 }
289 
290 void
291 root_allow_free (void)
292 {
293     dellist (&root_allow);
294 }
295 
296 bool
297 root_allow_ok (const char *arg)
298 {
299     if (!root_allow)
300     {
301 	/* Probably someone upgraded from CVS before 1.9.10 to 1.9.10
302 	   or later without reading the documentation about
303 	   --allow-root.  Printing an error here doesn't disclose any
304 	   particularly useful information to an attacker because a
305 	   CVS server configured in this way won't let *anyone* in.  */
306 
307 	/* Note that we are called from a context where we can spit
308 	   back "error" rather than waiting for the next request which
309 	   expects responses.  */
310 	printf ("\
311 error 0 Server configuration missing --allow-root in inetd.conf\n");
312 	exit (EXIT_FAILURE);
313     }
314 
315     if (findnode (root_allow, arg))
316 	return true;
317     return false;
318 }
319 
320 
321 
322 /* Get a config we stored in response to root_allow.
323  *
324  * RETURNS
325  *   The config associated with ARG.
326  */
327 struct config *
328 get_root_allow_config (const char *arg, const char *configPath)
329 {
330     Node *n;
331 
332     TRACE (TRACE_FUNCTION, "get_root_allow_config (%s)", arg);
333 
334     if (root_allow)
335 	n = findnode (root_allow, arg);
336     else
337 	n = NULL;
338 
339     if (n) return n->data;
340     return parse_config (arg, configPath);
341 }
342 
343 
344 
345 /* This global variable holds the global -d option.  It is NULL if -d
346    was not used, which means that we must get the CVSroot information
347    from the CVSROOT environment variable or from a CVS/Root file.  */
348 char *CVSroot_cmdline;
349 
350 
351 
352 /* FIXME - Deglobalize this. */
353 cvsroot_t *current_parsed_root = NULL;
354 /* Used to save the original root being processed so that we can still find it
355  * in lists and the like after a `Redirect' response.  Also set to mirror
356  * current_parsed_root in server mode so that code which runs on both the
357  * client and server but which wants to use original data on the client can
358  * just always reference the original_parsed_root.
359  */
360 const cvsroot_t *original_parsed_root;
361 
362 
363 /* allocate and initialize a cvsroot_t
364  *
365  * We must initialize the strings to NULL so we know later what we should
366  * free
367  *
368  * Some of the other zeroes remain meaningful as, "never set, use default",
369  * or the like
370  */
371 /* Functions which allocate memory are not pure.  */
372 static cvsroot_t *new_cvsroot_t(void)
373     __attribute__( (__malloc__) );
374 static cvsroot_t *
375 new_cvsroot_t (void)
376 {
377     cvsroot_t *newroot;
378 
379     /* gotta store it somewhere */
380     newroot = xmalloc(sizeof(cvsroot_t));
381 
382     newroot->original = NULL;
383     newroot->directory = NULL;
384     newroot->method = null_method;
385     newroot->isremote = false;
386 #ifdef CLIENT_SUPPORT
387     newroot->username = NULL;
388     newroot->password = NULL;
389     newroot->hostname = NULL;
390     newroot->cvs_rsh = NULL;
391     newroot->cvs_server = NULL;
392     newroot->port = 0;
393     newroot->proxy_hostname = NULL;
394     newroot->proxy_port = 0;
395     newroot->redirect = true;	/* Advertise Redirect support */
396 #endif /* CLIENT_SUPPORT */
397 
398     return newroot;
399 }
400 
401 
402 
403 /* Dispose of a cvsroot_t and its component parts.
404  *
405  * NOTE
406  *  It is dangerous for most code to call this function since parse_cvsroot
407  *  maintains a cache of parsed roots.
408  */
409 static void
410 free_cvsroot_t (cvsroot_t *root)
411 {
412     assert (root);
413     if (root->original != NULL)
414 	free (root->original);
415     if (root->directory != NULL)
416 	free (root->directory);
417 #ifdef CLIENT_SUPPORT
418     if (root->username != NULL)
419 	free (root->username);
420     if (root->password != NULL)
421     {
422 	/* I like to be paranoid */
423 	memset (root->password, 0, strlen (root->password));
424 	free (root->password);
425     }
426     if (root->hostname != NULL)
427 	free (root->hostname);
428     if (root->cvs_rsh != NULL)
429 	free (root->cvs_rsh);
430     if (root->cvs_server != NULL)
431 	free (root->cvs_server);
432     if (root->proxy_hostname != NULL)
433 	free (root->proxy_hostname);
434 #endif /* CLIENT_SUPPORT */
435     free (root);
436 }
437 
438 
439 
440 /*
441  * Parse a CVSROOT string to allocate and return a new cvsroot_t structure.
442  * Valid specifications are:
443  *
444  *	:(gserver|kserver|pserver):[[user][:password]@]host[:[port]]/path
445  *	[:(ext|server):][[user]@]host[:]/path
446  *	[:local:[e:]]/path
447  *	:fork:/path
448  *
449  * INPUTS
450  *	root_in		C String containing the CVSROOT to be parsed.
451  *
452  * RETURNS
453  *	A pointer to a newly allocated cvsroot_t structure upon success and
454  *	NULL upon failure.  The caller should never dispose of this structure,
455  *	as it is stored in a cache, but the caller may rely on it not to
456  *	change.
457  *
458  * NOTES
459  * 	This would have been a lot easier to write in Perl.
460  *
461  *	Would it make sense to reimplement the root and config file parsing
462  *	gunk in Lex/Yacc?
463  *
464  * SEE ALSO
465  * 	free_cvsroot_t()
466  */
467 cvsroot_t *
468 parse_cvsroot (const char *root_in)
469 {
470     cvsroot_t *newroot;			/* the new root to be returned */
471     char *cvsroot_save;			/* what we allocated so we can dispose
472 					 * it when finished */
473     char *cvsroot_copy, *p;		/* temporary pointers for parsing */
474 #if defined(CLIENT_SUPPORT) || defined (SERVER_SUPPORT)
475     char *q;				/* temporary pointer for parsing */
476     char *firstslash;			/* save where the path spec starts
477 					 * while we parse
478 					 * [[user][:password]@]host[:[port]]
479 					 */
480     int check_hostname, no_port, no_password, no_proxy;
481 #endif /* defined(CLIENT_SUPPORT) || defined (SERVER_SUPPORT) */
482     static List *cache = NULL;
483     Node *node;
484 
485     assert (root_in != NULL);
486 
487     /* This message is TRACE_FLOW since this function is called repeatedly by
488      * the recursion routines.
489      */
490     TRACE (TRACE_FLOW, "parse_cvsroot (%s)", root_in);
491 
492     if ((node = findnode (cache, root_in)))
493 	return node->data;
494 
495     assert (root_in);
496 
497     /* allocate some space */
498     newroot = new_cvsroot_t();
499 
500     /* save the original string */
501     newroot->original = xstrdup (root_in);
502 
503     /* and another copy we can munge while parsing */
504     cvsroot_save = cvsroot_copy = xstrdup (root_in);
505 
506     if (*cvsroot_copy == ':')
507     {
508 	char *method = ++cvsroot_copy;
509 
510 	/* Access method specified, as in
511 	 * "cvs -d :(gserver|kserver|pserver):[[user][:password]@]host[:[port]]/path",
512 	 * "cvs -d [:(ext|server):][[user]@]host[:]/path",
513 	 * "cvs -d :local:e:\path",
514 	 * "cvs -d :fork:/path".
515 	 * We need to get past that part of CVSroot before parsing the
516 	 * rest of it.
517 	 */
518 
519 	if (! (p = strchr (method, ':')))
520 	{
521 	    error (0, 0, "No closing `:' on method in CVSROOT.");
522 	    goto error_exit;
523 	}
524 	*p = '\0';
525 	cvsroot_copy = ++p;
526 
527 #if defined (CLIENT_SUPPORT) || defined (SERVER_SUPPORT)
528 	/* Look for method options, for instance, proxy, proxyport.
529 	 * Calling strtok again is saved until after parsing the method.
530 	 */
531 	method = strtok (method, ";");
532 	if (!method)
533 	    /* Could just exit now, but this keeps the error message in sync.
534 	     */
535 	    method = "";
536 #endif /* defined (CLIENT_SUPPORT) || defined (SERVER_SUPPORT) */
537 
538 	/* Now we have an access method -- see if it's valid. */
539 
540 	if (!strcasecmp (method, "local"))
541 	    newroot->method = local_method;
542 	else if (!strcasecmp (method, "pserver"))
543 	    newroot->method = pserver_method;
544 	else if (!strcasecmp (method, "kserver"))
545 	    newroot->method = kserver_method;
546 	else if (!strcasecmp (method, "gserver"))
547 	    newroot->method = gserver_method;
548 	else if (!strcasecmp (method, "server"))
549 	    newroot->method = server_method;
550 	else if (!strcasecmp (method, "ext"))
551 	    newroot->method = ext_method;
552 	else if (!strcasecmp (method, "fork"))
553 	    newroot->method = fork_method;
554 	else
555 	{
556 	    error (0, 0, "Unknown method (`%s') in CVSROOT.", method);
557 	    goto error_exit;
558 	}
559 
560 #if defined (CLIENT_SUPPORT) || defined (SERVER_SUPPORT)
561 	/* Parse the method options, for instance, proxy, proxyport */
562 	while ((p = strtok (NULL, ";")))
563 	{
564 	    char *q = strchr (p, '=');
565 	    if (q == NULL)
566 	    {
567 	        error (0, 0, "Option (`%s') has no argument in CVSROOT.",
568                        p);
569 	        goto error_exit;
570 	    }
571 
572 	    *q++ = '\0';
573 	    TRACE (TRACE_DATA, "CVSROOT option=`%s' value=`%s'", p, q);
574 	    if (!strcasecmp (p, "proxy"))
575 	    {
576 		newroot->proxy_hostname = xstrdup (q);
577 	    }
578 	    else if (!strcasecmp (p, "proxyport"))
579 	    {
580 		char *r = q;
581 		if (*r == '-') r++;
582 		while (*r)
583 		{
584 		    if (!isdigit(*r++))
585 		    {
586 			error (0, 0,
587 "CVSROOT may only specify a positive, non-zero, integer proxy port (not `%s').",
588 			       q);
589 			goto error_exit;
590 		    }
591 		}
592 		if ((newroot->proxy_port = atoi (q)) <= 0)
593 		    error (0, 0,
594 "CVSROOT may only specify a positive, non-zero, integer proxy port (not `%s').",
595 			   q);
596 	    }
597 	    else if (!strcasecmp (p, "CVS_RSH"))
598 	    {
599 		/* override CVS_RSH environment variable */
600 		if (newroot->method == ext_method)
601 		    newroot->cvs_rsh = xstrdup (q);
602 	    }
603 	    else if (!strcasecmp (p, "CVS_SERVER"))
604 	    {
605 		/* override CVS_SERVER environment variable */
606 		if (newroot->method == ext_method
607 		    || newroot->method == fork_method)
608 		    newroot->cvs_server = xstrdup (q);
609 	    }
610 	    else if (!strcasecmp (p, "Redirect"))
611 		readBool ("CVSROOT", "Redirect", q, &newroot->redirect);
612 	    else
613 	    {
614 	        error (0, 0, "Unknown option (`%s') in CVSROOT.", p);
615 	        goto error_exit;
616 	    }
617 	}
618 #endif /* defined (CLIENT_SUPPORT) || defined (SERVER_SUPPORT) */
619     }
620     else
621     {
622 	/* If the method isn't specified, assume EXT_METHOD if the string looks
623 	   like a relative path and LOCAL_METHOD otherwise.  */
624 
625 	newroot->method = ((*cvsroot_copy != '/' && strchr (cvsroot_copy, '/'))
626 			  ? ext_method
627 			  : local_method);
628     }
629 
630     /*
631      * There are a few sanity checks we can do now, only knowing the
632      * method of this root.
633      */
634 
635     newroot->isremote = (newroot->method != local_method);
636 
637 #if defined (CLIENT_SUPPORT) || defined (SERVER_SUPPORT)
638     if (readonlyfs && newroot->isremote)
639 	error (1, 0,
640 "Read-only repository feature unavailable with remote roots (cvsroot = %s)",
641 	       cvsroot_copy);
642 
643     if ((newroot->method != local_method)
644 	&& (newroot->method != fork_method)
645        )
646     {
647 	/* split the string into [[user][:password]@]host[:[port]] & /path
648 	 *
649 	 * this will allow some characters such as '@' & ':' to remain unquoted
650 	 * in the path portion of the spec
651 	 */
652 	if ((p = strchr (cvsroot_copy, '/')) == NULL)
653 	{
654 	    error (0, 0, "CVSROOT requires a path spec:");
655 	    error (0, 0,
656 ":(gserver|kserver|pserver):[[user][:password]@]host[:[port]]/path");
657 	    error (0, 0, "[:(ext|server):][[user]@]host[:]/path");
658 	    goto error_exit;
659 	}
660 	firstslash = p;		/* == NULL if '/' not in string */
661 	*p = '\0';
662 
663 	/* Check to see if there is a username[:password] in the string. */
664 	if ((p = strchr (cvsroot_copy, '@')) != NULL)
665 	{
666 	    *p = '\0';
667 	    /* check for a password */
668 	    if ((q = strchr (cvsroot_copy, ':')) != NULL)
669 	    {
670 		*q = '\0';
671 		newroot->password = xstrdup (++q);
672 		/* Don't check for *newroot->password == '\0' since
673 		 * a user could conceivably wish to specify a blank password
674 		 *
675 		 * (newroot->password == NULL means to use the
676 		 * password from .cvspass)
677 		 */
678 	    }
679 
680 	    /* copy the username */
681 	    if (*cvsroot_copy != '\0')
682 		/* a blank username is impossible, so leave it NULL in that
683 		 * case so we know to use the default username
684 		 */
685 		newroot->username = xstrdup (cvsroot_copy);
686 
687 	    cvsroot_copy = ++p;
688 	}
689 
690 	/* now deal with host[:[port]] */
691 
692 	/* the port */
693 	if ((p = strchr (cvsroot_copy, ':')) != NULL)
694 	{
695 	    *p++ = '\0';
696 	    if (strlen(p))
697 	    {
698 		q = p;
699 		if (*q == '-') q++;
700 		while (*q)
701 		{
702 		    if (!isdigit(*q++))
703 		    {
704 			error (0, 0,
705 "CVSROOT may only specify a positive, non-zero, integer port (not `%s').",
706 				p);
707 			error (0, 0,
708                                "Perhaps you entered a relative pathname?");
709 			goto error_exit;
710 		    }
711 		}
712 		if ((newroot->port = atoi (p)) <= 0)
713 		{
714 		    error (0, 0,
715 "CVSROOT may only specify a positive, non-zero, integer port (not `%s').",
716 			    p);
717 		    error (0, 0, "Perhaps you entered a relative pathname?");
718 		    goto error_exit;
719 		}
720 	    }
721 	}
722 
723 	/* copy host */
724 	if (*cvsroot_copy != '\0')
725 	    /* blank hostnames are invalid, but for now leave the field NULL
726 	     * and catch the error during the sanity checks later
727 	     */
728 	    newroot->hostname = xstrdup (cvsroot_copy);
729 
730 	/* restore the '/' */
731 	cvsroot_copy = firstslash;
732 	*cvsroot_copy = '/';
733     }
734 #endif /* defined(CLIENT_SUPPORT) || defined (SERVER_SUPPORT) */
735 
736     /*
737      * Parse the path for all methods.
738      */
739     /* Here & local_cvsroot() should be the only places this needs to be
740      * called on a CVSROOT now.  cvsroot->original is saved for error messages
741      * and, otherwise, we want no trailing slashes.
742      */
743     Sanitize_Repository_Name (cvsroot_copy);
744     newroot->directory = xstrdup (cvsroot_copy);
745 
746     /*
747      * Do various sanity checks.
748      */
749 
750 #if defined(CLIENT_SUPPORT) || defined (SERVER_SUPPORT)
751     if (newroot->username && ! newroot->hostname)
752     {
753 	error (0, 0, "Missing hostname in CVSROOT.");
754 	goto error_exit;
755     }
756 
757     /* We won't have attempted to parse these without CLIENT_SUPPORT or
758      * SERVER_SUPPORT.
759      */
760     check_hostname = 0;
761     no_password = 1;
762     no_proxy = 1;
763     no_port = 0;
764 #endif /* defined (CLIENT_SUPPORT) || defined (SERVER_SUPPORT) */
765     switch (newroot->method)
766     {
767     case local_method:
768 #if defined(CLIENT_SUPPORT) || defined (SERVER_SUPPORT)
769 	if (newroot->username || newroot->hostname)
770 	{
771 	    error (0, 0, "Can't specify hostname and username in CVSROOT");
772 	    error (0, 0, "when using local access method.");
773 	    goto error_exit;
774 	}
775 #endif /* defined(CLIENT_SUPPORT) || defined (SERVER_SUPPORT) */
776 	/* cvs.texinfo has always told people that CVSROOT must be an
777 	   absolute pathname.  Furthermore, attempts to use a relative
778 	   pathname produced various errors (I couldn't get it to work),
779 	   so there would seem to be little risk in making this a fatal
780 	   error.  */
781 	if (!ISABSOLUTE (newroot->directory))
782 	{
783 	    error (0, 0, "CVSROOT must be an absolute pathname (not `%s')",
784 		   newroot->directory);
785 	    error (0, 0, "when using local access method.");
786 	    goto error_exit;
787 	}
788 #if defined(CLIENT_SUPPORT) || defined (SERVER_SUPPORT)
789 	/* We don't need to check for these in :local: mode, really, since
790 	 * we shouldn't be able to hit the code above which parses them, but
791 	 * I'm leaving them here in lieu of assertions.
792 	 */
793 	no_port = 1;
794 	/* no_password already set */
795 #endif /* defined(CLIENT_SUPPORT) || defined (SERVER_SUPPORT) */
796 	break;
797 #if defined(CLIENT_SUPPORT) || defined (SERVER_SUPPORT)
798     case fork_method:
799 	/* We want :fork: to behave the same as other remote access
800            methods.  Therefore, don't check to see that the repository
801            name is absolute -- let the server do it.  */
802 	if (newroot->username || newroot->hostname)
803 	{
804 	    error (0, 0, "Can't specify hostname and username in CVSROOT");
805 	    error (0, 0, "when using fork access method.");
806 	    goto error_exit;
807 	}
808 	newroot->hostname = xstrdup("server");  /* for error messages */
809 	if (!ISABSOLUTE (newroot->directory))
810 	{
811 	    error (0, 0, "CVSROOT must be an absolute pathname (not `%s')",
812 		   newroot->directory);
813 	    error (0, 0, "when using fork access method.");
814 	    goto error_exit;
815 	}
816 	no_port = 1;
817 	/* no_password already set */
818 	break;
819     case kserver_method:
820 	check_hostname = 1;
821 	/* no_password already set */
822 	break;
823     case gserver_method:
824 	check_hostname = 1;
825 	no_proxy = 0;
826 	/* no_password already set */
827 	break;
828     case server_method:
829     case ext_method:
830 	no_port = 1;
831 	/* no_password already set */
832 	check_hostname = 1;
833 	break;
834     case pserver_method:
835 	no_password = 0;
836 	no_proxy = 0;
837 	check_hostname = 1;
838 	break;
839 #endif /* defined(CLIENT_SUPPORT) || defined (SERVER_SUPPORT) */
840     default:
841 	error (1, 0, "Invalid method found in parse_cvsroot");
842     }
843 
844 #if defined(CLIENT_SUPPORT) || defined (SERVER_SUPPORT)
845     if (no_password && newroot->password)
846     {
847 	error (0, 0, "CVSROOT password specification is only valid for");
848 	error (0, 0, "pserver connection method.");
849 	goto error_exit;
850     }
851     if (no_proxy && (newroot->proxy_hostname || newroot->proxy_port))
852     {
853 	error (0, 0,
854 "CVSROOT proxy specification is only valid for gserver and");
855 	error (0, 0, "pserver connection methods.");
856 	goto error_exit;
857     }
858 
859     if (!newroot->proxy_hostname && newroot->proxy_port)
860     {
861 	error (0, 0, "Proxy port specified in CVSROOT without proxy host.");
862 	goto error_exit;
863     }
864 
865     if (check_hostname && !newroot->hostname)
866     {
867 	error (0, 0, "Didn't specify hostname in CVSROOT.");
868 	goto error_exit;
869     }
870 
871     if (no_port && newroot->port)
872     {
873         error (0, 0,
874 "CVSROOT port specification is only valid for gserver, kserver,");
875         error (0, 0, "and pserver connection methods.");
876         goto error_exit;
877     }
878 #endif /* defined(CLIENT_SUPPORT) || defined (SERVER_SUPPORT) */
879 
880     if (*newroot->directory == '\0')
881     {
882 	error (0, 0, "Missing directory in CVSROOT.");
883 	goto error_exit;
884     }
885 
886     /* Hooray!  We finally parsed it! */
887     free (cvsroot_save);
888 
889     if (!cache) cache = getlist();
890     node = getnode();
891     node->key = xstrdup (newroot->original);
892     node->data = newroot;
893     addnode (cache, node);
894     return newroot;
895 
896 error_exit:
897     free (cvsroot_save);
898     free_cvsroot_t (newroot);
899     return NULL;
900 }
901 
902 
903 
904 #ifdef AUTH_CLIENT_SUPPORT
905 /* Use root->username, root->hostname, root->port, and root->directory
906  * to create a normalized CVSROOT fit for the .cvspass file
907  *
908  * username defaults to the result of getcaller()
909  * port defaults to the result of get_cvs_port_number()
910  *
911  * FIXME - we could cache the canonicalized version of a root inside the
912  * cvsroot_t, but we'd have to un'const the input here and stop expecting the
913  * caller to be responsible for our return value
914  *
915  * ASSUMPTIONS
916  *   ROOT->method == pserver_method
917  */
918 char *
919 normalize_cvsroot (const cvsroot_t *root)
920 {
921     char *cvsroot_canonical;
922     char *p, *hostname;
923 
924     assert (root && root->hostname && root->directory);
925 
926     /* use a lower case hostname since we know hostnames are case insensitive */
927     /* Some logic says we should be tacking our domain name on too if it isn't
928      * there already, but for now this works.  Reverse->Forward lookups are
929      * almost certainly too much since that would make CVS immune to some of
930      * the DNS trickery that makes life easier for sysadmins when they want to
931      * move a repository or the like
932      */
933     p = hostname = xstrdup (root->hostname);
934     while (*p)
935     {
936 	*p = tolower (*p);
937 	p++;
938     }
939 
940     cvsroot_canonical = Xasprintf (":pserver:%s@%s:%d%s",
941                                    root->username ? root->username
942                                                   : getcaller(),
943                                    hostname, get_cvs_port_number (root),
944                                    root->directory);
945 
946     free (hostname);
947     return cvsroot_canonical;
948 }
949 #endif /* AUTH_CLIENT_SUPPORT */
950 
951 
952 
953 #ifdef PROXY_SUPPORT
954 /* A walklist() function to walk the root_allow list looking for a PrimaryServer
955  * configuration with a directory matching the requested directory.
956  *
957  * If found, replace it.
958  */
959 static bool get_local_root_dir_done;
960 static int
961 get_local_root_dir (Node *p, void *root_in)
962 {
963     struct config *c = p->data;
964     char **r = root_in;
965 
966     if (get_local_root_dir_done)
967 	return 0;
968 
969     if (c->PrimaryServer && !strcmp (*r, c->PrimaryServer->directory))
970     {
971 	free (*r);
972 	*r = xstrdup (p->key);
973 	get_local_root_dir_done = true;
974     }
975     return 0;
976 }
977 #endif /* PROXY_SUPPORT */
978 
979 
980 
981 /* allocate and return a cvsroot_t structure set up as if we're using the local
982  * repository DIR.  */
983 cvsroot_t *
984 local_cvsroot (const char *dir)
985 {
986     cvsroot_t *newroot = new_cvsroot_t();
987 
988     newroot->original = xstrdup(dir);
989     newroot->method = local_method;
990     newroot->directory = xstrdup(dir);
991     /* Here and parse_cvsroot() should be the only places this needs to be
992      * called on a CVSROOT now.  cvsroot->original is saved for error messages
993      * and, otherwise, we want no trailing slashes.
994      */
995     Sanitize_Repository_Name (newroot->directory);
996 
997 #ifdef PROXY_SUPPORT
998     /* Translate the directory to a local one in the case that we are
999      * configured as a secondary.  If root_allow has not been initialized,
1000      * nothing happens.
1001      */
1002     get_local_root_dir_done = false;
1003     walklist (root_allow, get_local_root_dir, &newroot->directory);
1004 #endif /* PROXY_SUPPORT */
1005 
1006     return newroot;
1007 }
1008 
1009 
1010 
1011 #ifdef DEBUG
1012 /* This is for testing the parsing function.  Use
1013 
1014      gcc -I. -I.. -I../lib -DDEBUG root.c -o root
1015 
1016    to compile.  */
1017 
1018 #include <stdio.h>
1019 
1020 char *program_name = "testing";
1021 char *cvs_cmd_name = "parse_cvsroot";		/* XXX is this used??? */
1022 
1023 void
1024 main (int argc, char *argv[])
1025 {
1026     program_name = argv[0];
1027 
1028     if (argc != 2)
1029     {
1030 	fprintf (stderr, "Usage: %s <CVSROOT>\n", program_name);
1031 	exit (2);
1032     }
1033 
1034     if ((current_parsed_root = parse_cvsroot (argv[1])) == NULL)
1035     {
1036 	fprintf (stderr, "%s: Parsing failed.\n", program_name);
1037 	exit (1);
1038     }
1039     printf ("CVSroot: %s\n", argv[1]);
1040     printf ("current_parsed_root->method: %s\n",
1041 	    method_names[current_parsed_root->method]);
1042     printf ("current_parsed_root->username: %s\n",
1043 	    current_parsed_root->username
1044 	      ? current_parsed_root->username : "NULL");
1045     printf ("current_parsed_root->hostname: %s\n",
1046 	    current_parsed_root->hostname
1047 	      ? current_parsed_root->hostname : "NULL");
1048     printf ("current_parsed_root->directory: %s\n",
1049 	    current_parsed_root->directory);
1050 
1051    exit (0);
1052    /* NOTREACHED */
1053 }
1054 #endif
1055