PageRenderTime 149ms CodeModel.GetById 29ms app.highlight 100ms RepoModel.GetById 1ms app.codeStats 1ms

/contrib/cvs/src/client.c

https://bitbucket.org/freebsd/freebsd-head/
C | 5948 lines | 4003 code | 769 blank | 1176 comment | 924 complexity | 9511b64d9b8ee98d0142435b9235f1e7 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1/* CVS client-related stuff.
   2
   3   This program is free software; you can redistribute it and/or modify
   4   it under the terms of the GNU General Public License as published by
   5   the Free Software Foundation; either version 2, or (at your option)
   6   any later version.
   7
   8   This program is distributed in the hope that it will be useful,
   9   but WITHOUT ANY WARRANTY; without even the implied warranty of
  10   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11   GNU General Public License for more details.  */
  12
  13/*
  14 * $FreeBSD$
  15 */
  16
  17#ifdef HAVE_CONFIG_H
  18# include "config.h"
  19#endif /* HAVE_CONFIG_H */
  20
  21#include <assert.h>
  22#include "cvs.h"
  23#include "getline.h"
  24#include "edit.h"
  25#include "buffer.h"
  26#include "savecwd.h"
  27
  28#ifdef CLIENT_SUPPORT
  29
  30# include "md5.h"
  31
  32# if defined(AUTH_CLIENT_SUPPORT) || defined(HAVE_KERBEROS) || defined(HAVE_GSSAPI) || defined(SOCK_ERRNO) || defined(SOCK_STRERROR)
  33#   ifdef HAVE_WINSOCK_H
  34#     include <winsock.h>
  35#   else /* No winsock.h */
  36#     include <sys/socket.h>
  37#     include <netinet/in.h>
  38#     include <arpa/inet.h>
  39#     include <netdb.h>
  40#   endif /* No winsock.h */
  41# endif
  42
  43/* If SOCK_ERRNO is defined, then send()/recv() and other socket calls
  44   do not set errno, but that this macro should be used to obtain an
  45   error code.  This probably doesn't make sense unless
  46   NO_SOCKET_TO_FD is also defined. */
  47# ifndef SOCK_ERRNO
  48#   define SOCK_ERRNO errno
  49# endif
  50
  51/* If SOCK_STRERROR is defined, then the error codes returned by
  52   socket operations are not known to strerror, and this macro must be
  53   used instead to convert those error codes to strings. */
  54# ifndef SOCK_STRERROR
  55#   define SOCK_STRERROR strerror
  56
  57#   if STDC_HEADERS
  58#     include <string.h>
  59#   endif
  60
  61#   ifndef strerror
  62extern char *strerror ();
  63#   endif
  64# endif /* ! SOCK_STRERROR */
  65
  66# if HAVE_KERBEROS
  67
  68#   include <krb.h>
  69
  70extern char *krb_realmofhost ();
  71#   ifndef HAVE_KRB_GET_ERR_TEXT
  72#     define krb_get_err_text(status) krb_err_txt[status]
  73#   endif /* HAVE_KRB_GET_ERR_TEXT */
  74
  75/* Information we need if we are going to use Kerberos encryption.  */
  76static C_Block kblock;
  77static Key_schedule sched;
  78
  79# endif /* HAVE_KERBEROS */
  80
  81# ifdef HAVE_GSSAPI
  82
  83#   include "xgssapi.h"
  84
  85/* This is needed for GSSAPI encryption.  */
  86static gss_ctx_id_t gcontext;
  87
  88static int connect_to_gserver PROTO((cvsroot_t *, int, struct hostent *));
  89
  90# endif /* HAVE_GSSAPI */
  91
  92
  93
  94/* Keep track of any paths we are sending for Max-dotdot so that we can verify
  95 * that uplevel paths coming back form the server are valid.
  96 *
  97 * FIXME: The correct way to do this is probably provide some sort of virtual
  98 * path map on the client side.  This would be generic enough to be applied to
  99 * absolute paths supplied by the user too.
 100 */
 101static List *uppaths = NULL;
 102
 103
 104
 105static void add_prune_candidate PROTO((const char *));
 106
 107/* All the commands.  */
 108int add PROTO((int argc, char **argv));
 109int admin PROTO((int argc, char **argv));
 110int checkout PROTO((int argc, char **argv));
 111int commit PROTO((int argc, char **argv));
 112int diff PROTO((int argc, char **argv));
 113int history PROTO((int argc, char **argv));
 114int import PROTO((int argc, char **argv));
 115int cvslog PROTO((int argc, char **argv));
 116int patch PROTO((int argc, char **argv));
 117int release PROTO((int argc, char **argv));
 118int cvsremove PROTO((int argc, char **argv));
 119int rtag PROTO((int argc, char **argv));
 120int status PROTO((int argc, char **argv));
 121int tag PROTO((int argc, char **argv));
 122int update PROTO((int argc, char **argv));
 123
 124/* All the response handling functions.  */
 125static void handle_ok PROTO((char *, int));
 126static void handle_error PROTO((char *, int));
 127static void handle_valid_requests PROTO((char *, int));
 128static void handle_checked_in PROTO((char *, int));
 129static void handle_new_entry PROTO((char *, int));
 130static void handle_checksum PROTO((char *, int));
 131static void handle_copy_file PROTO((char *, int));
 132static void handle_updated PROTO((char *, int));
 133static void handle_merged PROTO((char *, int));
 134static void handle_patched PROTO((char *, int));
 135static void handle_rcs_diff PROTO((char *, int));
 136static void handle_removed PROTO((char *, int));
 137static void handle_remove_entry PROTO((char *, int));
 138static void handle_set_static_directory PROTO((char *, int));
 139static void handle_clear_static_directory PROTO((char *, int));
 140static void handle_set_sticky PROTO((char *, int));
 141static void handle_clear_sticky PROTO((char *, int));
 142static void handle_module_expansion PROTO((char *, int));
 143static void handle_wrapper_rcs_option PROTO((char *, int));
 144static void handle_m PROTO((char *, int));
 145static void handle_e PROTO((char *, int));
 146static void handle_f PROTO((char *, int));
 147static void handle_notified PROTO((char *, int));
 148
 149static size_t try_read_from_server PROTO ((char *, size_t));
 150
 151static void auth_server PROTO ((cvsroot_t *, struct buffer *, struct buffer *,
 152				int, int, struct hostent *));
 153
 154/* We need to keep track of the list of directories we've sent to the
 155   server.  This list, along with the current CVSROOT, will help us
 156   decide which command-line arguments to send.  */
 157List *dirs_sent_to_server = NULL;
 158
 159static int is_arg_a_parent_or_listed_dir PROTO((Node *, void *));
 160
 161static int
 162is_arg_a_parent_or_listed_dir (n, d)
 163    Node *n;
 164    void *d;
 165{
 166    char *directory = n->key;	/* name of the dir sent to server */
 167    char *this_argv_elem = xstrdup (d);	/* this argv element */
 168    int retval;
 169
 170    /* Say we should send this argument if the argument matches the
 171       beginning of a directory name sent to the server.  This way,
 172       the server will know to start at the top of that directory
 173       hierarchy and descend. */
 174
 175    strip_trailing_slashes (this_argv_elem);
 176    if (strncmp (directory, this_argv_elem, strlen (this_argv_elem)) == 0)
 177	retval = 1;
 178    else
 179	retval = 0;
 180
 181    free (this_argv_elem);
 182    return retval;
 183}
 184
 185static int arg_should_not_be_sent_to_server PROTO((char *));
 186
 187/* Return nonzero if this argument should not be sent to the
 188   server. */
 189
 190static int
 191arg_should_not_be_sent_to_server (arg)
 192    char *arg;
 193{
 194    /* Decide if we should send this directory name to the server.  We
 195       should always send argv[i] if:
 196
 197       1) the list of directories sent to the server is empty (as it
 198       will be for checkout, etc.).
 199
 200       2) the argument is "."
 201
 202       3) the argument is a file in the cwd and the cwd is checked out
 203       from the current root
 204
 205       4) the argument lies within one of the paths in
 206       dirs_sent_to_server.
 207
 208       */
 209
 210    if (list_isempty (dirs_sent_to_server))
 211	return 0;		/* always send it */
 212
 213    if (strcmp (arg, ".") == 0)
 214	return 0;		/* always send it */
 215
 216    /* We should send arg if it is one of the directories sent to the
 217       server or the parent of one; this tells the server to descend
 218       the hierarchy starting at this level. */
 219    if (isdir (arg))
 220    {
 221	if (walklist (dirs_sent_to_server, is_arg_a_parent_or_listed_dir, arg))
 222	    return 0;
 223
 224	/* If arg wasn't a parent, we don't know anything about it (we
 225	   would have seen something related to it during the
 226	   send_files phase).  Don't send it.  */
 227	return 1;
 228    }
 229
 230    /* Try to decide whether we should send arg to the server by
 231       checking the contents of the corresponding CVSADM directory. */
 232    {
 233	char *t, *root_string;
 234	cvsroot_t *this_root = NULL;
 235
 236	/* Calculate "dirname arg" */
 237	for (t = arg + strlen (arg) - 1; t >= arg; t--)
 238	{
 239	    if (ISDIRSEP(*t))
 240		break;
 241	}
 242
 243	/* Now we're either poiting to the beginning of the
 244	   string, or we found a path separator. */
 245	if (t >= arg)
 246	{
 247	    /* Found a path separator.  */
 248	    char c = *t;
 249	    *t = '\0';
 250	    
 251	    /* First, check to see if we sent this directory to the
 252               server, because it takes less time than actually
 253               opening the stuff in the CVSADM directory.  */
 254	    if (walklist (dirs_sent_to_server, is_arg_a_parent_or_listed_dir,
 255			  arg))
 256	    {
 257		*t = c;		/* make sure to un-truncate the arg */
 258		return 0;
 259	    }
 260
 261	    /* Since we didn't find it in the list, check the CVSADM
 262               files on disk.  */
 263	    this_root = Name_Root (arg, (char *) NULL);
 264	    root_string = this_root->original;
 265	    *t = c;
 266	}
 267	else
 268	{
 269	    /* We're at the beginning of the string.  Look at the
 270               CVSADM files in cwd.  */
 271	    if (CVSroot_cmdline)
 272		root_string = CVSroot_cmdline;
 273	    else
 274	    {
 275		this_root = Name_Root ((char *) NULL, (char *) NULL);
 276		root_string = this_root->original;
 277	    }
 278	}
 279
 280	/* Now check the value for root. */
 281	if (CVSroot_cmdline == NULL &&
 282	    root_string && current_parsed_root
 283	    && (strcmp (root_string, current_parsed_root->original) != 0))
 284	{
 285	    /* Don't send this, since the CVSROOTs don't match. */
 286	    if (this_root) free_cvsroot_t (this_root);
 287	    return 1;
 288	}
 289	if (this_root) free_cvsroot_t (this_root);
 290    }
 291    
 292    /* OK, let's send it. */
 293    return 0;
 294}
 295
 296
 297
 298#endif /* CLIENT_SUPPORT */
 299
 300
 301
 302#if defined(CLIENT_SUPPORT) || defined(SERVER_SUPPORT)
 303
 304/* Shared with server.  */
 305
 306/*
 307 * Return a malloc'd, '\0'-terminated string
 308 * corresponding to the mode in SB.
 309 */
 310char *
 311#ifdef __STDC__
 312mode_to_string (mode_t mode)
 313#else /* ! __STDC__ */
 314mode_to_string (mode)
 315	mode_t mode;
 316#endif /* __STDC__ */
 317{
 318    char buf[18], u[4], g[4], o[4];
 319    int i;
 320
 321    i = 0;
 322    if (mode & S_IRUSR) u[i++] = 'r';
 323    if (mode & S_IWUSR) u[i++] = 'w';
 324    if (mode & S_IXUSR) u[i++] = 'x';
 325    u[i] = '\0';
 326
 327    i = 0;
 328    if (mode & S_IRGRP) g[i++] = 'r';
 329    if (mode & S_IWGRP) g[i++] = 'w';
 330    if (mode & S_IXGRP) g[i++] = 'x';
 331    g[i] = '\0';
 332
 333    i = 0;
 334    if (mode & S_IROTH) o[i++] = 'r';
 335    if (mode & S_IWOTH) o[i++] = 'w';
 336    if (mode & S_IXOTH) o[i++] = 'x';
 337    o[i] = '\0';
 338
 339    sprintf(buf, "u=%s,g=%s,o=%s", u, g, o);
 340    return xstrdup(buf);
 341}
 342
 343/*
 344 * Change mode of FILENAME to MODE_STRING.
 345 * Returns 0 for success or errno code.
 346 * If RESPECT_UMASK is set, then honor the umask.
 347 */
 348int
 349change_mode (filename, mode_string, respect_umask)
 350    char *filename;
 351    char *mode_string;
 352    int respect_umask;
 353{
 354#ifdef CHMOD_BROKEN
 355    char *p;
 356    int writeable = 0;
 357
 358    /* We can only distinguish between
 359         1) readable
 360         2) writeable
 361         3) Picasso's "Blue Period"
 362       We handle the first two. */
 363    p = mode_string;
 364    while (*p != '\0')
 365    {
 366	if ((p[0] == 'u' || p[0] == 'g' || p[0] == 'o') && p[1] == '=')
 367	{
 368	    char *q = p + 2;
 369	    while (*q != ',' && *q != '\0')
 370	    {
 371		if (*q == 'w')
 372		    writeable = 1;
 373		++q;
 374	    }
 375	}
 376	/* Skip to the next field.  */
 377	while (*p != ',' && *p != '\0')
 378	    ++p;
 379	if (*p == ',')
 380	    ++p;
 381    }
 382
 383    /* xchmod honors the umask for us.  In the !respect_umask case, we
 384       don't try to cope with it (probably to handle that well, the server
 385       needs to deal with modes in data structures, rather than via the
 386       modes in temporary files).  */
 387    xchmod (filename, writeable);
 388	return 0;
 389
 390#else /* ! CHMOD_BROKEN */
 391
 392    char *p;
 393    mode_t mode = 0;
 394    mode_t oumask;
 395
 396    p = mode_string;
 397    while (*p != '\0')
 398    {
 399	if ((p[0] == 'u' || p[0] == 'g' || p[0] == 'o') && p[1] == '=')
 400	{
 401	    int can_read = 0, can_write = 0, can_execute = 0;
 402	    char *q = p + 2;
 403	    while (*q != ',' && *q != '\0')
 404	    {
 405		if (*q == 'r')
 406		    can_read = 1;
 407		else if (*q == 'w')
 408		    can_write = 1;
 409		else if (*q == 'x')
 410		    can_execute = 1;
 411		++q;
 412	    }
 413	    if (p[0] == 'u')
 414	    {
 415		if (can_read)
 416		    mode |= S_IRUSR;
 417		if (can_write)
 418		    mode |= S_IWUSR;
 419		if (can_execute)
 420		    mode |= S_IXUSR;
 421	    }
 422	    else if (p[0] == 'g')
 423	    {
 424		if (can_read)
 425		    mode |= S_IRGRP;
 426		if (can_write)
 427		    mode |= S_IWGRP;
 428		if (can_execute)
 429		    mode |= S_IXGRP;
 430	    }
 431	    else if (p[0] == 'o')
 432	    {
 433		if (can_read)
 434		    mode |= S_IROTH;
 435		if (can_write)
 436		    mode |= S_IWOTH;
 437		if (can_execute)
 438		    mode |= S_IXOTH;
 439	    }
 440	}
 441	/* Skip to the next field.  */
 442	while (*p != ',' && *p != '\0')
 443	    ++p;
 444	if (*p == ',')
 445	    ++p;
 446    }
 447
 448    if (respect_umask)
 449    {
 450	oumask = umask (0);
 451	(void) umask (oumask);
 452	mode &= ~oumask;
 453    }
 454
 455    if (chmod (filename, mode) < 0)
 456	return errno;
 457    return 0;
 458#endif /* ! CHMOD_BROKEN */
 459}
 460
 461#endif /* CLIENT_SUPPORT or SERVER_SUPPORT */
 462
 463#ifdef CLIENT_SUPPORT
 464
 465int client_prune_dirs;
 466
 467static List *ignlist = (List *) NULL;
 468
 469/* Buffer to write to the server.  */
 470static struct buffer *to_server;
 471
 472/* Buffer used to read from the server.  */
 473static struct buffer *from_server;
 474
 475
 476/* We want to be able to log data sent between us and the server.  We
 477   do it using log buffers.  Each log buffer has another buffer which
 478   handles the actual I/O, and a file to log information to.
 479
 480   This structure is the closure field of a log buffer.  */
 481
 482struct log_buffer
 483{
 484    /* The underlying buffer.  */
 485    struct buffer *buf;
 486    /* The file to log information to.  */
 487    FILE *log;
 488};
 489
 490static struct buffer *log_buffer_initialize
 491  PROTO((struct buffer *, FILE *, int, void (*) (struct buffer *)));
 492static int log_buffer_input PROTO((void *, char *, int, int, int *));
 493static int log_buffer_output PROTO((void *, const char *, int, int *));
 494static int log_buffer_flush PROTO((void *));
 495static int log_buffer_block PROTO((void *, int));
 496static int log_buffer_shutdown PROTO((struct buffer *));
 497
 498/* Create a log buffer.  */
 499
 500static struct buffer *
 501log_buffer_initialize (buf, fp, input, memory)
 502     struct buffer *buf;
 503     FILE *fp;
 504     int input;
 505     void (*memory) PROTO((struct buffer *));
 506{
 507    struct log_buffer *n;
 508
 509    n = (struct log_buffer *) xmalloc (sizeof *n);
 510    n->buf = buf;
 511    n->log = fp;
 512    return buf_initialize (input ? log_buffer_input : NULL,
 513			   input ? NULL : log_buffer_output,
 514			   input ? NULL : log_buffer_flush,
 515			   log_buffer_block,
 516			   log_buffer_shutdown,
 517			   memory,
 518			   n);
 519}
 520
 521/* The input function for a log buffer.  */
 522
 523static int
 524log_buffer_input (closure, data, need, size, got)
 525     void *closure;
 526     char *data;
 527     int need;
 528     int size;
 529     int *got;
 530{
 531    struct log_buffer *lb = (struct log_buffer *) closure;
 532    int status;
 533    size_t n_to_write;
 534
 535    if (lb->buf->input == NULL)
 536	abort ();
 537
 538    status = (*lb->buf->input) (lb->buf->closure, data, need, size, got);
 539    if (status != 0)
 540	return status;
 541
 542    if (*got > 0)
 543    {
 544	n_to_write = *got;
 545	if (fwrite (data, 1, n_to_write, lb->log) != n_to_write)
 546	    error (0, errno, "writing to log file");
 547    }
 548
 549    return 0;
 550}
 551
 552/* The output function for a log buffer.  */
 553
 554static int
 555log_buffer_output (closure, data, have, wrote)
 556     void *closure;
 557     const char *data;
 558     int have;
 559     int *wrote;
 560{
 561    struct log_buffer *lb = (struct log_buffer *) closure;
 562    int status;
 563    size_t n_to_write;
 564
 565    if (lb->buf->output == NULL)
 566	abort ();
 567
 568    status = (*lb->buf->output) (lb->buf->closure, data, have, wrote);
 569    if (status != 0)
 570	return status;
 571
 572    if (*wrote > 0)
 573    {
 574	n_to_write = *wrote;
 575	if (fwrite (data, 1, n_to_write, lb->log) != n_to_write)
 576	    error (0, errno, "writing to log file");
 577    }
 578
 579    return 0;
 580}
 581
 582/* The flush function for a log buffer.  */
 583
 584static int
 585log_buffer_flush (closure)
 586     void *closure;
 587{
 588    struct log_buffer *lb = (struct log_buffer *) closure;
 589
 590    if (lb->buf->flush == NULL)
 591	abort ();
 592
 593    /* We don't really have to flush the log file here, but doing it
 594       will let tail -f on the log file show what is sent to the
 595       network as it is sent.  */
 596    if (fflush (lb->log) != 0)
 597        error (0, errno, "flushing log file");
 598
 599    return (*lb->buf->flush) (lb->buf->closure);
 600}
 601
 602/* The block function for a log buffer.  */
 603
 604static int
 605log_buffer_block (closure, block)
 606     void *closure;
 607     int block;
 608{
 609    struct log_buffer *lb = (struct log_buffer *) closure;
 610
 611    if (block)
 612	return set_block (lb->buf);
 613    else
 614	return set_nonblock (lb->buf);
 615}
 616
 617/* The shutdown function for a log buffer.  */
 618
 619static int
 620log_buffer_shutdown (buf)
 621     struct buffer *buf;
 622{
 623    struct log_buffer *lb = (struct log_buffer *) buf->closure;
 624    int retval;
 625
 626    retval = buf_shutdown (lb->buf);
 627    if (fclose (lb->log) < 0)
 628	error (0, errno, "closing log file");
 629    return retval;
 630}
 631
 632#ifdef NO_SOCKET_TO_FD
 633
 634/* Under certain circumstances, we must communicate with the server
 635   via a socket using send() and recv().  This is because under some
 636   operating systems (OS/2 and Windows 95 come to mind), a socket
 637   cannot be converted to a file descriptor -- it must be treated as a
 638   socket and nothing else.
 639   
 640   We may also need to deal with socket routine error codes differently
 641   in these cases.  This is handled through the SOCK_ERRNO and
 642   SOCK_STRERROR macros. */
 643
 644/* These routines implement a buffer structure which uses send and
 645   recv.  The buffer is always in blocking mode so we don't implement
 646   the block routine.  */
 647
 648/* Note that it is important that these routines always handle errors
 649   internally and never return a positive errno code, since it would in
 650   general be impossible for the caller to know in general whether any
 651   error code came from a socket routine (to decide whether to use
 652   SOCK_STRERROR or simply strerror to print an error message). */
 653
 654/* We use an instance of this structure as the closure field.  */
 655
 656struct socket_buffer
 657{
 658    /* The socket number.  */
 659    int socket;
 660};
 661
 662static struct buffer *socket_buffer_initialize
 663  PROTO ((int, int, void (*) (struct buffer *)));
 664static int socket_buffer_input PROTO((void *, char *, int, int, int *));
 665static int socket_buffer_output PROTO((void *, const char *, int, int *));
 666static int socket_buffer_flush PROTO((void *));
 667static int socket_buffer_shutdown PROTO((struct buffer *));
 668
 669
 670
 671/* Create a buffer based on a socket.  */
 672
 673static struct buffer *
 674socket_buffer_initialize (socket, input, memory)
 675    int socket;
 676    int input;
 677    void (*memory) PROTO((struct buffer *));
 678{
 679    struct socket_buffer *n;
 680
 681    n = (struct socket_buffer *) xmalloc (sizeof *n);
 682    n->socket = socket;
 683    return buf_initialize (input ? socket_buffer_input : NULL,
 684			   input ? NULL : socket_buffer_output,
 685			   input ? NULL : socket_buffer_flush,
 686			   (int (*) PROTO((void *, int))) NULL,
 687			   socket_buffer_shutdown,
 688			   memory,
 689			   n);
 690}
 691
 692
 693
 694/* The buffer input function for a buffer built on a socket.  */
 695
 696static int
 697socket_buffer_input (closure, data, need, size, got)
 698     void *closure;
 699     char *data;
 700     int need;
 701     int size;
 702     int *got;
 703{
 704    struct socket_buffer *sb = (struct socket_buffer *) closure;
 705    int nbytes;
 706
 707    /* I believe that the recv function gives us exactly the semantics
 708       we want.  If there is a message, it returns immediately with
 709       whatever it could get.  If there is no message, it waits until
 710       one comes in.  In other words, it is not like read, which in
 711       blocking mode normally waits until all the requested data is
 712       available.  */
 713
 714    *got = 0;
 715
 716    do
 717    {
 718
 719	/* Note that for certain (broken?) networking stacks, like
 720	   VMS's UCX (not sure what version, problem reported with
 721	   recv() in 1997), and (according to windows-NT/config.h)
 722	   Windows NT 3.51, we must call recv or send with a
 723	   moderately sized buffer (say, less than 200K or something),
 724	   or else there may be network errors (somewhat hard to
 725	   produce, e.g. WAN not LAN or some such).  buf_read_data
 726	   makes sure that we only recv() BUFFER_DATA_SIZE bytes at
 727	   a time.  */
 728
 729	nbytes = recv (sb->socket, data, size, 0);
 730	if (nbytes < 0)
 731	    error (1, 0, "reading from server: %s", SOCK_STRERROR (SOCK_ERRNO));
 732	if (nbytes == 0)
 733	{
 734	    /* End of file (for example, the server has closed
 735	       the connection).  If we've already read something, we
 736	       just tell the caller about the data, not about the end of
 737	       file.  If we've read nothing, we return end of file.  */
 738	    if (*got == 0)
 739		return -1;
 740	    else
 741		return 0;
 742	}
 743	need -= nbytes;
 744	size -= nbytes;
 745	data += nbytes;
 746	*got += nbytes;
 747    }
 748    while (need > 0);
 749
 750    return 0;
 751}
 752
 753
 754
 755/* The buffer output function for a buffer built on a socket.  */
 756
 757static int
 758socket_buffer_output (closure, data, have, wrote)
 759     void *closure;
 760     const char *data;
 761     int have;
 762     int *wrote;
 763{
 764    struct socket_buffer *sb = (struct socket_buffer *) closure;
 765
 766    *wrote = have;
 767
 768    /* See comment in socket_buffer_input regarding buffer size we pass
 769       to send and recv.  */
 770
 771#ifdef SEND_NEVER_PARTIAL
 772    /* If send() never will produce a partial write, then just do it.  This
 773       is needed for systems where its return value is something other than
 774       the number of bytes written.  */
 775    if (send (sb->socket, data, have, 0) < 0)
 776	error (1, 0, "writing to server socket: %s", SOCK_STRERROR (SOCK_ERRNO));
 777#else
 778    while (have > 0)
 779    {
 780	int nbytes;
 781
 782	nbytes = send (sb->socket, data, have, 0);
 783	if (nbytes < 0)
 784	    error (1, 0, "writing to server socket: %s", SOCK_STRERROR (SOCK_ERRNO));
 785
 786	have -= nbytes;
 787	data += nbytes;
 788    }
 789#endif
 790
 791    return 0;
 792}
 793
 794
 795
 796/* The buffer flush function for a buffer built on a socket.  */
 797
 798/*ARGSUSED*/
 799static int
 800socket_buffer_flush (closure)
 801     void *closure;
 802{
 803    /* Nothing to do.  Sockets are always flushed.  */
 804    return 0;
 805}
 806
 807
 808
 809static int
 810socket_buffer_shutdown (buf)
 811    struct buffer *buf;
 812{
 813    struct socket_buffer *n = (struct socket_buffer *) buf->closure;
 814    char tmp;
 815
 816    /* no need to flush children of an endpoint buffer here */
 817
 818    if (buf->input)
 819    {
 820	int err = 0;
 821	if (! buf_empty_p (buf)
 822	    || (err = recv (n->socket, &tmp, 1, 0)) > 0)
 823	    error (0, 0, "dying gasps from %s unexpected", current_parsed_root->hostname);
 824	else if (err == -1)
 825	    error (0, 0, "reading from %s: %s", current_parsed_root->hostname, SOCK_STRERROR (SOCK_ERRNO));
 826
 827	/* shutdown() socket */
 828# ifdef SHUTDOWN_SERVER
 829	if (current_parsed_root->method != server_method)
 830# endif
 831	if (shutdown (n->socket, 0) < 0)
 832	{
 833	    error (1, 0, "shutting down server socket: %s", SOCK_STRERROR (SOCK_ERRNO));
 834	}
 835
 836	buf->input = NULL;
 837    }
 838    else if (buf->output)
 839    {
 840	/* shutdown() socket */
 841# ifdef SHUTDOWN_SERVER
 842	/* FIXME:  Should have a SHUTDOWN_SERVER_INPUT &
 843	 * SHUTDOWN_SERVER_OUTPUT
 844	 */
 845	if (current_parsed_root->method == server_method)
 846	    SHUTDOWN_SERVER (n->socket);
 847	else
 848# endif
 849	if (shutdown (n->socket, 1) < 0)
 850	{
 851	    error (1, 0, "shutting down server socket: %s", SOCK_STRERROR (SOCK_ERRNO));
 852	}
 853
 854	buf->output = NULL;
 855    }
 856
 857    return 0;
 858}
 859
 860#endif /* NO_SOCKET_TO_FD */
 861
 862/*
 863 * Read a line from the server.  Result does not include the terminating \n.
 864 *
 865 * Space for the result is malloc'd and should be freed by the caller.
 866 *
 867 * Returns number of bytes read.
 868 */
 869static int
 870read_line (resultp)
 871    char **resultp;
 872{
 873    int status;
 874    char *result;
 875    int len;
 876
 877    status = buf_flush (to_server, 1);
 878    if (status != 0)
 879	error (1, status, "writing to server");
 880
 881    status = buf_read_line (from_server, &result, &len);
 882    if (status != 0)
 883    {
 884	if (status == -1)
 885	    error (1, 0, "end of file from server (consult above messages if any)");
 886	else if (status == -2)
 887	    error (1, 0, "out of memory");
 888	else
 889	    error (1, status, "reading from server");
 890    }
 891
 892    if (resultp != NULL)
 893	*resultp = result;
 894    else
 895	free (result);
 896
 897    return len;
 898}
 899
 900#endif /* CLIENT_SUPPORT */
 901
 902
 903#if defined(CLIENT_SUPPORT) || defined(SERVER_SUPPORT)
 904
 905/*
 906 * Level of compression to use when running gzip on a single file.
 907 */
 908int file_gzip_level;
 909
 910#endif /* CLIENT_SUPPORT or SERVER_SUPPORT */
 911
 912#ifdef CLIENT_SUPPORT
 913
 914/*
 915 * The Repository for the top level of this command (not necessarily
 916 * the CVSROOT, just the current directory at the time we do it).
 917 */
 918static char *toplevel_repos = NULL;
 919
 920/* Working directory when we first started.  Note: we could speed things
 921   up on some systems by using savecwd.h here instead of just always
 922   storing a name.  */
 923char *toplevel_wd;
 924
 925static void
 926handle_ok (args, len)
 927    char *args;
 928    int len;
 929{
 930    return;
 931}
 932
 933static void
 934handle_error (args, len)
 935    char *args;
 936    int len;
 937{
 938    int something_printed;
 939    
 940    /*
 941     * First there is a symbolic error code followed by a space, which
 942     * we ignore.
 943     */
 944    char *p = strchr (args, ' ');
 945    if (p == NULL)
 946    {
 947	error (0, 0, "invalid data from cvs server");
 948	return;
 949    }
 950    ++p;
 951
 952    /* Next we print the text of the message from the server.  We
 953       probably should be prefixing it with "server error" or some
 954       such, because if it is something like "Out of memory", the
 955       current behavior doesn't say which machine is out of
 956       memory.  */
 957
 958    len -= p - args;
 959    something_printed = 0;
 960    for (; len > 0; --len)
 961    {
 962	something_printed = 1;
 963	putc (*p++, stderr);
 964    }
 965    if (something_printed)
 966	putc ('\n', stderr);
 967}
 968
 969static void
 970handle_valid_requests (args, len)
 971    char *args;
 972    int len;
 973{
 974    char *p = args;
 975    char *q;
 976    struct request *rq;
 977    do
 978    {
 979	q = strchr (p, ' ');
 980	if (q != NULL)
 981	    *q++ = '\0';
 982	for (rq = requests; rq->name != NULL; ++rq)
 983	{
 984	    if (strcmp (rq->name, p) == 0)
 985		break;
 986	}
 987	if (rq->name == NULL)
 988	    /*
 989	     * It is a request we have never heard of (and thus never
 990	     * will want to use).  So don't worry about it.
 991	     */
 992	    ;
 993	else
 994	{
 995	    if (rq->flags & RQ_ENABLEME)
 996	    {
 997		/*
 998		 * Server wants to know if we have this, to enable the
 999		 * feature.
1000		 */
1001		send_to_server (rq->name, 0);
1002                send_to_server ("\012", 0);
1003	    }
1004	    else
1005		rq->flags |= RQ_SUPPORTED;
1006	}
1007	p = q;
1008    } while (q != NULL);
1009    for (rq = requests; rq->name != NULL; ++rq)
1010    {
1011	if ((rq->flags & RQ_SUPPORTED)
1012	    || (rq->flags & RQ_ENABLEME))
1013	    continue;
1014	if (rq->flags & RQ_ESSENTIAL)
1015	    error (1, 0, "request `%s' not supported by server", rq->name);
1016    }
1017}
1018
1019
1020
1021/*
1022 * This is a proc for walklist().  It inverts the error return premise of
1023 * walklist.
1024 *
1025 * RETURNS
1026 *   True       If this path is prefixed by one of the paths in walklist and
1027 *              does not step above the prefix path.
1028 *   False      Otherwise.
1029 */
1030static
1031int path_list_prefixed (p, closure)
1032    Node *p;
1033    void *closure;
1034{
1035    const char *questionable = closure;
1036    const char *prefix = p->key;
1037    if (strncmp (prefix, questionable, strlen (prefix))) return 0;
1038    questionable += strlen (prefix);
1039    while (ISDIRSEP (*questionable)) questionable++;
1040    if (*questionable == '\0') return 1;
1041    return pathname_levels (questionable);
1042}
1043
1044
1045
1046/*
1047 * Need to validate the client pathname.  Disallowed paths include:
1048 *
1049 *   1. Absolute paths.
1050 *   2. Pathnames that do not reference a specifically requested update
1051 *      directory.
1052 *
1053 * In case 2, we actually only check that the directory is under the uppermost
1054 * directories mentioned on the command line.
1055 *
1056 * RETURNS
1057 *   True       If the path is valid.
1058 *   False      Otherwise.
1059 */
1060static
1061int is_valid_client_path (pathname)
1062    const char *pathname;
1063{
1064    /* 1. Absolute paths. */
1065    if (isabsolute (pathname)) return 0;
1066    /* 2. No up-references in path.  */
1067    if (pathname_levels (pathname) == 0) return 1;
1068    /* 2. No Max-dotdot paths registered.  */
1069    if (uppaths == NULL) return 0;
1070
1071    return walklist (uppaths, path_list_prefixed, (void *)pathname);
1072}
1073
1074
1075
1076/*
1077 * Do all the processing for PATHNAME, where pathname consists of the
1078 * repository and the filename.  The parameters we pass to FUNC are:
1079 * DATA is just the DATA parameter which was passed to
1080 * call_in_directory; ENT_LIST is a pointer to an entries list (which
1081 * we manage the storage for); SHORT_PATHNAME is the pathname of the
1082 * file relative to the (overall) directory in which the command is
1083 * taking place; and FILENAME is the filename portion only of
1084 * SHORT_PATHNAME.  When we call FUNC, the curent directory points to
1085 * the directory portion of SHORT_PATHNAME.  */
1086
1087static void
1088call_in_directory (pathname, func, data)
1089    char *pathname;
1090    void (*func) PROTO((char *data, List *ent_list, char *short_pathname,
1091			  char *filename));
1092    char *data;
1093{
1094    /* This variable holds the result of Entries_Open. */
1095    List *last_entries = NULL;
1096    char *dir_name;
1097    char *filename;
1098    /* This is what we get when we hook up the directory (working directory
1099       name) from PATHNAME with the filename from REPOSNAME.  For example:
1100       pathname: ccvs/src/
1101       reposname: /u/src/master/ccvs/foo/ChangeLog
1102       short_pathname: ccvs/src/ChangeLog
1103       */
1104    char *short_pathname;
1105    char *p;
1106
1107    /*
1108     * Do the whole descent in parallel for the repositories, so we
1109     * know what to put in CVS/Repository files.  I'm not sure the
1110     * full hair is necessary since the server does a similar
1111     * computation; I suspect that we only end up creating one
1112     * directory at a time anyway.
1113     *
1114     * Also note that we must *only* worry about this stuff when we
1115     * are creating directories; `cvs co foo/bar; cd foo/bar; cvs co
1116     * CVSROOT; cvs update' is legitimate, but in this case
1117     * foo/bar/CVSROOT/CVS/Repository is not a subdirectory of
1118     * foo/bar/CVS/Repository.
1119     */
1120    char *reposname;
1121    char *short_repos;
1122    char *reposdirname;
1123    char *rdirp;
1124    int reposdirname_absolute;
1125    int newdir = 0;
1126
1127    assert (pathname);
1128
1129    reposname = NULL;
1130    read_line (&reposname);
1131    assert (reposname != NULL);
1132
1133    reposdirname_absolute = 0;
1134    if (strncmp (reposname, toplevel_repos, strlen (toplevel_repos)) != 0)
1135    {
1136	reposdirname_absolute = 1;
1137	short_repos = reposname;
1138    }
1139    else
1140    {
1141	short_repos = reposname + strlen (toplevel_repos) + 1;
1142	if (short_repos[-1] != '/')
1143	{
1144	    reposdirname_absolute = 1;
1145	    short_repos = reposname;
1146	}
1147    }
1148
1149   /* Now that we have SHORT_REPOS, we can calculate the path to the file we
1150    * are being requested to operate on.
1151    */
1152    filename = strrchr (short_repos, '/');
1153    if (filename == NULL)
1154	filename = short_repos;
1155    else
1156	++filename;
1157
1158    short_pathname = xmalloc (strlen (pathname) + strlen (filename) + 5);
1159    strcpy (short_pathname, pathname);
1160    strcat (short_pathname, filename);
1161
1162    /* Now that we know the path to the file we were requested to operate on,
1163     * we can verify that it is valid.
1164     *
1165     * For security reasons, if SHORT_PATHNAME is absolute or attempts to
1166     * ascend outside of the current sanbbox, we abort.  The server should not
1167     * send us anything but relative paths which remain inside the sandbox
1168     * here.  Anything less means a trojan CVS server could create and edit
1169     * arbitrary files on the client.
1170     */
1171    if (!is_valid_client_path (short_pathname))
1172    {
1173	error (0, 0,
1174               "Server attempted to update a file via an invalid pathname:");
1175        error (1, 0, "`%s'.", short_pathname);
1176    }
1177
1178    reposdirname = xstrdup (short_repos);
1179    p = strrchr (reposdirname, '/');
1180    if (p == NULL)
1181    {
1182	reposdirname = xrealloc (reposdirname, 2);
1183	reposdirname[0] = '.'; reposdirname[1] = '\0';
1184    }
1185    else
1186	*p = '\0';
1187
1188    dir_name = xstrdup (pathname);
1189    p = strrchr (dir_name, '/');
1190    if (p == NULL)
1191    {
1192	dir_name = xrealloc (dir_name, 2);
1193	dir_name[0] = '.'; dir_name[1] = '\0';
1194    }
1195    else
1196	*p = '\0';
1197    if (client_prune_dirs)
1198	add_prune_candidate (dir_name);
1199
1200    if (toplevel_wd == NULL)
1201    {
1202	toplevel_wd = xgetwd ();
1203	if (toplevel_wd == NULL)
1204	    error (1, errno, "could not get working directory");
1205    }
1206
1207    if (CVS_CHDIR (toplevel_wd) < 0)
1208	error (1, errno, "could not chdir to %s", toplevel_wd);
1209
1210    if (CVS_CHDIR (dir_name) < 0)
1211    {
1212	char *dir;
1213	char *dirp;
1214	
1215	if (! existence_error (errno))
1216	    error (1, errno, "could not chdir to %s", dir_name);
1217	
1218	/* Directory does not exist, we need to create it.  */
1219	newdir = 1;
1220
1221	/* Provided we are willing to assume that directories get
1222	   created one at a time, we could simplify this a lot.
1223	   Do note that one aspect still would need to walk the
1224	   dir_name path: the checking for "fncmp (dir, CVSADM)".  */
1225
1226	dir = xmalloc (strlen (dir_name) + 1);
1227	dirp = dir_name;
1228	rdirp = reposdirname;
1229
1230	/* This algorithm makes nested directories one at a time
1231	   and create CVS administration files in them.  For
1232	   example, we're checking out foo/bar/baz from the
1233	   repository:
1234
1235	   1) create foo, point CVS/Repository to <root>/foo
1236	   2)     .. foo/bar                   .. <root>/foo/bar
1237	   3)     .. foo/bar/baz               .. <root>/foo/bar/baz
1238	   
1239	   As you can see, we're just stepping along DIR_NAME (with
1240	   DIRP) and REPOSDIRNAME (with RDIRP) respectively.
1241
1242	   We need to be careful when we are checking out a
1243	   module, however, since DIR_NAME and REPOSDIRNAME are not
1244	   going to be the same.  Since modules will not have any
1245	   slashes in their names, we should watch the output of
1246	   STRCHR to decide whether or not we should use STRCHR on
1247	   the RDIRP.  That is, if we're down to a module name,
1248	   don't keep picking apart the repository directory name.  */
1249
1250	do
1251	{
1252	    dirp = strchr (dirp, '/');
1253	    if (dirp)
1254	    {
1255		strncpy (dir, dir_name, dirp - dir_name);
1256		dir[dirp - dir_name] = '\0';
1257		/* Skip the slash.  */
1258		++dirp;
1259		if (rdirp == NULL)
1260		    /* This just means that the repository string has
1261		       fewer components than the dir_name string.  But
1262		       that is OK (e.g. see modules3-8 in testsuite).  */
1263		    ;
1264		else
1265		    rdirp = strchr (rdirp, '/');
1266	    }
1267	    else
1268	    {
1269		/* If there are no more slashes in the dir name,
1270		   we're down to the most nested directory -OR- to
1271		   the name of a module.  In the first case, we
1272		   should be down to a DIRP that has no slashes,
1273		   so it won't help/hurt to do another STRCHR call
1274		   on DIRP.  It will definitely hurt, however, if
1275		   we're down to a module name, since a module
1276		   name can point to a nested directory (that is,
1277		   DIRP will still have slashes in it.  Therefore,
1278		   we should set it to NULL so the routine below
1279		   copies the contents of REMOTEDIRNAME onto the
1280		   root repository directory (does this if rdirp
1281		   is set to NULL, because we used to do an extra
1282		   STRCHR call here). */
1283
1284		rdirp = NULL;
1285		strcpy (dir, dir_name);
1286	    }
1287
1288	    if (fncmp (dir, CVSADM) == 0)
1289	    {
1290		error (0, 0, "cannot create a directory named %s", dir);
1291		error (0, 0, "because CVS uses \"%s\" for its own uses",
1292		       CVSADM);
1293		error (1, 0, "rename the directory and try again");
1294	    }
1295
1296	    if (mkdir_if_needed (dir))
1297	    {
1298		/* It already existed, fine.  Just keep going.  */
1299	    }
1300	    else if (strcmp (cvs_cmd_name, "export") == 0)
1301		/* Don't create CVSADM directories if this is export.  */
1302		;
1303	    else
1304	    {
1305		/*
1306		 * Put repository in CVS/Repository.  For historical
1307		 * (pre-CVS/Root) reasons, this is an absolute pathname,
1308		 * but what really matters is the part of it which is
1309		 * relative to cvsroot.
1310		 */
1311		char *repo;
1312		char *r, *b;
1313
1314		repo = xmalloc (strlen (reposdirname)
1315				+ strlen (toplevel_repos)
1316				+ 80);
1317		if (reposdirname_absolute)
1318		    r = repo;
1319		else
1320		{
1321		    strcpy (repo, toplevel_repos);
1322		    strcat (repo, "/");
1323		    r = repo + strlen (repo);
1324		}
1325
1326		if (rdirp)
1327		{
1328		    /* See comment near start of function; the only
1329		       way that the server can put the right thing
1330		       in each CVS/Repository file is to create the
1331		       directories one at a time.  I think that the
1332		       CVS server has been doing this all along.  */
1333		    error (0, 0, "\
1334warning: server is not creating directories one at a time");
1335		    strncpy (r, reposdirname, rdirp - reposdirname);
1336		    r[rdirp - reposdirname] = '\0';
1337		}
1338		else
1339		    strcpy (r, reposdirname);
1340
1341		Create_Admin (dir, dir, repo,
1342			      (char *)NULL, (char *)NULL, 0, 0, 1);
1343		free (repo);
1344
1345		b = strrchr (dir, '/');
1346		if (b == NULL)
1347		    Subdir_Register ((List *) NULL, (char *) NULL, dir);
1348		else
1349		{
1350		    *b = '\0';
1351		    Subdir_Register ((List *) NULL, dir, b + 1);
1352		    *b = '/';
1353		}
1354	    }
1355
1356	    if (rdirp != NULL)
1357	    {
1358		/* Skip the slash.  */
1359		++rdirp;
1360	    }
1361
1362	} while (dirp != NULL);
1363	free (dir);
1364	/* Now it better work.  */
1365	if ( CVS_CHDIR (dir_name) < 0)
1366	    error (1, errno, "could not chdir to %s", dir_name);
1367    }
1368    else if (strcmp (cvs_cmd_name, "export") == 0)
1369	/* Don't create CVSADM directories if this is export.  */
1370	;
1371    else if (!isdir (CVSADM))
1372    {
1373	/*
1374	 * Put repository in CVS/Repository.  For historical
1375	 * (pre-CVS/Root) reasons, this is an absolute pathname,
1376	 * but what really matters is the part of it which is
1377	 * relative to cvsroot.
1378	 */
1379	char *repo;
1380
1381	if (reposdirname_absolute)
1382	    repo = reposdirname;
1383	else
1384	{
1385	    repo = xmalloc (strlen (reposdirname)
1386			    + strlen (toplevel_repos)
1387			    + 10);
1388	    strcpy (repo, toplevel_repos);
1389	    strcat (repo, "/");
1390	    strcat (repo, reposdirname);
1391	}
1392
1393	Create_Admin (".", ".", repo, (char *)NULL, (char *)NULL, 0, 1, 1);
1394	if (repo != reposdirname)
1395	    free (repo);
1396    }
1397
1398    if (strcmp (cvs_cmd_name, "export") != 0)
1399    {
1400	last_entries = Entries_Open (0, dir_name);
1401
1402	/* If this is a newly created directory, we will record
1403	   all subdirectory information, so call Subdirs_Known in
1404	   case there are no subdirectories.  If this is not a
1405	   newly created directory, it may be an old working
1406	   directory from before we recorded subdirectory
1407	   information in the Entries file.  We force a search for
1408	   all subdirectories now, to make sure our subdirectory
1409	   information is up to date.  If the Entries file does
1410	   record subdirectory information, then this call only
1411	   does list manipulation.  */
1412	if (newdir)
1413	    Subdirs_Known (last_entries);
1414	else
1415	{
1416	    List *dirlist;
1417
1418	    dirlist = Find_Directories ((char *) NULL, W_LOCAL,
1419					last_entries);
1420	    dellist (&dirlist);
1421	}
1422    }
1423    free (reposdirname);
1424    (*func) (data, last_entries, short_pathname, filename);
1425    if (last_entries != NULL)
1426	Entries_Close (last_entries);
1427    free (dir_name);
1428    free (short_pathname);
1429    free (reposname);
1430}
1431
1432static void
1433copy_a_file (data, ent_list, short_pathname, filename)
1434    char *data;
1435    List *ent_list;
1436    char *short_pathname;
1437    char *filename;
1438{
1439    char *newname;
1440#ifdef USE_VMS_FILENAMES
1441    char *p;
1442#endif
1443
1444    read_line (&newname);
1445
1446#ifdef USE_VMS_FILENAMES
1447    /* Mogrify the filename so VMS is happy with it. */
1448    for(p = newname; *p; p++)
1449       if(*p == '.' || *p == '#') *p = '_';
1450#endif
1451    /* cvsclient.texi has said for a long time that newname must be in the
1452       same directory.  Wouldn't want a malicious or buggy server overwriting
1453       ~/.profile, /etc/passwd, or anything like that.  */
1454    if (last_component (newname) != newname)
1455	error (1, 0, "protocol error: Copy-file tried to specify directory");
1456
1457    if (unlink_file (newname) && !existence_error (errno))
1458	error (0, errno, "unable to remove %s", newname);
1459    copy_file (filename, newname);
1460    free (newname);
1461}
1462
1463static void
1464handle_copy_file (args, len)
1465    char *args;
1466    int len;
1467{
1468    call_in_directory (args, copy_a_file, (char *)NULL);
1469}
1470
1471
1472
1473/* Attempt to read a file size from a string.  Accepts base 8 (0N), base 16
1474 * (0xN), or base 10.  Exits on error.
1475 *
1476 * RETURNS
1477 *   The file size, in a size_t.
1478 *
1479 * FATAL ERRORS
1480 *   1.  As strtoul().
1481 *   2.  If the number read exceeds SIZE_MAX.
1482 */
1483static size_t
1484strto_file_size (const char *s)
1485{
1486    unsigned long tmp;
1487    char *endptr;
1488
1489    /* Read it.  */
1490    errno = 0;
1491    tmp = strtoul (s, &endptr, 0);
1492
1493    /* Check for errors.  */
1494    if (errno || endptr == s)
1495	error (1, errno, "Server sent invalid file size `%s'", s);
1496    if (*endptr != '\0')
1497	error (1, 0,
1498	       "Server sent trailing characters in file size `%s'",
1499	       endptr);
1500    if (tmp > SIZE_MAX)
1501	error (1, 0, "Server sent file size exceeding client max.");
1502
1503    /* Return it.  */
1504    return (size_t)tmp;
1505}
1506
1507
1508
1509static void read_counted_file PROTO ((char *, char *));
1510
1511/* Read from the server the count for the length of a file, then read
1512   the contents of that file and write them to FILENAME.  FULLNAME is
1513   the name of the file for use in error messages.  FIXME-someday:
1514   extend this to deal with compressed files and make update_entries
1515   use it.  On error, gives a fatal error.  */
1516static void
1517read_counted_file (filename, fullname)
1518    char *filename;
1519    char *fullname;
1520{
1521    char *size_string;
1522    size_t size;
1523    char *buf;
1524
1525    /* Pointers in buf to the place to put data which will be read,
1526       and the data which needs to be written, respectively.  */
1527    char *pread;
1528    char *pwrite;
1529    /* Number of bytes left to read and number of bytes in buf waiting to
1530       be written, respectively.  */
1531    size_t nread;
1532    size_t nwrite;
1533
1534    FILE *fp;
1535
1536    read_line (&size_string);
1537    if (size_string[0] == 'z')
1538	error (1, 0, "\
1539protocol error: compressed files not supported for that operation");
1540    size = strto_file_size (size_string);
1541    free (size_string);
1542
1543    /* A more sophisticated implementation would use only a limited amount
1544       of buffer space (8K perhaps), and read that much at a time.  We allocate
1545       a buffer for the whole file only to make it easy to keep track what
1546       needs to be read and written.  */
1547    buf = xmalloc (size);
1548
1549    /* FIXME-someday: caller should pass in a flag saying whether it
1550       is binary or not.  I haven't carefully looked into whether
1551       CVS/Template files should use local text file conventions or
1552       not.  */
1553    fp = CVS_FOPEN (filename, "wb");
1554    if (fp == NULL)
1555	error (1, errno, "cannot write %s", fullname);
1556    nread = size;
1557    nwrite = 0;
1558    pread = buf;
1559    pwrite = buf;
1560    while (nread > 0 || nwrite > 0)
1561    {
1562	size_t n;
1563
1564	if (nread > 0)
1565	{
1566	    n = try_read_from_server (pread, nread);
1567	    nread -= n;
1568	    pread += n;
1569	    nwrite += n;
1570	}
1571
1572	if (nwrite > 0)
1573	{
1574	    n = fwrite (pwrite, 1, nwrite, fp);
1575	    if (ferror (fp))
1576		error (1, errno, "cannot write %s", fullname);
1577	    nwrite -= n;
1578	    pwrite += n;
1579	}
1580    }
1581    free (buf);
1582    if (fclose (fp) < 0)
1583	error (1, errno, "cannot close %s", fullname);
1584}
1585
1586/* OK, we want to swallow the "U foo.c" response and then output it only
1587   if we can update the file.  In the future we probably want some more
1588   systematic approach to parsing tagged text, but for now we keep it
1589   ad hoc.  "Why," I hear you cry, "do we not just look at the
1590   Update-existing and Created responses?"  That is an excellent question,
1591   and the answer is roughly conservatism/laziness--I haven't read through
1592   update.c enough to figure out the exact correspondence or lack thereof
1593   between those responses and a "U foo.c" line (note that Merged, from
1594   join_file, can be either "C foo" or "U foo" depending on the context).  */
1595/* Nonzero if we have seen +updated and not -updated.  */
1596static int updated_seen;
1597/* Filename from an "fname" tagged response within +updated/-updated.  */
1598static char *updated_fname;
1599
1600/* This struct is used to hold data when reading the +importmergecmd
1601   and -importmergecmd tags.  We put the variables in a struct only
1602   for namespace issues.  FIXME: As noted above, we need to develop a
1603   more systematic approach.  */
1604static struct
1605{
1606    /* Nonzero if we have seen +importmergecmd and not -importmergecmd.  */
1607    int seen;
1608    /* Number of conflicts, from a "conflicts" tagged response.  */
1609    int conflicts;
1610    /* First merge tag, from a "mergetag1" tagged response.  */
1611    char *mergetag1;
1612    /* Second merge tag, from a "mergetag2" tagged response.  */
1613    char *mergetag2;
1614    /* Repository, from a "repository" tagged response.  */
1615    char *repository;
1616} importmergecmd;
1617
1618/* Nonzero if we should arrange to return with a failure exit status.  */
1619static int failure_exit;
1620
1621
1622/*
1623 * The time stamp of the last file we registered.
1624 */
1625static time_t last_register_time;
1626
1627/*
1628 * The Checksum response gives the checksum for the file transferred
1629 * over by the next Updated, Merged or Patch response.  We just store
1630 * it here, and then check it in update_entries.
1631 */
1632
1633static int stored_checksum_valid;
1634static unsigned char stored_checksum[16];
1635
1636static void
1637handle_checksum (args, len)
1638    char *args;
1639    int len;
1640{
1641    char *s;
1642    char buf[3];
1643    int i;
1644
1645    if (stored_checksum_valid)
1646        error (1, 0, "Checksum received before last one was used");
1647
1648    s = args;
1649    buf[2] = '\0';
1650    for (i = 0; i < 16; i++)
1651    {
1652        char *bufend;
1653
1654	buf[0] = *s++;
1655	buf[1] = *s++;
1656	stored_checksum[i] = (char) strtol (buf, &bufend, 16);
1657	if (bufend != buf + 2)
1658	    break;
1659    }
1660
1661    if (i < 16 || *s != '\0')
1662        error (1, 0, "Invalid Checksum response: `%s'", args);
1663
1664    stored_checksum_valid = 1;
1665}
1666
1667/* Mode that we got in a "Mode" response (malloc'd), or NULL if none.  */
1668static char *stored_mode;
1669
1670static void handle_mode PROTO ((char *, int));
1671
1672static void
1673handle_mode (args, len)
1674    char *args;
1675    int len;
1676{
1677    if (stored_mode != NULL)
1678	error (1, 0, "protocol error: duplicate Mode");
1679    stored_mode = xstrdup (args);
1680}
1681
1682/* Nonzero if time was specified in Mod-time.  */
1683static int stored_modtime_valid;
1684/* Time specified in Mod-time.  */
1685static time_t stored_modtime;
1686
1687static void handle_mod_time PROTO ((char *, int));
1688
1689static void
1690handle_mod_time (args, len)
1691    char *args;
1692    int len;
1693{
1694    if (stored_modtime_valid)
1695	error (0, 0, "protocol error: duplicate Mod-time");
1696    stored_modtime = get_date (args, NULL);
1697    if (stored_modtime == (time_t) -1)
1698	error (0, 0, "protocol error: cannot parse date %s", args);
1699    else
1700	stored_modtime_valid = 1;
1701}
1702
1703/*
1704 * If we receive a patch, but the patch program fails to apply it, we
1705 * want to request the original file.  We keep a list of files whose
1706 * patches have failed.
1707 */
1708
1709char **failed_patches;
1710int failed_patches_count;
1711
1712struct update_entries_data
1713{
1714    enum {
1715      /*
1716       * We are just getting an Entries line; the local file is
1717       * correct.
1718       */
1719      UPDATE_ENTRIES_CHECKIN,
1720      /* We are getting the file contents as well.  */
1721      UPDATE_ENTRIES_UPDATE,
1722      /*
1723       * We are getting a patch against the existing local file, not
1724       * an entire new file.
1725       */
1726      UPDATE_ENTRIES_PATCH,
1727      /*
1728       * We are getting an RCS change text (diff -n output) against
1729       * the existing local file, not an entire new file.
1730       */
1731      UPDATE_ENTRIES_RCS_DIFF
1732    } contents;
1733
1734    enum {
1735	/* We are replacing an existing file.  */
1736	UPDATE_ENTRIES_EXISTING,
1737	/* We are creating a new file.  */
1738	UPDATE_ENTRIES_NEW,
1739	/* We don't know whether it is existing or new.  */
1740	UPDATE_ENTRIES_EXISTING_OR_NEW
1741    } existp;
1742
1743    /*
1744     * String to put in the timestamp field or NULL to use the timestamp
1745     * of the file.
1746     */
1747    char *timestamp;
1748};
1749
1750/* Update the Entries line for this file.  */
1751static void
1752update_entries (data_arg, ent_list, short_pathname, filename)
1753    char *data_arg;
1754    List *ent_list;
1755    char *short_pathname;
1756    char *filename;
1757{
1758    char *entries_line;
1759    struct update_entries_data *data = (struct update_entries_data *)data_arg;
1760
1761    char *cp;
1762    char *user;
1763    char *vn;
1764    /* Timestamp field.  Always empty according to the protocol.  */
1765    char *ts;
1766    char *options = NULL;
1767    char *tag = NULL;
1768    char *date = NULL;
1769    char *tag_or_date;
1770    char *scratch_entries = NULL;
1771    int bin;
1772
1773#ifdef UTIME_EXPECTS_WRITABLE
1774    int change_it_back = 0;
1775#endif
1776
1777    read_line (&entries_line);
1778
1779    /*
1780     * Parse the entries line.
1781     */
1782    scratch_entries = xstrdup (entries_line);
1783
1784    if (scratch_entries[0] != '/')
1785        error (1, 0, "bad entries line `%s' from server", entries_line);
1786    user = scratch_entries + 1;
1787    if ((cp = strchr (user, '/')) == NULL)
1788        error (1, 0, "bad entries line `%s' from server", entries_line);
1789    *cp++ = '\0';
1790    vn = cp;
1791    if ((cp = strchr (vn, '/')) == NULL)
1792        error (1, 0, "bad entries line `%s' from server", entries_line);
1793    *cp++ = '\0';
1794    
1795    ts = cp;
1796    if ((cp = strchr (ts, '/')) == NULL)
1797        error (1, 0, "bad entries line `%s' from server", entries_line);
1798    *cp++ = '\0';
1799    options = cp;
1800    if ((cp = strchr (options, '/')) == NULL)
1801        error (1, 0, "bad entries line `%s' from server", entries_line);
1802    *cp++ = '\0';
1803    tag_or_date = cp;
1804    
1805    /* If a slash ends the tag_or_date, ignore everything after it.  */
1806    cp = strchr (tag_or_date, '/');
1807    if (cp != NULL)
1808        *cp = '\0';
1809    if (*tag_or_date == 'T')
1810        tag = tag_or_date + 1;
1811    else if (*tag_or_date == 'D')
1812        date = tag_or_date + 1;
1813
1814    /* Done parsing the entries line. */
1815
1816    if (data->contents == UPDATE_ENTRIES_UPDATE
1817	|| data->contents == UPDATE_ENTRIES_PATCH
1818	|| data->contents == UPDATE_ENTRIES_RCS_DIFF)
1819    {
1820	char *size_string;
1821	char *mode_string;
1822	size_t size;
1823	char *buf;
1824	char *temp_filename;
1825	int use_gzip;
1826	int patch_failed;
1827	char *s;
1828
1829	read_line (&mode_string);
1830	
1831	read_line (&size_string);
1832	if (size_string[0] == 'z')
1833	{
1834	    use_gzip = 1;
1835	    s = size_string + 1;
1836	}
1837	else
1838	{
1839	    use_gzip = 0;
1840	    s = size_string;
1841	}
1842	size = strto_file_size (s);
1843	free (size_string);
1844
1845	/* Note that checking this separately from writing the file is
1846	   a race condition: if the existence or lack thereof of the
1847	   file changes between now and the actual calls which
1848	   operate on it, we lose.  However (a) there are so many
1849	   cases, I'm reluctant to try to fix them all, (b) in some
1850	   cases the system might not even have a system call which
1851	   does the right thing, and (c) it isn't clear this needs to
1852	   work.  */
1853	if (data->existp == UPDATE_ENTRIES_EXISTING
1854	    && !isfile (filename))
1855	    /* Emit a warning and update the file anyway.  */
1856	    error (0, 0, "warning: %s unexpectedly disappeared",
1857		   short_pathname);
1858
1859	if (data->existp == UPDATE_ENTRIES_NEW
1860	    && isfile (filename))
1861	{
1862	    /* Emit a warning and refuse to update the file; we don't want
1863	       to clobber a user's file.  */
1864	    size_t nread;
1865	    size_t toread;
1866
1867	    /* size should be unsigned, but until we get around to fixing
1868	       that, work around it.  */
1869	    size_t usize;
1870
1871	    char buf[8192];
1872
1873	    /* This error might be confusing; it isn't really clear to
1874	       the user what to do about it.  Keep in mind that it has
1875	       several causes: (1) something/someone creates the file
1876	       during the time that CVS is running, …

Large files files are truncated, but you can click here to view the full file