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