]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/cvs/src/client.c
This commit was generated by cvs2svn to compensate for changes in r170964,
[FreeBSD/FreeBSD.git] / contrib / cvs / src / client.c
1 /* CVS client-related stuff.
2
3    This program is free software; you can redistribute it and/or modify
4    it under the terms of the GNU General Public License as published by
5    the Free Software Foundation; either version 2, or (at your option)
6    any later version.
7
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.  */
12
13 /*
14  * $FreeBSD$
15  */
16
17 #ifdef HAVE_CONFIG_H
18 # include "config.h"
19 #endif /* HAVE_CONFIG_H */
20
21 #include <assert.h>
22 #include "cvs.h"
23 #include "getline.h"
24 #include "edit.h"
25 #include "buffer.h"
26 #include "savecwd.h"
27
28 #ifdef CLIENT_SUPPORT
29
30 # include "md5.h"
31
32 # if defined(AUTH_CLIENT_SUPPORT) || defined(HAVE_KERBEROS) || defined(HAVE_GSSAPI) || defined(SOCK_ERRNO) || defined(SOCK_STRERROR)
33 #   ifdef HAVE_WINSOCK_H
34 #     include <winsock.h>
35 #   else /* No winsock.h */
36 #     include <sys/socket.h>
37 #     include <netinet/in.h>
38 #     include <arpa/inet.h>
39 #     include <netdb.h>
40 #   endif /* No winsock.h */
41 # endif
42
43 /* If SOCK_ERRNO is defined, then send()/recv() and other socket calls
44    do not set errno, but that this macro should be used to obtain an
45    error code.  This probably doesn't make sense unless
46    NO_SOCKET_TO_FD is also defined. */
47 # ifndef SOCK_ERRNO
48 #   define SOCK_ERRNO errno
49 # endif
50
51 /* If SOCK_STRERROR is defined, then the error codes returned by
52    socket operations are not known to strerror, and this macro must be
53    used instead to convert those error codes to strings. */
54 # ifndef SOCK_STRERROR
55 #   define SOCK_STRERROR strerror
56
57 #   if STDC_HEADERS
58 #     include <string.h>
59 #   endif
60
61 #   ifndef strerror
62 extern char *strerror ();
63 #   endif
64 # endif /* ! SOCK_STRERROR */
65
66 # if HAVE_KERBEROS
67
68 #   include <krb.h>
69
70 extern char *krb_realmofhost ();
71 #   ifndef HAVE_KRB_GET_ERR_TEXT
72 #     define krb_get_err_text(status) krb_err_txt[status]
73 #   endif /* HAVE_KRB_GET_ERR_TEXT */
74
75 /* Information we need if we are going to use Kerberos encryption.  */
76 static C_Block kblock;
77 static Key_schedule sched;
78
79 # endif /* HAVE_KERBEROS */
80
81 # ifdef HAVE_GSSAPI
82
83 #   include "xgssapi.h"
84
85 /* This is needed for GSSAPI encryption.  */
86 static gss_ctx_id_t gcontext;
87
88 static int connect_to_gserver PROTO((cvsroot_t *, int, struct hostent *));
89
90 # endif /* HAVE_GSSAPI */
91
92
93
94 /* Keep track of any paths we are sending for Max-dotdot so that we can verify
95  * that uplevel paths coming back form the server are valid.
96  *
97  * FIXME: The correct way to do this is probably provide some sort of virtual
98  * path map on the client side.  This would be generic enough to be applied to
99  * absolute paths supplied by the user too.
100  */
101 static List *uppaths = NULL;
102
103
104
105 static void add_prune_candidate PROTO((const char *));
106
107 /* All the commands.  */
108 int add PROTO((int argc, char **argv));
109 int admin PROTO((int argc, char **argv));
110 int checkout PROTO((int argc, char **argv));
111 int commit PROTO((int argc, char **argv));
112 int diff PROTO((int argc, char **argv));
113 int history PROTO((int argc, char **argv));
114 int import PROTO((int argc, char **argv));
115 int cvslog PROTO((int argc, char **argv));
116 int patch PROTO((int argc, char **argv));
117 int release PROTO((int argc, char **argv));
118 int cvsremove PROTO((int argc, char **argv));
119 int rtag PROTO((int argc, char **argv));
120 int status PROTO((int argc, char **argv));
121 int tag PROTO((int argc, char **argv));
122 int update PROTO((int argc, char **argv));
123
124 /* All the response handling functions.  */
125 static void handle_ok PROTO((char *, int));
126 static void handle_error PROTO((char *, int));
127 static void handle_valid_requests PROTO((char *, int));
128 static void handle_checked_in PROTO((char *, int));
129 static void handle_new_entry PROTO((char *, int));
130 static void handle_checksum PROTO((char *, int));
131 static void handle_copy_file PROTO((char *, int));
132 static void handle_updated PROTO((char *, int));
133 static void handle_merged PROTO((char *, int));
134 static void handle_patched PROTO((char *, int));
135 static void handle_rcs_diff PROTO((char *, int));
136 static void handle_removed PROTO((char *, int));
137 static void handle_remove_entry PROTO((char *, int));
138 static void handle_set_static_directory PROTO((char *, int));
139 static void handle_clear_static_directory PROTO((char *, int));
140 static void handle_set_sticky PROTO((char *, int));
141 static void handle_clear_sticky PROTO((char *, int));
142 static void handle_module_expansion PROTO((char *, int));
143 static void handle_wrapper_rcs_option PROTO((char *, int));
144 static void handle_m PROTO((char *, int));
145 static void handle_e PROTO((char *, int));
146 static void handle_f PROTO((char *, int));
147 static void handle_notified PROTO((char *, int));
148
149 static size_t try_read_from_server PROTO ((char *, size_t));
150
151 static void auth_server PROTO ((cvsroot_t *, struct buffer *, struct buffer *,
152                                 int, int, struct hostent *));
153
154 /* We need to keep track of the list of directories we've sent to the
155    server.  This list, along with the current CVSROOT, will help us
156    decide which command-line arguments to send.  */
157 List *dirs_sent_to_server = NULL;
158
159 static int is_arg_a_parent_or_listed_dir PROTO((Node *, void *));
160
161 static int
162 is_arg_a_parent_or_listed_dir (n, d)
163     Node *n;
164     void *d;
165 {
166     char *directory = n->key;   /* name of the dir sent to server */
167     char *this_argv_elem = (char *) d;  /* this argv element */
168
169     /* Say we should send this argument if the argument matches the
170        beginning of a directory name sent to the server.  This way,
171        the server will know to start at the top of that directory
172        hierarchy and descend. */
173
174     if (strncmp (directory, this_argv_elem, strlen (this_argv_elem)) == 0)
175         return 1;
176
177     return 0;
178 }
179
180 static int arg_should_not_be_sent_to_server PROTO((char *));
181
182 /* Return nonzero if this argument should not be sent to the
183    server. */
184
185 static int
186 arg_should_not_be_sent_to_server (arg)
187     char *arg;
188 {
189     /* Decide if we should send this directory name to the server.  We
190        should always send argv[i] if:
191
192        1) the list of directories sent to the server is empty (as it
193        will be for checkout, etc.).
194
195        2) the argument is "."
196
197        3) the argument is a file in the cwd and the cwd is checked out
198        from the current root
199
200        4) the argument lies within one of the paths in
201        dirs_sent_to_server.
202
203        */
204
205     if (list_isempty (dirs_sent_to_server))
206         return 0;               /* always send it */
207
208     if (strcmp (arg, ".") == 0)
209         return 0;               /* always send it */
210
211     /* We should send arg if it is one of the directories sent to the
212        server or the parent of one; this tells the server to descend
213        the hierarchy starting at this level. */
214     if (isdir (arg))
215     {
216         if (walklist (dirs_sent_to_server, is_arg_a_parent_or_listed_dir, arg))
217             return 0;
218
219         /* If arg wasn't a parent, we don't know anything about it (we
220            would have seen something related to it during the
221            send_files phase).  Don't send it.  */
222         return 1;
223     }
224
225     /* Try to decide whether we should send arg to the server by
226        checking the contents of the corresponding CVSADM directory. */
227     {
228         char *t, *this_root;
229
230         /* Calculate "dirname arg" */
231         for (t = arg + strlen (arg) - 1; t >= arg; t--)
232         {
233             if (ISDIRSEP(*t))
234                 break;
235         }
236
237         /* Now we're either poiting to the beginning of the
238            string, or we found a path separator. */
239         if (t >= arg)
240         {
241             /* Found a path separator.  */
242             char c = *t;
243             *t = '\0';
244             
245             /* First, check to see if we sent this directory to the
246                server, because it takes less time than actually
247                opening the stuff in the CVSADM directory.  */
248             if (walklist (dirs_sent_to_server, is_arg_a_parent_or_listed_dir,
249                           arg))
250             {
251                 *t = c;         /* make sure to un-truncate the arg */
252                 return 0;
253             }
254
255             /* Since we didn't find it in the list, check the CVSADM
256                files on disk.  */
257             this_root = Name_Root (arg, (char *) NULL);
258             *t = c;
259         }
260         else
261         {
262             /* We're at the beginning of the string.  Look at the
263                CVSADM files in cwd.  */
264             this_root = (CVSroot_cmdline ? xstrdup(CVSroot_cmdline)
265                          : Name_Root ((char *) NULL, (char *) NULL));
266         }
267
268         /* Now check the value for root. */
269         if (CVSroot_cmdline == NULL && this_root && current_parsed_root
270             && (strcmp (this_root, current_parsed_root->original) != 0))
271         {
272             /* Don't send this, since the CVSROOTs don't match. */
273             free (this_root);
274             return 1;
275         }
276         free (this_root);
277     }
278     
279     /* OK, let's send it. */
280     return 0;
281 }
282
283
284
285 #endif /* CLIENT_SUPPORT */
286
287
288
289 #if defined(CLIENT_SUPPORT) || defined(SERVER_SUPPORT)
290
291 /* Shared with server.  */
292
293 /*
294  * Return a malloc'd, '\0'-terminated string
295  * corresponding to the mode in SB.
296  */
297 char *
298 #ifdef __STDC__
299 mode_to_string (mode_t mode)
300 #else /* ! __STDC__ */
301 mode_to_string (mode)
302         mode_t mode;
303 #endif /* __STDC__ */
304 {
305     char buf[18], u[4], g[4], o[4];
306     int i;
307
308     i = 0;
309     if (mode & S_IRUSR) u[i++] = 'r';
310     if (mode & S_IWUSR) u[i++] = 'w';
311     if (mode & S_IXUSR) u[i++] = 'x';
312     u[i] = '\0';
313
314     i = 0;
315     if (mode & S_IRGRP) g[i++] = 'r';
316     if (mode & S_IWGRP) g[i++] = 'w';
317     if (mode & S_IXGRP) g[i++] = 'x';
318     g[i] = '\0';
319
320     i = 0;
321     if (mode & S_IROTH) o[i++] = 'r';
322     if (mode & S_IWOTH) o[i++] = 'w';
323     if (mode & S_IXOTH) o[i++] = 'x';
324     o[i] = '\0';
325
326     sprintf(buf, "u=%s,g=%s,o=%s", u, g, o);
327     return xstrdup(buf);
328 }
329
330 /*
331  * Change mode of FILENAME to MODE_STRING.
332  * Returns 0 for success or errno code.
333  * If RESPECT_UMASK is set, then honor the umask.
334  */
335 int
336 change_mode (filename, mode_string, respect_umask)
337     char *filename;
338     char *mode_string;
339     int respect_umask;
340 {
341 #ifdef CHMOD_BROKEN
342     char *p;
343     int writeable = 0;
344
345     /* We can only distinguish between
346          1) readable
347          2) writeable
348          3) Picasso's "Blue Period"
349        We handle the first two. */
350     p = mode_string;
351     while (*p != '\0')
352     {
353         if ((p[0] == 'u' || p[0] == 'g' || p[0] == 'o') && p[1] == '=')
354         {
355             char *q = p + 2;
356             while (*q != ',' && *q != '\0')
357             {
358                 if (*q == 'w')
359                     writeable = 1;
360                 ++q;
361             }
362         }
363         /* Skip to the next field.  */
364         while (*p != ',' && *p != '\0')
365             ++p;
366         if (*p == ',')
367             ++p;
368     }
369
370     /* xchmod honors the umask for us.  In the !respect_umask case, we
371        don't try to cope with it (probably to handle that well, the server
372        needs to deal with modes in data structures, rather than via the
373        modes in temporary files).  */
374     xchmod (filename, writeable);
375         return 0;
376
377 #else /* ! CHMOD_BROKEN */
378
379     char *p;
380     mode_t mode = 0;
381     mode_t oumask;
382
383     p = mode_string;
384     while (*p != '\0')
385     {
386         if ((p[0] == 'u' || p[0] == 'g' || p[0] == 'o') && p[1] == '=')
387         {
388             int can_read = 0, can_write = 0, can_execute = 0;
389             char *q = p + 2;
390             while (*q != ',' && *q != '\0')
391             {
392                 if (*q == 'r')
393                     can_read = 1;
394                 else if (*q == 'w')
395                     can_write = 1;
396                 else if (*q == 'x')
397                     can_execute = 1;
398                 ++q;
399             }
400             if (p[0] == 'u')
401             {
402                 if (can_read)
403                     mode |= S_IRUSR;
404                 if (can_write)
405                     mode |= S_IWUSR;
406                 if (can_execute)
407                     mode |= S_IXUSR;
408             }
409             else if (p[0] == 'g')
410             {
411                 if (can_read)
412                     mode |= S_IRGRP;
413                 if (can_write)
414                     mode |= S_IWGRP;
415                 if (can_execute)
416                     mode |= S_IXGRP;
417             }
418             else if (p[0] == 'o')
419             {
420                 if (can_read)
421                     mode |= S_IROTH;
422                 if (can_write)
423                     mode |= S_IWOTH;
424                 if (can_execute)
425                     mode |= S_IXOTH;
426             }
427         }
428         /* Skip to the next field.  */
429         while (*p != ',' && *p != '\0')
430             ++p;
431         if (*p == ',')
432             ++p;
433     }
434
435     if (respect_umask)
436     {
437         oumask = umask (0);
438         (void) umask (oumask);
439         mode &= ~oumask;
440     }
441
442     if (chmod (filename, mode) < 0)
443         return errno;
444     return 0;
445 #endif /* ! CHMOD_BROKEN */
446 }
447
448 #endif /* CLIENT_SUPPORT or SERVER_SUPPORT */
449 \f
450 #ifdef CLIENT_SUPPORT
451
452 int client_prune_dirs;
453
454 static List *ignlist = (List *) NULL;
455
456 /* Buffer to write to the server.  */
457 static struct buffer *to_server;
458
459 /* Buffer used to read from the server.  */
460 static struct buffer *from_server;
461
462 \f
463 /* We want to be able to log data sent between us and the server.  We
464    do it using log buffers.  Each log buffer has another buffer which
465    handles the actual I/O, and a file to log information to.
466
467    This structure is the closure field of a log buffer.  */
468
469 struct log_buffer
470 {
471     /* The underlying buffer.  */
472     struct buffer *buf;
473     /* The file to log information to.  */
474     FILE *log;
475 };
476
477 static struct buffer *log_buffer_initialize
478   PROTO((struct buffer *, FILE *, int, void (*) (struct buffer *)));
479 static int log_buffer_input PROTO((void *, char *, int, int, int *));
480 static int log_buffer_output PROTO((void *, const char *, int, int *));
481 static int log_buffer_flush PROTO((void *));
482 static int log_buffer_block PROTO((void *, int));
483 static int log_buffer_shutdown PROTO((struct buffer *));
484
485 /* Create a log buffer.  */
486
487 static struct buffer *
488 log_buffer_initialize (buf, fp, input, memory)
489      struct buffer *buf;
490      FILE *fp;
491      int input;
492      void (*memory) PROTO((struct buffer *));
493 {
494     struct log_buffer *n;
495
496     n = (struct log_buffer *) xmalloc (sizeof *n);
497     n->buf = buf;
498     n->log = fp;
499     return buf_initialize (input ? log_buffer_input : NULL,
500                            input ? NULL : log_buffer_output,
501                            input ? NULL : log_buffer_flush,
502                            log_buffer_block,
503                            log_buffer_shutdown,
504                            memory,
505                            n);
506 }
507
508 /* The input function for a log buffer.  */
509
510 static int
511 log_buffer_input (closure, data, need, size, got)
512      void *closure;
513      char *data;
514      int need;
515      int size;
516      int *got;
517 {
518     struct log_buffer *lb = (struct log_buffer *) closure;
519     int status;
520     size_t n_to_write;
521
522     if (lb->buf->input == NULL)
523         abort ();
524
525     status = (*lb->buf->input) (lb->buf->closure, data, need, size, got);
526     if (status != 0)
527         return status;
528
529     if (*got > 0)
530     {
531         n_to_write = *got;
532         if (fwrite (data, 1, n_to_write, lb->log) != n_to_write)
533             error (0, errno, "writing to log file");
534     }
535
536     return 0;
537 }
538
539 /* The output function for a log buffer.  */
540
541 static int
542 log_buffer_output (closure, data, have, wrote)
543      void *closure;
544      const char *data;
545      int have;
546      int *wrote;
547 {
548     struct log_buffer *lb = (struct log_buffer *) closure;
549     int status;
550     size_t n_to_write;
551
552     if (lb->buf->output == NULL)
553         abort ();
554
555     status = (*lb->buf->output) (lb->buf->closure, data, have, wrote);
556     if (status != 0)
557         return status;
558
559     if (*wrote > 0)
560     {
561         n_to_write = *wrote;
562         if (fwrite (data, 1, n_to_write, lb->log) != n_to_write)
563             error (0, errno, "writing to log file");
564     }
565
566     return 0;
567 }
568
569 /* The flush function for a log buffer.  */
570
571 static int
572 log_buffer_flush (closure)
573      void *closure;
574 {
575     struct log_buffer *lb = (struct log_buffer *) closure;
576
577     if (lb->buf->flush == NULL)
578         abort ();
579
580     /* We don't really have to flush the log file here, but doing it
581        will let tail -f on the log file show what is sent to the
582        network as it is sent.  */
583     if (fflush (lb->log) != 0)
584         error (0, errno, "flushing log file");
585
586     return (*lb->buf->flush) (lb->buf->closure);
587 }
588
589 /* The block function for a log buffer.  */
590
591 static int
592 log_buffer_block (closure, block)
593      void *closure;
594      int block;
595 {
596     struct log_buffer *lb = (struct log_buffer *) closure;
597
598     if (block)
599         return set_block (lb->buf);
600     else
601         return set_nonblock (lb->buf);
602 }
603
604 /* The shutdown function for a log buffer.  */
605
606 static int
607 log_buffer_shutdown (buf)
608      struct buffer *buf;
609 {
610     struct log_buffer *lb = (struct log_buffer *) buf->closure;
611     int retval;
612
613     retval = buf_shutdown (lb->buf);
614     if (fclose (lb->log) < 0)
615         error (0, errno, "closing log file");
616     return retval;
617 }
618
619 #ifdef NO_SOCKET_TO_FD
620
621 /* Under certain circumstances, we must communicate with the server
622    via a socket using send() and recv().  This is because under some
623    operating systems (OS/2 and Windows 95 come to mind), a socket
624    cannot be converted to a file descriptor -- it must be treated as a
625    socket and nothing else.
626    
627    We may also need to deal with socket routine error codes differently
628    in these cases.  This is handled through the SOCK_ERRNO and
629    SOCK_STRERROR macros. */
630
631 /* These routines implement a buffer structure which uses send and
632    recv.  The buffer is always in blocking mode so we don't implement
633    the block routine.  */
634
635 /* Note that it is important that these routines always handle errors
636    internally and never return a positive errno code, since it would in
637    general be impossible for the caller to know in general whether any
638    error code came from a socket routine (to decide whether to use
639    SOCK_STRERROR or simply strerror to print an error message). */
640
641 /* We use an instance of this structure as the closure field.  */
642
643 struct socket_buffer
644 {
645     /* The socket number.  */
646     int socket;
647 };
648
649 static struct buffer *socket_buffer_initialize
650   PROTO ((int, int, void (*) (struct buffer *)));
651 static int socket_buffer_input PROTO((void *, char *, int, int, int *));
652 static int socket_buffer_output PROTO((void *, const char *, int, int *));
653 static int socket_buffer_flush PROTO((void *));
654 static int socket_buffer_shutdown PROTO((struct buffer *));
655
656
657
658 /* Create a buffer based on a socket.  */
659
660 static struct buffer *
661 socket_buffer_initialize (socket, input, memory)
662     int socket;
663     int input;
664     void (*memory) PROTO((struct buffer *));
665 {
666     struct socket_buffer *n;
667
668     n = (struct socket_buffer *) xmalloc (sizeof *n);
669     n->socket = socket;
670     return buf_initialize (input ? socket_buffer_input : NULL,
671                            input ? NULL : socket_buffer_output,
672                            input ? NULL : socket_buffer_flush,
673                            (int (*) PROTO((void *, int))) NULL,
674                            socket_buffer_shutdown,
675                            memory,
676                            n);
677 }
678
679
680
681 /* The buffer input function for a buffer built on a socket.  */
682
683 static int
684 socket_buffer_input (closure, data, need, size, got)
685      void *closure;
686      char *data;
687      int need;
688      int size;
689      int *got;
690 {
691     struct socket_buffer *sb = (struct socket_buffer *) closure;
692     int nbytes;
693
694     /* I believe that the recv function gives us exactly the semantics
695        we want.  If there is a message, it returns immediately with
696        whatever it could get.  If there is no message, it waits until
697        one comes in.  In other words, it is not like read, which in
698        blocking mode normally waits until all the requested data is
699        available.  */
700
701     *got = 0;
702
703     do
704     {
705
706         /* Note that for certain (broken?) networking stacks, like
707            VMS's UCX (not sure what version, problem reported with
708            recv() in 1997), and (according to windows-NT/config.h)
709            Windows NT 3.51, we must call recv or send with a
710            moderately sized buffer (say, less than 200K or something),
711            or else there may be network errors (somewhat hard to
712            produce, e.g. WAN not LAN or some such).  buf_read_data
713            makes sure that we only recv() BUFFER_DATA_SIZE bytes at
714            a time.  */
715
716         nbytes = recv (sb->socket, data, size, 0);
717         if (nbytes < 0)
718             error (1, 0, "reading from server: %s", SOCK_STRERROR (SOCK_ERRNO));
719         if (nbytes == 0)
720         {
721             /* End of file (for example, the server has closed
722                the connection).  If we've already read something, we
723                just tell the caller about the data, not about the end of
724                file.  If we've read nothing, we return end of file.  */
725             if (*got == 0)
726                 return -1;
727             else
728                 return 0;
729         }
730         need -= nbytes;
731         size -= nbytes;
732         data += nbytes;
733         *got += nbytes;
734     }
735     while (need > 0);
736
737     return 0;
738 }
739
740
741
742 /* The buffer output function for a buffer built on a socket.  */
743
744 static int
745 socket_buffer_output (closure, data, have, wrote)
746      void *closure;
747      const char *data;
748      int have;
749      int *wrote;
750 {
751     struct socket_buffer *sb = (struct socket_buffer *) closure;
752
753     *wrote = have;
754
755     /* See comment in socket_buffer_input regarding buffer size we pass
756        to send and recv.  */
757
758 #ifdef SEND_NEVER_PARTIAL
759     /* If send() never will produce a partial write, then just do it.  This
760        is needed for systems where its return value is something other than
761        the number of bytes written.  */
762     if (send (sb->socket, data, have, 0) < 0)
763         error (1, 0, "writing to server socket: %s", SOCK_STRERROR (SOCK_ERRNO));
764 #else
765     while (have > 0)
766     {
767         int nbytes;
768
769         nbytes = send (sb->socket, data, have, 0);
770         if (nbytes < 0)
771             error (1, 0, "writing to server socket: %s", SOCK_STRERROR (SOCK_ERRNO));
772
773         have -= nbytes;
774         data += nbytes;
775     }
776 #endif
777
778     return 0;
779 }
780
781
782
783 /* The buffer flush function for a buffer built on a socket.  */
784
785 /*ARGSUSED*/
786 static int
787 socket_buffer_flush (closure)
788      void *closure;
789 {
790     /* Nothing to do.  Sockets are always flushed.  */
791     return 0;
792 }
793
794
795
796 static int
797 socket_buffer_shutdown (buf)
798     struct buffer *buf;
799 {
800     struct socket_buffer *n = (struct socket_buffer *) buf->closure;
801     char tmp;
802
803     /* no need to flush children of an endpoint buffer here */
804
805     if (buf->input)
806     {
807         int err = 0;
808         if (! buf_empty_p (buf)
809             || (err = recv (n->socket, &tmp, 1, 0)) > 0)
810             error (0, 0, "dying gasps from %s unexpected", current_parsed_root->hostname);
811         else if (err == -1)
812             error (0, 0, "reading from %s: %s", current_parsed_root->hostname, SOCK_STRERROR (SOCK_ERRNO));
813
814         /* shutdown() socket */
815 # ifdef SHUTDOWN_SERVER
816         if (current_parsed_root->method != server_method)
817 # endif
818         if (shutdown (n->socket, 0) < 0)
819         {
820             error (1, 0, "shutting down server socket: %s", SOCK_STRERROR (SOCK_ERRNO));
821         }
822
823         buf->input = NULL;
824     }
825     else if (buf->output)
826     {
827         /* shutdown() socket */
828 # ifdef SHUTDOWN_SERVER
829         /* FIXME:  Should have a SHUTDOWN_SERVER_INPUT &
830          * SHUTDOWN_SERVER_OUTPUT
831          */
832         if (current_parsed_root->method == server_method)
833             SHUTDOWN_SERVER (n->socket);
834         else
835 # endif
836         if (shutdown (n->socket, 1) < 0)
837         {
838             error (1, 0, "shutting down server socket: %s", SOCK_STRERROR (SOCK_ERRNO));
839         }
840
841         buf->output = NULL;
842     }
843
844     return 0;
845 }
846
847 #endif /* NO_SOCKET_TO_FD */
848
849 /*
850  * Read a line from the server.  Result does not include the terminating \n.
851  *
852  * Space for the result is malloc'd and should be freed by the caller.
853  *
854  * Returns number of bytes read.
855  */
856 static int
857 read_line (resultp)
858     char **resultp;
859 {
860     int status;
861     char *result;
862     int len;
863
864     status = buf_flush (to_server, 1);
865     if (status != 0)
866         error (1, status, "writing to server");
867
868     status = buf_read_line (from_server, &result, &len);
869     if (status != 0)
870     {
871         if (status == -1)
872             error (1, 0, "end of file from server (consult above messages if any)");
873         else if (status == -2)
874             error (1, 0, "out of memory");
875         else
876             error (1, status, "reading from server");
877     }
878
879     if (resultp != NULL)
880         *resultp = result;
881     else
882         free (result);
883
884     return len;
885 }
886
887 #endif /* CLIENT_SUPPORT */
888
889 \f
890 #if defined(CLIENT_SUPPORT) || defined(SERVER_SUPPORT)
891
892 /*
893  * Zero if compression isn't supported or requested; non-zero to indicate
894  * a compression level to request from gzip.
895  */
896 int gzip_level;
897
898 /*
899  * Level of compression to use when running gzip on a single file.
900  */
901 int file_gzip_level;
902
903 #endif /* CLIENT_SUPPORT or SERVER_SUPPORT */
904 \f
905 #ifdef CLIENT_SUPPORT
906
907 /*
908  * The Repository for the top level of this command (not necessarily
909  * the CVSROOT, just the current directory at the time we do it).
910  */
911 static char *toplevel_repos = NULL;
912
913 /* Working directory when we first started.  Note: we could speed things
914    up on some systems by using savecwd.h here instead of just always
915    storing a name.  */
916 char *toplevel_wd;
917 \f
918 static void
919 handle_ok (args, len)
920     char *args;
921     int len;
922 {
923     return;
924 }
925
926 static void
927 handle_error (args, len)
928     char *args;
929     int len;
930 {
931     int something_printed;
932     
933     /*
934      * First there is a symbolic error code followed by a space, which
935      * we ignore.
936      */
937     char *p = strchr (args, ' ');
938     if (p == NULL)
939     {
940         error (0, 0, "invalid data from cvs server");
941         return;
942     }
943     ++p;
944
945     /* Next we print the text of the message from the server.  We
946        probably should be prefixing it with "server error" or some
947        such, because if it is something like "Out of memory", the
948        current behavior doesn't say which machine is out of
949        memory.  */
950
951     len -= p - args;
952     something_printed = 0;
953     for (; len > 0; --len)
954     {
955         something_printed = 1;
956         putc (*p++, stderr);
957     }
958     if (something_printed)
959         putc ('\n', stderr);
960 }
961
962 static void
963 handle_valid_requests (args, len)
964     char *args;
965     int len;
966 {
967     char *p = args;
968     char *q;
969     struct request *rq;
970     do
971     {
972         q = strchr (p, ' ');
973         if (q != NULL)
974             *q++ = '\0';
975         for (rq = requests; rq->name != NULL; ++rq)
976         {
977             if (strcmp (rq->name, p) == 0)
978                 break;
979         }
980         if (rq->name == NULL)
981             /*
982              * It is a request we have never heard of (and thus never
983              * will want to use).  So don't worry about it.
984              */
985             ;
986         else
987         {
988             if (rq->flags & RQ_ENABLEME)
989             {
990                 /*
991                  * Server wants to know if we have this, to enable the
992                  * feature.
993                  */
994                 send_to_server (rq->name, 0);
995                 send_to_server ("\012", 0);
996             }
997             else
998                 rq->flags |= RQ_SUPPORTED;
999         }
1000         p = q;
1001     } while (q != NULL);
1002     for (rq = requests; rq->name != NULL; ++rq)
1003     {
1004         if ((rq->flags & RQ_SUPPORTED)
1005             || (rq->flags & RQ_ENABLEME))
1006             continue;
1007         if (rq->flags & RQ_ESSENTIAL)
1008             error (1, 0, "request `%s' not supported by server", rq->name);
1009     }
1010 }
1011
1012
1013
1014 /*
1015  * This is a proc for walklist().  It inverts the error return premise of
1016  * walklist.
1017  *
1018  * RETURNS
1019  *   True       If this path is prefixed by one of the paths in walklist and
1020  *              does not step above the prefix path.
1021  *   False      Otherwise.
1022  */
1023 static
1024 int path_list_prefixed (p, closure)
1025     Node *p;
1026     void *closure;
1027 {
1028     const char *questionable = closure;
1029     const char *prefix = p->key;
1030     if (strncmp (prefix, questionable, strlen (prefix))) return 0;
1031     questionable += strlen (prefix);
1032     while (ISDIRSEP (*questionable)) questionable++;
1033     if (*questionable == '\0') return 1;
1034     return pathname_levels (questionable);
1035 }
1036
1037
1038
1039 /*
1040  * Need to validate the client pathname.  Disallowed paths include:
1041  *
1042  *   1. Absolute paths.
1043  *   2. Pathnames that do not reference a specifically requested update
1044  *      directory.
1045  *
1046  * In case 2, we actually only check that the directory is under the uppermost
1047  * directories mentioned on the command line.
1048  *
1049  * RETURNS
1050  *   True       If the path is valid.
1051  *   False      Otherwise.
1052  */
1053 static
1054 int is_valid_client_path (pathname)
1055     const char *pathname;
1056 {
1057     /* 1. Absolute paths. */
1058     if (isabsolute (pathname)) return 0;
1059     /* 2. No up-references in path.  */
1060     if (pathname_levels (pathname) == 0) return 1;
1061     /* 2. No Max-dotdot paths registered.  */
1062     if (uppaths == NULL) return 0;
1063
1064     return walklist (uppaths, path_list_prefixed, (void *)pathname);
1065 }
1066
1067
1068
1069 /*
1070  * Do all the processing for PATHNAME, where pathname consists of the
1071  * repository and the filename.  The parameters we pass to FUNC are:
1072  * DATA is just the DATA parameter which was passed to
1073  * call_in_directory; ENT_LIST is a pointer to an entries list (which
1074  * we manage the storage for); SHORT_PATHNAME is the pathname of the
1075  * file relative to the (overall) directory in which the command is
1076  * taking place; and FILENAME is the filename portion only of
1077  * SHORT_PATHNAME.  When we call FUNC, the curent directory points to
1078  * the directory portion of SHORT_PATHNAME.  */
1079
1080 static void
1081 call_in_directory (pathname, func, data)
1082     char *pathname;
1083     void (*func) PROTO((char *data, List *ent_list, char *short_pathname,
1084                           char *filename));
1085     char *data;
1086 {
1087     /* This variable holds the result of Entries_Open. */
1088     List *last_entries = NULL;
1089     char *dir_name;
1090     char *filename;
1091     /* This is what we get when we hook up the directory (working directory
1092        name) from PATHNAME with the filename from REPOSNAME.  For example:
1093        pathname: ccvs/src/
1094        reposname: /u/src/master/ccvs/foo/ChangeLog
1095        short_pathname: ccvs/src/ChangeLog
1096        */
1097     char *short_pathname;
1098     char *p;
1099
1100     /*
1101      * Do the whole descent in parallel for the repositories, so we
1102      * know what to put in CVS/Repository files.  I'm not sure the
1103      * full hair is necessary since the server does a similar
1104      * computation; I suspect that we only end up creating one
1105      * directory at a time anyway.
1106      *
1107      * Also note that we must *only* worry about this stuff when we
1108      * are creating directories; `cvs co foo/bar; cd foo/bar; cvs co
1109      * CVSROOT; cvs update' is legitimate, but in this case
1110      * foo/bar/CVSROOT/CVS/Repository is not a subdirectory of
1111      * foo/bar/CVS/Repository.
1112      */
1113     char *reposname;
1114     char *short_repos;
1115     char *reposdirname;
1116     char *rdirp;
1117     int reposdirname_absolute;
1118     int newdir = 0;
1119
1120     reposname = NULL;
1121     read_line (&reposname);
1122     assert (reposname != NULL);
1123
1124     reposdirname_absolute = 0;
1125     if (strncmp (reposname, toplevel_repos, strlen (toplevel_repos)) != 0)
1126     {
1127         reposdirname_absolute = 1;
1128         short_repos = reposname;
1129     }
1130     else
1131     {
1132         short_repos = reposname + strlen (toplevel_repos) + 1;
1133         if (short_repos[-1] != '/')
1134         {
1135             reposdirname_absolute = 1;
1136             short_repos = reposname;
1137         }
1138     }
1139
1140    /* Now that we have SHORT_REPOS, we can calculate the path to the file we
1141     * are being requested to operate on.
1142     */
1143     filename = strrchr (short_repos, '/');
1144     if (filename == NULL)
1145         filename = short_repos;
1146     else
1147         ++filename;
1148
1149     short_pathname = xmalloc (strlen (pathname) + strlen (filename) + 5);
1150     strcpy (short_pathname, pathname);
1151     strcat (short_pathname, filename);
1152
1153     /* Now that we know the path to the file we were requested to operate on,
1154      * we can verify that it is valid.
1155      *
1156      * For security reasons, if SHORT_PATHNAME is absolute or attempts to
1157      * ascend outside of the current sanbbox, we abort.  The server should not
1158      * send us anything but relative paths which remain inside the sandbox
1159      * here.  Anything less means a trojan CVS server could create and edit
1160      * arbitrary files on the client.
1161      */
1162     if (!is_valid_client_path (short_pathname))
1163     {
1164         error (0, 0,
1165                "Server attempted to update a file via an invalid pathname:");
1166         error (1, 0, "`%s'.", short_pathname);
1167     }
1168
1169     reposdirname = xstrdup (short_repos);
1170     p = strrchr (reposdirname, '/');
1171     if (p == NULL)
1172     {
1173         reposdirname = xrealloc (reposdirname, 2);
1174         reposdirname[0] = '.'; reposdirname[1] = '\0';
1175     }
1176     else
1177         *p = '\0';
1178
1179     dir_name = xstrdup (pathname);
1180     p = strrchr (dir_name, '/');
1181     if (p == NULL)
1182     {
1183         dir_name = xrealloc (dir_name, 2);
1184         dir_name[0] = '.'; dir_name[1] = '\0';
1185     }
1186     else
1187         *p = '\0';
1188     if (client_prune_dirs)
1189         add_prune_candidate (dir_name);
1190
1191     if (toplevel_wd == NULL)
1192     {
1193         toplevel_wd = xgetwd ();
1194         if (toplevel_wd == NULL)
1195             error (1, errno, "could not get working directory");
1196     }
1197
1198     if (CVS_CHDIR (toplevel_wd) < 0)
1199         error (1, errno, "could not chdir to %s", toplevel_wd);
1200
1201     /* Create the CVS directory at the top level if needed.  The
1202        isdir seems like an unneeded system call, but it *does*
1203        need to be called both if the CVS_CHDIR below succeeds
1204        (e.g.  "cvs co .") or if it fails (e.g. basicb-1a in
1205        testsuite).  We only need to do this for the "." case,
1206        since the server takes care of forcing this directory to be
1207        created in all other cases.  If we don't create CVSADM
1208        here, the call to Entries_Open below will fail.  FIXME:
1209        perhaps this means that we should change our algorithm
1210        below that calls Create_Admin instead of having this code
1211        here? */
1212     if (/* I think the reposdirname_absolute case has to do with
1213            things like "cvs update /foo/bar".  In any event, the
1214            code below which tries to put toplevel_repos into
1215            CVS/Repository is almost surely unsuited to
1216            the reposdirname_absolute case.  */
1217         !reposdirname_absolute
1218         && (strcmp (dir_name, ".") == 0)
1219         && ! isdir (CVSADM))
1220     {
1221         char *repo;
1222         char *r;
1223
1224         newdir = 1;
1225
1226         repo = xmalloc (strlen (toplevel_repos)
1227                         + 10);
1228         strcpy (repo, toplevel_repos);
1229         r = repo + strlen (repo);
1230         if (r[-1] != '.' || r[-2] != '/')
1231             strcpy (r, "/.");
1232
1233         Create_Admin (".", ".", repo, (char *) NULL,
1234                       (char *) NULL, 0, 1, 1);
1235
1236         free (repo);
1237     }
1238
1239     if (CVS_CHDIR (dir_name) < 0)
1240     {
1241         char *dir;
1242         char *dirp;
1243         
1244         if (! existence_error (errno))
1245             error (1, errno, "could not chdir to %s", dir_name);
1246         
1247         /* Directory does not exist, we need to create it.  */
1248         newdir = 1;
1249
1250         /* Provided we are willing to assume that directories get
1251            created one at a time, we could simplify this a lot.
1252            Do note that one aspect still would need to walk the
1253            dir_name path: the checking for "fncmp (dir, CVSADM)".  */
1254
1255         dir = xmalloc (strlen (dir_name) + 1);
1256         dirp = dir_name;
1257         rdirp = reposdirname;
1258
1259         /* This algorithm makes nested directories one at a time
1260            and create CVS administration files in them.  For
1261            example, we're checking out foo/bar/baz from the
1262            repository:
1263
1264            1) create foo, point CVS/Repository to <root>/foo
1265            2)     .. foo/bar                   .. <root>/foo/bar
1266            3)     .. foo/bar/baz               .. <root>/foo/bar/baz
1267            
1268            As you can see, we're just stepping along DIR_NAME (with
1269            DIRP) and REPOSDIRNAME (with RDIRP) respectively.
1270
1271            We need to be careful when we are checking out a
1272            module, however, since DIR_NAME and REPOSDIRNAME are not
1273            going to be the same.  Since modules will not have any
1274            slashes in their names, we should watch the output of
1275            STRCHR to decide whether or not we should use STRCHR on
1276            the RDIRP.  That is, if we're down to a module name,
1277            don't keep picking apart the repository directory name.  */
1278
1279         do
1280         {
1281             dirp = strchr (dirp, '/');
1282             if (dirp)
1283             {
1284                 strncpy (dir, dir_name, dirp - dir_name);
1285                 dir[dirp - dir_name] = '\0';
1286                 /* Skip the slash.  */
1287                 ++dirp;
1288                 if (rdirp == NULL)
1289                     /* This just means that the repository string has
1290                        fewer components than the dir_name string.  But
1291                        that is OK (e.g. see modules3-8 in testsuite).  */
1292                     ;
1293                 else
1294                     rdirp = strchr (rdirp, '/');
1295             }
1296             else
1297             {
1298                 /* If there are no more slashes in the dir name,
1299                    we're down to the most nested directory -OR- to
1300                    the name of a module.  In the first case, we
1301                    should be down to a DIRP that has no slashes,
1302                    so it won't help/hurt to do another STRCHR call
1303                    on DIRP.  It will definitely hurt, however, if
1304                    we're down to a module name, since a module
1305                    name can point to a nested directory (that is,
1306                    DIRP will still have slashes in it.  Therefore,
1307                    we should set it to NULL so the routine below
1308                    copies the contents of REMOTEDIRNAME onto the
1309                    root repository directory (does this if rdirp
1310                    is set to NULL, because we used to do an extra
1311                    STRCHR call here). */
1312
1313                 rdirp = NULL;
1314                 strcpy (dir, dir_name);
1315             }
1316
1317             if (fncmp (dir, CVSADM) == 0)
1318             {
1319                 error (0, 0, "cannot create a directory named %s", dir);
1320                 error (0, 0, "because CVS uses \"%s\" for its own uses",
1321                        CVSADM);
1322                 error (1, 0, "rename the directory and try again");
1323             }
1324
1325             if (mkdir_if_needed (dir))
1326             {
1327                 /* It already existed, fine.  Just keep going.  */
1328             }
1329             else if (strcmp (cvs_cmd_name, "export") == 0)
1330                 /* Don't create CVSADM directories if this is export.  */
1331                 ;
1332             else
1333             {
1334                 /*
1335                  * Put repository in CVS/Repository.  For historical
1336                  * (pre-CVS/Root) reasons, this is an absolute pathname,
1337                  * but what really matters is the part of it which is
1338                  * relative to cvsroot.
1339                  */
1340                 char *repo;
1341                 char *r, *b;
1342
1343                 repo = xmalloc (strlen (reposdirname)
1344                                 + strlen (toplevel_repos)
1345                                 + 80);
1346                 if (reposdirname_absolute)
1347                     r = repo;
1348                 else
1349                 {
1350                     strcpy (repo, toplevel_repos);
1351                     strcat (repo, "/");
1352                     r = repo + strlen (repo);
1353                 }
1354
1355                 if (rdirp)
1356                 {
1357                     /* See comment near start of function; the only
1358                        way that the server can put the right thing
1359                        in each CVS/Repository file is to create the
1360                        directories one at a time.  I think that the
1361                        CVS server has been doing this all along.  */
1362                     error (0, 0, "\
1363 warning: server is not creating directories one at a time");
1364                     strncpy (r, reposdirname, rdirp - reposdirname);
1365                     r[rdirp - reposdirname] = '\0';
1366                 }
1367                 else
1368                     strcpy (r, reposdirname);
1369
1370                 Create_Admin (dir, dir, repo,
1371                               (char *)NULL, (char *)NULL, 0, 0, 1);
1372                 free (repo);
1373
1374                 b = strrchr (dir, '/');
1375                 if (b == NULL)
1376                     Subdir_Register ((List *) NULL, (char *) NULL, dir);
1377                 else
1378                 {
1379                     *b = '\0';
1380                     Subdir_Register ((List *) NULL, dir, b + 1);
1381                     *b = '/';
1382                 }
1383             }
1384
1385             if (rdirp != NULL)
1386             {
1387                 /* Skip the slash.  */
1388                 ++rdirp;
1389             }
1390
1391         } while (dirp != NULL);
1392         free (dir);
1393         /* Now it better work.  */
1394         if ( CVS_CHDIR (dir_name) < 0)
1395             error (1, errno, "could not chdir to %s", dir_name);
1396     }
1397     else if (strcmp (cvs_cmd_name, "export") == 0)
1398         /* Don't create CVSADM directories if this is export.  */
1399         ;
1400     else if (!isdir (CVSADM))
1401     {
1402         /*
1403          * Put repository in CVS/Repository.  For historical
1404          * (pre-CVS/Root) reasons, this is an absolute pathname,
1405          * but what really matters is the part of it which is
1406          * relative to cvsroot.
1407          */
1408         char *repo;
1409
1410         if (reposdirname_absolute)
1411             repo = reposdirname;
1412         else
1413         {
1414             repo = xmalloc (strlen (reposdirname)
1415                             + strlen (toplevel_repos)
1416                             + 10);
1417             strcpy (repo, toplevel_repos);
1418             strcat (repo, "/");
1419             strcat (repo, reposdirname);
1420         }
1421
1422         Create_Admin (".", ".", repo, (char *)NULL, (char *)NULL, 0, 1, 1);
1423         if (repo != reposdirname)
1424             free (repo);
1425     }
1426
1427     if (strcmp (cvs_cmd_name, "export") != 0)
1428     {
1429         last_entries = Entries_Open (0, dir_name);
1430
1431         /* If this is a newly created directory, we will record
1432            all subdirectory information, so call Subdirs_Known in
1433            case there are no subdirectories.  If this is not a
1434            newly created directory, it may be an old working
1435            directory from before we recorded subdirectory
1436            information in the Entries file.  We force a search for
1437            all subdirectories now, to make sure our subdirectory
1438            information is up to date.  If the Entries file does
1439            record subdirectory information, then this call only
1440            does list manipulation.  */
1441         if (newdir)
1442             Subdirs_Known (last_entries);
1443         else
1444         {
1445             List *dirlist;
1446
1447             dirlist = Find_Directories ((char *) NULL, W_LOCAL,
1448                                         last_entries);
1449             dellist (&dirlist);
1450         }
1451     }
1452     free (reposdirname);
1453     (*func) (data, last_entries, short_pathname, filename);
1454     if (last_entries != NULL)
1455         Entries_Close (last_entries);
1456     free (dir_name);
1457     free (short_pathname);
1458     free (reposname);
1459 }
1460 \f
1461 static void
1462 copy_a_file (data, ent_list, short_pathname, filename)
1463     char *data;
1464     List *ent_list;
1465     char *short_pathname;
1466     char *filename;
1467 {
1468     char *newname;
1469 #ifdef USE_VMS_FILENAMES
1470     char *p;
1471 #endif
1472
1473     read_line (&newname);
1474
1475 #ifdef USE_VMS_FILENAMES
1476     /* Mogrify the filename so VMS is happy with it. */
1477     for(p = newname; *p; p++)
1478        if(*p == '.' || *p == '#') *p = '_';
1479 #endif
1480     /* cvsclient.texi has said for a long time that newname must be in the
1481        same directory.  Wouldn't want a malicious or buggy server overwriting
1482        ~/.profile, /etc/passwd, or anything like that.  */
1483     if (last_component (newname) != newname)
1484         error (1, 0, "protocol error: Copy-file tried to specify directory");
1485
1486     if (unlink_file (newname) && !existence_error (errno))
1487         error (0, errno, "unable to remove %s", newname);
1488     copy_file (filename, newname);
1489     free (newname);
1490 }
1491
1492 static void
1493 handle_copy_file (args, len)
1494     char *args;
1495     int len;
1496 {
1497     call_in_directory (args, copy_a_file, (char *)NULL);
1498 }
1499 \f
1500
1501 static void read_counted_file PROTO ((char *, char *));
1502
1503 /* Read from the server the count for the length of a file, then read
1504    the contents of that file and write them to FILENAME.  FULLNAME is
1505    the name of the file for use in error messages.  FIXME-someday:
1506    extend this to deal with compressed files and make update_entries
1507    use it.  On error, gives a fatal error.  */
1508 static void
1509 read_counted_file (filename, fullname)
1510     char *filename;
1511     char *fullname;
1512 {
1513     char *size_string;
1514     size_t size;
1515     char *buf;
1516
1517     /* Pointers in buf to the place to put data which will be read,
1518        and the data which needs to be written, respectively.  */
1519     char *pread;
1520     char *pwrite;
1521     /* Number of bytes left to read and number of bytes in buf waiting to
1522        be written, respectively.  */
1523     size_t nread;
1524     size_t nwrite;
1525
1526     FILE *fp;
1527
1528     read_line (&size_string);
1529     if (size_string[0] == 'z')
1530         error (1, 0, "\
1531 protocol error: compressed files not supported for that operation");
1532     /* FIXME: should be doing more error checking, probably.  Like using
1533        strtoul and making sure we used up the whole line.  */
1534     size = atoi (size_string);
1535     free (size_string);
1536
1537     /* A more sophisticated implementation would use only a limited amount
1538        of buffer space (8K perhaps), and read that much at a time.  We allocate
1539        a buffer for the whole file only to make it easy to keep track what
1540        needs to be read and written.  */
1541     buf = xmalloc (size);
1542
1543     /* FIXME-someday: caller should pass in a flag saying whether it
1544        is binary or not.  I haven't carefully looked into whether
1545        CVS/Template files should use local text file conventions or
1546        not.  */
1547     fp = CVS_FOPEN (filename, "wb");
1548     if (fp == NULL)
1549         error (1, errno, "cannot write %s", fullname);
1550     nread = size;
1551     nwrite = 0;
1552     pread = buf;
1553     pwrite = buf;
1554     while (nread > 0 || nwrite > 0)
1555     {
1556         size_t n;
1557
1558         if (nread > 0)
1559         {
1560             n = try_read_from_server (pread, nread);
1561             nread -= n;
1562             pread += n;
1563             nwrite += n;
1564         }
1565
1566         if (nwrite > 0)
1567         {
1568             n = fwrite (pwrite, 1, nwrite, fp);
1569             if (ferror (fp))
1570                 error (1, errno, "cannot write %s", fullname);
1571             nwrite -= n;
1572             pwrite += n;
1573         }
1574     }
1575     free (buf);
1576     if (fclose (fp) < 0)
1577         error (1, errno, "cannot close %s", fullname);
1578 }
1579 \f
1580 /* OK, we want to swallow the "U foo.c" response and then output it only
1581    if we can update the file.  In the future we probably want some more
1582    systematic approach to parsing tagged text, but for now we keep it
1583    ad hoc.  "Why," I hear you cry, "do we not just look at the
1584    Update-existing and Created responses?"  That is an excellent question,
1585    and the answer is roughly conservatism/laziness--I haven't read through
1586    update.c enough to figure out the exact correspondence or lack thereof
1587    between those responses and a "U foo.c" line (note that Merged, from
1588    join_file, can be either "C foo" or "U foo" depending on the context).  */
1589 /* Nonzero if we have seen +updated and not -updated.  */
1590 static int updated_seen;
1591 /* Filename from an "fname" tagged response within +updated/-updated.  */
1592 static char *updated_fname;
1593
1594 /* This struct is used to hold data when reading the +importmergecmd
1595    and -importmergecmd tags.  We put the variables in a struct only
1596    for namespace issues.  FIXME: As noted above, we need to develop a
1597    more systematic approach.  */
1598 static struct
1599 {
1600     /* Nonzero if we have seen +importmergecmd and not -importmergecmd.  */
1601     int seen;
1602     /* Number of conflicts, from a "conflicts" tagged response.  */
1603     int conflicts;
1604     /* First merge tag, from a "mergetag1" tagged response.  */
1605     char *mergetag1;
1606     /* Second merge tag, from a "mergetag2" tagged response.  */
1607     char *mergetag2;
1608     /* Repository, from a "repository" tagged response.  */
1609     char *repository;
1610 } importmergecmd;
1611
1612 /* Nonzero if we should arrange to return with a failure exit status.  */
1613 static int failure_exit;
1614
1615
1616 /*
1617  * The time stamp of the last file we registered.
1618  */
1619 static time_t last_register_time;
1620
1621 /*
1622  * The Checksum response gives the checksum for the file transferred
1623  * over by the next Updated, Merged or Patch response.  We just store
1624  * it here, and then check it in update_entries.
1625  */
1626
1627 static int stored_checksum_valid;
1628 static unsigned char stored_checksum[16];
1629
1630 static void
1631 handle_checksum (args, len)
1632     char *args;
1633     int len;
1634 {
1635     char *s;
1636     char buf[3];
1637     int i;
1638
1639     if (stored_checksum_valid)
1640         error (1, 0, "Checksum received before last one was used");
1641
1642     s = args;
1643     buf[2] = '\0';
1644     for (i = 0; i < 16; i++)
1645     {
1646         char *bufend;
1647
1648         buf[0] = *s++;
1649         buf[1] = *s++;
1650         stored_checksum[i] = (char) strtol (buf, &bufend, 16);
1651         if (bufend != buf + 2)
1652             break;
1653     }
1654
1655     if (i < 16 || *s != '\0')
1656         error (1, 0, "Invalid Checksum response: `%s'", args);
1657
1658     stored_checksum_valid = 1;
1659 }
1660
1661 /* Mode that we got in a "Mode" response (malloc'd), or NULL if none.  */
1662 static char *stored_mode;
1663
1664 static void handle_mode PROTO ((char *, int));
1665
1666 static void
1667 handle_mode (args, len)
1668     char *args;
1669     int len;
1670 {
1671     if (stored_mode != NULL)
1672         error (1, 0, "protocol error: duplicate Mode");
1673     stored_mode = xstrdup (args);
1674 }
1675 \f
1676 /* Nonzero if time was specified in Mod-time.  */
1677 static int stored_modtime_valid;
1678 /* Time specified in Mod-time.  */
1679 static time_t stored_modtime;
1680
1681 static void handle_mod_time PROTO ((char *, int));
1682
1683 static void
1684 handle_mod_time (args, len)
1685     char *args;
1686     int len;
1687 {
1688     if (stored_modtime_valid)
1689         error (0, 0, "protocol error: duplicate Mod-time");
1690     stored_modtime = get_date (args, NULL);
1691     if (stored_modtime == (time_t) -1)
1692         error (0, 0, "protocol error: cannot parse date %s", args);
1693     else
1694         stored_modtime_valid = 1;
1695 }
1696 \f
1697 /*
1698  * If we receive a patch, but the patch program fails to apply it, we
1699  * want to request the original file.  We keep a list of files whose
1700  * patches have failed.
1701  */
1702
1703 char **failed_patches;
1704 int failed_patches_count;
1705
1706 struct update_entries_data
1707 {
1708     enum {
1709       /*
1710        * We are just getting an Entries line; the local file is
1711        * correct.
1712        */
1713       UPDATE_ENTRIES_CHECKIN,
1714       /* We are getting the file contents as well.  */
1715       UPDATE_ENTRIES_UPDATE,
1716       /*
1717        * We are getting a patch against the existing local file, not
1718        * an entire new file.
1719        */
1720       UPDATE_ENTRIES_PATCH,
1721       /*
1722        * We are getting an RCS change text (diff -n output) against
1723        * the existing local file, not an entire new file.
1724        */
1725       UPDATE_ENTRIES_RCS_DIFF
1726     } contents;
1727
1728     enum {
1729         /* We are replacing an existing file.  */
1730         UPDATE_ENTRIES_EXISTING,
1731         /* We are creating a new file.  */
1732         UPDATE_ENTRIES_NEW,
1733         /* We don't know whether it is existing or new.  */
1734         UPDATE_ENTRIES_EXISTING_OR_NEW
1735     } existp;
1736
1737     /*
1738      * String to put in the timestamp field or NULL to use the timestamp
1739      * of the file.
1740      */
1741     char *timestamp;
1742 };
1743
1744 /* Update the Entries line for this file.  */
1745 static void
1746 update_entries (data_arg, ent_list, short_pathname, filename)
1747     char *data_arg;
1748     List *ent_list;
1749     char *short_pathname;
1750     char *filename;
1751 {
1752     char *entries_line;
1753     struct update_entries_data *data = (struct update_entries_data *)data_arg;
1754
1755     char *cp;
1756     char *user;
1757     char *vn;
1758     /* Timestamp field.  Always empty according to the protocol.  */
1759     char *ts;
1760     char *options = NULL;
1761     char *tag = NULL;
1762     char *date = NULL;
1763     char *tag_or_date;
1764     char *scratch_entries = NULL;
1765     int bin;
1766
1767 #ifdef UTIME_EXPECTS_WRITABLE
1768     int change_it_back = 0;
1769 #endif
1770
1771     read_line (&entries_line);
1772
1773     /*
1774      * Parse the entries line.
1775      */
1776     scratch_entries = xstrdup (entries_line);
1777
1778     if (scratch_entries[0] != '/')
1779         error (1, 0, "bad entries line `%s' from server", entries_line);
1780     user = scratch_entries + 1;
1781     if ((cp = strchr (user, '/')) == NULL)
1782         error (1, 0, "bad entries line `%s' from server", entries_line);
1783     *cp++ = '\0';
1784     vn = cp;
1785     if ((cp = strchr (vn, '/')) == NULL)
1786         error (1, 0, "bad entries line `%s' from server", entries_line);
1787     *cp++ = '\0';
1788     
1789     ts = cp;
1790     if ((cp = strchr (ts, '/')) == NULL)
1791         error (1, 0, "bad entries line `%s' from server", entries_line);
1792     *cp++ = '\0';
1793     options = cp;
1794     if ((cp = strchr (options, '/')) == NULL)
1795         error (1, 0, "bad entries line `%s' from server", entries_line);
1796     *cp++ = '\0';
1797     tag_or_date = cp;
1798     
1799     /* If a slash ends the tag_or_date, ignore everything after it.  */
1800     cp = strchr (tag_or_date, '/');
1801     if (cp != NULL)
1802         *cp = '\0';
1803     if (*tag_or_date == 'T')
1804         tag = tag_or_date + 1;
1805     else if (*tag_or_date == 'D')
1806         date = tag_or_date + 1;
1807
1808     /* Done parsing the entries line. */
1809
1810     if (data->contents == UPDATE_ENTRIES_UPDATE
1811         || data->contents == UPDATE_ENTRIES_PATCH
1812         || data->contents == UPDATE_ENTRIES_RCS_DIFF)
1813     {
1814         char *size_string;
1815         char *mode_string;
1816         int size;
1817         char *buf;
1818         char *temp_filename;
1819         int use_gzip;
1820         int patch_failed;
1821
1822         read_line (&mode_string);
1823         
1824         read_line (&size_string);
1825         if (size_string[0] == 'z')
1826         {
1827             use_gzip = 1;
1828             size = atoi (size_string+1);
1829         }
1830         else
1831         {
1832             use_gzip = 0;
1833             size = atoi (size_string);
1834         }
1835         free (size_string);
1836
1837         /* Note that checking this separately from writing the file is
1838            a race condition: if the existence or lack thereof of the
1839            file changes between now and the actual calls which
1840            operate on it, we lose.  However (a) there are so many
1841            cases, I'm reluctant to try to fix them all, (b) in some
1842            cases the system might not even have a system call which
1843            does the right thing, and (c) it isn't clear this needs to
1844            work.  */
1845         if (data->existp == UPDATE_ENTRIES_EXISTING
1846             && !isfile (filename))
1847             /* Emit a warning and update the file anyway.  */
1848             error (0, 0, "warning: %s unexpectedly disappeared",
1849                    short_pathname);
1850
1851         if (data->existp == UPDATE_ENTRIES_NEW
1852             && isfile (filename))
1853         {
1854             /* Emit a warning and refuse to update the file; we don't want
1855                to clobber a user's file.  */
1856             size_t nread;
1857             size_t toread;
1858
1859             /* size should be unsigned, but until we get around to fixing
1860                that, work around it.  */
1861             size_t usize;
1862
1863             char buf[8192];
1864
1865             /* This error might be confusing; it isn't really clear to
1866                the user what to do about it.  Keep in mind that it has
1867                several causes: (1) something/someone creates the file
1868                during the time that CVS is running, (2) the repository
1869                has two files whose names clash for the client because
1870                of case-insensitivity or similar causes, See 3 for
1871                additional notes.  (3) a special case of this is that a
1872                file gets renamed for example from a.c to A.C.  A
1873                "cvs update" on a case-insensitive client will get this
1874                error.  In this case and in case 2, the filename
1875                (short_pathname) printed in the error message will likely _not_
1876                have the same case as seen by the user in a directory listing.
1877                (4) the client has a file which the server doesn't know
1878                about (e.g. "? foo" file), and that name clashes with a file
1879                the server does know about, (5) classify.c will print the same
1880                message for other reasons.
1881
1882                I hope the above paragraph makes it clear that making this
1883                clearer is not a one-line fix.  */
1884             error (0, 0, "move away %s; it is in the way", short_pathname);
1885             if (updated_fname != NULL)
1886             {
1887                 cvs_output ("C ", 0);
1888                 cvs_output (updated_fname, 0);
1889                 cvs_output ("\n", 1);
1890             }
1891             failure_exit = 1;
1892
1893         discard_file_and_return:
1894             /* Now read and discard the file contents.  */
1895             usize = size;
1896             nread = 0;
1897             while (nread < usize)
1898             {
1899                 toread = usize - nread;
1900                 if (toread > sizeof buf)
1901                     toread = sizeof buf;
1902
1903                 nread += try_read_from_server (buf, toread);
1904                 if (nread == usize)
1905                     break;
1906             }
1907
1908             free (mode_string);
1909             free (scratch_entries);
1910             free (entries_line);
1911
1912             /* The Mode, Mod-time, and Checksum responses should not carry
1913                over to a subsequent Created (or whatever) response, even
1914                in the error case.  */
1915             if (stored_mode != NULL)
1916             {
1917                 free (stored_mode);
1918                 stored_mode = NULL;
1919             }
1920             stored_modtime_valid = 0;
1921             stored_checksum_valid = 0;
1922
1923             if (updated_fname != NULL)
1924             {
1925                 free (updated_fname);
1926                 updated_fname = NULL;
1927             }
1928             return;
1929         }
1930
1931         temp_filename = xmalloc (strlen (filename) + 80);
1932 #ifdef USE_VMS_FILENAMES
1933         /* A VMS rename of "blah.dat" to "foo" to implies a
1934            destination of "foo.dat" which is unfortinate for CVS */
1935        sprintf (temp_filename, "%s_new_", filename);
1936 #else
1937 #ifdef _POSIX_NO_TRUNC
1938         sprintf (temp_filename, ".new.%.9s", filename);
1939 #else /* _POSIX_NO_TRUNC */
1940         sprintf (temp_filename, ".new.%s", filename);
1941 #endif /* _POSIX_NO_TRUNC */
1942 #endif /* USE_VMS_FILENAMES */
1943
1944         buf = xmalloc (size);
1945
1946         /* Some systems, like OS/2 and Windows NT, end lines with CRLF
1947            instead of just LF.  Format translation is done in the C
1948            library I/O funtions.  Here we tell them whether or not to
1949            convert -- if this file is marked "binary" with the RCS -kb
1950            flag, then we don't want to convert, else we do (because
1951            CVS assumes text files by default). */
1952
1953         if (options)
1954             bin = !(strcmp (options, "-kb"));
1955         else
1956             bin = 0;
1957
1958         if (data->contents == UPDATE_ENTRIES_RCS_DIFF)
1959         {
1960             /* This is an RCS change text.  We just hold the change
1961                text in memory.  */
1962
1963             if (use_gzip)
1964                 error (1, 0,
1965                        "server error: gzip invalid with RCS change text");
1966
1967             read_from_server (buf, size);
1968         }
1969         else
1970         {
1971             int fd;
1972
1973             fd = CVS_OPEN (temp_filename,
1974                            (O_WRONLY | O_CREAT | O_TRUNC
1975                             | (bin ? OPEN_BINARY : 0)),
1976                            0777);
1977
1978             if (fd < 0)
1979             {
1980                 /* I can see a case for making this a fatal error; for
1981                    a condition like disk full or network unreachable
1982                    (for a file server), carrying on and giving an
1983                    error on each file seems unnecessary.  But if it is
1984                    a permission problem, or some such, then it is
1985                    entirely possible that future files will not have
1986                    the same problem.  */
1987                 error (0, errno, "cannot write %s", short_pathname);
1988                 goto discard_file_and_return;
1989             }
1990
1991             if (size > 0)
1992             {
1993                 read_from_server (buf, size);
1994
1995                 if (use_gzip)
1996                 {
1997                     if (gunzip_and_write (fd, short_pathname, 
1998                                           (unsigned char *) buf, size))
1999                         error (1, 0, "aborting due to compression error");
2000                 }
2001                 else if (write (fd, buf, size) != size)
2002                     error (1, errno, "writing %s", short_pathname);
2003             }
2004
2005             if (close (fd) < 0)
2006                 error (1, errno, "writing %s", short_pathname);
2007         }
2008
2009         /* This is after we have read the file from the net (a change
2010            from previous versions, where the server would send us
2011            "M U foo.c" before Update-existing or whatever), but before
2012            we finish writing the file (arguably a bug).  The timing
2013            affects a user who wants status info about how far we have
2014            gotten, and also affects whether "U foo.c" appears in addition
2015            to various error messages.  */
2016         if (updated_fname != NULL)
2017         {
2018             cvs_output ("U ", 0);
2019             cvs_output (updated_fname, 0);
2020             cvs_output ("\n", 1);
2021             free (updated_fname);
2022             updated_fname = 0;
2023         }
2024
2025         patch_failed = 0;
2026
2027         if (data->contents == UPDATE_ENTRIES_UPDATE)
2028         {
2029             rename_file (temp_filename, filename);
2030         }
2031         else if (data->contents == UPDATE_ENTRIES_PATCH)
2032         {
2033             /* You might think we could just leave Patched out of
2034                Valid-responses and not get this response.  However, if
2035                memory serves, the CVS 1.9 server bases this on -u
2036                (update-patches), and there is no way for us to send -u
2037                or not based on whether the server supports "Rcs-diff".  
2038
2039                Fall back to transmitting entire files.  */
2040             patch_failed = 1;
2041         }
2042         else
2043         {
2044             char *filebuf;
2045             size_t filebufsize;
2046             size_t nread;
2047             char *patchedbuf;
2048             size_t patchedlen;
2049
2050             /* Handle UPDATE_ENTRIES_RCS_DIFF.  */
2051
2052             if (!isfile (filename))
2053                 error (1, 0, "patch original file %s does not exist",
2054                        short_pathname);
2055             filebuf = NULL;
2056             filebufsize = 0;
2057             nread = 0;
2058
2059             get_file (filename, short_pathname, bin ? FOPEN_BINARY_READ : "r",
2060                       &filebuf, &filebufsize, &nread);
2061             /* At this point the contents of the existing file are in
2062                FILEBUF, and the length of the contents is in NREAD.
2063                The contents of the patch from the network are in BUF,
2064                and the length of the patch is in SIZE.  */
2065
2066             if (! rcs_change_text (short_pathname, filebuf, nread, buf, size,
2067                                    &patchedbuf, &patchedlen))
2068                 patch_failed = 1;
2069             else
2070             {
2071                 if (stored_checksum_valid)
2072                 {
2073                     struct cvs_MD5Context context;
2074                     unsigned char checksum[16];
2075
2076                     /* We have a checksum.  Check it before writing
2077                        the file out, so that we don't have to read it
2078                        back in again.  */
2079                     cvs_MD5Init (&context);
2080                     cvs_MD5Update (&context,
2081                                    (unsigned char *) patchedbuf, patchedlen);
2082                     cvs_MD5Final (checksum, &context);
2083                     if (memcmp (checksum, stored_checksum, 16) != 0)
2084                     {
2085                         error (0, 0,
2086                                "checksum failure after patch to %s; will refetch",
2087                                short_pathname);
2088
2089                         patch_failed = 1;
2090                     }
2091
2092                     stored_checksum_valid = 0;
2093                 }
2094
2095                 if (! patch_failed)
2096                 {
2097                     FILE *e;
2098
2099                     e = open_file (temp_filename,
2100                                    bin ? FOPEN_BINARY_WRITE : "w");
2101                     if (fwrite (patchedbuf, 1, patchedlen, e) != patchedlen)
2102                         error (1, errno, "cannot write %s", temp_filename);
2103                     if (fclose (e) == EOF)
2104                         error (1, errno, "cannot close %s", temp_filename);
2105                     rename_file (temp_filename, filename);
2106                 }
2107
2108                 free (patchedbuf);
2109             }
2110
2111             free (filebuf);
2112         }
2113
2114         free (temp_filename);
2115
2116         if (stored_checksum_valid && ! patch_failed)
2117         {
2118             FILE *e;
2119             struct cvs_MD5Context context;
2120             unsigned char buf[8192];
2121             unsigned len;
2122             unsigned char checksum[16];
2123
2124             /*
2125              * Compute the MD5 checksum.  This will normally only be
2126              * used when receiving a patch, so we always compute it
2127              * here on the final file, rather than on the received
2128              * data.
2129              *
2130              * Note that if the file is a text file, we should read it
2131              * here using text mode, so its lines will be terminated the same
2132              * way they were transmitted.
2133              */
2134             e = CVS_FOPEN (filename, "r");
2135             if (e == NULL)
2136                 error (1, errno, "could not open %s", short_pathname);
2137
2138             cvs_MD5Init (&context);
2139             while ((len = fread (buf, 1, sizeof buf, e)) != 0)
2140                 cvs_MD5Update (&context, buf, len);
2141             if (ferror (e))
2142                 error (1, errno, "could not read %s", short_pathname);
2143             cvs_MD5Final (checksum, &context);
2144
2145             fclose (e);
2146
2147             stored_checksum_valid = 0;
2148
2149             if (memcmp (checksum, stored_checksum, 16) != 0)
2150             {
2151                 if (data->contents != UPDATE_ENTRIES_PATCH)
2152                     error (1, 0, "checksum failure on %s",
2153                            short_pathname);
2154
2155                 error (0, 0,
2156                        "checksum failure after patch to %s; will refetch",
2157                        short_pathname);
2158
2159                 patch_failed = 1;
2160             }
2161         }
2162
2163         if (patch_failed)
2164         {
2165             /* Save this file to retrieve later.  */
2166             failed_patches = (char **) xrealloc ((char *) failed_patches,
2167                                                  ((failed_patches_count + 1)
2168                                                   * sizeof (char *)));
2169             failed_patches[failed_patches_count] = xstrdup (short_pathname);
2170             ++failed_patches_count;
2171
2172             stored_checksum_valid = 0;
2173
2174             free (mode_string);
2175             free (buf);
2176             free (scratch_entries);
2177             free (entries_line);
2178
2179             return;
2180         }
2181
2182         {
2183             int status = change_mode (filename, mode_string, 1);
2184             if (status != 0)
2185                 error (0, status, "cannot change mode of %s", short_pathname);
2186         }
2187
2188         free (mode_string);
2189         free (buf);
2190     }
2191
2192     if (stored_mode != NULL)
2193     {
2194         change_mode (filename, stored_mode, 1);
2195         free (stored_mode);
2196         stored_mode = NULL;
2197     }
2198    
2199     if (stored_modtime_valid)
2200     {
2201         struct utimbuf t;
2202
2203         memset (&t, 0, sizeof (t));
2204         t.modtime = stored_modtime;
2205         (void) time (&t.actime);
2206
2207 #ifdef UTIME_EXPECTS_WRITABLE
2208         if (!iswritable (filename))
2209         {
2210             xchmod (filename, 1);
2211             change_it_back = 1;
2212         }
2213 #endif  /* UTIME_EXPECTS_WRITABLE  */
2214
2215         if (utime (filename, &t) < 0)
2216             error (0, errno, "cannot set time on %s", filename);
2217
2218 #ifdef UTIME_EXPECTS_WRITABLE
2219         if (change_it_back)
2220         {
2221             xchmod (filename, 0);
2222             change_it_back = 0;
2223         }
2224 #endif  /*  UTIME_EXPECTS_WRITABLE  */
2225
2226         stored_modtime_valid = 0;
2227     }
2228
2229     /*
2230      * Process the entries line.  Do this after we've written the file,
2231      * since we need the timestamp.
2232      */
2233     if (strcmp (cvs_cmd_name, "export") != 0)
2234     {
2235         char *local_timestamp;
2236         char *file_timestamp;
2237
2238         (void) time (&last_register_time);
2239
2240         local_timestamp = data->timestamp;
2241         if (local_timestamp == NULL || ts[0] == '+')
2242             file_timestamp = time_stamp (filename);
2243         else
2244             file_timestamp = NULL;
2245
2246         /*
2247          * These special version numbers signify that it is not up to
2248          * date.  Create a dummy timestamp which will never compare
2249          * equal to the timestamp of the file.
2250          */
2251         if (vn[0] == '\0' || strcmp (vn, "0") == 0 || vn[0] == '-')
2252             local_timestamp = "dummy timestamp";
2253         else if (local_timestamp == NULL)
2254         {
2255             local_timestamp = file_timestamp;
2256
2257             /* Checking for cvs_cmd_name of "commit" doesn't seem like
2258                the cleanest way to handle this, but it seem to roughly
2259                parallel what the :local: code which calls
2260                mark_up_to_date ends up amounting to.  Some day, should
2261                think more about what the Checked-in response means
2262                vis-a-vis both Entries and Base and clarify
2263                cvsclient.texi accordingly.  */
2264
2265             if (!strcmp (cvs_cmd_name, "commit"))
2266                 mark_up_to_date (filename);
2267         }
2268
2269         Register (ent_list, filename, vn, local_timestamp,
2270                   options, tag, date, ts[0] == '+' ? file_timestamp : NULL);
2271
2272         if (file_timestamp)
2273             free (file_timestamp);
2274
2275     }
2276     free (scratch_entries);
2277     free (entries_line);
2278 }
2279
2280 static void
2281 handle_checked_in (args, len)
2282     char *args;
2283     int len;
2284 {
2285     struct update_entries_data dat;
2286     dat.contents = UPDATE_ENTRIES_CHECKIN;
2287     dat.existp = UPDATE_ENTRIES_EXISTING_OR_NEW;
2288     dat.timestamp = NULL;
2289     call_in_directory (args, update_entries, (char *)&dat);
2290 }
2291
2292 static void
2293 handle_new_entry (args, len)
2294     char *args;
2295     int len;
2296 {
2297     struct update_entries_data dat;
2298     dat.contents = UPDATE_ENTRIES_CHECKIN;
2299     dat.existp = UPDATE_ENTRIES_EXISTING_OR_NEW;
2300     dat.timestamp = "dummy timestamp from new-entry";
2301     call_in_directory (args, update_entries, (char *)&dat);
2302 }
2303
2304 static void
2305 handle_updated (args, len)
2306     char *args;
2307     int len;
2308 {
2309     struct update_entries_data dat;
2310     dat.contents = UPDATE_ENTRIES_UPDATE;
2311     dat.existp = UPDATE_ENTRIES_EXISTING_OR_NEW;
2312     dat.timestamp = NULL;
2313     call_in_directory (args, update_entries, (char *)&dat);
2314 }
2315
2316 static void handle_created PROTO((char *, int));
2317
2318 static void
2319 handle_created (args, len)
2320     char *args;
2321     int len;
2322 {
2323     struct update_entries_data dat;
2324     dat.contents = UPDATE_ENTRIES_UPDATE;
2325     dat.existp = UPDATE_ENTRIES_NEW;
2326     dat.timestamp = NULL;
2327     call_in_directory (args, update_entries, (char *)&dat);
2328 }
2329
2330 static void handle_update_existing PROTO((char *, int));
2331
2332 static void
2333 handle_update_existing (args, len)
2334     char *args;
2335     int len;
2336 {
2337     struct update_entries_data dat;
2338     dat.contents = UPDATE_ENTRIES_UPDATE;
2339     dat.existp = UPDATE_ENTRIES_EXISTING;
2340     dat.timestamp = NULL;
2341     call_in_directory (args, update_entries, (char *)&dat);
2342 }
2343
2344 static void
2345 handle_merged (args, len)
2346     char *args;
2347     int len;
2348 {
2349     struct update_entries_data dat;
2350     dat.contents = UPDATE_ENTRIES_UPDATE;
2351     /* Think this could be UPDATE_ENTRIES_EXISTING, but just in case...  */
2352     dat.existp = UPDATE_ENTRIES_EXISTING_OR_NEW;
2353     dat.timestamp = "Result of merge";
2354     call_in_directory (args, update_entries, (char *)&dat);
2355 }
2356
2357 static void
2358 handle_patched (args, len)
2359      char *args;
2360      int len;
2361 {
2362     struct update_entries_data dat;
2363     dat.contents = UPDATE_ENTRIES_PATCH;
2364     /* Think this could be UPDATE_ENTRIES_EXISTING, but just in case...  */
2365     dat.existp = UPDATE_ENTRIES_EXISTING_OR_NEW;
2366     dat.timestamp = NULL;
2367     call_in_directory (args, update_entries, (char *)&dat);
2368 }
2369
2370 static void
2371 handle_rcs_diff (args, len)
2372      char *args;
2373      int len;
2374 {
2375     struct update_entries_data dat;
2376     dat.contents = UPDATE_ENTRIES_RCS_DIFF;
2377     /* Think this could be UPDATE_ENTRIES_EXISTING, but just in case...  */
2378     dat.existp = UPDATE_ENTRIES_EXISTING_OR_NEW;
2379     dat.timestamp = NULL;
2380     call_in_directory (args, update_entries, (char *)&dat);
2381 }
2382 \f
2383 static void
2384 remove_entry (data, ent_list, short_pathname, filename)
2385     char *data;
2386     List *ent_list;
2387     char *short_pathname;
2388     char *filename;
2389 {
2390     Scratch_Entry (ent_list, filename);
2391 }
2392
2393 static void
2394 handle_remove_entry (args, len)
2395     char *args;
2396     int len;
2397 {
2398     call_in_directory (args, remove_entry, (char *)NULL);
2399 }
2400 \f
2401 static void
2402 remove_entry_and_file (data, ent_list, short_pathname, filename)
2403     char *data;
2404     List *ent_list;
2405     char *short_pathname;
2406     char *filename;
2407 {
2408     Scratch_Entry (ent_list, filename);
2409     /* Note that we don't ignore existence_error's here.  The server
2410        should be sending Remove-entry rather than Removed in cases
2411        where the file does not exist.  And if the user removes the
2412        file halfway through a cvs command, we should be printing an
2413        error.  */
2414     if (unlink_file (filename) < 0)
2415         error (0, errno, "unable to remove %s", short_pathname);
2416 }
2417
2418 static void
2419 handle_removed (args, len)
2420     char *args;
2421     int len;
2422 {
2423     call_in_directory (args, remove_entry_and_file, (char *)NULL);
2424 }
2425 \f
2426 /* Is this the top level (directory containing CVSROOT)?  */
2427 static int
2428 is_cvsroot_level (pathname)
2429     char *pathname;
2430 {
2431     if (strcmp (toplevel_repos, current_parsed_root->directory) != 0)
2432         return 0;
2433
2434     return strchr (pathname, '/') == NULL;
2435 }
2436 \f
2437 static void
2438 set_static (data, ent_list, short_pathname, filename)
2439     char *data;
2440     List *ent_list;
2441     char *short_pathname;
2442     char *filename;
2443 {
2444     FILE *fp;
2445     fp = open_file (CVSADM_ENTSTAT, "w+");
2446     if (fclose (fp) == EOF)
2447         error (1, errno, "cannot close %s", CVSADM_ENTSTAT);
2448 }
2449
2450 static void
2451 handle_set_static_directory (args, len)
2452     char *args;
2453     int len;
2454 {
2455     if (strcmp (cvs_cmd_name, "export") == 0)
2456     {
2457         /* Swallow the repository.  */
2458         read_line (NULL);
2459         return;
2460     }
2461     call_in_directory (args, set_static, (char *)NULL);
2462 }
2463
2464 static void
2465 clear_static (data, ent_list, short_pathname, filename)
2466     char *data;
2467     List *ent_list;
2468     char *short_pathname;
2469     char *filename;
2470 {
2471     if (unlink_file (CVSADM_ENTSTAT) < 0 && ! existence_error (errno))
2472         error (1, errno, "cannot remove file %s", CVSADM_ENTSTAT);
2473 }
2474
2475 static void
2476 handle_clear_static_directory (pathname, len)
2477     char *pathname;
2478     int len;
2479 {
2480     if (strcmp (cvs_cmd_name, "export") == 0)
2481     {
2482         /* Swallow the repository.  */
2483         read_line (NULL);
2484         return;
2485     }
2486
2487     if (is_cvsroot_level (pathname))
2488     {
2489         /*
2490          * Top level (directory containing CVSROOT).  This seems to normally
2491          * lack a CVS directory, so don't try to create files in it.
2492          */
2493         return;
2494     }
2495     call_in_directory (pathname, clear_static, (char *)NULL);
2496 }
2497 \f
2498 static void
2499 set_sticky (data, ent_list, short_pathname, filename)
2500     char *data;
2501     List *ent_list;
2502     char *short_pathname;
2503     char *filename;
2504 {
2505     char *tagspec;
2506     FILE *f;
2507
2508     read_line (&tagspec);
2509
2510     /* FIXME-update-dir: error messages should include the directory.  */
2511     f = CVS_FOPEN (CVSADM_TAG, "w+");
2512     if (f == NULL)
2513     {
2514         /* Making this non-fatal is a bit of a kludge (see dirs2
2515            in testsuite).  A better solution would be to avoid having
2516            the server tell us about a directory we shouldn't be doing
2517            anything with anyway (e.g. by handling directory
2518            addition/removal better).  */
2519         error (0, errno, "cannot open %s", CVSADM_TAG);
2520         free (tagspec);
2521         return;
2522     }
2523     if (fprintf (f, "%s\n", tagspec) < 0)
2524         error (1, errno, "writing %s", CVSADM_TAG);
2525     if (fclose (f) == EOF)
2526         error (1, errno, "closing %s", CVSADM_TAG);
2527     free (tagspec);
2528 }
2529
2530 static void
2531 handle_set_sticky (pathname, len)
2532     char *pathname;
2533     int len;
2534 {
2535     if (strcmp (cvs_cmd_name, "export") == 0)
2536     {
2537         /* Swallow the repository.  */
2538         read_line (NULL);
2539         /* Swallow the tag line.  */
2540         read_line (NULL);
2541         return;
2542     }
2543     if (is_cvsroot_level (pathname))
2544     {
2545         /*
2546          * Top level (directory containing CVSROOT).  This seems to normally
2547          * lack a CVS directory, so don't try to create files in it.
2548          */
2549
2550         /* Swallow the repository.  */
2551         read_line (NULL);
2552         /* Swallow the tag line.  */
2553         read_line (NULL);
2554         return;
2555     }
2556
2557     call_in_directory (pathname, set_sticky, (char *)NULL);
2558 }
2559
2560 static void
2561 clear_sticky (data, ent_list, short_pathname, filename)
2562     char *data;
2563     List *ent_list;
2564     char *short_pathname;
2565     char *filename;
2566 {
2567     if (unlink_file (CVSADM_TAG) < 0 && ! existence_error (errno))
2568         error (1, errno, "cannot remove %s", CVSADM_TAG);
2569 }
2570
2571 static void
2572 handle_clear_sticky (pathname, len)
2573     char *pathname;
2574     int len;
2575 {
2576     if (strcmp (cvs_cmd_name, "export") == 0)
2577     {
2578         /* Swallow the repository.  */
2579         read_line (NULL);
2580         return;
2581     }
2582
2583     if (is_cvsroot_level (pathname))
2584     {
2585         /*
2586          * Top level (directory containing CVSROOT).  This seems to normally
2587          * lack a CVS directory, so don't try to create files in it.
2588          */
2589         return;
2590     }
2591
2592     call_in_directory (pathname, clear_sticky, (char *)NULL);
2593 }
2594 \f
2595
2596 static void template PROTO ((char *, List *, char *, char *));
2597
2598 static void
2599 template (data, ent_list, short_pathname, filename)
2600     char *data;
2601     List *ent_list;
2602     char *short_pathname;
2603     char *filename;
2604 {
2605     char *buf = xmalloc ( strlen ( short_pathname )
2606                           + strlen ( CVSADM_TEMPLATE )
2607                           + 2 );
2608     sprintf ( buf, "%s/%s", short_pathname, CVSADM_TEMPLATE );
2609     read_counted_file ( CVSADM_TEMPLATE, buf );
2610     free ( buf );
2611 }
2612
2613 static void handle_template PROTO ((char *, int));
2614
2615 static void
2616 handle_template (pathname, len)
2617     char *pathname;
2618     int len;
2619 {
2620     call_in_directory (pathname, template, NULL);
2621 }
2622
2623
2624
2625 struct save_dir {
2626     char *dir;
2627     struct save_dir *next;
2628 };
2629
2630 struct save_dir *prune_candidates;
2631
2632 static void
2633 add_prune_candidate (dir)
2634     const char *dir;
2635 {
2636     struct save_dir *p;
2637
2638     if ((dir[0] == '.' && dir[1] == '\0')
2639         || (prune_candidates != NULL
2640             && strcmp (dir, prune_candidates->dir) == 0))
2641         return;
2642     p = (struct save_dir *) xmalloc (sizeof (struct save_dir));
2643     p->dir = xstrdup (dir);
2644     p->next = prune_candidates;
2645     prune_candidates = p;
2646 }
2647
2648 static void process_prune_candidates PROTO((void));
2649
2650 static void
2651 process_prune_candidates ()
2652 {
2653     struct save_dir *p;
2654     struct save_dir *q;
2655
2656     if (toplevel_wd != NULL)
2657     {
2658         if (CVS_CHDIR (toplevel_wd) < 0)
2659             error (1, errno, "could not chdir to %s", toplevel_wd);
2660     }
2661     for (p = prune_candidates; p != NULL; )
2662     {
2663         if (isemptydir (p->dir, 1))
2664         {
2665             char *b;
2666
2667             if (unlink_file_dir (p->dir) < 0)
2668                 error (0, errno, "cannot remove %s", p->dir);
2669             b = strrchr (p->dir, '/');
2670             if (b == NULL)
2671                 Subdir_Deregister ((List *) NULL, (char *) NULL, p->dir);
2672             else
2673             {
2674                 *b = '\0';
2675                 Subdir_Deregister ((List *) NULL, p->dir, b + 1);
2676             }
2677         }
2678         free (p->dir);
2679         q = p->next;
2680         free (p);
2681         p = q;
2682     }
2683     prune_candidates = NULL;
2684 }
2685 \f
2686 /* Send a Repository line.  */
2687
2688 static char *last_repos;
2689 static char *last_update_dir;
2690
2691 static void send_repository PROTO((const char *, const char *, const char *));
2692
2693 static void
2694 send_repository (dir, repos, update_dir)
2695     const char *dir;
2696     const char *repos;
2697     const char *update_dir;
2698 {
2699     char *adm_name;
2700
2701     /* FIXME: this is probably not the best place to check; I wish I
2702      * knew where in here's callers to really trap this bug.  To
2703      * reproduce the bug, just do this:
2704      * 
2705      *       mkdir junk
2706      *       cd junk
2707      *       cvs -d some_repos update foo
2708      *
2709      * Poof, CVS seg faults and dies!  It's because it's trying to
2710      * send a NULL string to the server but dies in send_to_server.
2711      * That string was supposed to be the repository, but it doesn't
2712      * get set because there's no CVSADM dir, and somehow it's not
2713      * getting set from the -d argument either... ?
2714      */
2715     if (repos == NULL)
2716     {
2717         /* Lame error.  I want a real fix but can't stay up to track
2718            this down right now. */
2719         error (1, 0, "no repository");
2720     }
2721
2722     if (update_dir == NULL || update_dir[0] == '\0')
2723         update_dir = ".";
2724
2725     if (last_repos != NULL
2726         && strcmp (repos, last_repos) == 0
2727         && last_update_dir != NULL
2728         && strcmp (update_dir, last_update_dir) == 0)
2729         /* We've already sent it.  */
2730         return;
2731
2732     if (client_prune_dirs)
2733         add_prune_candidate (update_dir);
2734
2735     /* Add a directory name to the list of those sent to the
2736        server. */
2737     if (update_dir && (*update_dir != '\0')
2738         && (strcmp (update_dir, ".") != 0)
2739         && (findnode (dirs_sent_to_server, update_dir) == NULL))
2740     {
2741         Node *n;
2742         n = getnode ();
2743         n->type = NT_UNKNOWN;
2744         n->key = xstrdup (update_dir);
2745         n->data = NULL;
2746
2747         if (addnode (dirs_sent_to_server, n))
2748             error (1, 0, "cannot add directory %s to list", n->key);
2749     }
2750
2751     /* 80 is large enough for any of CVSADM_*.  */
2752     adm_name = xmalloc (strlen (dir) + 80);
2753
2754     send_to_server ("Directory ", 0);
2755     {
2756         /* Send the directory name.  I know that this
2757            sort of duplicates code elsewhere, but each
2758            case seems slightly different...  */
2759         char buf[1];
2760         const char *p = update_dir;
2761         while (*p != '\0')
2762         {
2763             assert (*p != '\012');
2764             if (ISDIRSEP (*p))
2765             {
2766                 buf[0] = '/';
2767                 send_to_server (buf, 1);
2768             }
2769             else
2770             {
2771                 buf[0] = *p;
2772                 send_to_server (buf, 1);
2773             }
2774             ++p;
2775         }
2776     }
2777     send_to_server ("\012", 1);
2778     send_to_server (repos, 0);
2779     send_to_server ("\012", 1);
2780
2781     if (supported_request ("Static-directory"))
2782     {
2783         adm_name[0] = '\0';
2784         if (dir[0] != '\0')
2785         {
2786             strcat (adm_name, dir);
2787             strcat (adm_name, "/");
2788         }
2789         strcat (adm_name, CVSADM_ENTSTAT);
2790         if (isreadable (adm_name))
2791         {
2792             send_to_server ("Static-directory\012", 0);
2793         }
2794     }
2795     if (supported_request ("Sticky"))
2796     {
2797         FILE *f;
2798         if (dir[0] == '\0')
2799             strcpy (adm_name, CVSADM_TAG);
2800         else
2801             sprintf (adm_name, "%s/%s", dir, CVSADM_TAG);
2802
2803         f = CVS_FOPEN (adm_name, "r");
2804         if (f == NULL)
2805         {
2806             if (! existence_error (errno))
2807                 error (1, errno, "reading %s", adm_name);
2808         }
2809         else
2810         {
2811             char line[80];
2812             char *nl = NULL;
2813             send_to_server ("Sticky ", 0);
2814             while (fgets (line, sizeof (line), f) != NULL)
2815             {
2816                 send_to_server (line, 0);
2817                 nl = strchr (line, '\n');
2818                 if (nl != NULL)
2819                     break;
2820             }
2821             if (nl == NULL)
2822                 send_to_server ("\012", 1);
2823             if (fclose (f) == EOF)
2824                 error (0, errno, "closing %s", adm_name);
2825         }
2826     }
2827     free (adm_name);
2828     if (last_repos != NULL)
2829         free (last_repos);
2830     if (last_update_dir != NULL)
2831         free (last_update_dir);
2832     last_repos = xstrdup (repos);
2833     last_update_dir = xstrdup (update_dir);
2834 }
2835
2836 /* Send a Repository line and set toplevel_repos.  */
2837
2838 void
2839 send_a_repository (dir, repository, update_dir_in)
2840     const char *dir;
2841     const char *repository;
2842     const char *update_dir_in;
2843 {
2844     char *update_dir = xstrdup (update_dir_in);
2845
2846     if (toplevel_repos == NULL && repository != NULL)
2847     {
2848         if (update_dir[0] == '\0'
2849             || (update_dir[0] == '.' && update_dir[1] == '\0'))
2850             toplevel_repos = xstrdup (repository);
2851         else
2852         {
2853             /*
2854              * Get the repository from a CVS/Repository file if update_dir
2855              * is absolute.  This is not correct in general, because
2856              * the CVS/Repository file might not be the top-level one.
2857              * This is for cases like "cvs update /foo/bar" (I'm not
2858              * sure it matters what toplevel_repos we get, but it does
2859              * matter that we don't hit the "internal error" code below).
2860              */
2861             if (update_dir[0] == '/')
2862                 toplevel_repos = Name_Repository (update_dir, update_dir);
2863             else
2864             {
2865                 /*
2866                  * Guess the repository of that directory by looking at a
2867                  * subdirectory and removing as many pathname components
2868                  * as are in update_dir.  I think that will always (or at
2869                  * least almost always) be 1.
2870                  *
2871                  * So this deals with directories which have been
2872                  * renamed, though it doesn't necessarily deal with
2873                  * directories which have been put inside other
2874                  * directories (and cvs invoked on the containing
2875                  * directory).  I'm not sure the latter case needs to
2876                  * work.
2877                  *
2878                  * 21 Aug 1998: Well, Mr. Above-Comment-Writer, it
2879                  * does need to work after all.  When we are using the
2880                  * client in a multi-cvsroot environment, it will be
2881                  * fairly common that we have the above case (e.g.,
2882                  * cwd checked out from one repository but
2883                  * subdirectory checked out from another).  We can't
2884                  * assume that by walking up a directory in our wd we
2885                  * necessarily walk up a directory in the repository.
2886                  */
2887                 /*
2888                  * This gets toplevel_repos wrong for "cvs update ../foo"
2889                  * but I'm not sure toplevel_repos matters in that case.
2890                  */
2891
2892                 int repository_len, update_dir_len;
2893
2894                 strip_trailing_slashes (update_dir);
2895
2896                 repository_len = strlen (repository);
2897                 update_dir_len = strlen (update_dir);
2898
2899                 /* Try to remove the path components in UPDATE_DIR
2900                    from REPOSITORY.  If the path elements don't exist
2901                    in REPOSITORY, or the removal of those path
2902                    elements mean that we "step above"
2903                    current_parsed_root->directory, set toplevel_repos to
2904                    current_parsed_root->directory. */
2905                 if ((repository_len > update_dir_len)
2906                     && (strcmp (repository + repository_len - update_dir_len,
2907                                 update_dir) == 0)
2908                     /* TOPLEVEL_REPOS shouldn't be above current_parsed_root->directory */
2909                     && ((size_t)(repository_len - update_dir_len)
2910                         > strlen (current_parsed_root->directory)))
2911                 {
2912                     /* The repository name contains UPDATE_DIR.  Set
2913                        toplevel_repos to the repository name without
2914                        UPDATE_DIR. */
2915
2916                     toplevel_repos = xmalloc (repository_len - update_dir_len);
2917                     /* Note that we don't copy the trailing '/'.  */
2918                     strncpy (toplevel_repos, repository,
2919                              repository_len - update_dir_len - 1);
2920                     toplevel_repos[repository_len - update_dir_len - 1] = '\0';
2921                 }
2922                 else
2923                 {
2924                     toplevel_repos = xstrdup (current_parsed_root->directory);
2925                 }
2926             }
2927         }
2928     }
2929
2930     send_repository (dir, repository, update_dir);
2931     free (update_dir);
2932 }
2933
2934
2935
2936 /* The "expanded" modules.  */
2937 static int modules_count;
2938 static int modules_allocated;
2939 static char **modules_vector;
2940
2941 static void
2942 handle_module_expansion (args, len)
2943     char *args;
2944     int len;
2945 {
2946     if (modules_vector == NULL)
2947     {
2948         modules_allocated = 1; /* Small for testing */
2949         modules_vector = (char **) xmalloc
2950           (modules_allocated * sizeof (modules_vector[0]));
2951     }
2952     else if (modules_count >= modules_allocated)
2953     {
2954         modules_allocated *= 2;
2955         modules_vector = (char **) xrealloc
2956           ((char *) modules_vector,
2957            modules_allocated * sizeof (modules_vector[0]));
2958     }
2959     modules_vector[modules_count] = xmalloc (strlen (args) + 1);
2960     strcpy (modules_vector[modules_count], args);
2961     ++modules_count;
2962 }
2963
2964 /* Original, not "expanded" modules.  */
2965 static int module_argc;
2966 static char **module_argv;
2967
2968 void
2969 client_expand_modules (argc, argv, local)
2970     int argc;
2971     char **argv;
2972     int local;
2973 {
2974     int errs;
2975     int i;
2976
2977     module_argc = argc;
2978     module_argv = (char **) xmalloc ((argc + 1) * sizeof (module_argv[0]));
2979     for (i = 0; i < argc; ++i)
2980         module_argv[i] = xstrdup (argv[i]);
2981     module_argv[argc] = NULL;
2982
2983     for (i = 0; i < argc; ++i)
2984         send_arg (argv[i]);
2985     send_a_repository ("", current_parsed_root->directory, "");
2986
2987     send_to_server ("expand-modules\012", 0);
2988
2989     errs = get_server_responses ();
2990     if (last_repos != NULL)
2991         free (last_repos);
2992     last_repos = NULL;
2993     if (last_update_dir != NULL)
2994         free (last_update_dir);
2995     last_update_dir = NULL;
2996     if (errs)
2997         error (errs, 0, "cannot expand modules");
2998 }
2999
3000 void
3001 client_send_expansions (local, where, build_dirs)
3002     int local;
3003     char *where;
3004     int build_dirs;
3005 {
3006     int i;
3007     char *argv[1];
3008
3009     /* Send the original module names.  The "expanded" module name might
3010        not be suitable as an argument to a co request (e.g. it might be
3011        the result of a -d argument in the modules file).  It might be
3012        cleaner if we genuinely expanded module names, all the way to a
3013        local directory and repository, but that isn't the way it works
3014        now.  */
3015     send_file_names (module_argc, module_argv, 0);
3016
3017     for (i = 0; i < modules_count; ++i)
3018     {
3019         argv[0] = where ? where : modules_vector[i];
3020         if (isfile (argv[0]))
3021             send_files (1, argv, local, 0, build_dirs ? SEND_BUILD_DIRS : 0);
3022     }
3023     send_a_repository ("", current_parsed_root->directory, "");
3024 }
3025
3026 void
3027 client_nonexpanded_setup ()
3028 {
3029     send_a_repository ("", current_parsed_root->directory, "");
3030 }
3031 \f
3032 /* Receive a cvswrappers line from the server; it must be a line
3033    containing an RCS option (e.g., "*.exe   -k 'b'").
3034
3035    Note that this doesn't try to handle -t/-f options (which are a
3036    whole separate issue which noone has thought much about, as far
3037    as I know).
3038
3039    We need to know the keyword expansion mode so we know whether to
3040    read the file in text or binary mode.  */
3041
3042 static void
3043 handle_wrapper_rcs_option (args, len)
3044     char *args;
3045     int len;
3046 {
3047     char *p;
3048
3049     /* Enforce the notes in cvsclient.texi about how the response is not
3050        as free-form as it looks.  */
3051     p = strchr (args, ' ');
3052     if (p == NULL)
3053         goto handle_error;
3054     if (*++p != '-'
3055         || *++p != 'k'
3056         || *++p != ' '
3057         || *++p != '\'')
3058         goto handle_error;
3059     if (strchr (p, '\'') == NULL)
3060         goto handle_error;
3061
3062     /* Add server-side cvswrappers line to our wrapper list. */
3063     wrap_add (args, 0);
3064     return;
3065  handle_error:
3066     error (0, errno, "protocol error: ignoring invalid wrappers %s", args);
3067 }
3068
3069 \f
3070 static void
3071 handle_m (args, len)
3072     char *args;
3073     int len;
3074 {
3075     /* In the case where stdout and stderr point to the same place,
3076        fflushing stderr will make output happen in the correct order.
3077        Often stderr will be line-buffered and this won't be needed,
3078        but not always (is that true?  I think the comment is probably
3079        based on being confused between default buffering between
3080        stdout and stderr.  But I'm not sure).  */
3081     fflush (stderr);
3082     fwrite (args, len, sizeof (*args), stdout);
3083     putc ('\n', stdout);
3084 }
3085
3086 static void handle_mbinary PROTO ((char *, int));
3087
3088 static void
3089 handle_mbinary (args, len)
3090     char *args;
3091     int len;
3092 {
3093     char *size_string;
3094     size_t size;
3095     size_t totalread;
3096     size_t nread;
3097     size_t toread;
3098     char buf[8192];
3099
3100     /* See comment at handle_m about (non)flush of stderr.  */
3101
3102     /* Get the size.  */
3103     read_line (&size_string);
3104     size = atoi (size_string);
3105     free (size_string);
3106
3107     /* OK, now get all the data.  The algorithm here is that we read
3108        as much as the network wants to give us in
3109        try_read_from_server, and then we output it all, and then
3110        repeat, until we get all the data.  */
3111     totalread = 0;
3112     while (totalread < size)
3113     {
3114         toread = size - totalread;
3115         if (toread > sizeof buf)
3116             toread = sizeof buf;
3117
3118         nread = try_read_from_server (buf, toread);
3119         cvs_output_binary (buf, nread);
3120         totalread += nread;
3121     }
3122 }
3123
3124 static void
3125 handle_e (args, len)
3126     char *args;
3127     int len;
3128 {
3129     /* In the case where stdout and stderr point to the same place,
3130        fflushing stdout will make output happen in the correct order.  */
3131     fflush (stdout);
3132     fwrite (args, len, sizeof (*args), stderr);
3133     putc ('\n', stderr);
3134 }
3135
3136 /*ARGSUSED*/
3137 static void
3138 handle_f (args, len)
3139     char *args;
3140     int len;
3141 {
3142     fflush (stderr);
3143 }
3144
3145 static void handle_mt PROTO ((char *, int));
3146
3147 static void
3148 handle_mt (args, len)
3149     char *args;
3150     int len;
3151 {
3152     char *p;
3153     char *tag = args;
3154     char *text;
3155
3156     /* See comment at handle_m for more details.  */
3157     fflush (stderr);
3158
3159     p = strchr (args, ' ');
3160     if (p == NULL)
3161         text = NULL;
3162     else
3163     {
3164         *p++ = '\0';
3165         text = p;
3166     }
3167
3168     switch (tag[0])
3169     {
3170         case '+':
3171             if (strcmp (tag, "+updated") == 0)
3172                 updated_seen = 1;
3173             else if (strcmp (tag, "+importmergecmd") == 0)
3174                 importmergecmd.seen = 1;
3175             break;
3176         case '-':
3177             if (strcmp (tag, "-updated") == 0)
3178                 updated_seen = 0;
3179             else if (strcmp (tag, "-importmergecmd") == 0)
3180             {
3181                 char buf[80];
3182
3183                 /* Now that we have gathered the information, we can
3184                    output the suggested merge command.  */
3185
3186                 if (importmergecmd.conflicts == 0
3187                     || importmergecmd.mergetag1 == NULL
3188                     || importmergecmd.mergetag2 == NULL
3189                     || importmergecmd.repository == NULL)
3190                 {
3191                     error (0, 0,
3192                            "invalid server: incomplete importmergecmd tags");
3193                     break;
3194                 }
3195
3196                 sprintf (buf, "\n%d conflicts created by this import.\n",
3197                          importmergecmd.conflicts);
3198                 cvs_output (buf, 0);
3199                 cvs_output ("Use the following command to help the merge:\n\n",
3200                             0);
3201                 cvs_output ("\t", 1);
3202                 cvs_output (program_name, 0);
3203                 if (CVSroot_cmdline != NULL)
3204                 {
3205                     cvs_output (" -d ", 0);
3206                     cvs_output (CVSroot_cmdline, 0);
3207                 }
3208                 cvs_output (" checkout -j", 0);
3209                 cvs_output (importmergecmd.mergetag1, 0);
3210                 cvs_output (" -j", 0);
3211                 cvs_output (importmergecmd.mergetag2, 0);
3212                 cvs_output (" ", 1);
3213                 cvs_output (importmergecmd.repository, 0);
3214                 cvs_output ("\n\n", 0);
3215
3216                 /* Clear the static variables so that everything is
3217                    ready for any subsequent importmergecmd tag.  */
3218                 importmergecmd.conflicts = 0;
3219                 free (importmergecmd.mergetag1);
3220                 importmergecmd.mergetag1 = NULL;
3221                 free (importmergecmd.mergetag2);
3222                 importmergecmd.mergetag2 = NULL;
3223                 free (importmergecmd.repository);
3224                 importmergecmd.repository = NULL;
3225
3226                 importmergecmd.seen = 0;
3227             }
3228             break;
3229         default:
3230             if (updated_seen)
3231             {
3232                 if (strcmp (tag, "fname") == 0)
3233                 {
3234                     if (updated_fname != NULL)
3235                     {
3236                         /* Output the previous message now.  This can happen
3237                            if there was no Update-existing or other such
3238                            response, due to the -n global option.  */
3239                         cvs_output ("U ", 0);
3240                         cvs_output (updated_fname, 0);
3241                         cvs_output ("\n", 1);
3242                         free (updated_fname);
3243                     }
3244                     updated_fname = xstrdup (text);
3245                 }
3246                 /* Swallow all other tags.  Either they are extraneous
3247                    or they reflect future extensions that we can
3248                    safely ignore.  */
3249             }
3250             else if (importmergecmd.seen)
3251             {
3252                 if (strcmp (tag, "conflicts") == 0)
3253                     importmergecmd.conflicts = atoi (text);
3254                 else if (strcmp (tag, "mergetag1") == 0)
3255                     importmergecmd.mergetag1 = xstrdup (text);
3256                 else if (strcmp (tag, "mergetag2") == 0)
3257                     importmergecmd.mergetag2 = xstrdup (text);
3258                 else if (strcmp (tag, "repository") == 0)
3259                     importmergecmd.repository = xstrdup (text);
3260                 /* Swallow all other tags.  Either they are text for
3261                    which we are going to print our own version when we
3262                    see -importmergecmd, or they are future extensions
3263                    we can safely ignore.  */
3264             }
3265             else if (strcmp (tag, "newline") == 0)
3266                 printf ("\n");
3267             else if (text != NULL)
3268                 printf ("%s", text);
3269     }
3270 }
3271
3272 #endif /* CLIENT_SUPPORT */
3273 #if defined(CLIENT_SUPPORT) || defined(SERVER_SUPPORT)
3274
3275 /* This table must be writeable if the server code is included.  */
3276 struct response responses[] =
3277 {
3278 #ifdef CLIENT_SUPPORT
3279 #define RSP_LINE(n, f, t, s) {n, f, t, s}
3280 #else /* ! CLIENT_SUPPORT */
3281 #define RSP_LINE(n, f, t, s) {n, s}
3282 #endif /* CLIENT_SUPPORT */
3283
3284     RSP_LINE("ok", handle_ok, response_type_ok, rs_essential),
3285     RSP_LINE("error", handle_error, response_type_error, rs_essential),
3286     RSP_LINE("Valid-requests", handle_valid_requests, response_type_normal,
3287        rs_essential),
3288     RSP_LINE("Checked-in", handle_checked_in, response_type_normal,
3289        rs_essential),
3290     RSP_LINE("New-entry", handle_new_entry, response_type_normal, rs_optional),
3291     RSP_LINE("Checksum", handle_checksum, response_type_normal, rs_optional),
3292     RSP_LINE("Copy-file", handle_copy_file, response_type_normal, rs_optional),
3293     RSP_LINE("Updated", handle_updated, response_type_normal, rs_essential),
3294     RSP_LINE("Created", handle_created, response_type_normal, rs_optional),
3295     RSP_LINE("Update-existing", handle_update_existing, response_type_normal,
3296        rs_optional),
3297     RSP_LINE("Merged", handle_merged, response_type_normal, rs_essential),
3298     RSP_LINE("Patched", handle_patched, response_type_normal, rs_optional),
3299     RSP_LINE("Rcs-diff", handle_rcs_diff, response_type_normal, rs_optional),
3300     RSP_LINE("Mode", handle_mode, response_type_normal, rs_optional),
3301     RSP_LINE("Mod-time", handle_mod_time, response_type_normal, rs_optional),
3302     RSP_LINE("Removed", handle_removed, response_type_normal, rs_essential),
3303     RSP_LINE("Remove-entry", handle_remove_entry, response_type_normal,
3304        rs_optional),
3305     RSP_LINE("Set-static-directory", handle_set_static_directory,
3306        response_type_normal,
3307        rs_optional),
3308     RSP_LINE("Clear-static-directory", handle_clear_static_directory,
3309        response_type_normal,
3310        rs_optional),
3311     RSP_LINE("Set-sticky", handle_set_sticky, response_type_normal,
3312        rs_optional),
3313     RSP_LINE("Clear-sticky", handle_clear_sticky, response_type_normal,
3314        rs_optional),
3315     RSP_LINE("Template", handle_template, response_type_normal,
3316        rs_optional),
3317     RSP_LINE("Notified", handle_notified, response_type_normal, rs_optional),
3318     RSP_LINE("Module-expansion", handle_module_expansion, response_type_normal,
3319        rs_optional),
3320     RSP_LINE("Wrapper-rcsOption", handle_wrapper_rcs_option,
3321        response_type_normal,
3322        rs_optional),
3323     RSP_LINE("M", handle_m, response_type_normal, rs_essential),
3324     RSP_LINE("Mbinary", handle_mbinary, response_type_normal, rs_optional),
3325     RSP_LINE("E", handle_e, response_type_normal, rs_essential),
3326     RSP_LINE("F", handle_f, response_type_normal, rs_optional),
3327     RSP_LINE("MT", handle_mt, response_type_normal, rs_optional),
3328     /* Possibly should be response_type_error.  */
3329     RSP_LINE(NULL, NULL, response_type_normal, rs_essential)
3330
3331 #undef RSP_LINE
3332 };
3333
3334 #endif /* CLIENT_SUPPORT or SERVER_SUPPORT */
3335 #ifdef CLIENT_SUPPORT
3336
3337 /* 
3338  * If LEN is 0, then send_to_server() computes string's length itself.
3339  *
3340  * Therefore, pass the real length when transmitting data that might
3341  * contain 0's.
3342  */
3343 void
3344 send_to_server (str, len)
3345      const char *str;
3346      size_t len;
3347 {
3348     static int nbytes;
3349
3350     if (len == 0)
3351         len = strlen (str);
3352
3353     buf_output (to_server, str, len);
3354       
3355     /* There is no reason not to send data to the server, so do it
3356        whenever we've accumulated enough information in the buffer to
3357        make it worth sending.  */
3358     nbytes += len;
3359     if (nbytes >= 2 * BUFFER_DATA_SIZE)
3360     {
3361         int status;
3362
3363         status = buf_send_output (to_server);
3364         if (status != 0)
3365             error (1, status, "error writing to server");
3366         nbytes = 0;
3367     }
3368 }
3369
3370 /* Read up to LEN bytes from the server.  Returns actual number of
3371    bytes read, which will always be at least one; blocks if there is
3372    no data available at all.  Gives a fatal error on EOF or error.  */
3373 static size_t
3374 try_read_from_server (buf, len)
3375     char *buf;
3376     size_t len;
3377 {
3378     int status, nread;
3379     char *data;
3380
3381     status = buf_read_data (from_server, len, &data, &nread);
3382     if (status != 0)
3383     {
3384         if (status == -1)
3385             error (1, 0,
3386                    "end of file from server (consult above messages if any)");
3387         else if (status == -2)
3388             error (1, 0, "out of memory");
3389         else
3390             error (1, status, "reading from server");
3391     }
3392
3393     memcpy (buf, data, nread);
3394
3395     return nread;
3396 }
3397
3398 /*
3399  * Read LEN bytes from the server or die trying.
3400  */
3401 void
3402 read_from_server (buf, len)
3403     char *buf;
3404     size_t len;
3405 {
3406     size_t red = 0;
3407     while (red < len)
3408     {
3409         red += try_read_from_server (buf + red, len - red);
3410         if (red == len)
3411             break;
3412     }
3413 }
3414
3415 /*
3416  * Get some server responses and process them.  Returns nonzero for
3417  * error, 0 for success.  */
3418 int
3419 get_server_responses ()
3420 {
3421     struct response *rs;
3422     do
3423     {
3424         char *cmd;
3425         int len;
3426         
3427         len = read_line (&cmd);
3428         for (rs = responses; rs->name != NULL; ++rs)
3429             if (strncmp (cmd, rs->name, strlen (rs->name)) == 0)
3430             {
3431                 int cmdlen = strlen (rs->name);
3432                 if (cmd[cmdlen] == '\0')
3433                     ;
3434                 else if (cmd[cmdlen] == ' ')
3435                     ++cmdlen;
3436                 else
3437                     /*
3438                      * The first len characters match, but it's a different
3439                      * response.  e.g. the response is "oklahoma" but we
3440                      * matched "ok".
3441                      */
3442                     continue;
3443                 (*rs->func) (cmd + cmdlen, len - cmdlen);
3444                 break;
3445             }
3446         if (rs->name == NULL)
3447             /* It's OK to print just to the first '\0'.  */
3448             /* We might want to handle control characters and the like
3449                in some other way other than just sending them to stdout.
3450                One common reason for this error is if people use :ext:
3451                with a version of rsh which is doing CRLF translation or
3452                something, and so the client gets "ok^M" instead of "ok".
3453                Right now that will tend to print part of this error
3454                message over the other part of it.  It seems like we could
3455                do better (either in general, by quoting or omitting all
3456                control characters, and/or specifically, by detecting the CRLF
3457                case and printing a specific error message).  */
3458             error (0, 0,
3459                    "warning: unrecognized response `%s' from cvs server",
3460                    cmd);
3461         free (cmd);
3462     } while (rs->type == response_type_normal);
3463
3464     if (updated_fname != NULL)
3465     {
3466         /* Output the previous message now.  This can happen
3467            if there was no Update-existing or other such
3468            response, due to the -n global option.  */
3469         cvs_output ("U ", 0);
3470         cvs_output (updated_fname, 0);
3471         cvs_output ("\n", 1);
3472         free (updated_fname);
3473         updated_fname = NULL;
3474     }
3475
3476     if (rs->type == response_type_error)
3477         return 1;
3478     if (failure_exit)
3479         return 1;
3480     return 0;
3481 }
3482
3483
3484
3485 /* Get the responses and then close the connection.  */
3486
3487 /*
3488  * Flag var; we'll set it in start_server() and not one of its
3489  * callees, such as start_rsh_server().  This means that there might
3490  * be a small window between the starting of the server and the
3491  * setting of this var, but all the code in that window shouldn't care
3492  * because it's busy checking return values to see if the server got
3493  * started successfully anyway.
3494  */
3495 int server_started = 0;
3496
3497 int
3498 get_responses_and_close ()
3499 {
3500     int errs = get_server_responses ();
3501     int status;
3502
3503     /* The following is necessary when working with multiple cvsroots, at least
3504      * with commit.  It used to be buried nicely in do_deferred_progs() before
3505      * that function was removed.  I suspect it wouldn't be necessary if
3506      * call_in_directory() saved its working directory via save_cwd() before
3507      * changing its directory and restored the saved working directory via
3508      * restore_cwd() before exiting.  Of course, calling CVS_CHDIR only once,
3509      * here, may be more efficient.
3510      */
3511     if( toplevel_wd != NULL )
3512     {
3513         if( CVS_CHDIR( toplevel_wd ) < 0 )
3514             error( 1, errno, "could not chdir to %s", toplevel_wd );
3515     }
3516
3517     if (client_prune_dirs)
3518         process_prune_candidates ();
3519
3520     /* First we shut down TO_SERVER.  That tells the server that its input is
3521      * finished.  It then shuts down the buffer it is sending to us, at which
3522      * point our shut down of FROM_SERVER will complete.
3523      */
3524
3525     status = buf_shutdown (to_server);
3526     if (status != 0)
3527         error (0, status, "shutting down buffer to server");
3528     buf_free (to_server);
3529     to_server = NULL;
3530
3531     status = buf_shutdown (from_server);
3532     if (status != 0)
3533         error (0, status, "shutting down buffer from server");
3534     buf_free (from_server);
3535     from_server = NULL;
3536     server_started = 0;
3537
3538     /* see if we need to sleep before returning to avoid time-stamp races */
3539     if (last_register_time)
3540     {
3541         sleep_past (last_register_time);
3542     }
3543
3544     return errs;
3545 }
3546         
3547 #ifndef NO_EXT_METHOD
3548 static void start_rsh_server PROTO((cvsroot_t *, struct buffer **, struct buffer **));
3549 #endif
3550
3551 int
3552 supported_request (name)
3553     char *name;
3554 {
3555     struct request *rq;
3556
3557     for (rq = requests; rq->name; rq++)
3558         if (!strcmp (rq->name, name))
3559             return (rq->flags & RQ_SUPPORTED) != 0;
3560     error (1, 0, "internal error: testing support for unknown option?");
3561     /* NOTREACHED */
3562     return 0;
3563 }
3564
3565
3566
3567 #if defined (AUTH_CLIENT_SUPPORT) || defined (HAVE_KERBEROS) || defined (HAVE_GSSAPI)
3568 static struct hostent *init_sockaddr PROTO ((struct sockaddr_in *, char *,
3569                                              unsigned int));
3570
3571 static struct hostent *
3572 init_sockaddr (name, hostname, port)
3573     struct sockaddr_in *name;
3574     char *hostname;
3575     unsigned int port;
3576 {
3577     struct hostent *hostinfo;
3578     unsigned short shortport = port;
3579
3580     memset (name, 0, sizeof (*name));
3581     name->sin_family = AF_INET;
3582     name->sin_port = htons (shortport);
3583     hostinfo = gethostbyname (hostname);
3584     if (hostinfo == NULL)
3585     {
3586         fprintf (stderr, "Unknown host %s.\n", hostname);
3587         error_exit ();
3588     }
3589     name->sin_addr = *(struct in_addr *) hostinfo->h_addr;
3590     return hostinfo;
3591 }
3592
3593
3594
3595 /* Generic function to do port number lookup tasks.
3596  *
3597  * In order of precedence, will return:
3598  *      getenv (envname), if defined
3599  *      getservbyname (portname), if defined
3600  *      defaultport
3601  */
3602 static int
3603 get_port_number (envname, portname, defaultport)
3604     const char *envname;
3605     const char *portname;
3606     int defaultport;
3607 {
3608     struct servent *s;
3609     char *port_s;
3610
3611     if (envname && (port_s = getenv (envname)))
3612     {
3613         int port = atoi (port_s);
3614         if (port <= 0)
3615         {
3616             error (0, 0, "%s must be a positive integer!  If you", envname);
3617             error (0, 0, "are trying to force a connection via rsh, please");
3618             error (0, 0, "put \":server:\" at the beginning of your CVSROOT");
3619             error (1, 0, "variable.");
3620         }
3621         return port;
3622     }
3623     else if (portname && (s = getservbyname (portname, "tcp")))
3624         return ntohs (s->s_port);
3625     else
3626         return defaultport;
3627 }
3628
3629
3630
3631 /* get the port number for a client to connect to based on the port
3632  * and method of a cvsroot_t.
3633  *
3634  * we do this here instead of in parse_cvsroot so that we can keep network
3635  * code confined to a localized area and also to delay the lookup until the
3636  * last possible moment so it remains possible to run cvs client commands that
3637  * skip opening connections to the server (i.e. skip network operations
3638  * entirely)
3639  *
3640  * and yes, I know none of the commands do that now, but here's to planning
3641  * for the future, eh?  cheers.
3642  *
3643  * FIXME - We could cache the port lookup safely right now as we never change
3644  * it for a single root on the fly, but we'd have to un'const some other
3645  * functions - REMOVE_FIXME? This may be unecessary.  We're talking about,
3646  * what, usually one, sometimes two lookups of the port per invocation.  I
3647  * think twice is by far the rarer of the two cases - only the login function
3648  * will need to do it to save the canonical CVSROOT. -DRP
3649  */
3650 int
3651 get_cvs_port_number (root)
3652     const cvsroot_t *root;
3653 {
3654
3655     if (root->port) return root->port;
3656
3657     switch (root->method)
3658     {
3659 # ifdef HAVE_GSSAPI
3660         case gserver_method:
3661 # endif /* HAVE_GSSAPI */
3662 # ifdef AUTH_CLIENT_SUPPORT
3663         case pserver_method:
3664 # endif /* AUTH_CLIENT_SUPPORT */
3665 # if defined (AUTH_CLIENT_SUPPORT) || defined (HAVE_GSSAPI)
3666             return get_port_number ("CVS_CLIENT_PORT", "cvspserver", CVS_AUTH_PORT);
3667 # endif /* defined (AUTH_CLIENT_SUPPORT) || defined (HAVE_GSSAPI) */
3668 # ifdef HAVE_KERBEROS
3669         case kserver_method:
3670             return get_port_number ("CVS_CLIENT_PORT", "cvs", CVS_PORT);
3671 # endif /* HAVE_KERBEROS */
3672         default:
3673             error(1, EINVAL, "internal error: get_cvs_port_number called for invalid connection method (%s)",
3674                     method_names[root->method]);
3675             break;
3676     }
3677     /* NOTREACHED */
3678     return -1;
3679 }
3680
3681
3682
3683 void
3684 make_bufs_from_fds (tofd, fromfd, child_pid, to_server, from_server, is_sock)
3685     int tofd;
3686     int fromfd;
3687     int child_pid;
3688     struct buffer **to_server;
3689     struct buffer **from_server;
3690     int is_sock;
3691 {
3692     FILE *to_server_fp;
3693     FILE *from_server_fp;
3694
3695 # ifdef NO_SOCKET_TO_FD
3696     if (is_sock)
3697     {
3698         assert (tofd == fromfd);
3699         *to_server = socket_buffer_initialize (tofd, 0,
3700                                               (BUFMEMERRPROC) NULL);
3701         *from_server = socket_buffer_initialize (tofd, 1,
3702                                                 (BUFMEMERRPROC) NULL);
3703     }
3704     else
3705 # endif /* NO_SOCKET_TO_FD */
3706     {
3707         /* todo: some OS's don't need these calls... */
3708         close_on_exec (tofd);
3709         close_on_exec (fromfd);
3710
3711         /* SCO 3 and AIX have a nasty bug in the I/O libraries which precludes
3712            fdopening the same file descriptor twice, so dup it if it is the
3713            same.  */
3714         if (tofd == fromfd)
3715         {
3716             fromfd = dup (tofd);
3717             if (fromfd < 0)
3718                 error (1, errno, "cannot dup net connection");
3719         }
3720
3721         /* These will use binary mode on systems which have it.  */
3722         /*
3723          * Also, we know that from_server is shut down second, so we pass
3724          * child_pid in there.  In theory, it should be stored in both
3725          * buffers with a ref count...
3726          */
3727         to_server_fp = fdopen (tofd, FOPEN_BINARY_WRITE);
3728         if (to_server_fp == NULL)
3729             error (1, errno, "cannot fdopen %d for write", tofd);
3730         *to_server = stdio_buffer_initialize (to_server_fp, 0, 0,
3731                                              (BUFMEMERRPROC) NULL);
3732
3733         from_server_fp = fdopen (fromfd, FOPEN_BINARY_READ);
3734         if (from_server_fp == NULL)
3735             error (1, errno, "cannot fdopen %d for read", fromfd);
3736         *from_server = stdio_buffer_initialize (from_server_fp, child_pid, 1,
3737                                                (BUFMEMERRPROC) NULL);
3738     }
3739 }
3740 #endif /* defined (AUTH_CLIENT_SUPPORT) || defined (HAVE_KERBEROS) || defined(HAVE_GSSAPI) */
3741
3742
3743
3744 #if defined (AUTH_CLIENT_SUPPORT) || defined(HAVE_GSSAPI)
3745 /* Connect to the authenticating server.
3746
3747    If VERIFY_ONLY is non-zero, then just verify that the password is
3748    correct and then shutdown the connection.
3749
3750    If VERIFY_ONLY is 0, then really connect to the server.
3751
3752    If DO_GSSAPI is non-zero, then we use GSSAPI authentication rather
3753    than the pserver password authentication.
3754
3755    If we fail to connect or if access is denied, then die with fatal
3756    error.  */
3757 void
3758 connect_to_pserver (root, to_server_p, from_server_p, verify_only, do_gssapi)
3759     cvsroot_t *root;
3760     struct buffer **to_server_p;
3761     struct buffer **from_server_p;
3762     int verify_only;
3763     int do_gssapi;
3764 {
3765     int sock;
3766     int port_number;
3767     struct sockaddr_in client_sai;
3768     struct hostent *hostinfo;
3769     struct buffer *to_server, *from_server;
3770
3771     sock = socket (AF_INET, SOCK_STREAM, 0);
3772     if (sock == -1)
3773     {
3774         error (1, 0, "cannot create socket: %s", SOCK_STRERROR (SOCK_ERRNO));
3775     }
3776     port_number = get_cvs_port_number (root);
3777     hostinfo = init_sockaddr (&client_sai, root->hostname, port_number);
3778     if (trace)
3779     {
3780         fprintf (stderr, " -> Connecting to %s(%s):%d\n",
3781                  root->hostname,
3782                  inet_ntoa (client_sai.sin_addr), port_number);
3783     }
3784     if (connect (sock, (struct sockaddr *) &client_sai, sizeof (client_sai))
3785         < 0)
3786         error (1, 0, "connect to %s(%s):%d failed: %s",
3787                root->hostname,
3788                inet_ntoa (client_sai.sin_addr),
3789                port_number, SOCK_STRERROR (SOCK_ERRNO));
3790
3791     make_bufs_from_fds (sock, sock, 0, &to_server, &from_server, 1);
3792
3793     auth_server (root, to_server, from_server, verify_only, do_gssapi, hostinfo);
3794
3795     if (verify_only)
3796     {
3797         int status;
3798
3799         status = buf_shutdown (to_server);
3800         if (status != 0)
3801             error (0, status, "shutting down buffer to server");
3802         buf_free (to_server);
3803         to_server = NULL;
3804
3805         status = buf_shutdown (from_server);
3806         if (status != 0)
3807             error (0, status, "shutting down buffer from server");
3808         buf_free (from_server);
3809         from_server = NULL;
3810
3811         /* Don't need to set server_started = 0 since we don't set it to 1
3812          * until returning from this call.
3813          */
3814     }
3815     else
3816     {
3817         *to_server_p = to_server;
3818         *from_server_p = from_server;
3819     }
3820
3821     return;
3822 }
3823
3824
3825
3826 static void
3827 auth_server (root, lto_server, lfrom_server, verify_only, do_gssapi, hostinfo)
3828     cvsroot_t *root;
3829     struct buffer *lto_server;
3830     struct buffer *lfrom_server;
3831     int verify_only;
3832     int do_gssapi;
3833     struct hostent *hostinfo;
3834 {
3835     char *username;                     /* the username we use to connect */
3836     char no_passwd = 0;                 /* gets set if no password found */
3837
3838     /* FIXME!!!!!!!!!!!!!!!!!!
3839      *
3840      * THIS IS REALLY UGLY!
3841      *
3842      * I'm setting the globals here so we can make calls to send_to_server &
3843      * read_line.  This happens again _after_ we return if we're not in
3844      * verify_only mode.  We should be relying on the values we passed in, but
3845      * sent_to_server and read_line don't require an outside buf yet.
3846      */
3847     to_server = lto_server;
3848     from_server = lfrom_server;
3849
3850     /* Run the authorization mini-protocol before anything else. */
3851     if (do_gssapi)
3852     {
3853 # ifdef HAVE_GSSAPI
3854         FILE *fp = stdio_buffer_get_file(lto_server);
3855         int fd = fp ? fileno(fp) : -1;
3856         struct stat s;
3857
3858         if ((fd < 0) || (fstat (fd, &s) < 0) || !S_ISSOCK(s.st_mode))
3859         {
3860             error (1, 0, "gserver currently only enabled for socket connections");
3861         }
3862
3863         if (! connect_to_gserver (root, fd, hostinfo))
3864         {
3865             error (1, 0,
3866                     "authorization failed: server %s rejected access to %s",
3867                     root->hostname, root->directory);
3868         }
3869 # else /* ! HAVE_GSSAPI */
3870         error (1, 0, "INTERNAL ERROR: This client does not support GSSAPI authentication");
3871 # endif /* HAVE_GSSAPI */
3872     }
3873     else /* ! do_gssapi */
3874     {
3875 # ifdef AUTH_CLIENT_SUPPORT
3876         char *begin      = NULL;
3877         char *password   = NULL;
3878         char *end        = NULL;
3879         
3880         if (verify_only)
3881         {
3882             begin = "BEGIN VERIFICATION REQUEST";
3883             end   = "END VERIFICATION REQUEST";
3884         }
3885         else
3886         {
3887             begin = "BEGIN AUTH REQUEST";
3888             end   = "END AUTH REQUEST";
3889         }
3890
3891         /* Get the password, probably from ~/.cvspass. */
3892         password = get_cvs_password ();
3893         username = root->username ? root->username : getcaller();
3894
3895         /* Send the empty string by default.  This is so anonymous CVS
3896            access doesn't require client to have done "cvs login". */
3897         if (password == NULL) 
3898         {
3899             no_passwd = 1;
3900             password = scramble ("");
3901         }
3902
3903         /* Announce that we're starting the authorization protocol. */
3904         send_to_server(begin, 0);
3905         send_to_server("\012", 1);
3906
3907         /* Send the data the server needs. */
3908         send_to_server(root->directory, 0);
3909         send_to_server("\012", 1);
3910         send_to_server(username, 0);
3911         send_to_server("\012", 1);
3912         send_to_server(password, 0);
3913         send_to_server("\012", 1);
3914
3915         /* Announce that we're ending the authorization protocol. */
3916         send_to_server(end, 0);
3917         send_to_server("\012", 1);
3918
3919         /* Paranoia. */
3920         memset (password, 0, strlen (password));
3921 # else /* ! AUTH_CLIENT_SUPPORT */
3922         error (1, 0, "INTERNAL ERROR: This client does not support pserver authentication");
3923 # endif /* AUTH_CLIENT_SUPPORT */
3924     } /* if (do_gssapi) */
3925
3926     {
3927         char *read_buf;
3928
3929         /* Loop, getting responses from the server.  */
3930         while (1)
3931         {
3932             read_line (&read_buf);
3933
3934             if (strcmp (read_buf, "I HATE YOU") == 0)
3935             {
3936                 /* Authorization not granted.
3937                  *
3938                  * This is a little confusing since we can reach this while loop in GSSAPI
3939                  * mode, but if GSSAPI authentication failed, we already jumped to the
3940                  * rejected label (there is no case where the connect_to_gserver function
3941                  * can return 1 and we will not receive "I LOVE YOU" from the server, barring
3942                  * broken connections and garbled messages, of course).
3943                  *
3944                  * i.e. This is a pserver specific error message and should be since
3945                  * GSSAPI doesn't use username.
3946                  */
3947                 error (0, 0,
3948                         "authorization failed: server %s rejected access to %s for user %s",
3949                         root->hostname, root->directory, username);
3950
3951                 /* Output a special error message if authentication was attempted
3952                 with no password -- the user should be made aware that they may
3953                 have missed a step. */
3954                 if (no_passwd)
3955                 {
3956                     error (0, 0,
3957                             "used empty password; try \"cvs login\" with a real password");
3958                 }
3959                 error_exit();
3960             }
3961             else if (strncmp (read_buf, "E ", 2) == 0)
3962             {
3963                 fprintf (stderr, "%s\n", read_buf + 2);
3964
3965                 /* Continue with the authentication protocol.  */
3966             }
3967             else if (strncmp (read_buf, "error ", 6) == 0)
3968             {
3969                 char *p;
3970
3971                 /* First skip the code.  */
3972                 p = read_buf + 6;
3973                 while (*p != ' ' && *p != '\0')
3974                     ++p;
3975
3976                 /* Skip the space that follows the code.  */
3977                 if (*p == ' ')
3978                     ++p;
3979
3980                 /* Now output the text.  */
3981                 fprintf (stderr, "%s\n", p);
3982                 error_exit();
3983             }
3984             else if (strcmp (read_buf, "I LOVE YOU") == 0)
3985             {
3986                 free (read_buf);
3987                 break;
3988             }
3989             else
3990             {
3991                 error (1, 0, 
3992                        "unrecognized auth response from %s: %s", 
3993                        root->hostname, read_buf);
3994             }
3995             free (read_buf);
3996         }
3997     }
3998 }
3999 #endif /* defined (AUTH_CLIENT_SUPPORT) || defined(HAVE_GSSAPI) */
4000
4001
4002
4003 #ifdef CLIENT_SUPPORT
4004 /* void
4005  * connect_to_forked_server ( struct buffer **to_server,
4006  *                            struct buffer **from_server )
4007  *
4008  * Connect to a forked server process.
4009  */
4010 void
4011 connect_to_forked_server (to_server, from_server)
4012     struct buffer **to_server;
4013     struct buffer **from_server;
4014 {
4015     int tofd, fromfd;
4016     int child_pid;
4017
4018     /* This is pretty simple.  All we need to do is choose the correct
4019        cvs binary and call piped_child. */
4020
4021      const char *command[3];
4022
4023     command[0] = getenv ("CVS_SERVER");
4024     if (! command[0])
4025         command[0] = program_path;
4026     
4027     command[1] = "server";
4028     command[2] = NULL;
4029
4030     if (trace)
4031     {
4032         fprintf (stderr, " -> Forking server: %s %s\n", command[0], command[1]);
4033     }
4034
4035     child_pid = piped_child (command, &tofd, &fromfd);
4036     if (child_pid < 0)
4037         error (1, 0, "could not fork server process");
4038
4039     make_bufs_from_fds (tofd, fromfd, child_pid, to_server, from_server, 0);
4040 }
4041 #endif /* CLIENT_SUPPORT */
4042
4043
4044
4045 #ifdef HAVE_KERBEROS
4046 /* This function has not been changed to deal with NO_SOCKET_TO_FD
4047    (i.e., systems on which sockets cannot be converted to file
4048    descriptors).  The first person to try building a kerberos client
4049    on such a system (OS/2, Windows 95, and maybe others) will have to
4050    take care of this.  */
4051 void
4052 start_tcp_server (root, to_server, from_server)
4053     cvsroot_t *root;
4054     struct buffer **to_server;
4055     struct buffer **from_server;
4056 {
4057     int s;
4058     const char *portenv;
4059     int port;
4060     struct hostent *hp;
4061     struct sockaddr_in sin;
4062     char *hname;
4063
4064     s = socket (AF_INET, SOCK_STREAM, 0);
4065     if (s < 0)
4066         error (1, 0, "cannot create socket: %s", SOCK_STRERROR (SOCK_ERRNO));
4067
4068     port = get_cvs_port_number (root);
4069
4070     hp = init_sockaddr (&sin, root->hostname, port);
4071
4072     hname = xstrdup (hp->h_name);
4073   
4074     if (trace)
4075     {
4076         fprintf (stderr, " -> Connecting to %s(%s):%d\n",
4077                  root->hostname,
4078                  inet_ntoa (sin.sin_addr), port);
4079     }
4080
4081     if (connect (s, (struct sockaddr *) &sin, sizeof sin) < 0)
4082         error (1, 0, "connect to %s(%s):%d failed: %s",
4083                root->hostname,
4084                inet_ntoa (sin.sin_addr),
4085                port, SOCK_STRERROR (SOCK_ERRNO));
4086
4087     {
4088         const char *realm;
4089         struct sockaddr_in laddr;
4090         int laddrlen;
4091         KTEXT_ST ticket;
4092         MSG_DAT msg_data;
4093         CREDENTIALS cred;
4094         int status;
4095
4096         realm = krb_realmofhost (hname);
4097
4098         laddrlen = sizeof (laddr);
4099         if (getsockname (s, (struct sockaddr *) &laddr, &laddrlen) < 0)
4100             error (1, 0, "getsockname failed: %s", SOCK_STRERROR (SOCK_ERRNO));
4101
4102         /* We don't care about the checksum, and pass it as zero.  */
4103         status = krb_sendauth (KOPT_DO_MUTUAL, s, &ticket, "rcmd",
4104                                hname, realm, (unsigned long) 0, &msg_data,
4105                                &cred, sched, &laddr, &sin, "KCVSV1.0");
4106         if (status != KSUCCESS)
4107             error (1, 0, "kerberos authentication failed: %s",
4108                    krb_get_err_text (status));
4109         memcpy (kblock, cred.session, sizeof (C_Block));
4110     }
4111
4112     close_on_exec (s);
4113
4114     free (hname);
4115
4116     /* Give caller the values it wants. */
4117     make_bufs_from_fds (s, s, 0, to_server, from_server, 1);
4118 }
4119
4120 #endif /* HAVE_KERBEROS */
4121
4122 #ifdef HAVE_GSSAPI
4123
4124 /* Receive a given number of bytes.  */
4125
4126 static void
4127 recv_bytes (sock, buf, need)
4128      int sock;
4129      char *buf;
4130      int need;
4131 {
4132     while (need > 0)
4133     {
4134         int got;
4135
4136         got = recv (sock, buf, need, 0);
4137         if (got <= 0)
4138             error (1, 0, "recv() from server %s: %s", current_parsed_root->hostname,
4139                    got == 0 ? "EOF" : SOCK_STRERROR (SOCK_ERRNO));
4140
4141         buf += got;
4142         need -= got;
4143     }
4144 }
4145
4146 /* Connect to the server using GSSAPI authentication.  */
4147
4148 /* FIXME
4149  *
4150  * This really needs to be rewritten to use a buffer and not a socket.
4151  * This would enable gserver to work with the SSL code I'm about to commit
4152  * since the SSL connection is going to look like a FIFO and not a socket.
4153  *
4154  * I think, basically, it will need to use buf_output and buf_read directly
4155  * since I don't think there is a read_bytes function - only read_line.
4156  *
4157  * recv_bytes could then be removed too.
4158  *
4159  * Besides, I added some cruft to reenable the socket which shouldn't be
4160  * there.  This would also enable its removal.
4161  */
4162 #define BUFSIZE 1024
4163 static int
4164 connect_to_gserver (root, sock, hostinfo)
4165     cvsroot_t *root;
4166     int sock;
4167     struct hostent *hostinfo;
4168 {
4169     char *str;
4170     char buf[BUFSIZE];
4171     gss_buffer_desc *tok_in_ptr, tok_in, tok_out;
4172     OM_uint32 stat_min, stat_maj;
4173     gss_name_t server_name;
4174
4175     str = "BEGIN GSSAPI REQUEST\012";
4176
4177     if (send (sock, str, strlen (str), 0) < 0)
4178         error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));
4179
4180     if (strlen (hostinfo->h_name) > BUFSIZE - 5)
4181         error (1, 0, "Internal error: hostname exceeds length of buffer");
4182     sprintf (buf, "cvs@%s", hostinfo->h_name);
4183     tok_in.length = strlen (buf);
4184     tok_in.value = buf;
4185     gss_import_name (&stat_min, &tok_in, GSS_C_NT_HOSTBASED_SERVICE,
4186                      &server_name);
4187
4188     tok_in_ptr = GSS_C_NO_BUFFER;
4189     gcontext = GSS_C_NO_CONTEXT;
4190
4191     do
4192     {
4193         stat_maj = gss_init_sec_context (&stat_min, GSS_C_NO_CREDENTIAL,
4194                                          &gcontext, server_name,
4195                                          GSS_C_NULL_OID,
4196                                          (GSS_C_MUTUAL_FLAG
4197                                           | GSS_C_REPLAY_FLAG),
4198                                          0, NULL, tok_in_ptr, NULL, &tok_out,
4199                                          NULL, NULL);
4200         if (stat_maj != GSS_S_COMPLETE && stat_maj != GSS_S_CONTINUE_NEEDED)
4201         {
4202             OM_uint32 message_context;
4203             OM_uint32 new_stat_min;
4204
4205             message_context = 0;
4206             gss_display_status (&new_stat_min, stat_maj, GSS_C_GSS_CODE,
4207                                 GSS_C_NULL_OID, &message_context, &tok_out);
4208             error (0, 0, "GSSAPI authentication failed: %s",
4209                    (char *) tok_out.value);
4210
4211             message_context = 0;
4212             gss_display_status (&new_stat_min, stat_min, GSS_C_MECH_CODE,
4213                                 GSS_C_NULL_OID, &message_context, &tok_out);
4214             error (1, 0, "GSSAPI authentication failed: %s",
4215                    (char *) tok_out.value);
4216         }
4217
4218         if (tok_out.length == 0)
4219         {
4220             tok_in.length = 0;
4221         }
4222         else
4223         {
4224             char cbuf[2];
4225             int need;
4226
4227             cbuf[0] = (tok_out.length >> 8) & 0xff;
4228             cbuf[1] = tok_out.length & 0xff;
4229             if (send (sock, cbuf, 2, 0) < 0)
4230                 error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));
4231             if (send (sock, tok_out.value, tok_out.length, 0) < 0)
4232                 error (1, 0, "cannot send: %s", SOCK_STRERROR (SOCK_ERRNO));
4233
4234             recv_bytes (sock, cbuf, 2);
4235             need = ((cbuf[0] & 0xff) << 8) | (cbuf[1] & 0xff);
4236
4237             if (need > sizeof buf)
4238             {
4239                 int got;
4240
4241                 /* This usually means that the server sent us an error
4242                    message.  Read it byte by byte and print it out.
4243                    FIXME: This is a terrible error handling strategy.
4244                    However, even if we fix the server, we will still
4245                    want to do this to work with older servers.  */
4246                 buf[0] = cbuf[0];
4247                 buf[1] = cbuf[1];
4248                 got = recv (sock, buf + 2, sizeof buf - 2, 0);
4249                 if (got < 0)
4250                     error (1, 0, "recv() from server %s: %s",
4251                            root->hostname, SOCK_STRERROR (SOCK_ERRNO));
4252                 buf[got + 2] = '\0';
4253                 if (buf[got + 1] == '\n')
4254                     buf[got + 1] = '\0';
4255                 error (1, 0, "error from server %s: %s", root->hostname,
4256                        buf);
4257             }
4258
4259             recv_bytes (sock, buf, need);
4260             tok_in.length = need;
4261         }
4262
4263         tok_in.value = buf;
4264         tok_in_ptr = &tok_in;
4265     }
4266     while (stat_maj == GSS_S_CONTINUE_NEEDED);
4267
4268     return 1;
4269 }
4270
4271 #endif /* HAVE_GSSAPI */
4272
4273
4274
4275 static int send_variable_proc PROTO ((Node *, void *));
4276
4277 static int
4278 send_variable_proc (node, closure)
4279     Node *node;
4280     void *closure;
4281 {
4282     send_to_server ("Set ", 0);
4283     send_to_server (node->key, 0);
4284     send_to_server ("=", 1);
4285     send_to_server (node->data, 0);
4286     send_to_server ("\012", 1);
4287     return 0;
4288 }
4289
4290
4291
4292 /* Contact the server.  */
4293 void
4294 start_server ()
4295 {
4296     int rootless;
4297     char *log = getenv ("CVS_CLIENT_LOG");
4298
4299     /* Clear our static variables for this invocation. */
4300     if (toplevel_repos != NULL)
4301         free (toplevel_repos);
4302     toplevel_repos = NULL;
4303
4304     /* Note that generally speaking we do *not* fall back to a different
4305        way of connecting if the first one does not work.  This is slow
4306        (*really* slow on a 14.4kbps link); the clean way to have a CVS
4307        which supports several ways of connecting is with access methods.  */
4308
4309     switch (current_parsed_root->method)
4310     {
4311
4312 #ifdef AUTH_CLIENT_SUPPORT
4313         case pserver_method:
4314             /* Toss the return value.  It will die with an error message if
4315              * anything goes wrong anyway.
4316              */
4317             connect_to_pserver (current_parsed_root, &to_server, &from_server, 0, 0);
4318             break;
4319 #endif /* AUTH_CLIENT_SUPPORT */
4320
4321 #if HAVE_KERBEROS
4322         case kserver_method:
4323             start_tcp_server (current_parsed_root, &to_server, &from_server);
4324             break;
4325 #endif /* HAVE_KERBEROS */
4326
4327 #ifdef HAVE_GSSAPI
4328         case gserver_method:
4329             /* GSSAPI authentication is handled by the pserver.  */
4330             connect_to_pserver (current_parsed_root, &to_server, &from_server, 0, 1);
4331             break;
4332 #endif /* HAVE_GSSAPI */
4333
4334         case ext_method:
4335 #ifdef NO_EXT_METHOD
4336             error (0, 0, ":ext: method not supported by this port of CVS");
4337             error (1, 0, "try :server: instead");
4338 #else /* ! NO_EXT_METHOD */
4339             start_rsh_server (current_parsed_root, &to_server, &from_server);
4340 #endif /* NO_EXT_METHOD */
4341             break;
4342
4343         case server_method:
4344 #ifdef START_SERVER
4345             {
4346             int tofd, fromfd;
4347             START_SERVER (&tofd, &fromfd, getcaller (),
4348                           current_parsed_root->username, current_parsed_root->hostname,
4349                           current_parsed_root->directory);
4350 # ifdef START_SERVER_RETURNS_SOCKET
4351             make_bufs_from_fds (tofd, fromfd, 0, &to_server, &from_server, 1);
4352 # else /* ! START_SERVER_RETURNS_SOCKET */
4353             make_bufs_from_fds (tofd, fromfd, 0, &to_server, &from_server, 0);
4354 # endif /* START_SERVER_RETURNS_SOCKET */
4355             }
4356 #else /* ! START_SERVER */
4357             /* FIXME: It should be possible to implement this portably,
4358                like pserver, which would get rid of the duplicated code
4359                in {vms,windows-NT,...}/startserver.c.  */
4360             error (1, 0,
4361 "the :server: access method is not supported by this port of CVS");
4362 #endif /* START_SERVER */
4363             break;
4364
4365         case fork_method:
4366             connect_to_forked_server (&to_server, &from_server);
4367             break;
4368
4369         default:
4370             error (1, 0, "\
4371 (start_server internal error): unknown access method");
4372             break;
4373     }
4374
4375     /* "Hi, I'm Darlene and I'll be your server tonight..." */
4376     server_started = 1;
4377
4378     /* Set up logfiles, if any.
4379      *
4380      * We do this _after_ authentication on purpose.  Wouldn't really like to
4381      * worry about logging passwords...
4382      */
4383     if (log)
4384     {
4385         int len = strlen (log);
4386         char *buf = xmalloc (len + 5);
4387         char *p;
4388         FILE *fp;
4389
4390         strcpy (buf, log);
4391         p = buf + len;
4392
4393         /* Open logfiles in binary mode so that they reflect
4394            exactly what was transmitted and received (that is
4395            more important than that they be maximally
4396            convenient to view).  */
4397         /* Note that if we create several connections in a single CVS client
4398            (currently used by update.c), then the last set of logfiles will
4399            overwrite the others.  There is currently no way around this.  */
4400         strcpy (p, ".in");
4401         fp = open_file (buf, "wb");
4402         if (fp == NULL)
4403             error (0, errno, "opening to-server logfile %s", buf);
4404         else
4405             to_server = log_buffer_initialize (to_server, fp, 0,
4406                                                (BUFMEMERRPROC) NULL);
4407
4408         strcpy (p, ".out");
4409         fp = open_file (buf, "wb");
4410         if (fp == NULL)
4411             error (0, errno, "opening from-server logfile %s", buf);
4412         else
4413             from_server = log_buffer_initialize (from_server, fp, 1,
4414                                                  (BUFMEMERRPROC) NULL);
4415
4416         free (buf);
4417     }
4418
4419     /* Clear static variables.  */
4420     if (toplevel_repos != NULL)
4421         free (toplevel_repos);
4422     toplevel_repos = NULL;
4423     if (last_repos != NULL)
4424         free (last_repos);
4425     last_repos = NULL;
4426     if (last_update_dir != NULL)
4427         free (last_update_dir);
4428     last_update_dir = NULL;
4429     stored_checksum_valid = 0;
4430     if (stored_mode != NULL)
4431     {
4432         free (stored_mode);
4433         stored_mode = NULL;
4434     }
4435
4436     rootless = (strcmp (cvs_cmd_name, "init") == 0);
4437     if (!rootless)
4438     {
4439         send_to_server ("Root ", 0);
4440         send_to_server (current_parsed_root->directory, 0);
4441         send_to_server ("\012", 1);
4442     }
4443
4444     {
4445         struct response *rs;
4446
4447         send_to_server ("Valid-responses", 0);
4448
4449         for (rs = responses; rs->name != NULL; ++rs)
4450         {
4451             send_to_server (" ", 0);
4452             send_to_server (rs->name, 0);
4453         }
4454         send_to_server ("\012", 1);
4455     }
4456     send_to_server ("valid-requests\012", 0);
4457
4458     if (get_server_responses ())
4459         error_exit ();
4460
4461     /*
4462      * Now handle global options.
4463      *
4464      * -H, -f, -d, -e should be handled OK locally.
4465      *
4466      * -b we ignore (treating it as a server installation issue).
4467      * FIXME: should be an error message.
4468      *
4469      * -v we print local version info; FIXME: Add a protocol request to get
4470      * the version from the server so we can print that too.
4471      *
4472      * -l -t -r -w -q -n and -Q need to go to the server.
4473      */
4474
4475     {
4476         int have_global = supported_request ("Global_option");
4477
4478         if (noexec)
4479         {
4480             if (have_global)
4481             {
4482                 send_to_server ("Global_option -n\012", 0);
4483             }
4484             else
4485                 error (1, 0,
4486                        "This server does not support the global -n option.");
4487         }
4488         if (quiet)
4489         {
4490             if (have_global)
4491             {
4492                 send_to_server ("Global_option -q\012", 0);
4493             }
4494             else
4495                 error (1, 0,
4496                        "This server does not support the global -q option.");
4497         }
4498         if (really_quiet)
4499         {
4500             if (have_global)
4501             {
4502                 send_to_server ("Global_option -Q\012", 0);
4503             }
4504             else
4505                 error (1, 0,
4506                        "This server does not support the global -Q option.");
4507         }
4508         if (!cvswrite)
4509         {
4510             if (have_global)
4511             {
4512                 send_to_server ("Global_option -r\012", 0);
4513             }
4514             else
4515                 error (1, 0,
4516                        "This server does not support the global -r option.");
4517         }
4518         if (trace)
4519         {
4520             if (have_global)
4521             {
4522                 send_to_server ("Global_option -t\012", 0);
4523             }
4524             else
4525                 error (1, 0,
4526                        "This server does not support the global -t option.");
4527         }
4528     }
4529
4530     /* Find out about server-side cvswrappers.  An extra network
4531        turnaround for cvs import seems to be unavoidable, unless we
4532        want to add some kind of client-side place to configure which
4533        filenames imply binary.  For cvs add, we could avoid the
4534        problem by keeping a copy of the wrappers in CVSADM (the main
4535        reason to bother would be so we could make add work without
4536        contacting the server, I suspect).  */
4537
4538     if ((strcmp (cvs_cmd_name, "import") == 0)
4539         || (strcmp (cvs_cmd_name, "add") == 0))
4540     {
4541         if (supported_request ("wrapper-sendme-rcsOptions"))
4542         {
4543             int err;
4544             send_to_server ("wrapper-sendme-rcsOptions\012", 0);
4545             err = get_server_responses ();
4546             if (err != 0)
4547                 error (err, 0, "error reading from server");
4548         }
4549     }
4550
4551     if (cvsencrypt && !rootless)
4552     {
4553 #ifdef ENCRYPTION
4554         /* Turn on encryption before turning on compression.  We do
4555            not want to try to compress the encrypted stream.  Instead,
4556            we want to encrypt the compressed stream.  If we can't turn
4557            on encryption, bomb out; don't let the user think the data
4558            is being encrypted when it is not.  */
4559 #ifdef HAVE_KERBEROS
4560         if (current_parsed_root->method == kserver_method)
4561         {
4562             if (! supported_request ("Kerberos-encrypt"))
4563                 error (1, 0, "This server does not support encryption");
4564             send_to_server ("Kerberos-encrypt\012", 0);
4565             to_server = krb_encrypt_buffer_initialize (to_server, 0, sched,
4566                                                        kblock,
4567                                                        (BUFMEMERRPROC) NULL);
4568             from_server = krb_encrypt_buffer_initialize (from_server, 1,
4569                                                          sched, kblock,
4570                                                          (BUFMEMERRPROC) NULL);
4571         }
4572         else
4573 #endif /* HAVE_KERBEROS */
4574 #ifdef HAVE_GSSAPI
4575         if (current_parsed_root->method == gserver_method)
4576         {
4577             if (! supported_request ("Gssapi-encrypt"))
4578                 error (1, 0, "This server does not support encryption");
4579             send_to_server ("Gssapi-encrypt\012", 0);
4580             to_server = cvs_gssapi_wrap_buffer_initialize (to_server, 0,
4581                                                            gcontext,
4582                                                            ((BUFMEMERRPROC)
4583                                                             NULL));
4584             from_server = cvs_gssapi_wrap_buffer_initialize (from_server, 1,
4585                                                              gcontext,
4586                                                              ((BUFMEMERRPROC)
4587                                                               NULL));
4588             cvs_gssapi_encrypt = 1;
4589         }
4590         else
4591 #endif /* HAVE_GSSAPI */
4592             error (1, 0, "Encryption is only supported when using GSSAPI or Kerberos");
4593 #else /* ! ENCRYPTION */
4594         error (1, 0, "This client does not support encryption");
4595 #endif /* ! ENCRYPTION */
4596     }
4597
4598     if (gzip_level && !rootless)
4599     {
4600         if (supported_request ("Gzip-stream"))
4601         {
4602             char gzip_level_buf[5];
4603             send_to_server ("Gzip-stream ", 0);
4604             sprintf (gzip_level_buf, "%d", gzip_level);
4605             send_to_server (gzip_level_buf, 0);
4606             send_to_server ("\012", 1);
4607
4608             /* All further communication with the server will be
4609                compressed.  */
4610
4611             to_server = compress_buffer_initialize (to_server, 0, gzip_level,
4612                                                     (BUFMEMERRPROC) NULL);
4613             from_server = compress_buffer_initialize (from_server, 1,
4614                                                       gzip_level,
4615                                                       (BUFMEMERRPROC) NULL);
4616         }
4617 #ifndef NO_CLIENT_GZIP_PROCESS
4618         else if (supported_request ("gzip-file-contents"))
4619         {
4620             char gzip_level_buf[5];
4621             send_to_server ("gzip-file-contents ", 0);
4622             sprintf (gzip_level_buf, "%d", gzip_level);
4623             send_to_server (gzip_level_buf, 0);
4624
4625             send_to_server ("\012", 1);
4626
4627             file_gzip_level = gzip_level;
4628         }
4629 #endif
4630         else
4631         {
4632             fprintf (stderr, "server doesn't support gzip-file-contents\n");
4633             /* Setting gzip_level to 0 prevents us from giving the
4634                error twice if update has to contact the server again
4635                to fetch unpatchable files.  */
4636             gzip_level = 0;
4637         }
4638     }
4639
4640     if (cvsauthenticate && ! cvsencrypt && !rootless)
4641     {
4642         /* Turn on authentication after turning on compression, so
4643            that we can compress the authentication information.  We
4644            assume that encrypted data is always authenticated--the
4645            ability to decrypt the data stream is itself a form of
4646            authentication.  */
4647 #ifdef HAVE_GSSAPI
4648         if (current_parsed_root->method == gserver_method)
4649         {
4650             if (! supported_request ("Gssapi-authenticate"))
4651                 error (1, 0,
4652                        "This server does not support stream authentication");
4653             send_to_server ("Gssapi-authenticate\012", 0);
4654             to_server = cvs_gssapi_wrap_buffer_initialize (to_server, 0,
4655                                                            gcontext,
4656                                                            ((BUFMEMERRPROC)
4657                                                             NULL));
4658             from_server = cvs_gssapi_wrap_buffer_initialize (from_server, 1,
4659                                                              gcontext,
4660                                                              ((BUFMEMERRPROC)
4661                                                               NULL));
4662         }
4663         else
4664             error (1, 0, "Stream authentication is only supported when using GSSAPI");
4665 #else /* ! HAVE_GSSAPI */
4666         error (1, 0, "This client does not support stream authentication");
4667 #endif /* ! HAVE_GSSAPI */
4668     }
4669
4670     /* If "Set" is not supported, just silently fail to send the variables.
4671        Users with an old server should get a useful error message when it
4672        fails to recognize the ${=foo} syntax.  This way if someone uses
4673        several servers, some of which are new and some old, they can still
4674        set user variables in their .cvsrc without trouble.  */
4675     if (supported_request ("Set"))
4676         walklist (variable_list, send_variable_proc, NULL);
4677 }
4678
4679
4680
4681 #ifndef NO_EXT_METHOD
4682
4683 /* Contact the server by starting it with rsh.  */
4684
4685 /* Right now, we have two different definitions for this function,
4686    depending on whether we start the rsh server using popenRW or not.
4687    This isn't ideal, and the best thing would probably be to change
4688    the OS/2 port to be more like the regular Unix client (i.e., by
4689    implementing piped_child)... but I'm doing something else at the
4690    moment, and wish to make only one change at a time.  -Karl */
4691
4692 # ifdef START_RSH_WITH_POPEN_RW
4693
4694 /* This is actually a crock -- it's OS/2-specific, for no one else
4695    uses it.  If I get time, I want to make piped_child and all the
4696    other stuff in os2/run.c work right.  In the meantime, this gets us
4697    up and running, and that's most important. */
4698
4699 static void
4700 start_rsh_server (root, to_server, from_server)
4701     cvsroot_t *root;
4702     struct buffer **to_server;
4703     struct buffer **from_server;
4704 {
4705     int pipes[2];
4706     int child_pid;
4707
4708     /* If you're working through firewalls, you can set the
4709        CVS_RSH environment variable to a script which uses rsh to
4710        invoke another rsh on a proxy machine.  */
4711     char *cvs_rsh = getenv ("CVS_RSH");
4712     char *cvs_server = getenv ("CVS_SERVER");
4713     int i = 0;
4714     /* This needs to fit "rsh", "-b", "-l", "USER", "host",
4715        "cmd (w/ args)", and NULL.  We leave some room to grow. */
4716     char *rsh_argv[10];
4717
4718     if (!cvs_rsh)
4719         /* People sometimes suggest or assume that this should default
4720            to "remsh" on systems like HPUX in which that is the
4721            system-supplied name for the rsh program.  However, that
4722            causes various problems (keep in mind that systems such as
4723            HPUX might have non-system-supplied versions of "rsh", like
4724            a Kerberized one, which one might want to use).  If we
4725            based the name on what is found in the PATH of the person
4726            who runs configure, that would make it harder to
4727            consistently produce the same result in the face of
4728            different people producing binary distributions.  If we
4729            based it on "remsh" always being the default for HPUX
4730            (e.g. based on uname), that might be slightly better but
4731            would require us to keep track of what the defaults are for
4732            each system type, and probably would cope poorly if the
4733            existence of remsh or rsh varies from OS version to OS
4734            version.  Therefore, it seems best to have the default
4735            remain "rsh", and tell HPUX users to specify remsh, for
4736            example in CVS_RSH or other such mechanisms to be devised,
4737            if that is what they want (the manual already tells them
4738            that).  */
4739         cvs_rsh = "ssh";
4740     if (!cvs_server)
4741         cvs_server = "cvs";
4742
4743     /* The command line starts out with rsh. */
4744     rsh_argv[i++] = cvs_rsh;
4745
4746 #   ifdef RSH_NEEDS_BINARY_FLAG
4747     /* "-b" for binary, under OS/2. */
4748     rsh_argv[i++] = "-b";
4749 #   endif /* RSH_NEEDS_BINARY_FLAG */
4750
4751     /* Then we strcat more things on the end one by one. */
4752     if (root->username != NULL)
4753     {
4754         rsh_argv[i++] = "-l";
4755         rsh_argv[i++] = root->username;
4756     }
4757
4758     rsh_argv[i++] = root->hostname;
4759     rsh_argv[i++] = cvs_server;
4760     rsh_argv[i++] = "server";
4761
4762     /* Mark the end of the arg list. */
4763     rsh_argv[i]   = (char *) NULL;
4764
4765     if (trace)
4766     {
4767         fprintf (stderr, " -> Starting server: ");
4768         for (i = 0; rsh_argv[i]; i++)
4769             fprintf (stderr, "%s ", rsh_argv[i]);
4770         putc ('\n', stderr);
4771     }
4772
4773     /* Do the deed. */
4774     child_pid = popenRW (rsh_argv, pipes);
4775     if (child_pid < 0)
4776         error (1, errno, "cannot start server via rsh");
4777
4778     /* Give caller the file descriptors in a form it can deal with. */
4779     make_bufs_from_fds (pipes[0], pipes[1], child_pid, to_server, from_server, 0);
4780 }
4781
4782 # else /* ! START_RSH_WITH_POPEN_RW */
4783
4784 static void
4785 start_rsh_server (root, to_server, from_server)
4786     cvsroot_t *root;
4787     struct buffer **to_server;
4788     struct buffer **from_server;
4789 {
4790     /* If you're working through firewalls, you can set the
4791        CVS_RSH environment variable to a script which uses rsh to
4792        invoke another rsh on a proxy machine.  */
4793     char *cvs_rsh = getenv ("CVS_RSH");
4794     char *cvs_server = getenv ("CVS_SERVER");
4795     char *command;
4796     int tofd, fromfd;
4797     int child_pid;
4798
4799     if (!cvs_rsh)
4800         cvs_rsh = "ssh";
4801     if (!cvs_server)
4802         cvs_server = "cvs";
4803
4804     /* Pass the command to rsh as a single string.  This shouldn't
4805        affect most rsh servers at all, and will pacify some buggy
4806        versions of rsh that grab switches out of the middle of the
4807        command (they're calling the GNU getopt routines incorrectly).  */
4808     command = xmalloc (strlen (cvs_server) + 8);
4809
4810     /* If you are running a very old (Nov 3, 1994, before 1.5)
4811      * version of the server, you need to make sure that your .bashrc
4812      * on the server machine does not set CVSROOT to something
4813      * containing a colon (or better yet, upgrade the server).  */
4814     sprintf (command, "%s server", cvs_server);
4815
4816     {
4817         const char *argv[10];
4818         const char **p = argv;
4819
4820         *p++ = cvs_rsh;
4821
4822         /* If the login names differ between client and server
4823          * pass it on to rsh.
4824          */
4825         if (root->username != NULL)
4826         {
4827             *p++ = "-l";
4828             *p++ = root->username;
4829         }
4830
4831         *p++ = root->hostname;
4832         *p++ = command;
4833         *p++ = NULL;
4834
4835         if (trace)
4836         {
4837             int i;
4838
4839             fprintf (stderr, " -> Starting server: ");
4840             for (i = 0; argv[i]; i++)
4841                 fprintf (stderr, "%s ", argv[i]);
4842             putc ('\n', stderr);
4843         }
4844         child_pid = piped_child (argv, &tofd, &fromfd);
4845
4846         if (child_pid < 0)
4847             error (1, errno, "cannot start server via rsh");
4848     }
4849     free (command);
4850
4851     make_bufs_from_fds (tofd, fromfd, child_pid, to_server, from_server, 0);
4852 }
4853
4854 # endif /* START_RSH_WITH_POPEN_RW */
4855
4856 #endif /* NO_EXT_METHOD */
4857
4858
4859
4860 /* Send an argument STRING.  */
4861 void
4862 send_arg (string)
4863     char *string;
4864 {
4865     char buf[1];
4866     char *p = string;
4867
4868     send_to_server ("Argument ", 0);
4869
4870     while (*p)
4871     {
4872         if (*p == '\n')
4873         {
4874             send_to_server ("\012Argumentx ", 0);
4875         }
4876         else
4877         {
4878             buf[0] = *p;
4879             send_to_server (buf, 1);
4880         }
4881         ++p;
4882     }
4883     send_to_server ("\012", 1);
4884 }
4885
4886
4887
4888 static void send_modified PROTO ((const char *, const char *, Vers_TS *));
4889
4890 /* VERS->OPTIONS specifies whether the file is binary or not.  NOTE: BEFORE
4891    using any other fields of the struct vers, we would need to fix
4892    client_process_import_file to set them up.  */
4893
4894 static void
4895 send_modified (file, short_pathname, vers)
4896     const char *file;
4897     const char *short_pathname;
4898     Vers_TS *vers;
4899 {
4900     /* File was modified, send it.  */
4901     struct stat sb;
4902     int fd;
4903     char *buf;
4904     char *mode_string;
4905     size_t bufsize;
4906     int bin;
4907
4908     if (trace)
4909         (void) fprintf (stderr, " -> Sending file `%s' to server\n", file);
4910
4911     /* Don't think we can assume fstat exists.  */
4912     if ( CVS_STAT (file, &sb) < 0)
4913         error (1, errno, "reading %s", short_pathname);
4914
4915     mode_string = mode_to_string (sb.st_mode);
4916
4917     /* Beware: on systems using CRLF line termination conventions,
4918        the read and write functions will convert CRLF to LF, so the
4919        number of characters read is not the same as sb.st_size.  Text
4920        files should always be transmitted using the LF convention, so
4921        we don't want to disable this conversion.  */
4922     bufsize = sb.st_size;
4923     buf = xmalloc (bufsize);
4924
4925     /* Is the file marked as containing binary data by the "-kb" flag?
4926        If so, make sure to open it in binary mode: */
4927
4928     if (vers && vers->options)
4929       bin = !(strcmp (vers->options, "-kb"));
4930     else
4931       bin = 0;
4932
4933 #ifdef BROKEN_READWRITE_CONVERSION
4934     if (!bin)
4935     {
4936         /* If only stdio, not open/write/etc., do text/binary
4937            conversion, use convert_file which can compensate
4938            (FIXME: we could just use stdio instead which would
4939            avoid the whole problem).  */
4940         char tfile[1024]; strcpy(tfile, file); strcat(tfile, ".CVSBFCTMP");
4941         convert_file (file, O_RDONLY,
4942                       tfile, O_WRONLY | O_CREAT | O_TRUNC | OPEN_BINARY);
4943         fd = CVS_OPEN (tfile, O_RDONLY | OPEN_BINARY);
4944         if (fd < 0)
4945             error (1, errno, "reading %s", short_pathname);
4946     }
4947     else
4948         fd = CVS_OPEN (file, O_RDONLY | OPEN_BINARY);
4949 #else
4950     fd = CVS_OPEN (file, O_RDONLY | (bin ? OPEN_BINARY : 0));
4951 #endif
4952
4953     if (fd < 0)
4954         error (1, errno, "reading %s", short_pathname);
4955
4956     if (file_gzip_level && sb.st_size > 100)
4957     {
4958         size_t newsize = 0;
4959
4960         if (read_and_gzip (fd, short_pathname, (unsigned char **)&buf,
4961                            &bufsize, &newsize,
4962                            file_gzip_level))
4963             error (1, 0, "aborting due to compression error");
4964
4965         if (close (fd) < 0)
4966             error (0, errno, "warning: can't close %s", short_pathname);
4967
4968         {
4969           char tmp[80];
4970
4971           send_to_server ("Modified ", 0);
4972           send_to_server (file, 0);
4973           send_to_server ("\012", 1);
4974           send_to_server (mode_string, 0);
4975           send_to_server ("\012z", 2);
4976           sprintf (tmp, "%lu\n", (unsigned long) newsize);
4977           send_to_server (tmp, 0);
4978
4979           send_to_server (buf, newsize);
4980         }
4981     }
4982     else
4983     {
4984         int newsize;
4985
4986         {
4987             char *bufp = buf;
4988             int len;
4989
4990             /* FIXME: This is gross.  It assumes that we might read
4991                less than st_size bytes (true on NT), but not more.
4992                Instead of this we should just be reading a block of
4993                data (e.g. 8192 bytes), writing it to the network, and
4994                so on until EOF.  */
4995             while ((len = read (fd, bufp, (buf + sb.st_size) - bufp)) > 0)
4996                 bufp += len;
4997
4998             if (len < 0)
4999                 error (1, errno, "reading %s", short_pathname);
5000
5001             newsize = bufp - buf;
5002         }
5003         if (close (fd) < 0)
5004             error (0, errno, "warning: can't close %s", short_pathname);
5005
5006         {
5007           char tmp[80];
5008
5009           send_to_server ("Modified ", 0);
5010           send_to_server (file, 0);
5011           send_to_server ("\012", 1);
5012           send_to_server (mode_string, 0);
5013           send_to_server ("\012", 1);
5014           sprintf (tmp, "%lu\012", (unsigned long) newsize);
5015           send_to_server (tmp, 0);
5016         }
5017 #ifdef BROKEN_READWRITE_CONVERSION
5018         if (!bin)
5019         {
5020             char tfile[1024]; strcpy(tfile, file); strcat(tfile, ".CVSBFCTMP");
5021             if (CVS_UNLINK (tfile) < 0)
5022                 error (0, errno, "warning: can't remove temp file %s", tfile);
5023         }
5024 #endif
5025
5026         /*
5027          * Note that this only ends with a newline if the file ended with
5028          * one.
5029          */
5030         if (newsize > 0)
5031             send_to_server (buf, newsize);
5032     }
5033     free (buf);
5034     free (mode_string);
5035 }
5036
5037 /* The address of an instance of this structure is passed to
5038    send_fileproc, send_filesdoneproc, and send_direntproc, as the
5039    callerdat parameter.  */
5040
5041 struct send_data
5042 {
5043     /* Each of the following flags are zero for clear or nonzero for set.  */
5044     int build_dirs;
5045     int force;
5046     int no_contents;
5047     int backup_modified;
5048 };
5049
5050 static int send_fileproc PROTO ((void *callerdat, struct file_info *finfo));
5051
5052 /* Deal with one file.  */
5053 static int
5054 send_fileproc (callerdat, finfo)
5055     void *callerdat;
5056     struct file_info *finfo;
5057 {
5058     struct send_data *args = (struct send_data *) callerdat;
5059     Vers_TS *vers;
5060     struct file_info xfinfo;
5061     /* File name to actually use.  Might differ in case from
5062        finfo->file.  */
5063     const char *filename;
5064
5065     send_a_repository ("", finfo->repository, finfo->update_dir);
5066
5067     xfinfo = *finfo;
5068     xfinfo.repository = NULL;
5069     xfinfo.rcs = NULL;
5070     vers = Version_TS (&xfinfo, NULL, NULL, NULL, 0, 0);
5071
5072     if (vers->entdata != NULL)
5073         filename = vers->entdata->user;
5074     else
5075         filename = finfo->file;
5076
5077     if (vers->vn_user != NULL)
5078     {
5079         /* The Entries request.  */
5080         send_to_server ("Entry /", 0);
5081         send_to_server (filename, 0);
5082         send_to_server ("/", 0);
5083         send_to_server (vers->vn_user, 0);
5084         send_to_server ("/", 0);
5085         if (vers->ts_conflict != NULL)
5086         {
5087             if (vers->ts_user != NULL &&
5088                 strcmp (vers->ts_conflict, vers->ts_user) == 0)
5089                 send_to_server ("+=", 0);
5090             else
5091                 send_to_server ("+modified", 0);
5092         }
5093         send_to_server ("/", 0);
5094         send_to_server (vers->entdata != NULL
5095                         ? vers->entdata->options
5096                         : vers->options,
5097                         0);
5098         send_to_server ("/", 0);
5099         if (vers->entdata != NULL && vers->entdata->tag)
5100         {
5101             send_to_server ("T", 0);
5102             send_to_server (vers->entdata->tag, 0);
5103         }
5104         else if (vers->entdata != NULL && vers->entdata->date)
5105           {
5106             send_to_server ("D", 0);
5107             send_to_server (vers->entdata->date, 0);
5108           }
5109         send_to_server ("\012", 1);
5110     }
5111     else
5112     {
5113         /* It seems a little silly to re-read this on each file, but
5114            send_dirent_proc doesn't get called if filenames are specified
5115            explicitly on the command line.  */
5116         wrap_add_file (CVSDOTWRAPPER, 1);
5117
5118         if (wrap_name_has (filename, WRAP_RCSOPTION))
5119         {
5120             /* No "Entry", but the wrappers did give us a kopt so we better
5121                send it with "Kopt".  As far as I know this only happens
5122                for "cvs add".  Question: is there any reason why checking
5123                for options from wrappers isn't done in Version_TS?
5124
5125                Note: it might have been better to just remember all the
5126                kopts on the client side, rather than send them to the server,
5127                and have it send us back the same kopts.  But that seemed like
5128                a bigger change than I had in mind making now.  */
5129
5130             if (supported_request ("Kopt"))
5131             {
5132                 char *opt;
5133
5134                 send_to_server ("Kopt ", 0);
5135                 opt = wrap_rcsoption (filename, 1);
5136                 send_to_server (opt, 0);
5137                 send_to_server ("\012", 1);
5138                 free (opt);
5139             }
5140             else
5141                 error (0, 0,
5142                        "\
5143 warning: ignoring -k options due to server limitations");
5144         }
5145     }
5146
5147     if (vers->ts_user == NULL)
5148     {
5149         /*
5150          * Do we want to print "file was lost" like normal CVS?
5151          * Would it always be appropriate?
5152          */
5153         /* File no longer exists.  Don't do anything, missing files
5154            just happen.  */
5155     }
5156     else if (vers->ts_rcs == NULL
5157              || args->force
5158              || strcmp (vers->ts_user, vers->ts_rcs) != 0
5159              || (vers->vn_user && *vers->vn_user == '0'))
5160     {
5161         if (args->no_contents
5162             && supported_request ("Is-modified"))
5163         {
5164             send_to_server ("Is-modified ", 0);
5165             send_to_server (filename, 0);
5166             send_to_server ("\012", 1);
5167         }
5168         else
5169             send_modified (filename, finfo->fullname, vers);
5170
5171         if (args->backup_modified)
5172         {
5173             char *bakname;
5174             bakname = backup_file (filename, vers->vn_user);
5175             /* This behavior is sufficiently unexpected to
5176                justify overinformativeness, I think. */
5177             if (! really_quiet)
5178                 printf ("(Locally modified %s moved to %s)\n",
5179                         filename, bakname);
5180             free (bakname);
5181         }
5182     }
5183     else
5184     {
5185         send_to_server ("Unchanged ", 0);
5186         send_to_server (filename, 0);
5187         send_to_server ("\012", 1);
5188     }
5189
5190     /* if this directory has an ignore list, add this file to it */
5191     if (ignlist)
5192     {
5193         Node *p;
5194
5195         p = getnode ();
5196         p->type = FILES;
5197         p->key = xstrdup (finfo->file);
5198         (void) addnode (ignlist, p);
5199     }
5200
5201     freevers_ts (&vers);
5202     return 0;
5203 }
5204
5205
5206
5207 static void send_ignproc PROTO ((const char *, const char *));
5208
5209 static void
5210 send_ignproc (file, dir)
5211     const char *file;
5212     const char *dir;
5213 {
5214     if (ign_inhibit_server || !supported_request ("Questionable"))
5215     {
5216         if (dir[0] != '\0')
5217             (void) printf ("? %s/%s\n", dir, file);
5218         else
5219             (void) printf ("? %s\n", file);
5220     }
5221     else
5222     {
5223         send_to_server ("Questionable ", 0);
5224         send_to_server (file, 0);
5225         send_to_server ("\012", 1);
5226     }
5227 }
5228
5229
5230
5231 static int send_filesdoneproc PROTO ((void *, int, const char *, const char *,
5232                                       List *));
5233
5234 static int
5235 send_filesdoneproc (callerdat, err, repository, update_dir, entries)
5236     void *callerdat;
5237     int err;
5238     const char *repository;
5239     const char *update_dir;
5240     List *entries;
5241 {
5242     /* if this directory has an ignore list, process it then free it */
5243     if (ignlist)
5244     {
5245         ignore_files (ignlist, entries, update_dir, send_ignproc);
5246         dellist (&ignlist);
5247     }
5248
5249     return (err);
5250 }
5251
5252 static Dtype send_dirent_proc PROTO ((void *, const char *, const char *,
5253                                       const char *, List *));
5254
5255 /*
5256  * send_dirent_proc () is called back by the recursion processor before a
5257  * sub-directory is processed for update.
5258  * A return code of 0 indicates the directory should be
5259  * processed by the recursion code.  A return of non-zero indicates the
5260  * recursion code should skip this directory.
5261  *
5262  */
5263 static Dtype
5264 send_dirent_proc (callerdat, dir, repository, update_dir, entries)
5265     void *callerdat;
5266     const char *dir;
5267     const char *repository;
5268     const char *update_dir;
5269     List *entries;
5270 {
5271     struct send_data *args = (struct send_data *) callerdat;
5272     int dir_exists;
5273     char *cvsadm_name;
5274
5275     if (ignore_directory (update_dir))
5276     {
5277         /* print the warm fuzzy message */
5278         if (!quiet)
5279             error (0, 0, "Ignoring %s", update_dir);
5280         return (R_SKIP_ALL);
5281     }
5282
5283     /*
5284      * If the directory does not exist yet (e.g. "cvs update -d foo"),
5285      * no need to send any files from it.  If the directory does not
5286      * have a CVS directory, then we pretend that it does not exist.
5287      * Otherwise, we will fail when trying to open the Entries file.
5288      * This case will happen when checking out a module defined as
5289      * ``-a .''.
5290      */
5291     cvsadm_name = xmalloc (strlen (dir) + sizeof (CVSADM) + 10);
5292     sprintf (cvsadm_name, "%s/%s", dir, CVSADM);
5293     dir_exists = isdir (cvsadm_name);
5294     free (cvsadm_name);
5295
5296     /*
5297      * If there is an empty directory (e.g. we are doing `cvs add' on a
5298      * newly-created directory), the server still needs to know about it.
5299      */
5300
5301     if (dir_exists)
5302     {
5303         /*
5304          * Get the repository from a CVS/Repository file whenever possible.
5305          * The repository variable is wrong if the names in the local
5306          * directory don't match the names in the repository.
5307          */
5308         char *repos = Name_Repository (dir, update_dir);
5309         send_a_repository (dir, repos, update_dir);
5310         free (repos);
5311
5312         /* initialize the ignore list for this directory */
5313         ignlist = getlist ();
5314     }
5315     else
5316     {
5317         /* It doesn't make sense to send a non-existent directory,
5318            because there is no way to get the correct value for
5319            the repository (I suppose maybe via the expand-modules
5320            request).  In the case where the "obvious" choice for
5321            repository is correct, the server can figure out whether
5322            to recreate the directory; in the case where it is wrong
5323            (that is, does not match what modules give us), we might as
5324            well just fail to recreate it.
5325
5326            Checking for noexec is a kludge for "cvs -n add dir".  */
5327         /* Don't send a non-existent directory unless we are building
5328            new directories (build_dirs is true).  Otherwise, CVS may
5329            see a D line in an Entries file, and recreate a directory
5330            which the user removed by hand.  */
5331         if (args->build_dirs && noexec)
5332             send_a_repository (dir, repository, update_dir);
5333     }
5334
5335     return (dir_exists ? R_PROCESS : R_SKIP_ALL);
5336 }
5337
5338
5339
5340 static int send_dirleave_proc PROTO ((void *, const char *, int, const char *,
5341                                       List *));
5342
5343 /*
5344  * send_dirleave_proc () is called back by the recursion code upon leaving
5345  * a directory.  All it does is delete the ignore list if it hasn't already
5346  * been done (by send_filesdone_proc).
5347  */
5348 /* ARGSUSED */
5349 static int
5350 send_dirleave_proc (callerdat, dir, err, update_dir, entries)
5351     void *callerdat;
5352     const char *dir;
5353     int err;
5354     const char *update_dir;
5355     List *entries;
5356 {
5357
5358     /* Delete the ignore list if it hasn't already been done.  */
5359     if (ignlist)
5360         dellist (&ignlist);
5361     return err;
5362 }
5363
5364 /*
5365  * Send each option in a string to the server, one by one.
5366  * This assumes that the options are separated by spaces, for example
5367  * STRING might be "--foo -C5 -y".
5368  */
5369
5370 void
5371 send_option_string (string)
5372     char *string;
5373 {
5374     char *copy;
5375     char *p;
5376
5377     copy = xstrdup (string);
5378     p = copy;
5379     while (1)
5380     {
5381         char *s;
5382         char l;
5383
5384         for (s = p; *s != ' ' && *s != '\0'; s++)
5385             ;
5386         l = *s;
5387         *s = '\0';
5388         if (s != p)
5389             send_arg (p);
5390         if (l == '\0')
5391             break;
5392         p = s + 1;
5393     }
5394     free (copy);
5395 }
5396
5397
5398
5399 /* Send the names of all the argument files to the server.  */
5400 void
5401 send_file_names (argc, argv, flags)
5402     int argc;
5403     char **argv;
5404     unsigned int flags;
5405 {
5406     int i;
5407     
5408     /* The fact that we do this here as well as start_recursion is a bit 
5409        of a performance hit.  Perhaps worth cleaning up someday.  */
5410     if (flags & SEND_EXPAND_WILD)
5411         expand_wild (argc, argv, &argc, &argv);
5412
5413     for (i = 0; i < argc; ++i)
5414     {
5415         char buf[1];
5416         char *p;
5417 #ifdef FILENAMES_CASE_INSENSITIVE
5418         char *line = xmalloc (1);
5419         *line = '\0';
5420 #endif /* FILENAMES_CASE_INSENSITIVE */
5421
5422         if (arg_should_not_be_sent_to_server (argv[i]))
5423             continue;
5424
5425 #ifdef FILENAMES_CASE_INSENSITIVE
5426         /* We want to send the path as it appears in the
5427            CVS/Entries files.  We put this inside an ifdef
5428            to avoid doing all these system calls in
5429            cases where fncmp is just strcmp anyway.  */
5430         /* The isdir (CVSADM) check could more gracefully be replaced
5431            with a way of having Entries_Open report back the
5432            error to us and letting us ignore existence_error.
5433            Or some such.  */
5434         {
5435             List *stack;
5436             size_t line_len = 0;
5437             char *q, *r;
5438             struct saved_cwd sdir;
5439
5440             /* Split the argument onto the stack.  */
5441             stack = getlist();
5442             r = xstrdup (argv[i]);
5443             /* It's okay to discard the const from the last_component return
5444              * below since we know we passed in an arg that was not const.
5445              */
5446             while ((q = (char *)last_component (r)) != r)
5447             {
5448                 push (stack, xstrdup (q));
5449                 *--q = '\0';
5450             }
5451             push (stack, r);
5452
5453             /* Normalize the path into outstr. */
5454             save_cwd (&sdir);
5455             while (q = pop (stack))
5456             {
5457                 Node *node = NULL;
5458                 if (isdir (CVSADM))
5459                 {
5460                     List *entries;
5461
5462                     /* Note that if we are adding a directory,
5463                        the following will read the entry
5464                        that we just wrote there, that is, we
5465                        will get the case specified on the
5466                        command line, not the case of the
5467                        directory in the filesystem.  This
5468                        is correct behavior.  */
5469                     entries = Entries_Open (0, NULL);
5470                     node = findnode_fn (entries, q);
5471                     if (node != NULL)
5472                     {
5473                         /* Add the slash unless this is our first element. */
5474                         if (line_len)
5475                             xrealloc_and_strcat (&line, &line_len, "/");
5476                         xrealloc_and_strcat (&line, &line_len, node->key);
5477                         delnode (node);
5478                     }
5479                     Entries_Close (entries);
5480                 }
5481
5482                 /* If node is still NULL then we either didn't find CVSADM or
5483                  * we didn't find an entry there.
5484                  */
5485                 if (node == NULL)
5486                 {
5487                     /* Add the slash unless this is our first element. */
5488                     if (line_len)
5489                         xrealloc_and_strcat (&line, &line_len, "/");
5490                     xrealloc_and_strcat (&line, &line_len, q);
5491                     break;
5492                 }
5493
5494                 /* And descend the tree. */
5495                 if (isdir (q))
5496                     CVS_CHDIR (q);
5497                 free (q);
5498             }
5499             restore_cwd (&sdir, NULL);
5500             free_cwd (&sdir);
5501
5502             /* Now put everything we didn't find entries for back on. */
5503             while (q = pop (stack))
5504             {
5505                 if (line_len)
5506                     xrealloc_and_strcat (&line, &line_len, "/");
5507                 xrealloc_and_strcat (&line, &line_len, q);
5508                 free (q);
5509             }
5510
5511             p = line;
5512
5513             dellist (&stack);
5514         }
5515 #else /* !FILENAMES_CASE_INSENSITIVE */
5516         p = argv[i];
5517 #endif /* FILENAMES_CASE_INSENSITIVE */
5518
5519         send_to_server ("Argument ", 0);
5520
5521         while (*p)
5522         {
5523             if (*p == '\n')
5524             {
5525                 send_to_server ("\012Argumentx ", 0);
5526             }
5527             else if (ISDIRSEP (*p))
5528             {
5529                 buf[0] = '/';
5530                 send_to_server (buf, 1);
5531             }
5532             else
5533             {
5534                 buf[0] = *p;
5535                 send_to_server (buf, 1);
5536             }
5537             ++p;
5538         }
5539         send_to_server ("\012", 1);
5540 #ifdef FILENAMES_CASE_INSENSITIVE
5541         free (line);
5542 #endif /* FILENAMES_CASE_INSENSITIVE */
5543     }
5544
5545     if (flags & SEND_EXPAND_WILD)
5546     {
5547         int i;
5548         for (i = 0; i < argc; ++i)
5549             free (argv[i]);
5550         free (argv);
5551     }
5552 }
5553
5554
5555
5556 /* Calculate and send max-dotdot to the server */
5557 static void
5558 send_max_dotdot (argc, argv)
5559     int argc;
5560     char **argv;
5561 {
5562     int i;
5563     int level = 0;
5564     int max_level = 0;
5565
5566     /* Send Max-dotdot if needed.  */
5567     for (i = 0; i < argc; ++i)
5568     {
5569         level = pathname_levels (argv[i]);
5570         if (level > 0)
5571         {
5572             if (uppaths == NULL) uppaths = getlist();
5573             push_string (uppaths, xstrdup (argv[i]));
5574         }
5575         if (level > max_level)
5576             max_level = level;
5577     }
5578
5579     if (max_level > 0)
5580     {
5581         if (supported_request ("Max-dotdot"))
5582         {
5583             char buf[10];
5584             sprintf (buf, "%d", max_level);
5585
5586             send_to_server ("Max-dotdot ", 0);
5587             send_to_server (buf, 0);
5588             send_to_server ("\012", 1);
5589         }
5590         else
5591         {
5592             error (1, 0,
5593 "backreference in path (`..') not supported by old (pre-Max-dotdot) servers");
5594         }
5595     }
5596 }
5597
5598
5599
5600 /* Send Repository, Modified and Entry.  argc and argv contain only
5601   the files to operate on (or empty for everything), not options.
5602   local is nonzero if we should not recurse (-l option).  flags &
5603   SEND_BUILD_DIRS is nonzero if nonexistent directories should be
5604   sent.  flags & SEND_FORCE is nonzero if we should send unmodified
5605   files to the server as though they were modified.  flags &
5606   SEND_NO_CONTENTS means that this command only needs to know
5607   _whether_ a file is modified, not the contents.  Also sends Argument
5608   lines for argc and argv, so should be called after options are sent.  */
5609 void
5610 send_files (argc, argv, local, aflag, flags)
5611     int argc;
5612     char **argv;
5613     int local;
5614     int aflag;
5615     unsigned int flags;
5616 {
5617     struct send_data args;
5618     int err;
5619
5620     send_max_dotdot (argc, argv);
5621
5622     /*
5623      * aflag controls whether the tag/date is copied into the vers_ts.
5624      * But we don't actually use it, so I don't think it matters what we pass
5625      * for aflag here.
5626      */
5627     args.build_dirs = flags & SEND_BUILD_DIRS;
5628     args.force = flags & SEND_FORCE;
5629     args.no_contents = flags & SEND_NO_CONTENTS;
5630     args.backup_modified = flags & BACKUP_MODIFIED_FILES;
5631     err = start_recursion
5632         (send_fileproc, send_filesdoneproc,
5633          send_dirent_proc, send_dirleave_proc, (void *) &args,
5634          argc, argv, local, W_LOCAL, aflag, CVS_LOCK_NONE, (char *) NULL, 0,
5635          (char *) NULL);
5636     if (err)
5637         error_exit ();
5638     if (toplevel_repos == NULL)
5639         /*
5640          * This happens if we are not processing any files,
5641          * or for checkouts in directories without any existing stuff
5642          * checked out.  The following assignment is correct for the
5643          * latter case; I don't think toplevel_repos matters for the
5644          * former.
5645          */
5646         toplevel_repos = xstrdup (current_parsed_root->directory);
5647     send_repository ("", toplevel_repos, ".");
5648 }
5649 \f
5650 void
5651 client_import_setup (repository)
5652     char *repository;
5653 {
5654     if (toplevel_repos == NULL)         /* should always be true */
5655         send_a_repository ("", repository, "");
5656 }
5657
5658 /*
5659  * Process the argument import file.
5660  */
5661 int
5662 client_process_import_file (message, vfile, vtag, targc, targv, repository,
5663                             all_files_binary, modtime)
5664     char *message;
5665     char *vfile;
5666     char *vtag;
5667     int targc;
5668     char *targv[];
5669     char *repository;
5670     int all_files_binary;
5671
5672     /* Nonzero for "import -d".  */
5673     int modtime;
5674 {
5675     char *update_dir;
5676     char *fullname;
5677     Vers_TS vers;
5678
5679     assert (toplevel_repos != NULL);
5680
5681     if (strncmp (repository, toplevel_repos, strlen (toplevel_repos)) != 0)
5682         error (1, 0,
5683                "internal error: pathname `%s' doesn't specify file in `%s'",
5684                repository, toplevel_repos);
5685
5686     if (strcmp (repository, toplevel_repos) == 0)
5687     {
5688         update_dir = "";
5689         fullname = xstrdup (vfile);
5690     }
5691     else
5692     {
5693         update_dir = repository + strlen (toplevel_repos) + 1;
5694
5695         fullname = xmalloc (strlen (vfile) + strlen (update_dir) + 10);
5696         strcpy (fullname, update_dir);
5697         strcat (fullname, "/");
5698         strcat (fullname, vfile);
5699     }
5700
5701     send_a_repository ("", repository, update_dir);
5702     if (all_files_binary)
5703     {
5704         vers.options = xmalloc (4); /* strlen("-kb") + 1 */
5705         strcpy (vers.options, "-kb");
5706     }
5707     else
5708     {
5709         vers.options = wrap_rcsoption (vfile, 1);
5710     }
5711     if (vers.options != NULL)
5712     {
5713         if (supported_request ("Kopt"))
5714         {
5715             send_to_server ("Kopt ", 0);
5716             send_to_server (vers.options, 0);
5717             send_to_server ("\012", 1);
5718         }
5719         else
5720             error (0, 0,
5721                    "warning: ignoring -k options due to server limitations");
5722     }
5723     if (modtime)
5724     {
5725         if (supported_request ("Checkin-time"))
5726         {
5727             struct stat sb;
5728             char *rcsdate;
5729             char netdate[MAXDATELEN];
5730
5731             if (CVS_STAT (vfile, &sb) < 0)
5732                 error (1, errno, "cannot stat %s", fullname);
5733             rcsdate = date_from_time_t (sb.st_mtime);
5734             date_to_internet (netdate, rcsdate);
5735             free (rcsdate);
5736
5737             send_to_server ("Checkin-time ", 0);
5738             send_to_server (netdate, 0);
5739             send_to_server ("\012", 1);
5740         }
5741         else
5742             error (0, 0,
5743                    "warning: ignoring -d option due to server limitations");
5744     }
5745     send_modified (vfile, fullname, &vers);
5746     if (vers.options != NULL)
5747         free (vers.options);
5748     free (fullname);
5749     return 0;
5750 }
5751
5752 void
5753 client_import_done ()
5754 {
5755     if (toplevel_repos == NULL)
5756         /*
5757          * This happens if we are not processing any files,
5758          * or for checkouts in directories without any existing stuff
5759          * checked out.  The following assignment is correct for the
5760          * latter case; I don't think toplevel_repos matters for the
5761          * former.
5762          */
5763         /* FIXME: "can't happen" now that we call client_import_setup
5764            at the beginning.  */
5765         toplevel_repos = xstrdup (current_parsed_root->directory);
5766     send_repository ("", toplevel_repos, ".");
5767 }
5768
5769
5770
5771 static void
5772 notified_a_file (data, ent_list, short_pathname, filename)
5773     char *data;
5774     List *ent_list;
5775     char *short_pathname;
5776     char *filename;
5777 {
5778     FILE *fp;
5779     FILE *newf;
5780     size_t line_len = 8192;
5781     char *line = xmalloc (line_len);
5782     char *cp;
5783     int nread;
5784     int nwritten;
5785     char *p;
5786
5787     fp = open_file (CVSADM_NOTIFY, "r");
5788     if (getline (&line, &line_len, fp) < 0)
5789     {
5790         if (feof (fp))
5791             error (0, 0, "cannot read %s: end of file", CVSADM_NOTIFY);
5792         else
5793             error (0, errno, "cannot read %s", CVSADM_NOTIFY);
5794         goto error_exit;
5795     }
5796     cp = strchr (line, '\t');
5797     if (cp == NULL)
5798     {
5799         error (0, 0, "malformed %s file", CVSADM_NOTIFY);
5800         goto error_exit;
5801     }
5802     *cp = '\0';
5803     if (strcmp (filename, line + 1) != 0)
5804     {
5805         error (0, 0, "protocol error: notified %s, expected %s", filename,
5806                line + 1);
5807     }
5808
5809     if (getline (&line, &line_len, fp) < 0)
5810     {
5811         if (feof (fp))
5812         {
5813             free (line);
5814             if (fclose (fp) < 0)
5815                 error (0, errno, "cannot close %s", CVSADM_NOTIFY);
5816             if ( CVS_UNLINK (CVSADM_NOTIFY) < 0)
5817                 error (0, errno, "cannot remove %s", CVSADM_NOTIFY);
5818             return;
5819         }
5820         else
5821         {
5822             error (0, errno, "cannot read %s", CVSADM_NOTIFY);
5823             goto error_exit;
5824         }
5825     }
5826     newf = open_file (CVSADM_NOTIFYTMP, "w");
5827     if (fputs (line, newf) < 0)
5828     {
5829         error (0, errno, "cannot write %s", CVSADM_NOTIFYTMP);
5830         goto error2;
5831     }
5832     while ((nread = fread (line, 1, line_len, fp)) > 0)
5833     {
5834         p = line;
5835         while ((nwritten = fwrite (p, 1, nread, newf)) > 0)
5836         {
5837             nread -= nwritten;
5838             p += nwritten;
5839         }
5840         if (ferror (newf))
5841         {
5842             error (0, errno, "cannot write %s", CVSADM_NOTIFYTMP);
5843             goto error2;
5844         }
5845     }
5846     if (ferror (fp))
5847     {
5848         error (0, errno, "cannot read %s", CVSADM_NOTIFY);
5849         goto error2;
5850     }
5851     if (fclose (newf) < 0)
5852     {
5853         error (0, errno, "cannot close %s", CVSADM_NOTIFYTMP);
5854         goto error_exit;
5855     }
5856     free (line);
5857     if (fclose (fp) < 0)
5858     {
5859         error (0, errno, "cannot close %s", CVSADM_NOTIFY);
5860         return;
5861     }
5862
5863     {
5864         /* In this case, we want rename_file() to ignore noexec. */
5865         int saved_noexec = noexec;
5866         noexec = 0;
5867         rename_file (CVSADM_NOTIFYTMP, CVSADM_NOTIFY);
5868         noexec = saved_noexec;
5869     }
5870
5871     return;
5872   error2:
5873     (void) fclose (newf);
5874   error_exit:
5875     free (line);
5876     (void) fclose (fp);
5877 }
5878
5879 static void
5880 handle_notified (args, len)
5881     char *args;
5882     int len;
5883 {
5884     call_in_directory (args, notified_a_file, NULL);
5885 }
5886
5887 void
5888 client_notify (repository, update_dir, filename, notif_type, val)
5889     const char *repository;
5890     const char *update_dir;
5891     const char *filename;
5892     int notif_type;
5893     const char *val;
5894 {
5895     char buf[2];
5896
5897     send_a_repository ("", repository, update_dir);
5898     send_to_server ("Notify ", 0);
5899     send_to_server (filename, 0);
5900     send_to_server ("\012", 1);
5901     buf[0] = notif_type;
5902     buf[1] = '\0';
5903     send_to_server (buf, 1);
5904     send_to_server ("\t", 1);
5905     send_to_server (val, 0);
5906 }
5907 \f
5908 /*
5909  * Send an option with an argument, dealing correctly with newlines in
5910  * the argument.  If ARG is NULL, forget the whole thing.
5911  */
5912 void
5913 option_with_arg (option, arg)
5914     char *option;
5915     char *arg;
5916 {
5917     if (arg == NULL)
5918         return;
5919
5920     send_to_server ("Argument ", 0);
5921     send_to_server (option, 0);
5922     send_to_server ("\012", 1);
5923
5924     send_arg (arg);
5925 }
5926
5927 /* Send a date to the server.  The input DATE is in RCS format.
5928    The time will be GMT.
5929
5930    We then convert that to the format required in the protocol
5931    (including the "-D" option) and send it.  According to
5932    cvsclient.texi, RFC 822/1123 format is preferred.  */
5933
5934 void
5935 client_senddate (date)
5936     const char *date;
5937 {
5938     char buf[MAXDATELEN];
5939
5940     date_to_internet (buf, (char *)date);
5941     option_with_arg ("-D", buf);
5942 }
5943 \f
5944 void
5945 send_init_command ()
5946 {
5947     /* This is here because we need the current_parsed_root->directory variable.  */
5948     send_to_server ("init ", 0);
5949     send_to_server (current_parsed_root->directory, 0);
5950     send_to_server ("\012", 0);
5951 }
5952
5953 #endif /* CLIENT_SUPPORT */