SQLite

Check-in [80461e0d72]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Improved debugging output.
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | sqlite3-rsync
Files: files | file ages | folders
SHA3-256: 80461e0d724963aaf2646005298f1194c5f1c4c9ae41c1085d4d137ed485bd9f
User & Date: drh 2024-09-12 12:04:53.132
Context
2024-09-12
14:43
Add sha1() functions to the CLI. Fix sha1b() such that it actually returns a BLOB. (check-in: fe65821a3b user: drh tags: sqlite3-rsync)
12:04
Improved debugging output. (check-in: 80461e0d72 user: drh tags: sqlite3-rsync)
2024-09-11
17:02
Progress on the sqlite3-rsync utility. This is an incremental check-in. It does compile, but it does not work. (check-in: fa06977b6d user: drh tags: sqlite3-rsync)
Changes
Unified Diff Ignore Whitespace Patch
Changes to Makefile.in.
702
703
704
705
706
707
708

709
710
711
712
713
714
715

RSYNC_SRC = \
  $(TOP)/tool/sqlite3-rsync.c \
  $(TOP)/ext/misc/sha1.c \
  sqlite3.c

RSYNC_OPT = \

  -DSQLITE_THREADSAFE=0 \
  -DSQLITE_OMIT_LOAD_EXTENSION \
  -DSQLITE_OMIT_DEPRECATED

sqlite3-rsync$(TEXE):	$(RSYNC_SRC)
	$(TCC) -o $@ $(RSYNC_SRC) $(TLIBS)








>







702
703
704
705
706
707
708
709
710
711
712
713
714
715
716

RSYNC_SRC = \
  $(TOP)/tool/sqlite3-rsync.c \
  $(TOP)/ext/misc/sha1.c \
  sqlite3.c

RSYNC_OPT = \
  -DSQLITE_ENABLE_DBPAGE_VTAB \
  -DSQLITE_THREADSAFE=0 \
  -DSQLITE_OMIT_LOAD_EXTENSION \
  -DSQLITE_OMIT_DEPRECATED

sqlite3-rsync$(TEXE):	$(RSYNC_SRC)
	$(TCC) -o $@ $(RSYNC_SRC) $(TLIBS)

Changes to Makefile.msc.
1869
1870
1871
1872
1873
1874
1875

1876
1877
1878
1879
1880
1881
1882

RSYNC_SRC = \
  $(TOP)\tool\sqlite3-rsync.c \
  $(TOP)\ext\misc\sha1.c \
  $(SQLITE3C)

RSYNC_OPT = \

  -DSQLITE_THREADSAFE=0 \
  -DSQLITE_OMIT_LOAD_EXTENSION \
  -DSQLITE_OMIT_DEPRECATED

sqlite3-rsync.exe:	$(RSYNC_SRC) $(LIBRESOBJS)
	$(LTLINK) $(RSYNC_OPT) $(NO_WARN) $(RSYNC_SRC) /link $(LDFLAGS) $(LTLINKOPTS) $(LIBRESOBJS)








>







1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883

RSYNC_SRC = \
  $(TOP)\tool\sqlite3-rsync.c \
  $(TOP)\ext\misc\sha1.c \
  $(SQLITE3C)

RSYNC_OPT = \
  -DSQLITE_ENABLE_DBPAGE_VTAB \
  -DSQLITE_THREADSAFE=0 \
  -DSQLITE_OMIT_LOAD_EXTENSION \
  -DSQLITE_OMIT_DEPRECATED

sqlite3-rsync.exe:	$(RSYNC_SRC) $(LIBRESOBJS)
	$(LTLINK) $(RSYNC_OPT) $(NO_WARN) $(RSYNC_SRC) /link $(LDFLAGS) $(LTLINKOPTS) $(LIBRESOBJS)

Changes to main.mk.
570
571
572
573
574
575
576

577
578
579
580
581
582
583

RSYNC_SRC = \
  $(TOP)/tool/sqlite3-rsync.c \
  $(TOP)/ext/misc/sha1.c \
  sqlite3.c

RSYNC_OPT = \

  -DSQLITE_THREADSAFE=0 \
  -DSQLITE_OMIT_LOAD_EXTENSION \
  -DSQLITE_OMIT_DEPRECATED

sqlite3-rsync$(EXE):	$(RSYNC_SRC)
	$(TCC) -o $@ $(RSYNC_OPT) $(RSYNC_SRC) $(TLIBS)








>







570
571
572
573
574
575
576
577
578
579
580
581
582
583
584

