forked from mattn/go-sqlite3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlite_rsync.c
More file actions
2799 lines (2712 loc) · 75.6 KB
/
sqlite_rsync.c
File metadata and controls
2799 lines (2712 loc) · 75.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
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
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define SQLITE_ENABLE_DBPAGE_VTAB 1
#define SQLITE_RSYNC_NO_MAIN
#define SQLITE_RSYNC_USE_H
#ifndef SQLITE_RSYNC_C_INCLUDED
#define SQLITE_RSYNC_C_INCLUDED
/*
** 2024-09-10
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This is a utility program that makes a copy of a live SQLite database
** using a bandwidth-efficient protocol, similar to "rsync".
*/
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <stdarg.h>
#include "sqlite_rsync.h"
static const char zUsage[] =
"sqlite3_rsync ORIGIN REPLICA ?OPTIONS?\n"
"\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"
"\n"
"OPTIONS:\n"
"\n"
" --exe PATH Name of the sqlite3_rsync program on the remote side\n"
" --help Show this help screen\n"
" --protocol N Use sync protocol version N.\n"
" --ssh PATH Name of the SSH program used to reach the remote side\n"
" -v Verbose. Multiple v's for increasing output\n"
" --version Show detailed version information\n"
" --wal-only Do not sync unless both databases are in WAL mode\n";
#ifndef SQLITE_RSYNC_USE_H
typedef unsigned char u8;
typedef sqlite3_uint64 u64;
#endif
/* Context for the run */
#ifndef SQLITE_RSYNC_USE_H
typedef struct SQLiteRsync SQLiteRsync;
struct SQLiteRsync
{
const char *zOrigin; /* Name of the origin */
const char *zReplica; /* Name of the replica */
const char *zErrFile; /* Append error messages to this file */
const char *zDebugFile; /* Append debugging messages to this file */
FILE *pOut; /* Transmit to the other side */
FILE *pIn; /* Receive from the other side */
FILE *pLog; /* Duplicate output here if not NULL */
FILE *pDebug; /* Write debug info here if not NULL */
sqlite3 *db; /* Database connection */
int nErr; /* Number of errors encountered */
int nWrErr; /* Number of failed attempts to write on the pipe */
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 */
u8 isReplica; /* True if running on the replica side */
u8 iProtocol; /* Protocol version number */
u8 wrongEncoding; /* ATTACH failed due to wrong encoding */
u8 bWalOnly; /* Require WAL mode */
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 */
u64 nHashSent; /* Hashes sent (replica to origin) */
unsigned int nRound; /* Number of hash batches (replica to origin) */
unsigned int nPageSent; /* Page contents sent (origin to replica) */
};
#endif
/* The version number of the protocol. Sent in the *_BEGIN message
** to verify that both sides speak the same dialect.
*/
#define PROTOCOL_VERSION 2
/* Magic numbers to identify particular messages sent over the wire.
*/
/**** Baseline: protocol version 1 ****/
#define ORIGIN_BEGIN 0x41 /* Initial message */
#define ORIGIN_END 0x42 /* Time to quit */
#define ORIGIN_ERROR 0x43 /* Error message from the remote */
#define ORIGIN_PAGE 0x44 /* New page data */
#define ORIGIN_TXN 0x45 /* Transaction commit */
#define ORIGIN_MSG 0x46 /* Informational message */
/**** Added in protocol version 2 ****/
#define ORIGIN_DETAIL 0x47 /* Request finer-grain hash info */
#define ORIGIN_READY 0x48 /* Ready for next round of hash exchanges */
/**** Baseline: protocol version 1 ****/
#define REPLICA_BEGIN 0x61 /* Welcome message */
#define REPLICA_ERROR 0x62 /* Error. Report and quit. */
#define REPLICA_END 0x63 /* Replica wants to stop */
#define REPLICA_HASH 0x64 /* One or more pages hashes to report */
#define REPLICA_READY 0x65 /* Read to receive page content */
#define REPLICA_MSG 0x66 /* Informational message */
/**** Added in protocol version 2 ****/
#define REPLICA_CONFIG 0x67 /* Hash exchange configuration */
/****************************************************************************
** Beginning of the popen2() implementation copied from Fossil *************
****************************************************************************/
#ifdef _WIN32
#include <windows.h>
#include <io.h>
#include <fcntl.h>
/*
** Print a fatal error and quit.
*/
static void win32_fatal_error(const char *zMsg)
{
fprintf(stderr, "%s", zMsg);
exit(1);
}
extern int _open_osfhandle(intptr_t, int);
#else
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#endif
/*
** The following macros are used to cast pointers to integers and
** integers to pointers. The way you do this varies from one compiler
** to the next, so we have developed the following set of #if statements
** to generate appropriate macros for a wide range of compilers.
**
** The correct "ANSI" way to do this is to use the intptr_t type.
** Unfortunately, that typedef is not available on all compilers, or
** if it is available, it requires an #include of specific headers
** that vary from one machine to the next.
**
** This code is copied out of SQLite.
*/
#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
#define INT_TO_PTR(X) ((void *)(__PTRDIFF_TYPE__)(X))
#define PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
#elif !defined(__GNUC__) /* Works for compilers other than LLVM */
#define INT_TO_PTR(X) ((void *)&((char *)0)[X])
#define PTR_TO_INT(X) ((int)(((char *)X) - (char *)0))
#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
#define INT_TO_PTR(X) ((void *)(intptr_t)(X))
#define PTR_TO_INT(X) ((int)(intptr_t)(X))
#else /* Generates a warning - but it always works */
#define INT_TO_PTR(X) ((void *)(X))
#define PTR_TO_INT(X) ((int)(X))
#endif
/* Register SQL functions provided by ext/misc/sha1.c */
#ifndef SQLITE_RSYNC_USE_H
extern int sqlite3_sha_init(
sqlite3 *db,
char **pzErrMsg,
const sqlite3_api_routines *pApi);
#endif
#ifdef _WIN32
/*
** On windows, create a child process and specify the stdin, stdout,
** and stderr channels for that process to use.
**
** Return the number of errors.
*/
static int win32_create_child_process(
wchar_t *zCmd, /* The command that the child process will run */
HANDLE hIn, /* Standard input */
HANDLE hOut, /* Standard output */
HANDLE hErr, /* Standard error */
DWORD *pChildPid /* OUT: Child process handle */
)
{
STARTUPINFOW si;
PROCESS_INFORMATION pi;
BOOL rc;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES;
SetHandleInformation(hIn, HANDLE_FLAG_INHERIT, TRUE);
si.hStdInput = hIn;
SetHandleInformation(hOut, HANDLE_FLAG_INHERIT, TRUE);
si.hStdOutput = hOut;
SetHandleInformation(hErr, HANDLE_FLAG_INHERIT, TRUE);
si.hStdError = hErr;
rc = CreateProcessW(
NULL, /* Application Name */
zCmd, /* Command-line */
NULL, /* Process attributes */
NULL, /* Thread attributes */
TRUE, /* Inherit Handles */
0, /* Create flags */
NULL, /* Environment */
NULL, /* Current directory */
&si, /* Startup Info */
&pi /* Process Info */
);
if (rc)
{
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
*pChildPid = pi.dwProcessId;
}
else
{
win32_fatal_error("cannot create child process");
}
return rc != 0;
}
void *win32_utf8_to_unicode(const char *zUtf8)
{
int nByte = MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, 0, 0);
wchar_t *zUnicode = malloc(nByte * 2);
MultiByteToWideChar(CP_UTF8, 0, zUtf8, -1, zUnicode, nByte);
return zUnicode;
}
#endif
/*
** Create a child process running shell command "zCmd". *ppOut is
** a FILE that becomes the standard input of the child process.
** (The caller writes to *ppOut in order to send text to the child.)
** *ppIn is stdout from the child process. (The caller
** reads from *ppIn in order to receive input from the child.)
** Note that *ppIn is an unbuffered file descriptor, not a FILE.
** The process ID of the child is written into *pChildPid.
**
** Return the number of errors.
*/
static int popen2(
const char *zCmd, /* Command to run in the child process */
FILE **ppIn, /* Read from child using this file descriptor */
FILE **ppOut, /* Write to child using this file descriptor */
int *pChildPid, /* PID of the child process */
int bDirect /* 0: run zCmd as a shell cmd. 1: run directly */
)
{
#ifdef _WIN32
HANDLE hStdinRd, hStdinWr, hStdoutRd, hStdoutWr, hStderr;
SECURITY_ATTRIBUTES saAttr;
DWORD childPid = 0;
int fd;
saAttr.nLength = sizeof(saAttr);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
hStderr = GetStdHandle(STD_ERROR_HANDLE);
if (!CreatePipe(&hStdoutRd, &hStdoutWr, &saAttr, 4096))
{
win32_fatal_error("cannot create pipe for stdout");
}
SetHandleInformation(hStdoutRd, HANDLE_FLAG_INHERIT, FALSE);
if (!CreatePipe(&hStdinRd, &hStdinWr, &saAttr, 4096))
{
win32_fatal_error("cannot create pipe for stdin");
}
SetHandleInformation(hStdinWr, HANDLE_FLAG_INHERIT, FALSE);
win32_create_child_process(win32_utf8_to_unicode(zCmd),
hStdinRd, hStdoutWr, hStderr, &childPid);
*pChildPid = childPid;
fd = _open_osfhandle(PTR_TO_INT(hStdoutRd), 0);
*ppIn = fdopen(fd, "rb");
fd = _open_osfhandle(PTR_TO_INT(hStdinWr), 0);
*ppOut = _fdopen(fd, "wb");
CloseHandle(hStdinRd);
CloseHandle(hStdoutWr);
return 0;
#else
int pin[2], pout[2];
*ppIn = 0;
*ppOut = 0;
*pChildPid = 0;
if (pipe(pin) < 0)
{
return 1;
}
if (pipe(pout) < 0)
{
close(pin[0]);
close(pin[1]);
return 1;
}
*pChildPid = fork();
if (*pChildPid < 0)
{
close(pin[0]);
close(pin[1]);
close(pout[0]);
close(pout[1]);
*pChildPid = 0;
return 1;
}
signal(SIGPIPE, SIG_IGN);
if (*pChildPid == 0)
{
int fd;
/* This is the child process */
close(0);
fd = dup(pout[0]);
if (fd != 0)
{
fprintf(stderr, "popen2() failed to open file descriptor 0");
exit(1);
}
close(pout[0]);
close(pout[1]);
close(1);
fd = dup(pin[1]);
if (fd != 1)
{
fprintf(stderr, "popen() failed to open file descriptor 1");
exit(1);
}
close(pin[0]);
close(pin[1]);
if (bDirect)
{
execl(zCmd, zCmd, (char *)0);
}
else
{
execl("/bin/sh", "/bin/sh", "-c", zCmd, (char *)0);
}
return 1;
}
else
{
/* This is the parent process */
close(pin[1]);
*ppIn = fdopen(pin[0], "r");
close(pout[0]);
*ppOut = fdopen(pout[1], "w");
return 0;
}
#endif
}
/*
** Close the connection to a child process previously created using
** popen2().
*/
static void pclose2(FILE *pIn, FILE *pOut, int childPid)
{
#ifdef _WIN32
/* Not implemented, yet */
fclose(pIn);
fclose(pOut);
#else
fclose(pIn);
fclose(pOut);
while (waitpid(0, 0, WNOHANG) > 0)
{
}
#endif
}
/*****************************************************************************
** End of the popen2() implementation copied from Fossil *********************
*****************************************************************************/
/*****************************************************************************
** Beginning of the append_escaped_arg() routine, adapted from the Fossil **
** subroutine nameed blob_append_escaped_arg() **
*****************************************************************************/
/*
** ASCII (for reference):
** x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf
** 0x ^` ^a ^b ^c ^d ^e ^f ^g \b \t \n () \f \r ^n ^o
** 1x ^p ^q ^r ^s ^t ^u ^v ^w ^x ^y ^z ^{ ^| ^} ^~ ^
** 2x () ! " # $ % & ' ( ) * + , - . /
** 3x 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
** 4x @ A B C D E F G H I J K L M N O
** 5x P Q R S T U V W X Y Z [ \ ] ^ _
** 6x ` a b c d e f g h i j k l m n o
** 7x p q r s t u v w x y z { | } ~ ^_
*/
/*
** Meanings for bytes in a filename:
**
** 0 Ordinary character. No encoding required
** 1 Needs to be escaped
** 2 Illegal character. Do not allow in a filename
** 3 First byte of a 2-byte UTF-8
** 4 First byte of a 3-byte UTF-8
** 5 First byte of a 4-byte UTF-8
*/
static const char aSafeChar[256] = {
#ifdef _WIN32
/* Windows
** Prohibit: all control characters, including tab, \r and \n.
** Escape: (space) " # $ % & ' ( ) * ; < > ? [ ] ^ ` { | }
*/
/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x */
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 1x */
1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 2x */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, /* 3x */
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, /* 5x */
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 6x */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, /* 7x */
#else
/* Unix
** Prohibit: all control characters, including tab, \r and \n
** Escape: (space) ! " # $ % & ' ( ) * ; < > ? [ \ ] ^ ` { | }
*/
/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 0x */
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 1x */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 2x */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, /* 3x */
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, /* 5x */
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 6x */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, /* 7x */
#endif
/* all bytes 0x80 through 0xbf are unescaped, being secondary
** bytes to UTF8 characters. Bytes 0xc0 through 0xff are the
** first byte of a UTF8 character and do get escaped */
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 8x */
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* 9x */
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* ax */
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* bx */
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* cx */
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* dx */
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, /* ex */
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 /* fx */
};
/*
** pStr is a shell command under construction. This routine safely
** appends filename argument zIn. It returns 0 on success or non-zero
** on any error.
**
** The argument is escaped if it contains white space or other characters
** that need to be escaped for the shell. If zIn contains characters
** that cannot be safely escaped, then throw a fatal error.
**
** If the isFilename argument is true, then the argument is expected
** to be a filename. As shell commands commonly have command-line
** options that begin with "-" and since we do not want an attacker
** to be able to invoke these switches using filenames that begin
** with "-", if zIn begins with "-", prepend an additional "./"
** (or ".\\" on Windows).
*/
int append_escaped_arg(sqlite3_str *pStr, const char *zIn, int isFilename)
{
int i;
unsigned char c;
int needEscape = 0;
int n = sqlite3_str_length(pStr);
char *z = sqlite3_str_value(pStr);
/* Look for illegal byte-sequences and byte-sequences that require
** escaping. No control-characters are allowed. All spaces and
** non-ASCII unicode characters and some punctuation characters require
** escaping. */
for (i = 0; (c = (unsigned char)zIn[i]) != 0; i++)
{
if (aSafeChar[c])
{
unsigned char x = aSafeChar[c];
needEscape = 1;
if (x == 2)
{
/* Bad ASCII character */
return 1;
}
else if (x > 2)
{
if ((zIn[i + 1] & 0xc0) != 0x80 || (x >= 4 && (zIn[i + 2] & 0xc0) != 0x80) || (x == 5 && (zIn[i + 3] & 0xc0) != 0x80))
{
/* Bad UTF8 character */
return 1;
}
i += x - 2;
}
}
}
/* Separate from the previous argument by a space */
if (n > 0 && !isspace(z[n - 1]))
{
sqlite3_str_appendchar(pStr, 1, ' ');
}
/* Check for characters that need quoting */
if (!needEscape)
{
if (isFilename && zIn[0] == '-')
{
sqlite3_str_appendchar(pStr, 1, '.');
#if defined(_WIN32)
sqlite3_str_appendchar(pStr, 1, '\\');
#else
sqlite3_str_appendchar(pStr, 1, '/');
#endif
}
sqlite3_str_appendall(pStr, zIn);
}
else
{
#if defined(_WIN32)
/* Quoting strategy for windows:
** Put the entire name inside of "...". Any " characters within
** the name get doubled.
*/
sqlite3_str_appendchar(pStr, 1, '"');
if (isFilename && zIn[0] == '-')
{
sqlite3_str_appendchar(pStr, 1, '.');
sqlite3_str_appendchar(pStr, 1, '\\');
}
else if (zIn[0] == '/')
{
sqlite3_str_appendchar(pStr, 1, '.');
}
for (i = 0; (c = (unsigned char)zIn[i]) != 0; i++)
{
sqlite3_str_appendchar(pStr, 1, (char)c);
if (c == '"')
sqlite3_str_appendchar(pStr, 1, '"');
if (c == '\\')
sqlite3_str_appendchar(pStr, 1, '\\');
if (c == '%' && isFilename)
sqlite3_str_append(pStr, "%cd:~,%", 7);
}
sqlite3_str_appendchar(pStr, 1, '"');
#else
/* Quoting strategy for unix:
** If the name does not contain ', then surround the whole thing
** with '...'. If there is one or more ' characters within the
** name, then put \ before each special character.
*/
if (strchr(zIn, '\''))
{
if (isFilename && zIn[0] == '-')
{
sqlite3_str_appendchar(pStr, 1, '.');
sqlite3_str_appendchar(pStr, 1, '/');
}
for (i = 0; (c = (unsigned char)zIn[i]) != 0; i++)
{
if (aSafeChar[c] && aSafeChar[c] != 2)
{
sqlite3_str_appendchar(pStr, 1, '\\');
}
sqlite3_str_appendchar(pStr, 1, (char)c);
}
}
else
{
sqlite3_str_appendchar(pStr, 1, '\'');
if (isFilename && zIn[0] == '-')
{
sqlite3_str_appendchar(pStr, 1, '.');
sqlite3_str_appendchar(pStr, 1, '/');
}
sqlite3_str_appendall(pStr, zIn);
sqlite3_str_appendchar(pStr, 1, '\'');
}
#endif
}
return 0;
}
/* Add an approprate PATH= argument to the SSH command under construction
** in pStr
**
** About This Feature
** ==================
**
** On some ssh servers (Macs in particular are guilty of this) the PATH
** variable in the shell that runs the command that is sent to the remote
** host contains a limited number of read-only system directories:
**
** /usr/bin:/bin:/usr/sbin:/sbin
**
** The sqlite3_rsync executable cannot be installed into any of those
** directories because they are locked down, and so the "sqlite3_rsync"
** command cannot run.
**
** To work around this, the sqlite3_rsync command is prefixed with a PATH=
** argument, inserted by this function, to augment the PATH with additional
** directories in which the sqlite3_rsync executable can be installed.
**
** But other ssh servers are confused by this initial PATH= argument.
** Some ssh servers have a list of programs that they are allowed to run
** and will fail if the first argument is not on that list, and PATH=....
** is not on that list.
**
** So that sqlite3_rsync can invoke itself on a remote system using ssh
** on a variety of platforms, the following algorithm is used:
**
** * First try running the sqlite3_rsync without any PATH= argument.
** If that works (and it does on a majority of systems) then we are
** done.
**
** * If the first attempt fails, then try again after adding the
** PATH= prefix argument. (This function is what adds that
** argument.)
**
** A consequence of this is that if the remote system is a Mac, the
** "ssh" command always ends up being invoked twice. If anybody knows a
** way around that problem, please bring it to the attention of the
** developers.
*/
void add_path_argument(sqlite3_str *pStr)
{
append_escaped_arg(pStr,
"PATH=$HOME/bin:/usr/local/bin:/opt/homebrew/bin:$PATH", 0);
}
/*****************************************************************************
** End of the append_escaped_arg() routine, adapted from the Fossil **
*****************************************************************************/
/*****************************************************************************
** The Hash Engine
**
** This is basically SHA3, though with a 160-bit hash, and reducing the
** number of rounds in the KeccakF1600 step function from 24 to 6.
*/
/*
** Macros to determine whether the machine is big or little endian,
** and whether or not that determination is run-time or compile-time.
**
** For best performance, an attempt is made to guess at the byte-order
** using C-preprocessor macros. If that is unsuccessful, or if
** -DHash_BYTEORDER=0 is set, then byte-order is determined
** at run-time.
*/
#ifndef Hash_BYTEORDER
#if defined(i386) || defined(__i386__) || defined(_M_IX86) || \
defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
defined(__arm__)
#define Hash_BYTEORDER 1234
#elif defined(sparc) || defined(__ppc__)
#define Hash_BYTEORDER 4321
#else
#define Hash_BYTEORDER 0
#endif
#endif
/*
** State structure for a Hash hash in progress
*/
#ifndef SQLITE_RSYNC_USE_H
typedef struct HashContext HashContext;
struct HashContext
{
union
{
u64 s[25]; /* Keccak state. 5x5 lines of 64 bits each */
unsigned char x[1600]; /* ... or 1600 bytes */
} u;
unsigned nRate; /* Bytes of input accepted per Keccak iteration */
unsigned nLoaded; /* Input bytes loaded into u.x[] so far this cycle */
unsigned ixMask; /* Insert next input into u.x[nLoaded^ixMask]. */
unsigned iSize; /* 224, 256, 358, or 512 */
};
#endif
/*
** A single step of the Keccak mixing function for a 1600-bit state
*/
static void KeccakF1600Step(HashContext *p)
{
int i;
u64 b0, b1, b2, b3, b4;
u64 c0, c1, c2, c3, c4;
u64 d0, d1, d2, d3, d4;
static const u64 RC[] = {
0x0000000000000001ULL, 0x0000000000008082ULL,
0x800000000000808aULL, 0x8000000080008000ULL,
0x000000000000808bULL, 0x0000000080000001ULL,
0x8000000080008081ULL, 0x8000000000008009ULL,
0x000000000000008aULL, 0x0000000000000088ULL,
0x0000000080008009ULL, 0x000000008000000aULL,
0x000000008000808bULL, 0x800000000000008bULL,
0x8000000000008089ULL, 0x8000000000008003ULL,
0x8000000000008002ULL, 0x8000000000000080ULL,
0x000000000000800aULL, 0x800000008000000aULL,
0x8000000080008081ULL, 0x8000000000008080ULL,
0x0000000080000001ULL, 0x8000000080008008ULL};
#define a00 (p->u.s[0])
#define a01 (p->u.s[1])
#define a02 (p->u.s[2])
#define a03 (p->u.s[3])
#define a04 (p->u.s[4])
#define a10 (p->u.s[5])
#define a11 (p->u.s[6])
#define a12 (p->u.s[7])
#define a13 (p->u.s[8])
#define a14 (p->u.s[9])
#define a20 (p->u.s[10])
#define a21 (p->u.s[11])
#define a22 (p->u.s[12])
#define a23 (p->u.s[13])
#define a24 (p->u.s[14])
#define a30 (p->u.s[15])
#define a31 (p->u.s[16])
#define a32 (p->u.s[17])
#define a33 (p->u.s[18])
#define a34 (p->u.s[19])
#define a40 (p->u.s[20])
#define a41 (p->u.s[21])
#define a42 (p->u.s[22])
#define a43 (p->u.s[23])
#define a44 (p->u.s[24])
#define ROL64(a, x) ((a << x) | (a >> (64 - x)))
/* v---- Number of rounds. SHA3 has 24 here. */
for (i = 0; i < 6; i++)
{
c0 = a00 ^ a10 ^ a20 ^ a30 ^ a40;
c1 = a01 ^ a11 ^ a21 ^ a31 ^ a41;
c2 = a02 ^ a12 ^ a22 ^ a32 ^ a42;
c3 = a03 ^ a13 ^ a23 ^ a33 ^ a43;
c4 = a04 ^ a14 ^ a24 ^ a34 ^ a44;
d0 = c4 ^ ROL64(c1, 1);
d1 = c0 ^ ROL64(c2, 1);
d2 = c1 ^ ROL64(c3, 1);
d3 = c2 ^ ROL64(c4, 1);
d4 = c3 ^ ROL64(c0, 1);
b0 = (a00 ^ d0);
b1 = ROL64((a11 ^ d1), 44);
b2 = ROL64((a22 ^ d2), 43);
b3 = ROL64((a33 ^ d3), 21);
b4 = ROL64((a44 ^ d4), 14);
a00 = b0 ^ ((~b1) & b2);
a00 ^= RC[i];
a11 = b1 ^ ((~b2) & b3);
a22 = b2 ^ ((~b3) & b4);
a33 = b3 ^ ((~b4) & b0);
a44 = b4 ^ ((~b0) & b1);
b2 = ROL64((a20 ^ d0), 3);
b3 = ROL64((a31 ^ d1), 45);
b4 = ROL64((a42 ^ d2), 61);
b0 = ROL64((a03 ^ d3), 28);
b1 = ROL64((a14 ^ d4), 20);
a20 = b0 ^ ((~b1) & b2);
a31 = b1 ^ ((~b2) & b3);
a42 = b2 ^ ((~b3) & b4);
a03 = b3 ^ ((~b4) & b0);
a14 = b4 ^ ((~b0) & b1);
b4 = ROL64((a40 ^ d0), 18);
b0 = ROL64((a01 ^ d1), 1);
b1 = ROL64((a12 ^ d2), 6);
b2 = ROL64((a23 ^ d3), 25);
b3 = ROL64((a34 ^ d4), 8);
a40 = b0 ^ ((~b1) & b2);
a01 = b1 ^ ((~b2) & b3);
a12 = b2 ^ ((~b3) & b4);
a23 = b3 ^ ((~b4) & b0);
a34 = b4 ^ ((~b0) & b1);
b1 = ROL64((a10 ^ d0), 36);
b2 = ROL64((a21 ^ d1), 10);
b3 = ROL64((a32 ^ d2), 15);
b4 = ROL64((a43 ^ d3), 56);
b0 = ROL64((a04 ^ d4), 27);
a10 = b0 ^ ((~b1) & b2);
a21 = b1 ^ ((~b2) & b3);
a32 = b2 ^ ((~b3) & b4);
a43 = b3 ^ ((~b4) & b0);
a04 = b4 ^ ((~b0) & b1);
b3 = ROL64((a30 ^ d0), 41);
b4 = ROL64((a41 ^ d1), 2);
b0 = ROL64((a02 ^ d2), 62);
b1 = ROL64((a13 ^ d3), 55);
b2 = ROL64((a24 ^ d4), 39);
a30 = b0 ^ ((~b1) & b2);
a41 = b1 ^ ((~b2) & b3);
a02 = b2 ^ ((~b3) & b4);
a13 = b3 ^ ((~b4) & b0);
a24 = b4 ^ ((~b0) & b1);
}
}
/*
** Initialize a new hash. iSize determines the size of the hash
** in bits and should be one of 224, 256, 384, or 512. Or iSize
** can be zero to use the default hash size of 256 bits.
*/
static void HashInit(HashContext *p, int iSize)
{
memset(p, 0, sizeof(*p));
p->iSize = iSize;
if (iSize >= 128 && iSize <= 512)
{
p->nRate = (1600 - ((iSize + 31) & ~31) * 2) / 8;
}
else
{
p->nRate = (1600 - 2 * 256) / 8;
}
#if Hash_BYTEORDER == 1234
/* Known to be little-endian at compile-time. No-op */
#elif Hash_BYTEORDER == 4321
p->ixMask = 7; /* Big-endian */
#else
{
static unsigned int one = 1;
if (1 == *(unsigned char *)&one)
{
/* Little endian. No byte swapping. */
p->ixMask = 0;
}
else
{
/* Big endian. Byte swap. */
p->ixMask = 7;
}
}
#endif
}
/*
** Make consecutive calls to the HashUpdate function to add new content
** to the hash
*/
static void HashUpdate(
HashContext *p,
const unsigned char *aData,
unsigned int nData)
{
unsigned int i = 0;
if (aData == 0)
return;
#if Hash_BYTEORDER == 1234
if ((p->nLoaded % 8) == 0 && ((aData - (const unsigned char *)0) & 7) == 0)
{
for (; i + 7 < nData; i += 8)
{
p->u.s[p->nLoaded / 8] ^= *(u64 *)&aData[i];
p->nLoaded += 8;
if (p->nLoaded >= p->nRate)
{
KeccakF1600Step(p);
p->nLoaded = 0;
}
}
}
#endif
for (; i < nData; i++)
{
#if Hash_BYTEORDER == 1234
p->u.x[p->nLoaded] ^= aData[i];
#elif Hash_BYTEORDER == 4321
p->u.x[p->nLoaded ^ 0x07] ^= aData[i];
#else
p->u.x[p->nLoaded ^ p->ixMask] ^= aData[i];
#endif
p->nLoaded++;
if (p->nLoaded == p->nRate)
{
KeccakF1600Step(p);
p->nLoaded = 0;
}
}
}
/*
** After all content has been added, invoke HashFinal() to compute
** the final hash. The function returns a pointer to the binary
** hash value.
*/
static unsigned char *HashFinal(HashContext *p)
{
unsigned int i;
if (p->nLoaded == p->nRate - 1)
{
const unsigned char c1 = 0x86;
HashUpdate(p, &c1, 1);
}
else
{
const unsigned char c2 = 0x06;
const unsigned char c3 = 0x80;
HashUpdate(p, &c2, 1);
p->nLoaded = p->nRate - 1;
HashUpdate(p, &c3, 1);
}
for (i = 0; i < p->nRate; i++)
{
p->u.x[i + p->nRate] = p->u.x[i ^ p->ixMask];
}
return &p->u.x[p->nRate];
}
/*
** Implementation of the hash(X) function.
**
** Return a 160-bit BLOB which is the hash of X.
*/
static void hashFunc(
sqlite3_context *context,
int argc,
sqlite3_value **argv)
{
HashContext cx;
int eType = sqlite3_value_type(argv[0]);
int nByte = sqlite3_value_bytes(argv[0]);
if (eType == SQLITE_NULL)
return;
HashInit(&cx, 160);
if (eType == SQLITE_BLOB)
{
HashUpdate(&cx, sqlite3_value_blob(argv[0]), nByte);
}
else
{
HashUpdate(&cx, sqlite3_value_text(argv[0]), nByte);
}
sqlite3_result_blob(context, HashFinal(&cx), 160 / 8, SQLITE_TRANSIENT);
}
/*
** Implementation of the agghash(X) function.
**
** Return a 160-bit BLOB which is the hash of the concatenation
** of all X inputs.
*/
static void agghashStep(
sqlite3_context *context,
int argc,
sqlite3_value **argv)
{
HashContext *pCx;
int eType = sqlite3_value_type(argv[0]);
int nByte = sqlite3_value_bytes(argv[0]);
if (eType == SQLITE_NULL)
return;
pCx = (HashContext *)sqlite3_aggregate_context(context, sizeof(*pCx));
if (pCx == 0)
return;
if (pCx->iSize == 0)
HashInit(pCx, 160);
if (eType == SQLITE_BLOB)
{
HashUpdate(pCx, sqlite3_value_blob(argv[0]), nByte);
}
else
{
HashUpdate(pCx, sqlite3_value_text(argv[0]), nByte);
}
}
static void agghashFinal(sqlite3_context *context)
{
HashContext *pCx = (HashContext *)sqlite3_aggregate_context(context, 0);
if (pCx)
{
sqlite3_result_blob(context, HashFinal(pCx), 160 / 8, SQLITE_TRANSIENT);
}
}
/* Register the hash function */
static int hashRegister(sqlite3 *db)
{
int rc;
rc = sqlite3_create_function(db, "hash", 1,
SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
0, hashFunc, 0, 0);
if (rc == SQLITE_OK)
{
rc = sqlite3_create_function(db, "agghash", 1,
SQLITE_UTF8 | SQLITE_INNOCUOUS | SQLITE_DETERMINISTIC,
0, 0, agghashStep, agghashFinal);
}
return rc;
}
/* End of the hashing logic
*****************************************************************************/
/*
** Return the tail of a file pathname. The tail is the last component
** of the path. For example, the tail of "/a/b/c.d" is "c.d".
*/