Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/tool/sqlite3_rsync.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / tool / sqlite3_rsync.c` 2505 lines ยท 78638 bytes Raw Blame History 1 /* 2 ** 2024-09-10 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** 13 ** This is a utility program that makes a copy of a live SQLite database 14 ** using a bandwidth-efficient protocol, similar to "rsync". 15 */ 16 #include 17 #include 18 #include 19 #include 20 #include 21 #include "sqlite3.h" 22 23 static const char zUsage[] = 24 "sqlite3_rsync ORIGIN REPLICA ?OPTIONS?\n" 25 "\n" 26 "One of ORIGIN or REPLICA is a pathname to a database on the local\n" 27 "machine and the other is of the form \"USER@HOST:PATH\" describing\n" 28 "a database on a remote machine. This utility makes REPLICA into a\n" 29 "copy of ORIGIN\n" 30 "\n" 31 "OPTIONS:\n" 32 "\n" 33 " --exe PATH Name of the sqlite3_rsync program on the remote side\n" 34 " --help Show this help screen\n" 35 " -p|--port PORT Run SSH over TCP port PORT instead of the default 22\n" 36 " --protocol N Use sync protocol version N.\n" 37 " --ssh PATH Name of the SSH program used to reach the remote side\n" 38 " -v Verbose. Multiple v's for increasing output\n" 39 " --version Show detailed version information\n" 40 " --wal-only Do not sync unless both databases are in WAL mode\n" 41 ; 42 43 typedef unsigned char u8; 44 typedef sqlite3_uint64 u64; 45 46 /* Context for the run */ 47 typedef struct SQLiteRsync SQLiteRsync; 48 struct SQLiteRsync { 49 const char *zOrigin; /* Name of the origin */ 50 const char *zReplica; /* Name of the replica */ 51 const char *zErrFile; /* Append error messages to this file */ 52 const char *zDebugFile; /* Append debugging messages to this file */ 53 FILE *pOut; /* Transmit to the other side */ 54 FILE *pIn; /* Receive from the other side */ 55 FILE *pLog; /* Duplicate output here if not NULL */ 56 FILE *pDebug; /* Write debug info here if not NULL */ 57 sqlite3 *db; /* Database connection */ 58 int nErr; /* Number of errors encountered */ 59 int nWrErr; /* Number of failed attempts to write on the pipe */ 60 u8 eVerbose; /* Bigger for more output. 0 means none. */ 61 u8 bCommCheck; /* True to debug the communication protocol */ 62 u8 isRemote; /* On the remote side of a connection */ 63 u8 isReplica; /* True if running on the replica side */ 64 u8 iProtocol; /* Protocol version number */ 65 u8 wrongEncoding; /* ATTACH failed due to wrong encoding */ 66 u8 bWalOnly; /* Require WAL mode */ 67 sqlite3_uint64 nOut; /* Bytes transmitted */ 68 sqlite3_uint64 nIn; /* Bytes received */ 69 unsigned int nPage; /* Total number of pages in the database */ 70 unsigned int szPage; /* Database page size */ 71 u64 nHashSent; /* Hashes sent (replica to origin) */ 72 unsigned int nRound; /* Number of hash batches (replica to origin) */ 73 unsigned int nPageSent; /* Page contents sent (origin to replica) */ 74 }; 75 76 /* The version number of the protocol. Sent in the *_BEGIN message 77 ** to verify that both sides speak the same dialect. 78 */ 79 #define PROTOCOL_VERSION 2 80 81 82 /* Magic numbers to identify particular messages sent over the wire. 83 */ 84 /**** Baseline: protocol version 1 ****/ 85 #define ORIGIN_BEGIN 0x41 /* Initial message */ 86 #define ORIGIN_END 0x42 /* Time to quit */ 87 #define ORIGIN_ERROR 0x43 /* Error message from the remote */ 88 #define ORIGIN_PAGE 0x44 /* New page data */ 89 #define ORIGIN_TXN 0x45 /* Transaction commit */ 90 #define ORIGIN_MSG 0x46 /* Informational message */ 91 /**** Added in protocol version 2 ****/ 92 #define ORIGIN_DETAIL 0x47 /* Request finer-grain hash info */ 93 #define ORIGIN_READY 0x48 /* Ready for next round of hash exchanges */ 94 95 /**** Baseline: protocol version 1 ****/ 96 #define REPLICA_BEGIN 0x61 /* Welcome message */ 97 #define REPLICA_ERROR 0x62 /* Error. Report and quit. */ 98 #define REPLICA_END 0x63 /* Replica wants to stop */ 99 #define REPLICA_HASH 0x64 /* One or more pages hashes to report */ 100 #define REPLICA_READY 0x65 /* Read to receive page content */ 101 #define REPLICA_MSG 0x66 /* Informational message */ 102 /**** Added in protocol version 2 ****/ 103 #define REPLICA_CONFIG 0x67 /* Hash exchange configuration */ 104 105 /**************************************************************************** 106 ** Beginning of the popen2() implementation copied from Fossil ************* 107 ****************************************************************************/ 108 #ifdef _WIN32 109 #include 110 #include 111 #include 112 /* 113 ** Print a fatal error and quit. 114 */ 115 static void win32_fatal_error(const char *zMsg){ 116 fprintf(stderr, "%s", zMsg); 117 exit(1); 118 } 119 extern int _open_osfhandle(intptr_t,int); 120 #else 121 #include 122 #include 123 #include 124 #endif 125 126 /* 127 ** The following macros are used to cast pointers to integers and 128 ** integers to pointers. The way you do this varies from one compiler 129 ** to the next, so we have developed the following set of #if statements 130 ** to generate appropriate macros for a wide range of compilers. 131 ** 132 ** The correct "ANSI" way to do this is to use the intptr_t type. 133 ** Unfortunately, that typedef is not available on all compilers, or 134 ** if it is available, it requires an #include of specific headers 135 ** that vary from one machine to the next. 136 ** 137 ** This code is copied out of SQLite. 138 */ 139 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */ 140 # define INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X)) 141 # define PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X)) 142 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */ 143 # define INT_TO_PTR(X) ((void*)&((char*)0)[X]) 144 # define PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) 145 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */ 146 # define INT_TO_PTR(X) ((void*)(intptr_t)(X)) 147 # define PTR_TO_INT(X) ((int)(intptr_t)(X)) 148 #else /* Generates a warning - but it always works */ 149 # define INT_TO_PTR(X) ((void*)(X)) 150 # define PTR_TO_INT(X) ((int)(X)) 151 #endif 152 153 /* Register SQL functions provided by ext/misc/sha1.c */ 154 extern int sqlite3_sha_init( 155 sqlite3 *db, 156 char **pzErrMsg, 157 const sqlite3_api_routines *pApi 158 ); 159 160 #ifdef _WIN32 161 /* 162 ** On windows, create a child process and specify the stdin, stdout, 163 ** and stderr channels for that process to use. 164 ** 165 ** Return the number of errors. 166 */ 167 static int win32_create_child_process( 168 wchar_t *zCmd, /* The command that the child process will run */ 169 HANDLE hIn, /* Standard input */ 170 HANDLE hOut, /* Standard output */ 171 HANDLE hErr, /* Standard error */ 172 DWORD *pChildPid /* OUT: Child process handle */ 173 ){ 174 STARTUPINFOW si; 175 PROCESS_INFORMATION pi; 176 BOOL rc; 177 178 memset(&si, 0, sizeof(si)); 179 si.cb = sizeof(si); 180 si.dwFlags = STARTF_USESTDHANDLES; 181 SetHandleInformation(hIn, HANDLE_FLAG_INHERIT, TRUE); 182 si.hStdInput = hIn; 183 SetHandleInformation(hOut, HANDLE_FLAG_INHERIT, TRUE); 184 si.hStdOutput = hOut; 185 SetHandleInformation(hErr, HANDLE_FLAG_INHERIT, TRUE); 186 si.hStdError = hErr; 187 rc = CreateProcessW( 188 NULL, /* Application Name */ 189 zCmd, /* Command-line */ 190 NULL, /* Process attributes */ 191 NULL, /* Thread attributes */ 192 TRUE, /* Inherit Handles */ 193 0, /* Create flags */ 194 NULL, /* Environment */ 195 NULL, /* Current directory */ 196 &si, /* Startup Info */ 197 &pi /* Process Info */ 198 ); 199 if( rc ){ 200 CloseHandle( pi.hProcess ); 201 CloseHandle( pi.hThread ); 202 *pChildPid = pi.dwProcessId; 203 }else{ 204 win32_fatal_error("cannot create child process"); 205 } 206 return rc!=0; 207 } 208 void *win32_utf8_to_unicode(const char *zUtf8){ 209 int nByte = MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, 0, 0); 210 wchar_t *zUnicode = malloc( nByte*2 ); 211 MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, zUnicode, nByte); 212 return zUnicode; 213 } 214 #endif 215 216 /* 217 ** Create a child process running shell command "zCmd". *ppOut is 218 ** a FILE that becomes the standard input of the child process. 219 ** (The caller writes to *ppOut in order to send text to the child.) 220 ** *ppIn is stdout from the child process. (The caller 221 ** reads from *ppIn in order to receive input from the child.) 222 ** Note that *ppIn is an unbuffered file descriptor, not a FILE. 223 ** The process ID of the child is written into *pChildPid. 224 ** 225 ** Return the number of errors. 226 */ 227 static int popen2( 228 const char *zCmd, /* Command to run in the child process */ 229 FILE **ppIn, /* Read from child using this file descriptor */ 230 FILE **ppOut, /* Write to child using this file descriptor */ 231 int *pChildPid, /* PID of the child process */ 232 int bDirect /* 0: run zCmd as a shell cmd. 1: run directly */ 233 ){ 234 #ifdef _WIN32 235 HANDLE hStdinRd, hStdinWr, hStdoutRd, hStdoutWr, hStderr; 236 SECURITY_ATTRIBUTES saAttr; 237 DWORD childPid = 0; 238 int fd; 239 240 saAttr.nLength = sizeof(saAttr); 241 saAttr.bInheritHandle = TRUE; 242 saAttr.lpSecurityDescriptor = NULL; 243 hStderr = GetStdHandle(STD_ERROR_HANDLE); 244 if( !CreatePipe(&hStdoutRd, &hStdoutWr, &saAttr, 4096) ){ 245 win32_fatal_error("cannot create pipe for stdout"); 246 } 247 SetHandleInformation( hStdoutRd, HANDLE_FLAG_INHERIT, FALSE); 248 249 if( !CreatePipe(&hStdinRd, &hStdinWr, &saAttr, 4096) ){ 250 win32_fatal_error("cannot create pipe for stdin"); 251 } 252 SetHandleInformation( hStdinWr, HANDLE_FLAG_INHERIT, FALSE); 253 254 win32_create_child_process(win32_utf8_to_unicode(zCmd), 255 hStdinRd, hStdoutWr, hStderr,&childPid); 256 *pChildPid = childPid; 257 fd = _open_osfhandle(PTR_TO_INT(hStdoutRd), 0); 258 *ppIn = fdopen(fd, "rb"); 259 fd = _open_osfhandle(PTR_TO_INT(hStdinWr), 0); 260 *ppOut = _fdopen(fd, "wb"); 261 CloseHandle(hStdinRd); 262 CloseHandle(hStdoutWr); 263 return 0; 264 #else 265 int pin[2], pout[2]; 266 *ppIn = 0; 267 *ppOut = 0; 268 *pChildPid = 0; 269 270 if( pipe(pin)<0 ){ 271 return 1; 272 } 273 if( pipe(pout)<0 ){ 274 close(pin[0]); 275 close(pin[1]); 276 return 1; 277 } 278 *pChildPid = fork(); 279 if( *pChildPid<0 ){ 280 close(pin[0]); 281 close(pin[1]); 282 close(pout[0]); 283 close(pout[1]); 284 *pChildPid = 0; 285 return 1; 286 } 287 signal(SIGPIPE,SIG_IGN); 288 if( *pChildPid==0 ){ 289 int fd; 290 /* This is the child process */ 291 close(0); 292 fd = dup(pout[0]); 293 if( fd!=0 ) { 294 fprintf(stderr,"popen2() failed to open file descriptor 0"); 295 exit(1); 296 } 297 close(pout[0]); 298 close(pout[1]); 299 close(1); 300 fd = dup(pin[1]); 301 if( fd!=1 ){ 302 fprintf(stderr,"popen() failed to open file descriptor 1"); 303 exit(1); 304 } 305 close(pin[0]); 306 close(pin[1]); 307 if( bDirect ){ 308 execl(zCmd, zCmd, (char*)0); 309 }else{ 310 execl("/bin/sh", "/bin/sh", "-c", zCmd, (char*)0); 311 } 312 return 1; 313 }else{ 314 /* This is the parent process */ 315 close(pin[1]); 316 *ppIn = fdopen(pin[0], "r"); 317 close(pout[0]); 318 *ppOut = fdopen(pout[1], "w"); 319 return 0; 320 } 321 #endif 322 } 323 324 /* 325 ** Close the connection to a child process previously created using 326 ** popen2(). 327 */ 328 static int pclose2(FILE *pIn, FILE *pOut, int childPid){ 329 #ifdef _WIN32 330 /* Not implemented, yet */ 331 fclose(pIn); 332 fclose(pOut); 333 return 0; 334 #else 335 int wp, rc = 0; 336 fclose(pIn); 337 fclose(pOut); 338 do{ 339 wp = waitpid(0, &rc, WNOHANG); 340 if( wp>0 ){ 341 if( WIFEXITED(rc) ){ 342 rc = WEXITSTATUS(rc); 343 }else if( WIFSIGNALED(rc) ){ 344 rc = WTERMSIG(rc); 345 }else{ 346 rc = 0/*???*/; 347 } 348 } 349 } while( wp>0 ); 350 return rc; 351 #endif 352 } 353 /***************************************************************************** 354 ** End of the popen2() implementation copied from Fossil ********************* 355 *****************************************************************************/ 356 357 /***************************************************************************** 358 ** Beginning of the append_escaped_arg() routine, adapted from the Fossil ** 359 ** subroutine nameed blob_append_escaped_arg() ** 360 *****************************************************************************/ 361 /* 362 ** ASCII (for reference): 363 ** x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf 364 ** 0x ^` ^a ^b ^c ^d ^e ^f ^g \b \t \n () \f \r ^n ^o 365 ** 1x ^p ^q ^r ^s ^t ^u ^v ^w ^x ^y ^z ^{ ^| ^} ^~ ^ 366 ** 2x () ! " # $ % & ' ( ) * + , - . / 367 ** 3x 0 1 2 3 4 5 6 7 8 9 : ; < = > ? 368 ** 4x @ A B C D E F G H I J K L M N O 369 ** 5x P Q R S T U V W X Y Z [ \ ] ^ _ 370 ** 6x ` a b c d e f g h i j k l m n o 371 ** 7x p q r s t u v w x y z { | } ~ ^_ 372 */ 373 374 /* 375 ** Meanings for bytes in a filename: 376 ** 377 ** 0 Ordinary character. No encoding required 378 ** 1 Needs to be escaped 379 ** 2 Illegal character. Do not allow in a filename 380 ** 3 First byte of a 2-byte UTF-8 381 ** 4 First byte of a 3-byte UTF-8 382 ** 5 First byte of a 4-byte UTF-8 383 */ 384 static const char aSafeChar[256] = { 385 /* 386 ** Prohibit: all control characters, including tab, \r and \n 387 ** Escape: (space) ! " # $ % & ' ( ) * ; < > ? [ \ ] ^ ` { | } 388 */ 389 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */ 390 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x */ 391 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 1x */ 392 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 2x */ 393 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, /* 3x */ 394 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */ 395 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, /* 5x */ 396 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 6x */ 397 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, /* 7x */ 398 /* all bytes 0x80 through 0xbf are unescaped, being secondary 399 ** bytes to UTF8 characters. Bytes 0xc0 through 0xff are the 400 ** first byte of a UTF8 character and do get escaped */ 401 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 8x */ 402 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 9x */ 403 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* ax */ 404 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* bx */ 405 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* cx */ 406 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* dx */ 407 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* ex */ 408 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 /* fx */ 409 }; 410 411 /* 412 ** Return true if the input contains special characters that need 413 ** to be escaped. 414 */ 415 int need_escape(const char *zIn){ 416 size_t i; 417 unsigned char c; 418 419 /* Look for characters that need to be escaped */ 420 for(i=0; (c = (unsigned char)zIn[i])!=0; i++){ 421 if( aSafeChar[c] ) return 1; 422 } 423 return 0; 424 } 425 426 /* 427 ** Increment this global variable whenever the isFilename==2 hex encoding 428 ** is used. 429 */ 430 static int nHexEncode = 0; 431 432 /* 433 ** pStr is a shell command under construction. This routine safely 434 ** appends filename argument zIn. 435 ** 436 ** The argument is escaped if it contains white space or other characters 437 ** that need to be escaped for the shell. If zIn contains characters 438 ** that cannot be safely escaped, then throw a fatal error. 439 ** 440 ** If the isFilename argument is 1 or 2, then the argument is expected 441 ** to be a filename. isFilename==1 means to use shell-style escaping 442 ** as the argument is going directly to the shell. isFilename==2 means 443 ** to escape as hexadecimal (using A-P as the hex digits) instead of 444 ** shell escaping. isFilename==2 argument are interpreted by another 445 ** instance of sqlite3_rsync which knows how to decode them. 446 ** 447 ** For isFilename==1, because shell commands commonly have command-line 448 ** options that begin with "-" and since we do not want an attacker 449 ** to be able to invoke these switches using filenames that begin 450 ** with "-", if zIn begins with "-", prepend an additional "./". 451 ** 452 ** For isFilename==2, if the filename could be mistaken for a hexadecimal 453 ** string (if it is an even number of characters and all characters are 454 ** between A and P) then "./" is prepended so that the receiver 455 ** will know that it is not an encoded filename. 456 */ 457 void append_escaped_arg(sqlite3_str *pStr, const char *zIn, int isFilename){ 458 int n = sqlite3_str_length(pStr); 459 char *z = sqlite3_str_value(pStr); 460 size_t nIn = strlen(zIn); 461 462 /* Separate from the previous argument by a space */ 463 if( n>0 && !isspace(z[n-1]) ){ 464 sqlite3_str_appendchar(pStr, 1, ' '); 465 } 466 467 /* Check for characters that need quoting */ 468 if( !need_escape(zIn) ){ 469 if( (isFilename>=1 && zIn[0]=='-') 470 || (isFilename==2 && (nIn&1)==0 && strspn(zIn,"ABCDEFGHIJKLMNOP")==nIn) 471 ){ 472 sqlite3_str_appendchar(pStr, 1, '.'); 473 sqlite3_str_appendchar(pStr, 1, '/'); 474 } 475 sqlite3_str_appendall(pStr, zIn); 476 }else if( isFilename==2 ){ 477 /* Encode as hexadecimal using A-P as the hex digits. */ 478 size_t j; 479 for(j=0; j>4)&0xf)+'A'); 481 sqlite3_str_appendchar(pStr, 1, ((zIn[j])&0xf)+'A'); 482 } 483 nHexEncode++; 484 }else{ 485 /* Use shell escapes */ 486 #if defined(_WIN32) 487 /* Quoting strategy for windows: 488 ** Put the entire name inside of "...". Any " characters within 489 ** the name get doubled. 490 */ 491 size_t i; 492 unsigned char c; 493 sqlite3_str_appendchar(pStr, 1, '"'); 494 if( isFilename && zIn[0]=='-' ){ 495 sqlite3_str_appendchar(pStr, 1, '.'); 496 sqlite3_str_appendchar(pStr, 1, '\\'); 497 }else if( zIn[0]=='/' ){ 498 sqlite3_str_appendchar(pStr, 1, '.'); 499 } 500 for(i=0; (c = (unsigned char)zIn[i])!=0; i++){ 501 sqlite3_str_appendchar(pStr, 1, (char)c); 502 if( c=='"' ) sqlite3_str_appendchar(pStr, 1, '"'); 503 if( c=='\\' ) sqlite3_str_appendchar(pStr, 1, '\\'); 504 if( c=='%' && isFilename ) sqlite3_str_append(pStr, "%cd:~,%", 7); 505 } 506 sqlite3_str_appendchar(pStr, 1, '"'); 507 #else 508 /* Quoting strategy for unix: 509 ** If the name does not contain ', then surround the whole thing 510 ** with '...'. If there is one or more ' characters within the 511 ** name, then put \ before each special character. 512 */ 513 if( strchr(zIn,'\'') ){ 514 unsigned char c; 515 size_t i; 516 if( isFilename && zIn[0]=='-' ){ 517 sqlite3_str_appendchar(pStr, 1, '.'); 518 sqlite3_str_appendchar(pStr, 1, '/'); 519 } 520 for(i=0; (c = (unsigned char)zIn[i])!=0; i++){ 521 if( aSafeChar[c] && aSafeChar[c]!=2 ){ 522 sqlite3_str_appendchar(pStr, 1, '\\'); 523 } 524 sqlite3_str_appendchar(pStr, 1, (char)c); 525 } 526 }else{ 527 sqlite3_str_appendchar(pStr, 1, '\''); 528 if( isFilename && zIn[0]=='-' ){ 529 sqlite3_str_appendchar(pStr, 1, '.'); 530 sqlite3_str_appendchar(pStr, 1, '/'); 531 } 532 sqlite3_str_appendall(pStr, zIn); 533 sqlite3_str_appendchar(pStr, 1, '\''); 534 } 535 #endif 536 } 537 } 538 539 /* Add an approprate PATH= argument to the SSH command under construction 540 ** in pStr 541 ** 542 ** About This Feature 543 ** ================== 544 ** 545 ** On some ssh servers (Macs in particular are guilty of this) the PATH 546 ** variable in the shell that runs the command that is sent to the remote 547 ** host contains a limited number of read-only system directories: 548 ** 549 ** /usr/bin:/bin:/usr/sbin:/sbin 550 ** 551 ** The sqlite3_rsync executable cannot be installed into any of those 552 ** directories because they are locked down, and so the "sqlite3_rsync" 553 ** command cannot run. 554 ** 555 ** To work around this, the sqlite3_rsync command is prefixed with a PATH= 556 ** argument, inserted by this function, to augment the PATH with additional 557 ** directories in which the sqlite3_rsync executable can be installed. 558 ** 559 ** But other ssh servers are confused by this initial PATH= argument. 560 ** Some ssh servers have a list of programs that they are allowed to run 561 ** and will fail if the first argument is not on that list, and PATH=.... 562 ** is not on that list. 563 ** 564 ** So that sqlite3_rsync can invoke itself on a remote system using ssh 565 ** on a variety of platforms, the following algorithm is used: 566 ** 567 ** * First try running the sqlite3_rsync without any PATH= argument. 568 ** If that works (and it does on a majority of systems) then we are 569 ** done. 570 ** 571 ** * If the first attempt fails, then try again after adding the 572 ** PATH= prefix argument. (This function is what adds that 573 ** argument.) 574 ** 575 ** A consequence of this is that if the remote system is a Mac, the 576 ** "ssh" command always ends up being invoked twice. If anybody knows a 577 ** way around that problem, please bring it to the attention of the 578 ** developers. 579 */ 580 void add_path_argument(sqlite3_str *pStr){ 581 append_escaped_arg(pStr, 582 "PATH=$HOME/bin:/usr/local/bin:/opt/homebrew/bin" 583 ":/opt/local/bin:$PATH", 0); 584 } 585 586 /* 587 ** The input is a filename, possibly encoded as hexadecimal using 588 ** characters 'A' through 'P' as the hexadecimal digits (instead of 589 ** the usual '0' through 'F'). 590 ** 591 ** Return a copy of that filename, decoded if necessary. 592 */ 593 static char *decode_filename(const char *zIn){ 594 size_t n; 595 if( zIn==0 ) return 0; 596 n = strlen(zIn); 597 if( (n&1)==1 || strspn(zIn,"ABCDEFGHIJKLMNOP")!=n ){ 598 /* Name is literal. No decoding required. */ 599 return sqlite3_mprintf("%s", zIn); 600 }else{ 601 /* Name is hex encoded. Need to decode it. */ 602 char *zOut = sqlite3_malloc64(n/2 + 1); 603 size_t i; 604 if( zOut==0 ){ 605 fprintf(stderr, "out of memory\n"); 606 exit(1); 607 } 608 for(i=0; iu.s[0]) 686 # define a01 (p->u.s[1]) 687 # define a02 (p->u.s[2]) 688 # define a03 (p->u.s[3]) 689 # define a04 (p->u.s[4]) 690 # define a10 (p->u.s[5]) 691 # define a11 (p->u.s[6]) 692 # define a12 (p->u.s[7]) 693 # define a13 (p->u.s[8]) 694 # define a14 (p->u.s[9]) 695 # define a20 (p->u.s[10]) 696 # define a21 (p->u.s[11]) 697 # define a22 (p->u.s[12]) 698 # define a23 (p->u.s[13]) 699 # define a24 (p->u.s[14]) 700 # define a30 (p->u.s[15]) 701 # define a31 (p->u.s[16]) 702 # define a32 (p->u.s[17]) 703 # define a33 (p->u.s[18]) 704 # define a34 (p->u.s[19]) 705 # define a40 (p->u.s[20]) 706 # define a41 (p->u.s[21]) 707 # define a42 (p->u.s[22]) 708 # define a43 (p->u.s[23]) 709 # define a44 (p->u.s[24]) 710 # define ROL64(a,x) ((a<>(64-x))) 711 712 /* v---- Number of rounds. SHA3 has 24 here. */ 713 for(i=0; i<6; i++){ 714 c0 = a00^a10^a20^a30^a40; 715 c1 = a01^a11^a21^a31^a41; 716 c2 = a02^a12^a22^a32^a42; 717 c3 = a03^a13^a23^a33^a43; 718 c4 = a04^a14^a24^a34^a44; 719 d0 = c4^ROL64(c1, 1); 720 d1 = c0^ROL64(c2, 1); 721 d2 = c1^ROL64(c3, 1); 722 d3 = c2^ROL64(c4, 1); 723 d4 = c3^ROL64(c0, 1); 724 725 b0 = (a00^d0); 726 b1 = ROL64((a11^d1), 44); 727 b2 = ROL64((a22^d2), 43); 728 b3 = ROL64((a33^d3), 21); 729 b4 = ROL64((a44^d4), 14); 730 a00 = b0 ^((~b1)& b2 ); 731 a00 ^= RC[i]; 732 a11 = b1 ^((~b2)& b3 ); 733 a22 = b2 ^((~b3)& b4 ); 734 a33 = b3 ^((~b4)& b0 ); 735 a44 = b4 ^((~b0)& b1 ); 736 737 b2 = ROL64((a20^d0), 3); 738 b3 = ROL64((a31^d1), 45); 739 b4 = ROL64((a42^d2), 61); 740 b0 = ROL64((a03^d3), 28); 741 b1 = ROL64((a14^d4), 20); 742 a20 = b0 ^((~b1)& b2 ); 743 a31 = b1 ^((~b2)& b3 ); 744 a42 = b2 ^((~b3)& b4 ); 745 a03 = b3 ^((~b4)& b0 ); 746 a14 = b4 ^((~b0)& b1 ); 747 748 b4 = ROL64((a40^d0), 18); 749 b0 = ROL64((a01^d1), 1); 750 b1 = ROL64((a12^d2), 6); 751 b2 = ROL64((a23^d3), 25); 752 b3 = ROL64((a34^d4), 8); 753 a40 = b0 ^((~b1)& b2 ); 754 a01 = b1 ^((~b2)& b3 ); 755 a12 = b2 ^((~b3)& b4 ); 756 a23 = b3 ^((~b4)& b0 ); 757 a34 = b4 ^((~b0)& b1 ); 758 759 b1 = ROL64((a10^d0), 36); 760 b2 = ROL64((a21^d1), 10); 761 b3 = ROL64((a32^d2), 15); 762 b4 = ROL64((a43^d3), 56); 763 b0 = ROL64((a04^d4), 27); 764 a10 = b0 ^((~b1)& b2 ); 765 a21 = b1 ^((~b2)& b3 ); 766 a32 = b2 ^((~b3)& b4 ); 767 a43 = b3 ^((~b4)& b0 ); 768 a04 = b4 ^((~b0)& b1 ); 769 770 b3 = ROL64((a30^d0), 41); 771 b4 = ROL64((a41^d1), 2); 772 b0 = ROL64((a02^d2), 62); 773 b1 = ROL64((a13^d3), 55); 774 b2 = ROL64((a24^d4), 39); 775 a30 = b0 ^((~b1)& b2 ); 776 a41 = b1 ^((~b2)& b3 ); 777 a02 = b2 ^((~b3)& b4 ); 778 a13 = b3 ^((~b4)& b0 ); 779 a24 = b4 ^((~b0)& b1 ); 780 } 781 } 782 783 /* 784 ** Initialize a new hash. iSize determines the size of the hash 785 ** in bits and should be one of 224, 256, 384, or 512. Or iSize 786 ** can be zero to use the default hash size of 256 bits. 787 */ 788 static void HashInit(HashContext *p, int iSize){ 789 memset(p, 0, sizeof(*p)); 790 p->iSize = iSize; 791 if( iSize>=128 && iSize<=512 ){ 792 p->nRate = (1600 - ((iSize + 31)&~31)*2)/8; 793 }else{ 794 p->nRate = (1600 - 2*256)/8; 795 } 796 #if Hash_BYTEORDER==1234 797 /* Known to be little-endian at compile-time. No-op */ 798 #elif Hash_BYTEORDER==4321 799 p->ixMask = 7; /* Big-endian */ 800 #else 801 { 802 static unsigned int one = 1; 803 if( 1==*(unsigned char*)&one ){ 804 /* Little endian. No byte swapping. */ 805 p->ixMask = 0; 806 }else{ 807 /* Big endian. Byte swap. */ 808 p->ixMask = 7; 809 } 810 } 811 #endif 812 } 813 814 /* 815 ** Make consecutive calls to the HashUpdate function to add new content 816 ** to the hash 817 */ 818 static void HashUpdate( 819 HashContext *p, 820 const unsigned char *aData, 821 unsigned int nData 822 ){ 823 unsigned int i = 0; 824 if( aData==0 ) return; 825 #if Hash_BYTEORDER==1234 826 if( (p->nLoaded % 8)==0 && ((aData - (const unsigned char*)0)&7)==0 ){ 827 for(; i+7u.s[p->nLoaded/8] ^= *(u64*)&aData[i]; 829 p->nLoaded += 8; 830 if( p->nLoaded>=p->nRate ){ 831 KeccakF1600Step(p); 832 p->nLoaded = 0; 833 } 834 } 835 } 836 #endif 837 for(; iu.x[p->nLoaded] ^= aData[i]; 840 #elif Hash_BYTEORDER==4321 841 p->u.x[p->nLoaded^0x07] ^= aData[i]; 842 #else 843 p->u.x[p->nLoaded^p->ixMask] ^= aData[i]; 844 #endif 845 p->nLoaded++; 846 if( p->nLoaded==p->nRate ){ 847 KeccakF1600Step(p); 848 p->nLoaded = 0; 849 } 850 } 851 } 852 853 /* 854 ** After all content has been added, invoke HashFinal() to compute 855 ** the final hash. The function returns a pointer to the binary 856 ** hash value. 857 */ 858 static unsigned char *HashFinal(HashContext *p){ 859 unsigned int i; 860 if( p->nLoaded==p->nRate-1 ){ 861 const unsigned char c1 = 0x86; 862 HashUpdate(p, &c1, 1); 863 }else{ 864 const unsigned char c2 = 0x06; 865 const unsigned char c3 = 0x80; 866 HashUpdate(p, &c2, 1); 867 p->nLoaded = p->nRate - 1; 868 HashUpdate(p, &c3, 1); 869 } 870 for(i=0; inRate; i++){ 871 p->u.x[i+p->nRate] = p->u.x[i^p->ixMask]; 872 } 873 return &p->u.x[p->nRate]; 874 } 875 876 /* 877 ** Implementation of the hash(X) function. 878 ** 879 ** Return a 160-bit BLOB which is the hash of X. 880 */ 881 static void hashFunc( 882 sqlite3_context *context, 883 int argc, 884 sqlite3_value **argv 885 ){ 886 HashContext cx; 887 int eType = sqlite3_value_type(argv[0]); 888 int nByte = sqlite3_value_bytes(argv[0]); 889 if( eType==SQLITE_NULL ) return; 890 HashInit(&cx, 160); 891 if( eType==SQLITE_BLOB ){ 892 HashUpdate(&cx, sqlite3_value_blob(argv[0]), nByte); 893 }else{ 894 HashUpdate(&cx, sqlite3_value_text(argv[0]), nByte); 895 } 896 sqlite3_result_blob(context, HashFinal(&cx), 160/8, SQLITE_TRANSIENT); 897 } 898 899 /* 900 ** Implementation of the agghash(X) function. 901 ** 902 ** Return a 160-bit BLOB which is the hash of the concatenation 903 ** of all X inputs. 904 */ 905 static void agghashStep( 906 sqlite3_context *context, 907 int argc, 908 sqlite3_value **argv 909 ){ 910 HashContext *pCx; 911 int eType = sqlite3_value_type(argv[0]); 912 int nByte = sqlite3_value_bytes(argv[0]); 913 if( eType==SQLITE_NULL ) return; 914 pCx = (HashContext*)sqlite3_aggregate_context(context, sizeof(*pCx)); 915 if( pCx==0 ) return; 916 if( pCx->iSize==0 ) HashInit(pCx, 160); 917 if( eType==SQLITE_BLOB ){ 918 HashUpdate(pCx, sqlite3_value_blob(argv[0]), nByte); 919 }else{ 920 HashUpdate(pCx, sqlite3_value_text(argv[0]), nByte); 921 } 922 } 923 static void agghashFinal(sqlite3_context *context){ 924 HashContext *pCx = (HashContext*)sqlite3_aggregate_context(context, 0); 925 if( pCx ){ 926 sqlite3_result_blob(context, HashFinal(pCx), 160/8, SQLITE_TRANSIENT); 927 } 928 } 929 930 /* Register the hash function */ 931 static int hashRegister(sqlite3 *db){ 932 int rc; 933 rc = sqlite3_create_function(db, "hash", 1, 934 SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, 935 0, hashFunc, 0, 0); 936 if( rc==SQLITE_OK ){ 937 rc = sqlite3_create_function(db, "agghash", 1, 938 SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC, 939 0, 0, agghashStep, agghashFinal); 940 } 941 return rc; 942 } 943 944 /* End of the hashing logic 945 *****************************************************************************/ 946 947 /* 948 ** Return the tail of a file pathname. The tail is the last component 949 ** of the path. For example, the tail of "/a/b/c.d" is "c.d". 950 */ 951 const char *file_tail(const char *z){ 952 const char *zTail = z; 953 if( !zTail ) return 0; 954 while( z[0] ){ 955 if( z[0]=='/' ) zTail = &z[1]; 956 z++; 957 } 958 return zTail; 959 } 960 961 /* 962 ** Append error message text to the error file, if an error file is 963 ** specified. In any case, increment the error count. 964 */ 965 static void logError(SQLiteRsync *p, const char *zFormat, ...){ 966 if( p->zErrFile ){ 967 FILE *pErr = fopen(p->zErrFile, "a"); 968 if( pErr ){ 969 va_list ap; 970 va_start(ap, zFormat); 971 vfprintf(pErr, zFormat, ap); 972 va_end(ap); 973 fclose(pErr); 974 } 975 } 976 p->nErr++; 977 } 978 979 /* 980 ** Append text to the debugging mesage file, if an that file is 981 ** specified. 982 */ 983 static void debugMessage(SQLiteRsync *p, const char *zFormat, ...){ 984 if( p->zDebugFile ){ 985 if( p->pDebug==0 ){ 986 p->pDebug = fopen(p->zDebugFile, "wb"); 987 } 988 if( p->pDebug ){ 989 va_list ap; 990 va_start(ap, zFormat); 991 vfprintf(p->pDebug, zFormat, ap); 992 va_end(ap); 993 fflush(p->pDebug); 994 } 995 } 996 } 997 998 999 /* Read a single big-endian 32-bit unsigned integer from the input 1000 ** stream. Return 0 on success and 1 if there are any errors. 1001 */ 1002 static int readUint32(SQLiteRsync *p, unsigned int *pU){ 1003 unsigned char buf[4]; 1004 if( fread(buf, sizeof(buf), 1, p->pIn)==1 ){ 1005 *pU = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3]; 1006 p->nIn += 4; 1007 return 0; 1008 }else{ 1009 logError(p, "failed to read a 32-bit integer\n"); 1010 return 1; 1011 } 1012 } 1013 1014 /* Write a single big-endian 32-bit unsigned integer to the output stream. 1015 ** Return 0 on success and 1 if there are any errors. 1016 */ 1017 static int writeUint32(SQLiteRsync *p, unsigned int x){ 1018 unsigned char buf[4]; 1019 buf[3] = x & 0xff; 1020 x >>= 8; 1021 buf[2] = x & 0xff; 1022 x >>= 8; 1023 buf[1] = x & 0xff; 1024 x >>= 8; 1025 buf[0] = x; 1026 if( p->pLog ) fwrite(buf, sizeof(buf), 1, p->pLog); 1027 if( fwrite(buf, sizeof(buf), 1, p->pOut)!=1 ){ 1028 logError(p, "failed to write 32-bit integer 0x%x\n", x); 1029 p->nWrErr++; 1030 return 1; 1031 } 1032 p->nOut += 4; 1033 return 0; 1034 } 1035 1036 /* Read a single byte from the wire. 1037 */ 1038 int readByte(SQLiteRsync *p){ 1039 int c = fgetc(p->pIn); 1040 if( c!=EOF ) p->nIn++; 1041 return c; 1042 } 1043 1044 /* Write a single byte into the wire. 1045 */ 1046 void writeByte(SQLiteRsync *p, int c){ 1047 if( p->pLog ) fputc(c, p->pLog); 1048 fputc(c, p->pOut); 1049 p->nOut++; 1050 } 1051 1052 /* Read a power of two page size encoded as a single byte. 1053 */ 1054 int readPow2(SQLiteRsync *p){ 1055 int x = readByte(p); 1056 if( x<0 || x>16 ){ 1057 logError(p, "read invalid page size %d\n", x); 1058 return 0; 1059 } 1060 return 1<1; n++){ c /= 2; } 1071 writeByte(p, n); 1072 } 1073 1074 /* Read an array of bytes from the wire. 1075 */ 1076 void readBytes(SQLiteRsync *p, int nByte, void *pData){ 1077 if( fread(pData, 1, nByte, p->pIn)==nByte ){ 1078 p->nIn += nByte; 1079 }else{ 1080 logError(p, "failed to read %d bytes\n", nByte); 1081 } 1082 } 1083 1084 /* Write an array of bytes onto the wire. 1085 */ 1086 void writeBytes(SQLiteRsync *p, int nByte, const void *pData){ 1087 if( p->pLog ) fwrite(pData, 1, nByte, p->pLog); 1088 if( fwrite(pData, 1, nByte, p->pOut)==nByte ){ 1089 p->nOut += nByte; 1090 }else{ 1091 logError(p, "failed to write %d bytes\n", nByte); 1092 p->nWrErr++; 1093 } 1094 } 1095 1096 /* Report an error. 1097 ** 1098 ** If this happens on the remote side, we send back a *_ERROR 1099 ** message. On the local side, the error message goes to stderr. 1100 */ 1101 static void reportError(SQLiteRsync *p, const char *zFormat, ...){ 1102 va_list ap; 1103 char *zMsg; 1104 unsigned int nMsg; 1105 va_start(ap, zFormat); 1106 zMsg = sqlite3_vmprintf(zFormat, ap); 1107 va_end(ap); 1108 nMsg = zMsg ? (unsigned int)strlen(zMsg) : 0; 1109 if( p->isRemote ){ 1110 if( p->isReplica ){ 1111 putc(REPLICA_ERROR, p->pOut); 1112 }else{ 1113 putc(ORIGIN_ERROR, p->pOut); 1114 } 1115 writeUint32(p, nMsg); 1116 writeBytes(p, nMsg, zMsg); 1117 fflush(p->pOut); 1118 }else{ 1119 fprintf(stderr, "%s\n", zMsg); 1120 } 1121 logError(p, "%s\n", zMsg); 1122 sqlite3_free(zMsg); 1123 } 1124 1125 /* Send an informational message. 1126 ** 1127 ** If this happens on the remote side, we send back a *_MSG 1128 ** message. On the local side, the message goes to stdout. 1129 */ 1130 static void infoMsg(SQLiteRsync *p, const char *zFormat, ...){ 1131 va_list ap; 1132 char *zMsg; 1133 unsigned int nMsg; 1134 va_start(ap, zFormat); 1135 zMsg = sqlite3_vmprintf(zFormat, ap); 1136 va_end(ap); 1137 nMsg = zMsg ? (unsigned int)strlen(zMsg) : 0; 1138 if( p->isRemote ){ 1139 if( p->isReplica ){ 1140 putc(REPLICA_MSG, p->pOut); 1141 }else{ 1142 putc(ORIGIN_MSG, p->pOut); 1143 } 1144 writeUint32(p, nMsg); 1145 writeBytes(p, nMsg, zMsg); 1146 fflush(p->pOut); 1147 }else{ 1148 printf("%s\n", zMsg); 1149 } 1150 sqlite3_free(zMsg); 1151 } 1152 1153 /* Receive and report an error message coming from the other side. 1154 */ 1155 static void readAndDisplayMessage(SQLiteRsync *p, int c){ 1156 unsigned int n = 0; 1157 char *zMsg; 1158 const char *zPrefix; 1159 if( c==ORIGIN_ERROR || c==REPLICA_ERROR ){ 1160 zPrefix = "ERROR: "; 1161 }else{ 1162 zPrefix = ""; 1163 } 1164 readUint32(p, &n); 1165 if( n==0 ){ 1166 fprintf(stderr,"ERROR: unknown (possibly out-of-memory)\n"); 1167 }else{ 1168 zMsg = sqlite3_malloc64( n+1 ); 1169 if( zMsg==0 ){ 1170 fprintf(stderr, "ERROR: out-of-memory\n"); 1171 return; 1172 } 1173 memset(zMsg, 0, n+1); 1174 readBytes(p, n, zMsg); 1175 fprintf(stderr,"%s%s\n", zPrefix, zMsg); 1176 if( zPrefix[0] ) logError(p, "%s%s\n", zPrefix, zMsg); 1177 sqlite3_free(zMsg); 1178 } 1179 } 1180 1181 /* Construct a new prepared statement. Report an error and return NULL 1182 ** if anything goes wrong. 1183 */ 1184 static sqlite3_stmt *prepareStmtVA( 1185 SQLiteRsync *p, 1186 char *zFormat, 1187 va_list ap 1188 ){ 1189 sqlite3_stmt *pStmt = 0; 1190 char *zSql; 1191 char *zToFree = 0; 1192 int rc; 1193 1194 if( strchr(zFormat,'%') ){ 1195 zSql = sqlite3_vmprintf(zFormat, ap); 1196 if( zSql==0 ){ 1197 reportError(p, "out-of-memory"); 1198 return 0; 1199 }else{ 1200 zToFree = zSql; 1201 } 1202 }else{ 1203 zSql = zFormat; 1204 } 1205 rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); 1206 if( rc || pStmt==0 ){ 1207 reportError(p, "unable to prepare SQL [%s]: %s", zSql, 1208 sqlite3_errmsg(p->db)); 1209 sqlite3_finalize(pStmt); 1210 pStmt = 0; 1211 } 1212 if( zToFree ) sqlite3_free(zToFree); 1213 return pStmt; 1214 } 1215 static sqlite3_stmt *prepareStmt( 1216 SQLiteRsync *p, 1217 char *zFormat, 1218 ... 1219 ){ 1220 sqlite3_stmt *pStmt; 1221 va_list ap; 1222 va_start(ap, zFormat); 1223 pStmt = prepareStmtVA(p, zFormat, ap); 1224 va_end(ap); 1225 return pStmt; 1226 } 1227 1228 /* Run a single SQL statement. Report an error if something goes 1229 ** wrong. 1230 ** 1231 ** As a special case, if the statement starts with "ATTACH" (but not 1232 ** "Attach") and if the error message is about an incorrect encoding, 1233 ** then do not report the error, but instead set the wrongEncoding flag. 1234 ** This is a kludgy work-around to the problem of attaching a database 1235 ** with a non-UTF8 encoding to the empty :memory: database that is 1236 ** opened on the replica. 1237 */ 1238 static void runSql(SQLiteRsync *p, char *zSql, ...){ 1239 sqlite3_stmt *pStmt; 1240 va_list ap; 1241 1242 va_start(ap, zSql); 1243 pStmt = prepareStmtVA(p, zSql, ap); 1244 va_end(ap); 1245 if( pStmt ){ 1246 int rc = sqlite3_step(pStmt); 1247 if( rc==SQLITE_ROW ) rc = sqlite3_step(pStmt); 1248 if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ 1249 const char *zErr = sqlite3_errmsg(p->db); 1250 if( strncmp(zSql,"ATTACH ", 7)==0 1251 && strstr(zErr,"must use the same text encoding")!=0 1252 ){ 1253 p->wrongEncoding = 1; 1254 }else{ 1255 reportError(p, "SQL statement [%s] failed: %s", zSql, 1256 sqlite3_errmsg(p->db)); 1257 } 1258 } 1259 sqlite3_finalize(pStmt); 1260 } 1261 } 1262 1263 /* Run an SQL statement that returns a single unsigned 32-bit integer result 1264 */ 1265 static int runSqlReturnUInt( 1266 SQLiteRsync *p, 1267 unsigned int *pRes, 1268 char *zSql, 1269 ... 1270 ){ 1271 sqlite3_stmt *pStmt; 1272 int res = 0; 1273 va_list ap; 1274 1275 va_start(ap, zSql); 1276 pStmt = prepareStmtVA(p, zSql, ap); 1277 va_end(ap); 1278 if( pStmt==0 ){ 1279 res = 1; 1280 }else{ 1281 int rc = sqlite3_step(pStmt); 1282 if( rc==SQLITE_ROW ){ 1283 *pRes = (unsigned int)(sqlite3_column_int64(pStmt, 0)&0xffffffff); 1284 }else{ 1285 reportError(p, "SQL statement [%s] failed: %s", zSql, 1286 sqlite3_errmsg(p->db)); 1287 res = 1; 1288 } 1289 sqlite3_finalize(pStmt); 1290 } 1291 return res; 1292 } 1293 1294 /* Run an SQL statement that returns a single TEXT value that is no more 1295 ** than 99 bytes in length. 1296 */ 1297 static int runSqlReturnText( 1298 SQLiteRsync *p, 1299 char *pRes, 1300 char *zSql, 1301 ... 1302 ){ 1303 sqlite3_stmt *pStmt; 1304 int res = 0; 1305 va_list ap; 1306 1307 va_start(ap, zSql); 1308 pStmt = prepareStmtVA(p, zSql, ap); 1309 va_end(ap); 1310 pRes[0] = 0; 1311 if( pStmt==0 ){ 1312 res = 1; 1313 }else{ 1314 int rc = sqlite3_step(pStmt); 1315 if( rc==SQLITE_ROW ){ 1316 const unsigned char *a = sqlite3_column_text(pStmt, 0); 1317 int n; 1318 if( a==0 ){ 1319 pRes[0] = 0; 1320 }else{ 1321 n = sqlite3_column_bytes(pStmt, 0); 1322 if( n>99 ) n = 99; 1323 memcpy(pRes, a, n); 1324 pRes[n] = 0; 1325 } 1326 }else{ 1327 reportError(p, "SQL statement [%s] failed: %s", zSql, 1328 sqlite3_errmsg(p->db)); 1329 res = 1; 1330 } 1331 sqlite3_finalize(pStmt); 1332 } 1333 return res; 1334 } 1335 1336 /* Close the database connection associated with p 1337 */ 1338 static void closeDb(SQLiteRsync *p){ 1339 if( p->db ){ 1340 sqlite3_stmt *pStmt; 1341 while( (pStmt = sqlite3_next_stmt(p->db, 0))!=0 ){ 1342 sqlite3_finalize(pStmt); 1343 } 1344 sqlite3_close(p->db); 1345 p->db = 0; 1346 } 1347 } 1348 1349 /* 1350 ** Run the origin-side protocol. 1351 ** 1352 ** Begin by sending the ORIGIN_BEGIN message with two arguments, 1353 ** nPage, and szPage. Then enter a loop responding to message from 1354 ** the replica: 1355 ** 1356 ** REPLICA_BEGIN iProtocol 1357 ** 1358 ** An optional message sent by the replica in response to the 1359 ** prior ORIGIN_BEGIN with a counter-proposal for the protocol 1360 ** level. If seen, try to reduce the protocol level to what is 1361 ** requested and send a new ORGIN_BEGIN. 1362 ** 1363 ** REPLICA_ERROR size text 1364 ** 1365 ** Report an error from the replica and quit 1366 ** 1367 ** REPLICA_END 1368 ** 1369 ** The replica is terminating. Stop processing now. 1370 ** 1371 ** REPLICA_HASH hash 1372 ** 1373 ** The argument is the 20-byte SHA1 hash for the next page or 1374 ** block of pages. Hashes appear in sequential order with no gaps, 1375 ** unless there is an intervening REPLICA_CONFIG message. 1376 ** 1377 ** REPLICA_CONFIG pgno cnt 1378 ** 1379 ** Set counters used by REPLICA_HASH. The next hash will start 1380 ** on page pgno and all subsequent hashes will cover cnt pages 1381 ** each. Note that for a multi-page hash, the hash value is 1382 ** actually a hash of the individual page hashes. 1383 ** 1384 ** REPLICA_READY 1385 ** 1386 ** The replica has sent all the hashes that it intends to send. 1387 ** This side (the origin) can now start responding with page 1388 ** content for pages that do not have a matching hash or with 1389 ** ORIGIN_DETAIL messages with requests for more detail. 1390 */ 1391 static void originSide(SQLiteRsync *p){ 1392 int rc = 0; 1393 int c = 0; 1394 unsigned int nPage = 0; 1395 unsigned int iHash = 1; /* Pgno for next hash to receive */ 1396 unsigned int nHash = 1; /* Number of pages per hash received */ 1397 unsigned int mxHash = 0; /* Maximum hash value received */ 1398 unsigned int lockBytePage = 0; 1399 unsigned int szPg = 0; 1400 sqlite3_stmt *pCkHash = 0; /* Verify hash on a single page */ 1401 sqlite3_stmt *pCkHashN = 0; /* Verify a multi-page hash */ 1402 sqlite3_stmt *pInsHash = 0; /* Record a bad hash */ 1403 char buf[200]; 1404 1405 p->isReplica = 0; 1406 if( p->bCommCheck ){ 1407 infoMsg(p, "origin zOrigin=%Q zReplica=%Q isRemote=%d protocol=%d", 1408 p->zOrigin, p->zReplica, p->isRemote, p->iProtocol); 1409 writeByte(p, ORIGIN_END); 1410 fflush(p->pOut); 1411 }else{ 1412 /* Open the ORIGIN database. */ 1413 rc = sqlite3_open_v2(p->zOrigin, &p->db, SQLITE_OPEN_READWRITE, 0); 1414 if( rc ){ 1415 reportError(p, "cannot open origin \"%s\": %s", 1416 p->zOrigin, sqlite3_errmsg(p->db)); 1417 closeDb(p); 1418 return; 1419 } 1420 hashRegister(p->db); 1421 runSql(p, "BEGIN"); 1422 if( p->bWalOnly ){ 1423 runSqlReturnText(p, buf, "PRAGMA journal_mode"); 1424 if( sqlite3_stricmp(buf,"wal")!=0 ){ 1425 reportError(p, "Origin database is not in WAL mode"); 1426 } 1427 } 1428 runSqlReturnUInt(p, &nPage, "PRAGMA page_count"); 1429 runSqlReturnUInt(p, &szPg, "PRAGMA page_size"); 1430 1431 if( p->nErr==0 ){ 1432 /* Send the ORIGIN_BEGIN message */ 1433 writeByte(p, ORIGIN_BEGIN); 1434 writeByte(p, p->iProtocol); 1435 writePow2(p, szPg); 1436 writeUint32(p, nPage); 1437 fflush(p->pOut); 1438 if( p->zDebugFile ){ 1439 debugMessage(p, "-> ORIGIN_BEGIN %u %u %u\n", p->iProtocol,szPg,nPage); 1440 } 1441 p->nPage = nPage; 1442 p->szPage = szPg; 1443 lockBytePage = (1<<30)/szPg + 1; 1444 } 1445 } 1446 1447 /* Respond to message from the replica */ 1448 while( p->nErr<=p->nWrErr && (c = readByte(p))!=EOF && c!=REPLICA_END ){ 1449 switch( c ){ 1450 case REPLICA_BEGIN: { 1451 /* This message is only sent if the replica received an origin-protocol 1452 ** that is larger than what it knows about. The replica sends back 1453 ** a counter-proposal of an earlier protocol which the origin can 1454 ** accept by resending a new ORIGIN_BEGIN. */ 1455 u8 newProtocol = readByte(p); 1456 if( p->zDebugFile ){ 1457 debugMessage(p, "<- REPLICA_BEGIN %d\n", (int)newProtocol); 1458 } 1459 if( newProtocol < p->iProtocol ){ 1460 p->iProtocol = newProtocol; 1461 writeByte(p, ORIGIN_BEGIN); 1462 writeByte(p, p->iProtocol); 1463 writePow2(p, p->szPage); 1464 writeUint32(p, p->nPage); 1465 fflush(p->pOut); 1466 if( p->zDebugFile ){ 1467 debugMessage(p, "-> ORIGIN_BEGIN %d %d %u\n", p->iProtocol, 1468 p->szPage, p->nPage); 1469 } 1470 }else{ 1471 reportError(p, "Invalid REPLICA_BEGIN reply"); 1472 } 1473 break; 1474 } 1475 case REPLICA_MSG: 1476 case REPLICA_ERROR: { 1477 readAndDisplayMessage(p, c); 1478 break; 1479 } 1480 case REPLICA_CONFIG: { 1481 readUint32(p, &iHash); 1482 readUint32(p, &nHash); 1483 if( p->zDebugFile ){ 1484 debugMessage(p, "<- REPLICA_CONFIG %u %u\n", iHash, nHash); 1485 } 1486 break; 1487 } 1488 case REPLICA_HASH: { 1489 int bMatch = 0; 1490 if( pCkHash==0 ){ 1491 runSql(p, "CREATE TEMP TABLE badHash(" 1492 " pgno INTEGER PRIMARY KEY," 1493 " sz INT)"); 1494 pCkHash = prepareStmt(p, 1495 "SELECT hash(data)==?3 FROM sqlite_dbpage('main')" 1496 " WHERE pgno=?1" 1497 ); 1498 if( pCkHash==0 ) break; 1499 pInsHash = prepareStmt(p, "INSERT INTO badHash VALUES(?1,?2)"); 1500 if( pInsHash==0 ) break; 1501 } 1502 p->nHashSent++; 1503 readBytes(p, 20, buf); 1504 if( nHash>1 ){ 1505 if( pCkHashN==0 ){ 1506 pCkHashN = prepareStmt(p, 1507 "WITH c(n) AS " 1508 " (VALUES(?1) UNION ALL SELECT n+1 FROM c WHERE ndb)); 1523 } 1524 sqlite3_reset(pCkHashN); 1525 }else{ 1526 sqlite3_bind_int64(pCkHash, 1, iHash); 1527 sqlite3_bind_blob(pCkHash, 3, buf, 20, SQLITE_STATIC); 1528 rc = sqlite3_step(pCkHash); 1529 if( rc==SQLITE_ERROR ){ 1530 reportError(p, "SQL statement [%s] failed: %s", 1531 sqlite3_sql(pCkHash), sqlite3_errmsg(p->db)); 1532 }else if( rc==SQLITE_ROW && sqlite3_column_int(pCkHash,0) ){ 1533 bMatch = 1; 1534 } 1535 sqlite3_reset(pCkHash); 1536 } 1537 if( p->zDebugFile ){ 1538 debugMessage(p, "<- REPLICA_HASH %u %u %s %08x...\n", 1539 iHash, nHash, 1540 bMatch ? "match" : "fail", 1541 *(unsigned int*)buf 1542 ); 1543 } 1544 if( !bMatch ){ 1545 sqlite3_bind_int64(pInsHash, 1, iHash); 1546 sqlite3_bind_int64(pInsHash, 2, nHash); 1547 rc = sqlite3_step(pInsHash); 1548 if( rc!=SQLITE_DONE ){ 1549 reportError(p, "SQL statement [%s] failed: %s", 1550 sqlite3_sql(pInsHash), sqlite3_errmsg(p->db)); 1551 } 1552 sqlite3_reset(pInsHash); 1553 } 1554 if( iHash+nHash>mxHash ) mxHash = iHash+nHash; 1555 iHash += nHash; 1556 break; 1557 } 1558 case REPLICA_READY: { 1559 int nMulti = 0; 1560 sqlite3_stmt *pStmt; 1561 if( p->zDebugFile ){ 1562 debugMessage(p, "<- REPLICA_READY\n"); 1563 } 1564 p->nRound++; 1565 pStmt = prepareStmt(p,"SELECT pgno, sz FROM badHash WHERE sz>1"); 1566 if( pStmt==0 ) break; 1567 while( sqlite3_step(pStmt)==SQLITE_ROW ){ 1568 unsigned int pgno = (unsigned int)sqlite3_column_int64(pStmt,0); 1569 unsigned int cnt = (unsigned int)sqlite3_column_int64(pStmt,1); 1570 writeByte(p, ORIGIN_DETAIL); 1571 writeUint32(p, pgno); 1572 writeUint32(p, cnt); 1573 nMulti++; 1574 if( p->zDebugFile ){ 1575 debugMessage(p, "-> ORIGIN_DETAIL %u %u\n", pgno, cnt); 1576 } 1577 } 1578 sqlite3_finalize(pStmt); 1579 if( nMulti ){ 1580 runSql(p, "DELETE FROM badHash WHERE sz>1"); 1581 writeByte(p, ORIGIN_READY); 1582 if( p->zDebugFile ) debugMessage(p, "-> ORIGIN_READY\n"); 1583 }else{ 1584 sqlite3_finalize(pCkHash); 1585 sqlite3_finalize(pCkHashN); 1586 sqlite3_finalize(pInsHash); 1587 pCkHash = 0; 1588 pInsHash = 0; 1589 if( mxHash<=p->nPage ){ 1590 runSql(p, "WITH RECURSIVE c(n) AS" 1591 " (VALUES(%d) UNION ALL SELECT n+1 FROM c WHERE n<%d)" 1592 " INSERT INTO badHash SELECT n, 1 FROM c", 1593 mxHash, p->nPage); 1594 } 1595 runSql(p, "DELETE FROM badHash WHERE pgno=%d", lockBytePage); 1596 pStmt = prepareStmt(p, 1597 "SELECT pgno, data" 1598 " FROM badHash JOIN sqlite_dbpage('main') USING(pgno)"); 1599 if( pStmt==0 ) break; 1600 while( sqlite3_step(pStmt)==SQLITE_ROW 1601 && p->nErr==0 1602 && p->nWrErr==0 1603 ){ 1604 unsigned int pgno = (unsigned int)sqlite3_column_int64(pStmt,0); 1605 const void *pContent = sqlite3_column_blob(pStmt, 1); 1606 writeByte(p, ORIGIN_PAGE); 1607 writeUint32(p, pgno); 1608 writeBytes(p, szPg, pContent); 1609 p->nPageSent++; 1610 if( p->zDebugFile ){ 1611 debugMessage(p, "-> ORIGIN_PAGE %u\n", pgno); 1612 } 1613 } 1614 sqlite3_finalize(pStmt); 1615 writeByte(p, ORIGIN_TXN); 1616 writeUint32(p, nPage); 1617 if( p->zDebugFile ){ 1618 debugMessage(p, "-> ORIGIN_TXN %u\n", nPage); 1619 } 1620 writeByte(p, ORIGIN_END); 1621 } 1622 fflush(p->pOut); 1623 break; 1624 } 1625 default: { 1626 reportError(p, "Unknown message 0x%02x %lld bytes into conversation", 1627 c, p->nIn); 1628 break; 1629 } 1630 } 1631 } 1632 1633 if( pCkHash ) sqlite3_finalize(pCkHash); 1634 if( pInsHash ) sqlite3_finalize(pInsHash); 1635 closeDb(p); 1636 } 1637 1638 /* 1639 ** Send a REPLICA_HASH message for each entry in the sendHash table. 1640 ** The sendHash table looks like this: 1641 ** 1642 ** CREATE TABLE sendHash( 1643 ** fpg INTEGER PRIMARY KEY, -- Page number of the hash 1644 ** npg INT -- Number of pages in this hash 1645 ** ); 1646 ** 1647 ** If iHash is page number for the next page that the origin will 1648 ** be expecting, and nHash is the number of pages that the origin will 1649 ** be expecting in the hash that follows. Send a REPLICA_CONFIG message 1650 ** if either of these values if not correct. 1651 */ 1652 static void sendHashMessages( 1653 SQLiteRsync *p, /* The replica-side of the sync */ 1654 unsigned int iHash, /* Next page expected by origin */ 1655 unsigned int nHash /* Next number of pages expected by origin */ 1656 ){ 1657 sqlite3_stmt *pStmt; 1658 pStmt = prepareStmt(p, 1659 "SELECT if(npg==1," 1660 " (SELECT hash(data) FROM sqlite_dbpage('replica') WHERE pgno=fpg)," 1661 " (WITH RECURSIVE c(n) AS" 1662 " (SELECT fpg UNION ALL SELECT n+1 FROM c WHERE nnErr==0 && p->nWrErr==0 ){ 1670 const unsigned char *a = sqlite3_column_blob(pStmt, 0); 1671 unsigned int pgno = (unsigned int)sqlite3_column_int64(pStmt, 1); 1672 unsigned int npg = (unsigned int)sqlite3_column_int64(pStmt, 2); 1673 if( pgno!=iHash || npg!=nHash ){ 1674 writeByte(p, REPLICA_CONFIG); 1675 writeUint32(p, pgno); 1676 writeUint32(p, npg); 1677 if( p->zDebugFile ){ 1678 debugMessage(p, "-> REPLICA_CONFIG %u %u\n", pgno, npg); 1679 } 1680 } 1681 if( a==0 ){ 1682 if( p->zDebugFile ){ 1683 debugMessage(p, "# Oops: No hash for %u %u\n", pgno, npg); 1684 } 1685 }else{ 1686 writeByte(p, REPLICA_HASH); 1687 writeBytes(p, 20, a); 1688 if( p->zDebugFile ){ 1689 debugMessage(p, "-> REPLICA_HASH %u %u (%08x...)\n", 1690 pgno, npg, *(unsigned int*)a); 1691 } 1692 } 1693 p->nHashSent++; 1694 iHash = pgno + npg; 1695 nHash = npg; 1696 } 1697 sqlite3_finalize(pStmt); 1698 runSql(p, "DELETE FROM sendHash"); 1699 writeByte(p, REPLICA_READY); 1700 fflush(p->pOut); 1701 p->nRound++; 1702 if( p->zDebugFile ) debugMessage(p, "-> REPLICA_READY\n"); 1703 } 1704 1705 /* 1706 ** Make entries in the sendHash table to send hashes for 1707 ** npg (mnemonic: Number of PaGes) pages starting with fpg 1708 ** (mnemonic: First PaGe). 1709 */ 1710 static void subdivideHashRange( 1711 SQLiteRsync *p, /* The replica-side of the sync */ 1712 unsigned int fpg, /* First page of the range */ 1713 unsigned int npg /* Number of pages */ 1714 ){ 1715 unsigned int nChunk; /* How many pages to request per hash */ 1716 sqlite3_uint64 iEnd; /* One more than the last page */ 1717 if( npg<=30 ){ 1718 nChunk = 1; 1719 }else if( npg<=1000 ){ 1720 nChunk = 30; 1721 }else{ 1722 nChunk = 1000; 1723 } 1724 iEnd = fpg; 1725 iEnd += npg; 1726 runSql(p, 1727 "WITH RECURSIVE c(n) AS" 1728 " (VALUES(%u) UNION ALL SELECT n+%u FROM c WHERE n<%llu)" 1729 "REPLACE INTO sendHash(fpg,npg)" 1730 " SELECT n, min(%llu-n,%u) FROM c", 1731 fpg, nChunk, iEnd-nChunk, iEnd, nChunk 1732 ); 1733 } 1734 1735 /* 1736 ** Run the replica-side protocol. The protocol is passive in the sense 1737 ** that it only response to message from the origin side. 1738 ** 1739 ** ORIGIN_BEGIN idProtocol szPage nPage 1740 ** 1741 ** The origin is reporting the protocol version number, the size of 1742 ** each page in the origin database (sent as a single-byte power-of-2), 1743 ** and the number of pages in the origin database. 1744 ** This procedure checks compatibility, and if everything is ok, 1745 ** it starts sending hashes back to the origin using REPLICA_HASH 1746 ** and/or REPLICA_CONFIG message, followed by a single REPLICA_READY. 1747 ** REPLICA_CONFIG is only sent if the protocol is 2 or greater. 1748 ** 1749 ** ORIGIN_ERROR size text 1750 ** 1751 ** Report an error and quit. 1752 ** 1753 ** ORIGIN_DETAIL pgno cnt 1754 ** 1755 ** The origin reports that a multi-page hash starting at pgno and 1756 ** spanning cnt pages failed to match. The origin is requesting 1757 ** details (more REPLICA_HASH message with a smaller cnt). The 1758 ** replica must wait on ORIGIN_READY before sending its reply. 1759 ** 1760 ** ORIGIN_READY 1761 ** 1762 ** After sending one or more ORIGIN_DETAIL messages, the ORIGIN_READY 1763 ** is sent by the origin to indicate that it has finished sending 1764 ** requests for detail and is ready for the replicate to reply 1765 ** with a new round of REPLICA_CONFIG and REPLICA_HASH messages. 1766 ** 1767 ** ORIGIN_PAGE pgno content 1768 ** 1769 ** Once the origin believes it knows exactly which pages need to be 1770 ** updated in the replica, it starts sending those pages using these 1771 ** messages. These messages will only appear immediately after 1772 ** REPLICA_READY. The origin never mixes ORIGIN_DETAIL and 1773 ** ORIGIN_PAGE messages in the same batch. 1774 ** 1775 ** ORIGIN_TXN pgno 1776 ** 1777 ** Close the update transaction. The total database size is pgno 1778 ** pages. 1779 ** 1780 ** ORIGIN_END 1781 ** 1782 ** Expect no more transmissions from the origin. 1783 */ 1784 static void replicaSide(SQLiteRsync *p){ 1785 int c; 1786 sqlite3_stmt *pIns = 0; 1787 char eJMode = 0; /* Journal mode prior to sync */ 1788 char buf[65536]; 1789 1790 p->isReplica = 1; 1791 if( p->bCommCheck ){ 1792 infoMsg(p, "replica zOrigin=%Q zReplica=%Q isRemote=%d protocol=%d", 1793 p->zOrigin, p->zReplica, p->isRemote, p->iProtocol); 1794 writeByte(p, REPLICA_END); 1795 fflush(p->pOut); 1796 } 1797 if( p->iProtocol<=0 ) p->iProtocol = PROTOCOL_VERSION; 1798 1799 /* Respond to message from the origin. The origin will initiate the 1800 ** the conversation with an ORIGIN_BEGIN message. 1801 */ 1802 while( p->nErr<=p->nWrErr && (c = readByte(p))!=EOF && c!=ORIGIN_END ){ 1803 switch( c ){ 1804 case ORIGIN_MSG: 1805 case ORIGIN_ERROR: { 1806 readAndDisplayMessage(p, c); 1807 break; 1808 } 1809 case ORIGIN_BEGIN: { 1810 unsigned int nOPage = 0; 1811 unsigned int nRPage = 0, szRPage = 0; 1812 unsigned int szOPage = 0; 1813 int rc = 0; 1814 u8 iProtocol; 1815 1816 closeDb(p); 1817 pIns = 0; 1818 iProtocol = readByte(p); 1819 szOPage = readPow2(p); 1820 readUint32(p, &nOPage); 1821 if( p->zDebugFile ){ 1822 debugMessage(p, "<- ORIGIN_BEGIN %d %d %u\n", iProtocol, szOPage, 1823 nOPage); 1824 } 1825 if( p->nErr ) break; 1826 if( iProtocol>p->iProtocol ){ 1827 /* If the protocol version on the origin side is larger, send back 1828 ** a REPLICA_BEGIN message with the protocol version number of the 1829 ** replica side. This gives the origin an opportunity to resend 1830 ** a new ORIGIN_BEGIN with a reduced protocol version. */ 1831 writeByte(p, REPLICA_BEGIN); 1832 writeByte(p, p->iProtocol); 1833 fflush(p->pOut); 1834 if( p->zDebugFile ){ 1835 debugMessage(p, "-> REPLICA_BEGIN %u\n", p->iProtocol); 1836 } 1837 break; 1838 } 1839 p->iProtocol = iProtocol; 1840 p->nPage = nOPage; 1841 p->szPage = szOPage; 1842 rc = sqlite3_open(":memory:", &p->db); 1843 if( rc ){ 1844 reportError(p, "cannot open in-memory database: %s", 1845 sqlite3_errmsg(p->db)); 1846 closeDb(p); 1847 pIns = 0; 1848 break; 1849 } 1850 sqlite3_db_config(p->db, SQLITE_DBCONFIG_WRITABLE_SCHEMA, 1, 0); 1851 runSql(p, "ATTACH %Q AS 'replica'", p->zReplica); 1852 if( p->wrongEncoding ){ 1853 p->wrongEncoding = 0; 1854 runSql(p, "PRAGMA encoding=utf16le"); 1855 runSql(p, "ATTACH %Q AS 'replica'", p->zReplica); 1856 if( p->wrongEncoding ){ 1857 p->wrongEncoding = 0; 1858 runSql(p, "PRAGMA encoding=utf16be"); 1859 runSql(p, "Attach %Q AS 'replica'", p->zReplica); 1860 } 1861 } 1862 if( p->nErr ){ 1863 closeDb(p); 1864 pIns = 0; 1865 break; 1866 } 1867 runSql(p, 1868 "CREATE TABLE sendHash(" 1869 " fpg INTEGER PRIMARY KEY," /* The page number of hash to send */ 1870 " npg INT" /* Number of pages in this hash */ 1871 ")" 1872 ); 1873 hashRegister(p->db); 1874 if( runSqlReturnUInt(p, &nRPage, "PRAGMA replica.page_count") ){ 1875 break; 1876 } 1877 if( nRPage==0 ){ 1878 runSql(p, "PRAGMA replica.page_size=%u", szOPage); 1879 runSql(p, "SELECT * FROM replica.sqlite_schema"); 1880 } 1881 runSql(p, "BEGIN IMMEDIATE"); 1882 runSqlReturnText(p, buf, "PRAGMA replica.journal_mode"); 1883 if( strcmp(buf, "wal")!=0 ){ 1884 if( p->bWalOnly && nRPage>0 ){ 1885 reportError(p, "replica is not in WAL mode"); 1886 break; 1887 } 1888 eJMode = 1; /* Non-WAL mode prior to sync */ 1889 }else{ 1890 eJMode = 2; /* WAL-mode prior to sync */ 1891 } 1892 runSqlReturnUInt(p, &nRPage, "PRAGMA replica.page_count"); 1893 runSqlReturnUInt(p, &szRPage, "PRAGMA replica.page_size"); 1894 if( szRPage!=szOPage ){ 1895 reportError(p, "page size mismatch; origin is %d bytes and " 1896 "replica is %d bytes", szOPage, szRPage); 1897 break; 1898 } 1899 if( p->iProtocol<2 || nRPage<=100 ){ 1900 runSql(p, 1901 "WITH RECURSIVE c(n) AS" 1902 "(VALUES(1) UNION ALL SELECT n+1 FROM c WHERE n<%d)" 1903 "INSERT INTO sendHash(fpg, npg) SELECT n, 1 FROM c", 1904 nRPage); 1905 }else{ 1906 runSql(p,"INSERT INTO sendHash VALUES(1,1)"); 1907 subdivideHashRange(p, 2, nRPage-1); 1908 } 1909 sendHashMessages(p, 1, 1); 1910 runSql(p, "PRAGMA writable_schema=ON"); 1911 break; 1912 } 1913 case ORIGIN_DETAIL: { 1914 unsigned int fpg, npg; 1915 readUint32(p, &fpg); 1916 readUint32(p, &npg); 1917 if( p->zDebugFile ){ 1918 debugMessage(p, "<- ORIGIN_DETAIL %u %u\n", fpg, npg); 1919 } 1920 subdivideHashRange(p, fpg, npg); 1921 break; 1922 } 1923 case ORIGIN_READY: { 1924 if( p->zDebugFile ){ 1925 debugMessage(p, "<- ORIGIN_READY\n"); 1926 } 1927 sendHashMessages(p, 0, 0); 1928 break; 1929 } 1930 case ORIGIN_TXN: { 1931 unsigned int nOPage = 0; 1932 readUint32(p, &nOPage); 1933 if( p->zDebugFile ){ 1934 debugMessage(p, "<- ORIGIN_TXN %u\n", nOPage); 1935 } 1936 if( pIns==0 ){ 1937 /* Nothing has changed */ 1938 runSql(p, "COMMIT"); 1939 }else if( p->nErr ){ 1940 runSql(p, "ROLLBACK"); 1941 }else{ 1942 if( nOPage<0xffffffff ){ 1943 int rc; 1944 sqlite3_bind_int64(pIns, 1, nOPage+1); 1945 sqlite3_bind_null(pIns, 2); 1946 rc = sqlite3_step(pIns); 1947 if( rc!=SQLITE_DONE ){ 1948 reportError(p, 1949 "SQL statement [%s] failed (pgno=%u, data=NULL): %s", 1950 sqlite3_sql(pIns), nOPage, sqlite3_errmsg(p->db)); 1951 } 1952 sqlite3_reset(pIns); 1953 } 1954 p->nPage = nOPage; 1955 runSql(p, "COMMIT"); 1956 } 1957 break; 1958 } 1959 case ORIGIN_PAGE: { 1960 unsigned int pgno = 0; 1961 int rc; 1962 readUint32(p, &pgno); 1963 if( p->zDebugFile ){ 1964 debugMessage(p, "<- ORIGIN_PAGE %u\n", pgno); 1965 } 1966 if( p->nErr ) break; 1967 if( pIns==0 ){ 1968 pIns = prepareStmt(p, 1969 "INSERT INTO sqlite_dbpage(pgno,data,schema)VALUES(?1,?2,'replica')" 1970 ); 1971 if( pIns==0 ) break; 1972 } 1973 readBytes(p, p->szPage, buf); 1974 if( p->nErr ) break; 1975 if( pgno==1 && eJMode==2 && buf[18]==1 ){ 1976 /* Do not switch the replica out of WAL mode if it started in 1977 ** WAL mode */ 1978 buf[18] = buf[19] = 2; 1979 } 1980 p->nPageSent++; 1981 sqlite3_bind_int64(pIns, 1, pgno); 1982 sqlite3_bind_blob(pIns, 2, buf, p->szPage, SQLITE_STATIC); 1983 rc = sqlite3_step(pIns); 1984 if( rc!=SQLITE_DONE ){ 1985 reportError(p, "SQL statement [%s] failed (pgno=%u): %s", 1986 sqlite3_sql(pIns), pgno, sqlite3_errmsg(p->db)); 1987 } 1988 sqlite3_reset(pIns); 1989 break; 1990 } 1991 default: { 1992 reportError(p, "Unknown message 0x%02x %lld bytes into conversation", 1993 c, p->nIn); 1994 break; 1995 } 1996 } 1997 } 1998 1999 closeDb(p); 2000 } 2001 2002 /* 2003 ** The argument might be -vvv...vv with any number of "v"s. Return 2004 ** the number of "v"s. Return 0 if the argument is not a -vvv...v. 2005 */ 2006 static int numVs(const char *z){ 2007 int n = 0; 2008 if( z[0]!='-' ) return 0; 2009 z++; 2010 if( z[0]=='-' ) z++; 2011 while( z[0]=='v' ){ n++; z++; } 2012 if( z[0]==0 ) return n; 2013 return 0; 2014 } 2015 2016 /* 2017 ** Get the argument to an --option. Throw an error and die if no argument 2018 ** is available. 2019 */ 2020 static const char *cmdline_option_value(int argc, const char * const*argv, 2021 int i){ 2022 if( i==argc ){ 2023 fprintf(stderr,"%s: Error: missing argument to %s\n", 2024 argv[0], argv[argc-1]); 2025 exit(1); 2026 } 2027 return argv[i]; 2028 } 2029 2030 /* 2031 ** Return the current time in milliseconds since the Julian epoch. 2032 */ 2033 sqlite3_int64 currentTime(void){ 2034 sqlite3_int64 now = 0; 2035 sqlite3_vfs *pVfs = sqlite3_vfs_find(0); 2036 if( pVfs && pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64!=0 ){ 2037 pVfs->xCurrentTimeInt64(pVfs, &now); 2038 } 2039 return now; 2040 } 2041 2042 /* 2043 ** Input string zIn might be in any of these formats: 2044 ** 2045 ** (1) PATH 2046 ** (2) HOST:PATH 2047 ** (3) USER@HOST:PATH 2048 ** 2049 ** For format 1, return NULL. For formats 2 and 3, return 2050 ** a pointer to the ':' character that separates the hostname 2051 ** from the path. 2052 */ 2053 static char *hostSeparator(const char *zIn){ 2054 char *zPath = strchr(zIn, ':'); 2055 if( zPath==0 ) return 0; 2056 #ifdef _WIN32 2057 if( isalpha(zIn[0]) && zIn[1]==':' && (zIn[2]=='/' || zIn[2]=='\\') ){ 2058 return 0; 2059 } 2060 #endif 2061 while( zInPROTOCOL_VERSION ){ 2144 ctx.iProtocol = PROTOCOL_VERSION; 2145 } 2146 continue; 2147 } 2148 if( strcmp(z, "-ssh")==0 ){ 2149 zSsh = cli_opt_val; 2150 continue; 2151 } 2152 if( strcmp(z, "-port")==0 || strcmp(z, "-p")==0 ){ 2153 const char *zPort = cli_opt_val; 2154 iPort = atoi(zPort); 2155 if( iPort<1 || iPort>65535 ){ 2156 fprintf(stderr, "invalid TCP port number: \"%s\"\n", zPort); 2157 return 1; 2158 } 2159 continue; 2160 } 2161 if( strcmp(z, "-exe")==0 ){ 2162 zExe = cli_opt_val; 2163 if( need_escape(zExe) ){ 2164 fprintf(stderr, "executable name uses special characters: \"%s\"\n", 2165 zExe); 2166 return 1; 2167 } 2168 continue; 2169 } 2170 if( strcmp(z, "-wal-only")==0 ){ 2171 ctx.bWalOnly = 1; 2172 continue; 2173 } 2174 if( strcmp(z, "-encoded-filenames")==0 ){ 2175 /* Internal use only */ 2176 nEncoded = atoi(cli_opt_val); 2177 if( nEncoded<1 ){ 2178 fprintf(stderr, "invalid argument to %s\n", argv[i-1]); 2179 return 1; 2180 } 2181 continue; 2182 } 2183 if( strcmp(z, "-version")==0 ){ 2184 printf("%s\n", sqlite3_sourceid()); 2185 return 0; 2186 } 2187 if( strcmp(z, "-help")==0 || strcmp(z, "--help")==0 2188 || strcmp(z, "-?")==0 2189 ){ 2190 printf("%s", zUsage); 2191 return 0; 2192 } 2193 if( strcmp(z, "-logfile")==0 ){ 2194 /* DEBUG OPTION: --logfile FILENAME 2195 ** Cause all local output traffic to be duplicated in FILENAME */ 2196 const char *zLog = cli_opt_val; 2197 if( ctx.pLog ) fclose(ctx.pLog); 2198 ctx.pLog = fopen(zLog, "wb"); 2199 if( ctx.pLog==0 ){ 2200 fprintf(stderr, "cannot open \"%s\" for writing\n", argv[i]); 2201 return 1; 2202 } 2203 continue; 2204 } 2205 if( strcmp(z, "-errorfile")==0 ){ 2206 /* DEBUG OPTION: --errorfile FILENAME 2207 ** Error messages on the local side are written into FILENAME */ 2208 ctx.zErrFile = cli_opt_val; 2209 continue; 2210 } 2211 if( strcmp(z, "-remote-errorfile")==0 ){ 2212 /* DEBUG OPTION: --remote-errorfile FILENAME 2213 ** Error messages on the remote side are written into FILENAME on 2214 ** the remote side. */ 2215 zRemoteErrFile = cli_opt_val; 2216 continue; 2217 } 2218 if( strcmp(z, "-debugfile")==0 ){ 2219 /* DEBUG OPTION: --debugfile FILENAME 2220 ** Debugging messages on the local side are written into FILENAME */ 2221 ctx.zDebugFile = cli_opt_val; 2222 continue; 2223 } 2224 if( strcmp(z, "-remote-debugfile")==0 ){ 2225 /* DEBUG OPTION: --remote-debugfile FILENAME 2226 ** Error messages on the remote side are written into FILENAME on 2227 ** the remote side. */ 2228 zRemoteDebugFile = cli_opt_val; 2229 continue; 2230 } 2231 if( strcmp(z,"-commcheck")==0 ){ /* DEBUG ONLY */ 2232 /* Run a communication check with the remote side. Do not attempt 2233 ** to exchange any database connection */ 2234 ctx.bCommCheck = 1; 2235 continue; 2236 } 2237 if( strcmp(z,"-arg-escape-check")==0 ){ /* DEBUG ONLY */ 2238 /* Test the append_escaped_arg() routine by using it to render a 2239 ** copy of the input command-line, assuming all arguments except 2240 ** this one are filenames. */ 2241 sqlite3_str *pStr = sqlite3_str_new(0); 2242 int k; 2243 for(k=0; k0 ) sqlite3_str_appendf(pStr, " -p %d", iPort); 2336 sqlite3_str_appendf(pStr, " -e none"); 2337 append_escaped_arg(pStr, ctx.zOrigin, 1); 2338 if( iRetry ) add_path_argument(pStr); 2339 append_escaped_arg(pStr, zExe, 1); 2340 append_escaped_arg(pStr, "--origin", 0); 2341 if( ctx.bCommCheck ){ 2342 append_escaped_arg(pStr, "--commcheck", 0); 2343 if( ctx.eVerbose==0 ) ctx.eVerbose = 1; 2344 } 2345 if( zRemoteErrFile ){ 2346 append_escaped_arg(pStr, "--errorfile", 0); 2347 append_escaped_arg(pStr, zRemoteErrFile, 2); 2348 } 2349 if( zRemoteDebugFile ){ 2350 append_escaped_arg(pStr, "--debugfile", 0); 2351 append_escaped_arg(pStr, zRemoteDebugFile, 2); 2352 } 2353 if( ctx.bWalOnly ){ 2354 append_escaped_arg(pStr, "--wal-only", 0); 2355 } 2356 append_escaped_arg(pStr, zDiv, 2); 2357 append_escaped_arg(pStr, file_tail(ctx.zReplica), 2); 2358 if( nHexEncode>0 ){ 2359 sqlite3_str_appendf(pStr, " --encoded-filenames %d", nHexEncode); 2360 } 2361 if( ctx.eVerbose<2 && iRetry==0 ){ 2362 append_escaped_arg(pStr, "2>/dev/null", 0); 2363 } 2364 zCmd = sqlite3_str_finish(pStr); 2365 if( ctx.eVerbose>=2 ) printf("%s\n", zCmd); 2366 if( popen2(zCmd, &ctx.pIn, &ctx.pOut, &childPid, 0) ){ 2367 if( iRetry>=1 ){ 2368 fprintf(stderr, "Could not start auxiliary process: %s\n", zCmd); 2369 return 1; 2370 } 2371 if( ctx.eVerbose>=2 ){ 2372 printf("ssh FAILED. Retry with a PATH= argument...\n"); 2373 } 2374 continue; 2375 } 2376 replicaSide(&ctx); 2377 if( ctx.nHashSent==0 && iRetry==0 ) continue; 2378 break; 2379 } 2380 }else if( (zDiv = hostSeparator(ctx.zReplica))!=0 ){ 2381 /* Local ORIGIN and remote REPLICA */ 2382 int iRetry; 2383 *(zDiv++) = 0; 2384 for(iRetry=0; 1 /*exit-by-break*/; iRetry++){ 2385 sqlite3_str *pStr = sqlite3_str_new(0); 2386 append_escaped_arg(pStr, zSsh, 1); 2387 if( iPort>0 ) sqlite3_str_appendf(pStr, " -p %d", iPort); 2388 sqlite3_str_appendf(pStr, " -e none"); 2389 append_escaped_arg(pStr, ctx.zReplica, 1); 2390 if( iRetry==1 ) add_path_argument(pStr); 2391 append_escaped_arg(pStr, zExe, 1); 2392 append_escaped_arg(pStr, "--replica", 0); 2393 if( ctx.bCommCheck ){ 2394 append_escaped_arg(pStr, "--commcheck", 0); 2395 if( ctx.eVerbose==0 ) ctx.eVerbose = 1; 2396 } 2397 if( zRemoteErrFile ){ 2398 append_escaped_arg(pStr, "--errorfile", 0); 2399 append_escaped_arg(pStr, zRemoteErrFile, 2); 2400 } 2401 if( zRemoteDebugFile ){ 2402 append_escaped_arg(pStr, "--debugfile", 0); 2403 append_escaped_arg(pStr, zRemoteDebugFile, 2); 2404 } 2405 if( ctx.bWalOnly ){ 2406 append_escaped_arg(pStr, "--wal-only", 0); 2407 } 2408 append_escaped_arg(pStr, file_tail(ctx.zOrigin), 2); 2409 append_escaped_arg(pStr, zDiv, 2); 2410 if( nHexEncode>0 ){ 2411 sqlite3_str_appendf(pStr, " --encoded-filenames %d", nHexEncode); 2412 } 2413 if( ctx.eVerbose<2 && iRetry==0 ){ 2414 append_escaped_arg(pStr, "2>/dev/null", 0); 2415 } 2416 zCmd = sqlite3_str_finish(pStr); 2417 if( ctx.eVerbose>=2 ) printf("%s\n", zCmd); 2418 if( popen2(zCmd, &ctx.pIn, &ctx.pOut, &childPid, 0) ){ 2419 if( iRetry>=1 ){ 2420 fprintf(stderr, "Could not start auxiliary process: %s\n", zCmd); 2421 return 1; 2422 }else if( ctx.eVerbose>=2 ){ 2423 printf("ssh FAILED. Retry with a PATH= argument...\n"); 2424 } 2425 continue; 2426 } 2427 originSide(&ctx); 2428 if( ctx.nHashSent==0 && iRetry==0 ) continue; 2429 break; 2430 } 2431 }else{ 2432 /* Local ORIGIN and REPLICA */ 2433 sqlite3_str *pStr = sqlite3_str_new(0); 2434 append_escaped_arg(pStr, argv[0], 1); 2435 append_escaped_arg(pStr, "--replica", 0); 2436 if( ctx.bCommCheck ){ 2437 append_escaped_arg(pStr, "--commcheck", 0); 2438 } 2439 if( zRemoteErrFile ){ 2440 append_escaped_arg(pStr, "--errorfile", 0); 2441 append_escaped_arg(pStr, zRemoteErrFile, 2); 2442 } 2443 if( zRemoteDebugFile ){ 2444 append_escaped_arg(pStr, "--debugfile", 0); 2445 append_escaped_arg(pStr, zRemoteDebugFile, 2); 2446 } 2447 append_escaped_arg(pStr, ctx.zOrigin, 2); 2448 append_escaped_arg(pStr, ctx.zReplica, 2); 2449 if( nHexEncode>0 ){ 2450 sqlite3_str_appendf(pStr, " --encoded-filenames %d", nHexEncode); 2451 } 2452 zCmd = sqlite3_str_finish(pStr); 2453 if( ctx.eVerbose>=2 ) printf("%s\n", zCmd); 2454 if( popen2(zCmd, &ctx.pIn, &ctx.pOut, &childPid, 0) ){ 2455 fprintf(stderr, "Could not start auxiliary process: %s\n", zCmd); 2456 return 1; 2457 } 2458 originSide(&ctx); 2459 } 2460 ctx.nErr += !!pclose2(ctx.pIn, ctx.pOut, childPid); 2461 if( ctx.pLog ) fclose(ctx.pLog); 2462 tmEnd = currentTime(); 2463 tmElapse = tmEnd - tmStart; /* Elapse time in milliseconds */ 2464 if( ctx.nErr ){ 2465 printf("Databases were not synced due to errors\n"); 2466 } 2467 if( ctx.eVerbose>=1 ){ 2468 char *zMsg; 2469 sqlite3_int64 szTotal = (sqlite3_int64)ctx.nPage*(sqlite3_int64)ctx.szPage; 2470 sqlite3_int64 nIO = ctx.nOut +ctx.nIn; 2471 zMsg = sqlite3_mprintf("sent %,lld bytes, received %,lld bytes", 2472 ctx.nOut, ctx.nIn); 2473 printf("%s", zMsg); 2474 sqlite3_free(zMsg); 2475 if( tmElapse>0 ){ 2476 zMsg = sqlite3_mprintf(", %,.2f bytes/sec", 2477 1000.0*(double)nIO/(double)tmElapse); 2478 printf("%s\n", zMsg); 2479 sqlite3_free(zMsg); 2480 }else{ 2481 printf("\n"); 2482 } 2483 if( ctx.nErr==0 ){ 2484 if( nIO<=szTotal && nIO>0 ){ 2485 zMsg = sqlite3_mprintf("total size %,lld speedup is %.2f", 2486 szTotal, (double)szTotal/(double)nIO); 2487 }else{ 2488 zMsg = sqlite3_mprintf("total size %,lld", szTotal); 2489 } 2490 printf("%s\n", zMsg); 2491 sqlite3_free(zMsg); 2492 } 2493 if( ctx.eVerbose>=3 ){ 2494 printf("hashes: %lld hash-rounds: %d" 2495 " page updates: %d protocol: %d\n", 2496 ctx.nHashSent, ctx.nRound, ctx.nPageSent, ctx.iProtocol); 2497 } 2498 } 2499 sqlite3_free(zCmd); 2500 if( pIn!=0 && pOut!=0 ){ 2501 pclose2(pIn, pOut, childPid); 2502 } 2503 sqlite3_shutdown(); 2504 return ctx.nErr; 2505 }