RSYNC_SRC = \
  $(TOP)/tool/sqlite3-rsync.c \
  $(TOP)/ext/misc/sha1.c \
  sqlite3.c

RSYNC_OPT = \
  -DSQLITE_ENABLE_DBPAGE_VTAB \
  -DSQLITE_THREADSAFE=0 \
  -DSQLITE_OMIT_LOAD_EXTENSION \
  -DSQLITE_OMIT_DEPRECATED

sqlite3-rsync$(EXE):	$(RSYNC_SRC)
	$(TCC) -o $@ $(RSYNC_OPT) $(RSYNC_SRC) $(TLIBS)

Changes to tool/sqlite3-rsync.c.
25
26
27
28
29
30
31


32
33
34
35
36
37
38
39
40
41
42
43
44
45






46
47
48
49
50
51
52
  "\n"
  "One of ORIGIN or REPLICA is a pathname to a database on the local\n"
  "machine and the other is of the form \"USER@HOST:PATH\" describing\n"
  "a database on a remote machine.  This utility makes REPLICA into a\n"
  "copy of ORIGIN\n"
;



/* Context for the run */
typedef struct SQLiteRsync SQLiteRsync;
struct SQLiteRsync {
  const char *zOrigin;     /* Name of the origin */
  const char *zReplica;    /* Name of the replica */
  FILE *pOut;              /* Transmit to the other side */
  FILE *pIn;               /* Receive from the other side */
  sqlite3_uint64 nOut;     /* Bytes transmitted */
  sqlite3_uint64 nIn;      /* Bytes received */
  sqlite3 *db;             /* Database connection */
  int nErr;                /* Number of errors encountered */
  int eVerbose;            /* Bigger for more output.  0 means none. */
  int bCommCheck;          /* True to debug the communication protocol */
  int isRemote;            /* On the remote side of a connection */






};


/* Magic numbers to identify particular messages sent over the wire.
*/
#define ORIGIN_BEGIN    0x41     /* Initial message */
#define ORIGIN_END      0x42     /* Time to quit */







>
>







<
<


|
|
|
>
>
>
>
>
>







25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  "\n"
  "One of ORIGIN or REPLICA is a pathname to a database on the local\n"
  "machine and the other is of the form \"USER@HOST:PATH\" describing\n"
  "a database on a remote machine.  This utility makes REPLICA into a\n"
  "copy of ORIGIN\n"
;

typedef unsigned char u8;

/* Context for the run */
typedef struct SQLiteRsync SQLiteRsync;
struct SQLiteRsync {
  const char *zOrigin;     /* Name of the origin */
  const char *zReplica;    /* Name of the replica */
  FILE *pOut;              /* Transmit to the other side */
  FILE *pIn;               /* Receive from the other side */


  sqlite3 *db;             /* Database connection */
  int nErr;                /* Number of errors encountered */
  u8 eVerbose;             /* Bigger for more output.  0 means none. */
  u8 bCommCheck;           /* True to debug the communication protocol */
  u8 isRemote;             /* On the remote side of a connection */
  sqlite3_uint64 nOut;     /* Bytes transmitted */
  sqlite3_uint64 nIn;      /* Bytes received */
  unsigned int nPage;      /* Total number of pages in the database */
  unsigned int szPage;     /* Database page size */
  unsigned int nHashSent;  /* Hashes sent (replica to origin) */
  unsigned int nPageSent;  /* Page contents sent (origin to replica) */
};


/* Magic numbers to identify particular messages sent over the wire.
*/
#define ORIGIN_BEGIN    0x41     /* Initial message */
#define ORIGIN_END      0x42     /* Time to quit */
500
501
502
503
504
505
506

507
508
509
510
511
512
513
/* Read a single big-endian 32-bit unsigned integer from the input
** stream.  Return 0 on success and 1 if there are any errors.
*/
static int readUint32(SQLiteRsync *p, unsigned int *pU){
  unsigned char buf[4];
  if( fread(buf, sizeof(buf), 1, p->pIn)==1 ){
    *pU = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];

    return 0;
  }else{
    p->nErr++;
    return 1;
  }
}








>







506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
/* Read a single big-endian 32-bit unsigned integer from the input
** stream.  Return 0 on success and 1 if there are any errors.
*/
static int readUint32(SQLiteRsync *p, unsigned int *pU){
  unsigned char buf[4];
  if( fread(buf, sizeof(buf), 1, p->pIn)==1 ){
    *pU = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
    p->nIn += 4;
    return 0;
  }else{
    p->nErr++;
    return 1;
  }
}

