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