523
524
525
526
527
528
529

530
531



































532
533
534
535
536
537
538
  buf[1] = x & 0xff;
  x >>= 8;
  buf[0] = x;
  if( fwrite(buf, sizeof(buf), 1, p->pOut)!=1 ){
    p->nErr++;
    return 1;
  }

  return 0;
}




































/* Report an error.
**
** If this happens on the remote side, we send back a REMOTE_ERROR
** message.  On the local side, the error message goes to stderr.
*/
static void reportError(SQLiteRsync *p, const char *zFormat, ...){







>


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
  buf[1] = x & 0xff;
  x >>= 8;
  buf[0] = x;
  if( fwrite(buf, sizeof(buf), 1, p->pOut)!=1 ){
    p->nErr++;
    return 1;
  }
  p->nOut += 4;
  return 0;
}

/* Read a single byte from the wire.
*/
int readByte(SQLiteRsync *p){
  int c = fgetc(p->pIn);
  if( c!=EOF ) p->nIn++;
  return c;
}

/* Write a single byte into the wire.
*/
void writeByte(SQLiteRsync *p, int c){
  fputc(c, p->pOut);
  p->nOut++;
}

/* Read an array of bytes from the wire.
*/
void readBytes(SQLiteRsync *p, int nByte, void *pData){
  if( fread(pData, 1, nByte, p->pIn)==nByte ){
    p->nIn += nByte;
  }else{
    p->nErr++;
  }
}

/* Write an array of bytes onto the wire.
*/
void writeBytes(SQLiteRsync *p, int nByte, const void *pData){
  if( fwrite(pData, 1, nByte, p->pOut)==nByte ){
    p->nOut += nByte;
  }else{
    p->nErr++;
  }
}

/* Report an error.
**
** If this happens on the remote side, we send back a REMOTE_ERROR
** message.  On the local side, the error message goes to stderr.
*/
static void reportError(SQLiteRsync *p, const char *zFormat, ...){
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
  if( p->isRemote ){
    if( p->zReplica ){
      putc(REPLICA_ERROR, p->pOut);
    }else{
      putc(ORIGIN_ERROR, p->pOut);
    }
    writeUint32(p, nMsg);
    fwrite(zMsg, nMsg, 1, p->pOut);
    fflush(p->pOut);
  }else{
    fprintf(stderr, "%s\n", zMsg);
  }
  sqlite3_free(zMsg);
  p->nErr++;
}







|







589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
  if( p->isRemote ){
    if( p->zReplica ){
      putc(REPLICA_ERROR, p->pOut);
    }else{
      putc(ORIGIN_ERROR, p->pOut);
    }
    writeUint32(p, nMsg);
    writeBytes(p, nMsg, zMsg);
    fflush(p->pOut);
  }else{
    fprintf(stderr, "%s\n", zMsg);
  }
  sqlite3_free(zMsg);
  p->nErr++;
}
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
  }else{
    zMsg = sqlite3_malloc64( n+1 );
    if( zMsg==0 ){
      fprintf(stderr, "ERROR: out-of-memory\n");
      return;
    }
    memset(zMsg, 0, n+1);
    fread(zMsg, 1, n, p->pIn);
    fprintf(stderr,"ERROR: %s\n", zMsg);
    sqlite3_free(zMsg);
  }
  p->nErr++;
}

/* Construct a new prepared statement.  Report an error and return NULL







|







613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
  }else{
    zMsg = sqlite3_malloc64( n+1 );
    if( zMsg==0 ){
      fprintf(stderr, "ERROR: out-of-memory\n");
      return;
    }
    memset(zMsg, 0, n+1);
    readBytes(p, n, zMsg);
    fprintf(stderr,"ERROR: %s\n", zMsg);
    sqlite3_free(zMsg);
  }
  p->nErr++;
}

/* Construct a new prepared statement.  Report an error and return NULL
635
636
637
638
639
640
641

642
643
644
645
646
647
648
  va_list ap;

  va_start(ap, zSql);
  pStmt = prepareStmtVA(p, zSql, ap);
  va_end(ap);
  if( pStmt ){
    int rc = sqlite3_step(pStmt);

    if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){
      reportError(p, "SQL statement [%s] failed: %s", zSql,
                  sqlite3_errmsg(p->db));
    }
    sqlite3_finalize(pStmt);
  }
}







>







678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
  va_list ap;

  va_start(ap, zSql);
  pStmt = prepareStmtVA(p, zSql, ap);
  va_end(ap);
  if( pStmt ){
    int rc = sqlite3_step(pStmt);
    if( rc==SQLITE_ROW ) rc = sqlite3_step(pStmt);
    if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){
      reportError(p, "SQL statement [%s] failed: %s", zSql,
                  sqlite3_errmsg(p->db));
    }
    sqlite3_finalize(pStmt);
  }
}
728
729
730
731
732
733
734
735

736



737
738
739



740




741



742
743
744
745
746
747

748

749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783


784
785
786
787
788
789
790
791
792
793






794
795
796


797





798
799
800
801
802











803












804
805
806
807
808
809
810
811


812
813
814
815
816

817
818



819

820

821

822



823


824

825


826
827
828


829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858


859
860
861
862
863
864
865
    p->db = 0;
  }
}

/*
** Run the origin-side protocol.
**
**    1.  Send the origin-begin message

**    2.  Receive replica-begin message



**         -  Error check and abort if necessary
**    3.  Receive replica-hash messages
**    4.  BEGIN



**    5.  Send changed pages




**    6.  COMMIT



**    7.  Send origin-end message
*/
static void originSide(SQLiteRsync *p){
  int rc = 0;
  int c = 0;
  unsigned int nPage = 0;

  unsigned int szPg = 0;

  char buf[100];

  if( p->bCommCheck ){
    fprintf(p->pOut, "sqlite3-rsync origin-begin %s\n", p->zOrigin);
    fflush(p->pOut);
    echoOneLine(p);
    fprintf(p->pOut, "origin-end\n");
    fflush(p->pOut);
    echoOneLine(p);
    return;
  }

  /* Open the ORIGIN database. */
  rc = sqlite3_open_v2(p->zOrigin, &p->db, SQLITE_OPEN_READONLY, 0);
  if( rc ){
    reportError(p, "unable to open origin database file \"%s\": %s",
                sqlite3_errmsg(p->db));
    closeDb(p);
    return;
  }
  sqlite3_sha_init(p->db, 0, 0);
  runSql(p, "BEGIN");
  runSqlReturnText(p, buf, "PRAGMA journal_mode");
  if( sqlite3_stricmp(buf,"wal")!=0 ){
    reportError(p, "Origin database is not in WAL mode");
  }
  runSqlReturnUInt(p, &nPage, "PRAGMA page_count");
  runSqlReturnUInt(p, &szPg, "PRAGMA page_size");

  if( p->nErr==0 ){
    /* Send the ORIGIN_BEGIN message */
    fputc(ORIGIN_BEGIN, p->pOut);
    writeUint32(p, nPage);
    writeUint32(p, szPg);
    fflush(p->pOut);


  }

  /* Respond to message from the replica */
  while( p->nErr==0 && (c = fgetc(p->pIn))!=EOF ){
    switch( c ){
      case REPLICA_ERROR: {
        readAndDisplayError(p);
        break;
      }
      case REPLICA_BEGIN: {






        break;
      }
      case REPLICA_END: {


        break;





      }
      case REPLICA_HASH: {
        break;
      }
      case REPLICA_READY: {











        break;












      }
      default: {
        reportError(p, "Origin side received unknown message: 0x%02x", c);
        break;
      }
    }
  }



  closeDb(p);
}

/*
** Run the replica-side protocol.

**
**    1.  Receive the origin-begin message



**         -  Error check.  If unable to continue, send replica-error and quit

**    2.  BEGIN IMMEDIATE

**    3.  Send replica-begin message

**    4.  Send replica-hash messages



**    5.  Receive changed pages and apply them


**    6.  Receive origin-end message

**    7.  COMMIT


*/
static void replicaSide(SQLiteRsync *p){
  int c;


  char buf[100];
  if( p->bCommCheck ){
    echoOneLine(p);
    fprintf(p->pOut, "replica-begin %s\n", p->zReplica);
    fflush(p->pOut);
    echoOneLine(p);
    fprintf(p->pOut, "replica-end\n");
    fflush(p->pOut);
    return;
  }

  /* Respond to message from the origin.  The origin will initiate the
  ** the conversation with an ORIGIN_BEGIN message.
  */
  while( p->nErr==0 && (c = fgetc(p->pIn))!=EOF ){
    switch( c ){
      case ORIGIN_ERROR: {
        readAndDisplayError(p);
        break;
      }
      case ORIGIN_BEGIN: {
        unsigned int nOPage = 0, szOPage = 0;
        unsigned int nRPage = 0, szRPage = 0;
        int rc = 0;
        sqlite3_stmt *pStmt = 0;

        closeDb(p);
        readUint32(p, &nOPage);
        readUint32(p, &szOPage);
        if( p->nErr ) break;


        rc = sqlite3_open(p->zReplica, &p->db);
        if( rc ){
          reportError(p, "cannot open replica database \"%s\": %s",
                      p->zReplica, sqlite3_errmsg(p->db));
          closeDb(p);
          break;
        }







|
>
|
>
>
>
|
|
|
>
>
>
|
>
>
>
>
|
>
>
>
|





>

>
|












|

















|



>
>



|





|
>
>
>
>
>
>
|
|
|
>
>
|
>
>
>
>
>
|
|



>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>








>
>




|
>

|
>
>
>
|
>
|
>
|
>
|
>
>
>
|
>
>
|
>
|
>
>



>
>
|













|






|








>
>







772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
    p->db = 0;
  }
}

/*
** Run the origin-side protocol.
**
** Begin by sending the ORIGIN_BEGIN message with two arguments,
** nPage, and szPage.  Then enter a loop responding to message from
** the replica:
**
**    REPLICA_ERROR  size  text
**
**         Report an error from the replica and quit
**
**    REPLICA_END
**
**         The replica is terminating.  Stop processing now.
**
**    REPLICA_HASH  hash
**
**         The argument is the 20-byte SHA1 hash for the next page
**         page hashes appear in sequential order with no gaps.
**
**    REPLICA_READY
**
**         The replica has sent all the hashes that it intends to send.
**         This side (the origin) can now start responding with page
**         content for pages that do not have a matching hash.
*/
static void originSide(SQLiteRsync *p){
  int rc = 0;
  int c = 0;
  unsigned int nPage = 0;
  unsigned int iPage = 0;
  unsigned int szPg = 0;
  sqlite3_stmt *pCkHash = 0;
  char buf[200];

  if( p->bCommCheck ){
    fprintf(p->pOut, "sqlite3-rsync origin-begin %s\n", p->zOrigin);
    fflush(p->pOut);
    echoOneLine(p);
    fprintf(p->pOut, "origin-end\n");
    fflush(p->pOut);
    echoOneLine(p);
    return;
  }

  /* Open the ORIGIN database. */
  rc = sqlite3_open_v2(p->zOrigin, &p->db, SQLITE_OPEN_READWRITE, 0);
  if( rc ){
    reportError(p, "unable to open origin database file \"%s\": %s",
                sqlite3_errmsg(p->db));
    closeDb(p);
    return;
  }
  sqlite3_sha_init(p->db, 0, 0);
  runSql(p, "BEGIN");
  runSqlReturnText(p, buf, "PRAGMA journal_mode");
  if( sqlite3_stricmp(buf,"wal")!=0 ){
    reportError(p, "Origin database is not in WAL mode");
  }
  runSqlReturnUInt(p, &nPage, "PRAGMA page_count");
  runSqlReturnUInt(p, &szPg, "PRAGMA page_size");

  if( p->nErr==0 ){
    /* Send the ORIGIN_BEGIN message */
    writeByte(p, ORIGIN_BEGIN);
    writeUint32(p, nPage);
    writeUint32(p, szPg);
    fflush(p->pOut);
    p->nPage = nPage;
    p->szPage = szPg;
  }

  /* Respond to message from the replica */
  while( p->nErr==0 && (c = readByte(p))!=EOF && c!=REPLICA_END ){
    switch( c ){
      case REPLICA_ERROR: {
        readAndDisplayError(p);
        break;
      }
      case REPLICA_HASH: {
        if( pCkHash==0 ){
          runSql(p, "CREATE TEMP TABLE badHash(pgno INTEGER PRIMARY KEY)");
          pCkHash = prepareStmt(p,
            "INSERT INTO badHash SELECT pgno FROM sqlite_dbpage('main')"
            " WHERE pgno=?1 AND sha1b(data)!=?2"
          );
          if( pCkHash==0 ) break;
        }
        p->nHashSent++;
        iPage++;
        sqlite3_bind_int64(pCkHash, 1, iPage);
        readBytes(p, 20, buf);
        sqlite3_bind_blob(pCkHash, 2, buf, 20, SQLITE_STATIC);
        rc = sqlite3_step(pCkHash);
        if( rc!=SQLITE_DONE ){
          reportError(p, "SQL statement [%s] failed: %s",
                      sqlite3_sql(pCkHash), sqlite3_errmsg(p->db));
        }
        sqlite3_reset(pCkHash);
        break;
      }
      case REPLICA_READY: {
        sqlite3_stmt *pStmt;
        sqlite3_finalize(pCkHash);
        pCkHash = 0;
        pStmt = prepareStmt(p,
               "SELECT pgno, data"
               "  FROM badHash JOIN sqlite_dbpage('main') USING(pgno) "
               "UNION ALL "
               "SELECT pgno, data"
               "  FROM sqlite_dbpage('main')"
               " WHERE pgno>%d",
               iPage);
        if( pStmt==0 ) break;
        while( sqlite3_step(pStmt)==SQLITE_ROW && p->nErr==0 ){
          const void *pContent = sqlite3_column_blob(pStmt, 1);
          writeByte(p, ORIGIN_PAGE);
          writeUint32(p, (unsigned int)sqlite3_column_int64(pStmt, 0));
          writeBytes(p, szPg, pContent);
          p->nPageSent++;
        }
        sqlite3_finalize(pStmt);
        writeByte(p, ORIGIN_TXN);
        writeUint32(p, nPage);
        writeByte(p, ORIGIN_END);
        goto origin_end;
      }
      default: {
        reportError(p, "Origin side received unknown message: 0x%02x", c);
        break;
      }
    }
  }

origin_end:
  if( pCkHash ) sqlite3_finalize(pCkHash);
  closeDb(p);
}

/*
** Run the replica-side protocol.  The protocol is passive in the sense
** that it only response to message from the origin side.
**
**    ORIGIN_BEGIN  nPage szPage
**
**         The origin is reporting the number of pages and the size of each
**         pages.  This procedure checks compatibility, and if everything is
**         ok, it sends hash for all its extant pages.
**
**    ORIGIN_ERROR  size text
**
**         Report the received error and quit.
**
**    ORIGIN_PAGE  pgno content
**
**         Update the content of the given page.
**
**    ORIGIN_TXN   pgno
**
**         Close the update transaction.  The total database size is pgno
**         pages.
**
**    ORIGIN_END
**
**         Expect no more transmissions from the origin.
*/
static void replicaSide(SQLiteRsync *p){
  int c;
  sqlite3_stmt *pIns = 0;
  unsigned int szOPage = 0;
  char buf[65536];
  if( p->bCommCheck ){
    echoOneLine(p);
    fprintf(p->pOut, "replica-begin %s\n", p->zReplica);
    fflush(p->pOut);
    echoOneLine(p);
    fprintf(p->pOut, "replica-end\n");
    fflush(p->pOut);
    return;
  }

  /* Respond to message from the origin.  The origin will initiate the
  ** the conversation with an ORIGIN_BEGIN message.
  */
  while( p->nErr==0 && (c = readByte(p))!=EOF && c!=ORIGIN_END ){
    switch( c ){
      case ORIGIN_ERROR: {
        readAndDisplayError(p);
        break;
      }
      case ORIGIN_BEGIN: {
        unsigned int nOPage = 0;
        unsigned int nRPage = 0, szRPage = 0;
        int rc = 0;
        sqlite3_stmt *pStmt = 0;

        closeDb(p);
        readUint32(p, &nOPage);
        readUint32(p, &szOPage);
        if( p->nErr ) break;
        p->nPage = nOPage;
        p->szPage = szOPage;
        rc = sqlite3_open(p->zReplica, &p->db);
        if( rc ){
          reportError(p, "cannot open replica database \"%s\": %s",
                      p->zReplica, sqlite3_errmsg(p->db));
          closeDb(p);
          break;
        }
881
882
883
884
885
886
887
888
889







890


891
892
893



















894
895
896





















897
898
899
900
901
902
903
904
905

906
907














908
909
910
911
912
913
914
        runSqlReturnUInt(p, &szRPage, "PRAGMA page_size");
        if( szRPage!=szOPage ){
          reportError(p, "page size mismatch; origin is %d bytes and "
                         "replica is %d bytes", szOPage, szRPage);
          break;
        }
        pStmt = prepareStmt(p,
                   "SELECT pgno, sha1(data) FROM sqlite_dbpage"
                   " WHERE pgno<=min(%d,%d)", nRPage, nOPage);







        sqlite3_finalize(pStmt);


        break;
      }
      case ORIGIN_END: {



















        break;
      }
      case ORIGIN_PAGE: {





















        break;
      }
      default: {
        reportError(p, "Replica side received unknown message: 0x%02x", c);
        break;
      }
    }
  }


  closeDb(p);
}
















/*
** Parse command-line arguments.  Dispatch subroutines to do the
** requested work.
**
** Input formats:







|
|
>
>
>
>
>
>
>

>
>


|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>









>


>
>
>
>
>
>
>
>
>
>
>
>
>
>







1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
        runSqlReturnUInt(p, &szRPage, "PRAGMA page_size");
        if( szRPage!=szOPage ){
          reportError(p, "page size mismatch; origin is %d bytes and "
                         "replica is %d bytes", szOPage, szRPage);
          break;
        }
        pStmt = prepareStmt(p,
                   "SELECT sha1b(data) FROM sqlite_dbpage"
                   " WHERE pgno<=min(%d,%d)"
                   " ORDER BY pgno", nRPage, nOPage);
        while( sqlite3_step(pStmt)==SQLITE_ROW && p->nErr==0 ){
          const unsigned char *a = sqlite3_column_blob(pStmt, 0);
          writeByte(p, REPLICA_HASH);
          writeBytes(p, 20, a);
          p->nHashSent++;
        }
        sqlite3_finalize(pStmt);
        writeByte(p, REPLICA_READY);
        fflush(p->pOut);
        break;
      }
      case ORIGIN_TXN: {
        unsigned int nOPage = 0;
        readUint32(p, &nOPage);
        if( pIns==0 ){
          /* Nothing has changed */
          runSql(p, "COMMIT");
        }else if( p->nErr ){
          runSql(p, "ROLLBACK");
        }else{
          int rc;
          sqlite3_bind_int64(pIns, 1, nOPage);
          sqlite3_bind_null(pIns, 2);
          rc = sqlite3_step(pIns);
          if( rc!=SQLITE_DONE ){
            reportError(p, "SQL statement [%s] failed: %s",
                   sqlite3_sql(pIns), sqlite3_errmsg(p->db));
          }
          sqlite3_reset(pIns);
          runSql(p, "COMMIT");
        }
        break;
      }
      case ORIGIN_PAGE: {
        unsigned int pgno = 0;
        int rc;
        readUint32(p, &pgno);
        if( p->nErr ) break;
        if( pIns==0 ){
          pIns = prepareStmt(p,
            "INSERT INTO sqlite_dbpage(pgno,data,schema) VALUES(?1,?2,'main')"
          );
          if( pIns==0 ) break;
        }
        readBytes(p, szOPage, buf);
        if( p->nErr ) break;
        p->nPageSent++;
        sqlite3_bind_int64(pIns, 1, pgno);
        sqlite3_bind_blob(pIns, 2, buf, szOPage, SQLITE_STATIC);
        rc = sqlite3_step(pIns);
        if( rc!=SQLITE_DONE ){
          reportError(p, "SQL statement [%s] failed: %s",
                 sqlite3_sql(pIns), sqlite3_errmsg(p->db));
        }
        sqlite3_reset(pIns);
        break;
      }
      default: {
        reportError(p, "Replica side received unknown message: 0x%02x", c);
        break;
      }
    }
  }

  if( pIns ) sqlite3_finalize(pIns);
  closeDb(p);
}

/*
** The argument might be -vvv...vv with any number of "v"s.  Return
** the number of "v"s.  Return 0 if the argument is not a -vvv...v.
*/
static int numVs(const char *z){
  int n = 0;
  if( z[0]!='-' ) return 0;
  z++;
  if( z[0]=='-' ) z++;
  while( z[0]=='v' ){ n++; z++; }
  if( z[0]==0 ) return n;
  return 0;
}


/*
** Parse command-line arguments.  Dispatch subroutines to do the
** requested work.
**
** Input formats:
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
      isOrigin = 1;
      continue;
    }
    if( strcmp(z,"--replica")==0 ){
      isReplica = 1;
      continue;
    }
    if( strcmp(z, "-v")==0 ){
      ctx.eVerbose++;
      continue;
    }
    if( strcmp(z, "--ssh")==0 ){
      zSsh = argv[++i];
      continue;
    }
    if( strcmp(z, "--exe")==0 ){







|
|







1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
      isOrigin = 1;
      continue;
    }
    if( strcmp(z,"--replica")==0 ){
      isReplica = 1;
      continue;
    }
    if( numVs(z) ){
      ctx.eVerbose += numVs(z);
      continue;
    }
    if( strcmp(z, "--ssh")==0 ){
      zSsh = argv[++i];
      continue;
    }
    if( strcmp(z, "--exe")==0 ){
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
    append_escaped_arg(pStr, zDiv, 1);
    zCmd = sqlite3_str_finish(pStr);
    if( ctx.eVerbose ) printf("%s\n", zCmd);
    if( popen2(zCmd, &ctx.pIn, &ctx.pOut, &childPid, 0) ){
      fprintf(stderr, "Could not start auxiliary process: %s\n", zCmd);
      return 1;
    }
    originSide(&ctx);
  }else if( (zDiv = strchr(ctx.zReplica,':'))!=0 ){
    /* Local ORIGIN and remote REPLICA */
    sqlite3_str *pStr = sqlite3_str_new(0);
    append_escaped_arg(pStr, zSsh, 1);
    sqlite3_str_appendf(pStr, " -e none");
    *(zDiv++) = 0;
    append_escaped_arg(pStr, ctx.zReplica, 0);







|







1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
    append_escaped_arg(pStr, zDiv, 1);
    zCmd = sqlite3_str_finish(pStr);
    if( ctx.eVerbose ) printf("%s\n", zCmd);
    if( popen2(zCmd, &ctx.pIn, &ctx.pOut, &childPid, 0) ){
      fprintf(stderr, "Could not start auxiliary process: %s\n", zCmd);
      return 1;
    }
    replicaSide(&ctx);
  }else if( (zDiv = strchr(ctx.zReplica,':'))!=0 ){
    /* Local ORIGIN and remote REPLICA */
    sqlite3_str *pStr = sqlite3_str_new(0);
    append_escaped_arg(pStr, zSsh, 1);
    sqlite3_str_appendf(pStr, " -e none");
    *(zDiv++) = 0;
    append_escaped_arg(pStr, ctx.zReplica, 0);
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106










1107
1108
1109
1110
1111
1112
1113
      fprintf(stderr, "Could not start auxiliary process: %s\n", zCmd);
      return 1;
    }
    originSide(&ctx);
  }else{
    /* Local ORIGIN and REPLICA */
    sqlite3_str *pStr = sqlite3_str_new(0);
    append_escaped_arg(pStr, zExe, 1);
    append_escaped_arg(pStr, "--replica", 0);
    if( ctx.bCommCheck ){
      append_escaped_arg(pStr, "--commcheck", 0);
    }
    append_escaped_arg(pStr, ctx.zReplica, 1);
    zCmd = sqlite3_str_finish(pStr);
    if( ctx.eVerbose ) printf("%s\n", zCmd);
    if( popen2(zCmd, &ctx.pIn, &ctx.pOut, &childPid, 0) ){
      fprintf(stderr, "Could not start auxiliary process: %s\n", zCmd);
      return 1;
    }
    originSide(&ctx);










  }
  sqlite3_free(zCmd);
  if( pIn!=0 && pOut!=0 ){
    pclose2(pIn, pOut, childPid);
  }
  return 0;
}







|












>
>
>
>
>
>
>
>
>
>







1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
      fprintf(stderr, "Could not start auxiliary process: %s\n", zCmd);
      return 1;
    }
    originSide(&ctx);
  }else{
    /* Local ORIGIN and REPLICA */
    sqlite3_str *pStr = sqlite3_str_new(0);
    append_escaped_arg(pStr, argv[0], 1);
    append_escaped_arg(pStr, "--replica", 0);
    if( ctx.bCommCheck ){
      append_escaped_arg(pStr, "--commcheck", 0);
    }
    append_escaped_arg(pStr, ctx.zReplica, 1);
    zCmd = sqlite3_str_finish(pStr);
    if( ctx.eVerbose ) printf("%s\n", zCmd);
    if( popen2(zCmd, &ctx.pIn, &ctx.pOut, &childPid, 0) ){
      fprintf(stderr, "Could not start auxiliary process: %s\n", zCmd);
      return 1;
    }
    originSide(&ctx);
  }
  if( ctx.eVerbose ){
    if( ctx.nErr ) printf("%d errors, ", ctx.nErr);
    printf("%lld bytes sent, %lld bytes received\n", ctx.nOut, ctx.nIn);
    if( ctx.eVerbose>=2 ){
      printf("Database is %u pages of %u bytes each.\n",
             ctx.nPage, ctx.szPage);
      printf("Sent %u hashes, %u page contents\n",
             ctx.nHashSent, ctx.nPageSent);
    }
  }
  sqlite3_free(zCmd);
  if( pIn!=0 && pOut!=0 ){
    pclose2(pIn, pOut, childPid);
  }
  return 0;
}