-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathpcompat.c
More file actions
4308 lines (3964 loc) · 117 KB
/
pcompat.c
File metadata and controls
4308 lines (3964 loc) · 117 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
/* Copyright (c) 2013 Anton Titov.
* Copyright (c) 2013 pCloud Ltd.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or materials provided with the distribution.
* * Neither the name of pCloud Ltd nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL pCloud Ltd BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stddef.h>
#include <time.h>
#include "pcompat.h"
#include "psynclib.h"
#include "plibs.h"
#include "psettings.h"
#include "pssl.h"
#include "ptimer.h"
#if defined(P_OS_LINUX)
#include <sys/sysinfo.h>
#endif
#if defined(P_OS_MACOSX)
#include <sys/sysctl.h>
#include <sys/attr.h>
#include <SystemConfiguration/SystemConfiguration.h>
#endif
#if defined(P_OS_POSIX)
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/statvfs.h>
#include <sys/utsname.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <netinet/tcp.h>
#include <net/if.h>
#include <utime.h>
#include <limits.h>
#include <unistd.h>
#include <ifaddrs.h>
#include <dirent.h>
#include <fcntl.h>
#include <signal.h>
#include <ctype.h>
#include <pwd.h>
#include <grp.h>
extern char **environ;
#if defined(MAP_ANONYMOUS)
#define PSYNC_MAP_ANONYMOUS MAP_ANONYMOUS
#elif defined(MAP_ANON)
#define PSYNC_MAP_ANONYMOUS MAP_ANON
#endif
#elif defined(P_OS_WINDOWS)
#include <process.h>
#include <windows.h>
#include <winhttp.h>
#include <ws2tcpip.h>
#include <wincrypt.h>
#include <tlhelp32.h>
#include <iphlpapi.h>
#include <shlobj.h>
#pragma comment(lib, "winhttp.lib")
#endif
#define PROXY_NONE 0
#define PROXY_CONNECT 1
typedef struct {
psync_thread_start0 run;
const char *name;
} psync_run_data0;
typedef struct {
psync_thread_start1 run;
void *ptr;
const char *name;
} psync_run_data1;
#if defined(P_OS_POSIX)
static uid_t psync_uid;
static gid_t psync_gid;
static gid_t *psync_gids;
static int psync_gids_cnt;
#endif
static int proxy_type=PROXY_NONE;
static int proxy_detected=0;
static char proxy_host[256];
static char proxy_port[8];
static int psync_page_size;
static const char *psync_software_name=PSYNC_LIB_VERSION;
static const char *psync_os_name=NULL;
PSYNC_THREAD const char *psync_thread_name="no name";
static pthread_mutex_t socket_mutex=PTHREAD_MUTEX_INITIALIZER;
const unsigned char psync_invalid_filename_chars[256]={
#if defined(P_OS_WINDOWS)
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0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in");
if (!ag)
return 0;
for (i=0; i<psync_gids_cnt; i++)
if (ag->gr_gid==psync_gids[i])
return 1;
return 0;
#else
return 0;
#endif
}
#if defined(P_OS_WINDOWS)
#if !defined(gmtime_r)
struct tm *gmtime_r(const time_t *timep, struct tm *result){
struct tm *res=gmtime(timep);
*result=*res;
return result;
}
#endif
static wchar_t *utf8_to_wchar(const char *str){
int len;
wchar_t *ret;
len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
ret=psync_new_cnt(wchar_t, len);
MultiByteToWideChar(CP_UTF8, 0, str, -1, ret, len);
return ret;
}
static wchar_t *utf8_to_wchar_path(const char *str){
int len;
wchar_t *ret;
len=MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
/* MAX_PATH seems not to be apporopriate here as it is defined as 260, and CreateDirectory() description says:
* There is a default string size limit for paths of 248 characters. This limit is related to how the CreateDirectory function parses paths.
*/
// if (len>=248){
ret=psync_new_cnt(wchar_t, len+4);
memcpy(ret, L"\\\\?\\", 4*sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, str, -1, ret+4, len);
// }
// else{
// ret=psync_new_cnt(wchar_t, len);
// MultiByteToWideChar(CP_UTF8, 0, str, -1, ret, len);
// }
return ret;
}
static char *wchar_to_utf8(const wchar_t *str){
int len;
char *ret;
len=WideCharToMultiByte(CP_UTF8, 0, str, -1, NULL, 0, NULL, NULL);
ret=psync_new_cnt(char, len);
WideCharToMultiByte(CP_UTF8, 0, str, -1, ret, len, NULL, NULL);
return ret;
}
int psync_stat(const char *path, psync_stat_t *st){
wchar_t *wpath;
HANDLE fd;
BOOL ret;
DWORD flag, attr;
wpath=utf8_to_wchar_path(path);
retry:
attr=GetFileAttributesW(wpath);
if (attr==INVALID_FILE_ATTRIBUTES){
psync_free(wpath);
return -1;
}
if (attr&FILE_ATTRIBUTE_DIRECTORY)
flag=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_POSIX_SEMANTICS;
else
flag=FILE_ATTRIBUTE_NORMAL|FILE_FLAG_POSIX_SEMANTICS;
fd=CreateFileW(wpath, 0, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, NULL, OPEN_EXISTING, flag, NULL);
if (unlikely_log(fd==INVALID_HANDLE_VALUE)){
if (GetLastError()==ERROR_SHARING_VIOLATION){
debug(D_WARNING, "file %s is locked by another process, will retry after sleep", path);
psync_milisleep(PSYNC_SLEEP_ON_OS_LOCK);
goto retry;
}
else
debug(D_NOTICE, "could not open file %s, error %d", path, (int)GetLastError());
psync_free(wpath);
return -1;
}
psync_free(wpath);
ret=GetFileInformationByHandle(fd, st);
CloseHandle(fd);
return psync_bool_to_zero(ret);
}
#endif
void psync_compat_init(){
#if defined(P_OS_POSIX)
struct rlimit limit;
limit.rlim_cur=limit.rlim_max=2048;
if (setrlimit(RLIMIT_NOFILE, &limit))
debug(D_ERROR, "setrlimit failed errno=%d", errno);
#if IS_DEBUG
if (getrlimit(RLIMIT_CORE, &limit))
debug(D_ERROR, "getrlimit failed errno=%d", errno);
else{
limit.rlim_cur=limit.rlim_max;
if (setrlimit(RLIMIT_CORE, &limit))
debug(D_ERROR, "setrlimit failed errno=%d", errno);
}
#endif
signal(SIGPIPE, SIG_IGN);
psync_uid=getuid();
psync_gid=getgid();
psync_gids_cnt=getgroups(0, NULL);
psync_gids=psync_new_cnt(gid_t, psync_gids_cnt);
if (unlikely_log(getgroups(psync_gids_cnt, psync_gids)!=psync_gids_cnt))
psync_gids_cnt=0;
#if defined(PAGESIZE)
psync_page_size=PAGESIZE;
#else
psync_page_size=sysconf(_SC_PAGESIZE);
#endif
#elif defined(P_OS_WINDOWS)
SYSTEM_INFO si;
GetSystemInfo(&si);
psync_page_size=si.dwPageSize;
#else
psync_page_size=-1;
#endif
debug(D_NOTICE, "detected page size %d", psync_page_size);
}
int psync_stat_mode_ok(psync_stat_t *buf, unsigned int bits){
#if defined(P_OS_POSIX)
int i;
if (psync_uid==0)
return 1;
if (buf->st_uid==psync_uid){
bits<<=6;
return (buf->st_mode&bits)==bits;
}
if (buf->st_gid==psync_gid){
bits<<=3;
return (buf->st_mode&bits)==bits;
}
for (i=0; i<psync_gids_cnt; i++)
if (buf->st_gid==psync_gids[i]){
bits<<=3;
return (buf->st_mode&bits)==bits;
}
return (buf->st_mode&bits)==bits;
#else
return 1;
#endif
}
char *psync_get_default_database_path_old(){
#if defined(P_OS_POSIX)
struct stat st;
const char *dir;
dir=getenv("HOME");
if (unlikely_log(!dir) || unlikely_log(stat(dir, &st)) || unlikely_log(!psync_stat_mode_ok(&st, 7))){
struct passwd pwd;
struct passwd *result;
char buff[4096];
if (unlikely_log(getpwuid_r(getuid(), &pwd, buff, sizeof(buff), &result)) || unlikely_log(stat(result->pw_dir, &st)) ||
unlikely_log(!psync_stat_mode_ok(&st, 7)))
return NULL;
dir=result->pw_dir;
}
return psync_strcat(dir, PSYNC_DIRECTORY_SEPARATOR, PSYNC_DEFAULT_POSIX_DBNAME, NULL);
#elif defined(P_OS_WINDOWS)
const char *dir;
dir=getenv("UserProfile");
if (unlikely_log(!dir))
return NULL;
return psync_strcat(dir, PSYNC_DIRECTORY_SEPARATOR, PSYNC_DEFAULT_WINDOWS_DBNAME, NULL);
#else
#error "Function not implemented for your operating system"
#endif
}
static char *psync_get_pcloud_path_nc(){
#if defined(P_OS_POSIX)
struct stat st;
const char *dir;
dir=getenv("HOME");
if (unlikely_log(!dir) || unlikely_log(stat(dir, &st)) || unlikely_log(!psync_stat_mode_ok(&st, 7))){
struct passwd pwd;
struct passwd *result;
char buff[4096];
if (unlikely_log(getpwuid_r(getuid(), &pwd, buff, sizeof(buff), &result)) || unlikely_log(stat(result->pw_dir, &st)) ||
unlikely_log(!psync_stat_mode_ok(&st, 7)))
return NULL;
dir=result->pw_dir;
}
return psync_strcat(dir, PSYNC_DIRECTORY_SEPARATOR, PSYNC_DEFAULT_POSIX_DIR, NULL);
#elif defined(P_OS_WINDOWS)
wchar_t path[MAX_PATH], *wdir;
char *dir, *ret;
if (SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA|CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, path)==S_OK)
wdir=path;
else{
wdir=_wgetenv(L"LOCALAPPDATA");
if (!wdir){
wdir=_wgetenv(L"APPDATA");
if (unlikely_log(!wdir))
return NULL;
}
}
dir=wchar_to_utf8(wdir);
ret=psync_strcat(dir, PSYNC_DIRECTORY_SEPARATOR, PSYNC_DEFAULT_WINDOWS_DIR, NULL);
psync_free(dir);
return ret;
#else
#error "Function not implemented for your operating system"
#endif
}
char *psync_get_pcloud_path(){
char *path;
psync_stat_t st;
path=psync_get_pcloud_path_nc();
if (unlikely_log(!path))
return NULL;
if (psync_stat(path, &st) && unlikely_log(psync_mkdir(path))){
psync_free(path);
return NULL;
}
return path;
}
char *psync_get_private_dir(char *name){
char *path, *rpath;
psync_stat_t st;
path=psync_get_pcloud_path();
if (!path)
return NULL;
rpath=psync_strcat(path, PSYNC_DIRECTORY_SEPARATOR, name, NULL);
free(path);
if (psync_stat(rpath, &st) && psync_mkdir(rpath)){
psync_free(rpath);
return NULL;
}
return rpath;
}
char *psync_get_private_tmp_dir(){
return psync_get_private_dir(PSYNC_DEFAULT_TMP_DIR);
}
char *psync_get_default_database_path(){
char *dirpath, *path;
psync_stat_t st;
dirpath=psync_get_pcloud_path();
if (!dirpath)
return NULL;
path=psync_strcat(dirpath, PSYNC_DIRECTORY_SEPARATOR, PSYNC_DEFAULT_DB_NAME, NULL);
psync_free(dirpath);
if (psync_stat(path, &st) && (dirpath=psync_get_default_database_path_old())){
if (!psync_stat(dirpath, &st)){
if (psync_sql_reopen(dirpath)){
psync_free(path);
return dirpath;
}
else
psync_file_rename(dirpath, path);
}
psync_free(dirpath);
}
return path;
}
char *psync_get_home_dir(){
#if defined(P_OS_POSIX)
struct stat st;
const char *dir;
dir=getenv("HOME");
if (unlikely_log(!dir) || unlikely_log(stat(dir, &st)) || unlikely_log(!psync_stat_mode_ok(&st, 7))){
struct passwd pwd;
struct passwd *result;
char buff[4096];
if (unlikely_log(getpwuid_r(getuid(), &pwd, buff, sizeof(buff), &result)) || unlikely_log(stat(result->pw_dir, &st)) ||
unlikely_log(!psync_stat_mode_ok(&st, 7)))
return NULL;
dir=result->pw_dir;
}
return psync_strdup(dir);
#elif defined(P_OS_WINDOWS)
const char *dir;
dir=getenv("UserProfile");
if (unlikely_log(!dir))
return NULL;
return psync_strdup(dir);
#else
#error "Function not implemented for your operating system"
#endif
}
void psync_yield_cpu(){
#if defined(_POSIX_PRIORITY_SCHEDULING)
sched_yield();
#elif defined(P_OS_WINDOWS)
SwitchToThread();
#else
psync_milisleep(1);
#endif
}
static void thread_started(){
//debug(D_NOTICE, "thread started"); //This repeats too many times because of the overlays
}
static void thread_exited(){
// debug(D_NOTICE, "thread exited"); //This repeats too many times because of the overlays
}
static void *thread_entry0(void *data){
psync_thread_start0 run;
run=((psync_run_data0 *)data)->run;
psync_thread_name=((psync_run_data0 *)data)->name;
psync_free(data);
thread_started();
run();
thread_exited();
return NULL;
}
void psync_run_thread(const char *name, psync_thread_start0 run){
psync_run_data0 *data;
pthread_t thread;
pthread_attr_t attr;
data=psync_new(psync_run_data0);
data->run=run;
data->name=name;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_attr_setstacksize(&attr, PSYNC_STACK_SIZE);
pthread_create(&thread, &attr, thread_entry0, data);
pthread_attr_destroy(&attr);
}
static void *thread_entry1(void *data){
psync_thread_start1 run;
void *ptr;
run=((psync_run_data1 *)data)->run;
ptr=((psync_run_data1 *)data)->ptr;
psync_thread_name=((psync_run_data1 *)data)->name;
psync_free(data);
thread_started();
run(ptr);
thread_exited();
return NULL;
}
void psync_run_thread1(const char *name, psync_thread_start1 run, void *ptr){
psync_run_data1 *data;
pthread_t thread;
pthread_attr_t attr;
data=psync_new(psync_run_data1);
data->run=run;
data->ptr=ptr;
data->name=name;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_attr_setstacksize(&attr, PSYNC_STACK_SIZE);
pthread_create(&thread, &attr, thread_entry1, data);
pthread_attr_destroy(&attr);
}
static void psync_check_no_sql_lock(uint64_t millisec){
#if IS_DEBUG
if (psync_sql_islocked()){
debug(D_CRITICAL, "trying to sleep while holding sql lock, aborting");
psync_sql_dump_locks();
abort();
}
#endif
}
void psync_milisleep_nosqlcheck(uint64_t millisec){
#if defined(P_OS_POSIX)
struct timespec tm;
tm.tv_sec=millisec/1000;
tm.tv_nsec=(millisec%1000)*1000000;
nanosleep(&tm, NULL);
#elif defined(P_OS_WINDOWS)
Sleep(millisec);
#else
#error "Function not implemented for your operating system"
#endif
}
void psync_milisleep(uint64_t millisec){
psync_check_no_sql_lock(millisec);
psync_milisleep_nosqlcheck(millisec);
}
time_t psync_time(){
#if defined(P_OS_MACOSX)
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec;
#elif defined(_POSIX_TIMERS) && _POSIX_TIMERS>0
struct timespec ts;
if (likely_log(clock_gettime(CLOCK_REALTIME, &ts)==0))
return ts.tv_sec;
else
return time(NULL);
#else
return time(NULL);
#endif
}
void psync_nanotime(struct timespec *tm){
#if defined(_POSIX_TIMERS) && _POSIX_TIMERS>0
clock_gettime(CLOCK_REALTIME, tm);
#elif defined(P_OS_WINDOWS)
FILETIME ft;
uint64_t t;
GetSystemTimeAsFileTime(&ft);
t=psync_32to64(ft.dwHighDateTime, ft.dwLowDateTime)-116444736000000000ULL;
tm->tv_sec=t/10000000UL;
tm->tv_nsec=(t%10000000UL)*100;
#elif defined(P_OS_POSIX)
struct timeval tv;
gettimeofday(&tv, NULL);
tm->tv_sec=tv.tv_sec;
tm->tv_nsec=tv.tv_usec*1000;
#else
#error "Function not implemented for your operating system"
#endif
}
uint64_t psync_millitime(){
struct timespec tm;
psync_nanotime(&tm);
return tm.tv_sec*1000+tm.tv_nsec/1000000;
}
#if defined(P_OS_POSIX)
static void psync_add_file_to_seed(const char *fn, psync_lhash_ctx *hctx, size_t max){
char buff[4096];
ssize_t rd;
int fd, mode;
mode=O_RDONLY;
#if defined(O_NONBLOCK)
mode+=O_NONBLOCK;
#elif defined(O_NDELAY)
mode+=O_NDELAY;
#endif
fd=open(fn, mode);
if (fd!=-1){
if (!max || max>sizeof(buff))
max=sizeof(buff);
rd=read(fd, buff, max);
if (rd>0)
psync_lhash_update(hctx, buff, rd);
close(fd);
}
}
#endif
#if defined(P_OS_LINUX)
static void psync_get_random_seed_linux(psync_lhash_ctx *hctx){
struct sysinfo si;
if (likely_log(!sysinfo(&si)))
psync_lhash_update(hctx, &si, sizeof(si));
psync_add_file_to_seed("/proc/stat", hctx, 0);
psync_add_file_to_seed("/proc/vmstat", hctx, 0);
psync_add_file_to_seed("/proc/meminfo", hctx, 0);
psync_add_file_to_seed("/proc/modules", hctx, 0);
psync_add_file_to_seed("/proc/mounts", hctx, 0);
psync_add_file_to_seed("/proc/diskstats", hctx, 0);
psync_add_file_to_seed("/proc/interrupts", hctx, 0);
psync_add_file_to_seed("/proc/net/dev", hctx, 0);
psync_add_file_to_seed("/proc/net/arp", hctx, 0);
}
#endif
static void psync_get_random_seed_from_query(psync_lhash_ctx *hctx, psync_sql_res *res){
psync_variant_row row;
struct timespec tm;
int i;
while ((row=psync_sql_fetch_row(res))){
for (i=0; i<res->column_count; i++)
if (row[i].type==PSYNC_TSTRING)
psync_lhash_update(hctx, row[i].str, row[i].length);
psync_lhash_update(hctx, row, sizeof(psync_variant)*res->column_count);
}
psync_sql_free_result(res);
psync_nanotime(&tm);
psync_lhash_update(hctx, &tm, sizeof(&tm));
}
static void psync_get_random_seed_from_db(psync_lhash_ctx *hctx){
psync_sql_res *res;
struct timespec tm;
unsigned char rnd[PSYNC_LHASH_DIGEST_LEN];
psync_nanotime(&tm);
psync_lhash_update(hctx, &tm, sizeof(&tm));
res=psync_sql_query_rdlock("SELECT * FROM setting ORDER BY RANDOM()");
psync_get_random_seed_from_query(hctx, res);
res=psync_sql_query_rdlock("SELECT * FROM resolver ORDER BY RANDOM() LIMIT 50");
psync_get_random_seed_from_query(hctx, res);
/* res=psync_sql_query_rdlock("SELECT * FROM filerevision ORDER BY RANDOM() LIMIT 50");
psync_get_random_seed_from_query(hctx, res);
res=psync_sql_query_rdlock("SELECT * FROM file ORDER BY RANDOM() LIMIT 50");
psync_get_random_seed_from_query(hctx, res);
res=psync_sql_query_rdlock("SELECT * FROM localfile ORDER BY RANDOM() LIMIT 50");
psync_get_random_seed_from_query(hctx, res);
res=psync_sql_query_rdlock("SELECT * FROM folder ORDER BY RANDOM() LIMIT 25");
psync_get_random_seed_from_query(hctx, res);
res=psync_sql_query_rdlock("SELECT * FROM localfolder ORDER BY RANDOM() LIMIT 25");
psync_get_random_seed_from_query(hctx, res);
res=psync_sql_query_rdlock("SELECT * FROM hashchecksum ORDER BY RANDOM() LIMIT 25");
psync_get_random_seed_from_query(hctx, res);
res=psync_sql_query_rdlock("SELECT * FROM pagecache WHERE type=1 AND rowid>(ABS(RANDOM())%(SELECT MAX(rowid)+1 FROM pagecache)) ORDER BY rowid LIMIT 50");
psync_get_random_seed_from_query(hctx, res); */
psync_sql_statement("REPLACE INTO setting (id, value) VALUES ('random', RANDOM())");
psync_nanotime(&tm);
psync_lhash_update(hctx, &tm, sizeof(&tm));
psync_sql_sync();
psync_nanotime(&tm);
psync_lhash_update(hctx, &tm, sizeof(&tm));
sqlite3_randomness(sizeof(rnd), rnd);
psync_lhash_update(hctx, rnd, sizeof(rnd));
}
static void psync_rehash_cnt(unsigned char *hashbin, psync_uint_t cnt){
psync_lhash_ctx hctx;
psync_uint_t i;
struct timespec tm;
for (i=0; i<cnt; i++){
psync_lhash_init(&hctx);
if ((i&511)==0){
psync_nanotime(&tm);
psync_lhash_update(&hctx, &tm, sizeof(&tm));
}
else
psync_lhash_update(&hctx, &i, sizeof(i));
psync_lhash_update(&hctx, hashbin, PSYNC_LHASH_DIGEST_LEN);
psync_lhash_final(hashbin, &hctx);
}
}
static void psync_store_seed_in_db(const unsigned char *seed){
psync_sql_res *res;
unsigned char hashbin[PSYNC_LHASH_DIGEST_LEN];
char hashhex[PSYNC_LHASH_DIGEST_HEXLEN], nm[16];
memcpy(hashbin, seed, PSYNC_LHASH_DIGEST_LEN);
psync_rehash_cnt(hashbin, 2000);
psync_binhex(hashhex, hashbin, PSYNC_LHASH_DIGEST_LEN);
res=psync_sql_prep_statement("REPLACE INTO setting (id, value) VALUES ('randomhash', ?)");
psync_sql_bind_lstring(res, 1, hashhex, PSYNC_LHASH_DIGEST_HEXLEN);
psync_sql_run_free(res);
psync_rehash_cnt(hashbin, 2000);
psync_binhex(hashhex, hashbin, PSYNC_LHASH_DIGEST_LEN);
memcpy(nm, "randomhash", 10);
nm[10]=hashhex[0];
nm[11]=0;
res=psync_sql_prep_statement("REPLACE INTO setting (id, value) VALUES (?, ?)");
psync_sql_bind_lstring(res, 1, nm, 11);
psync_sql_bind_lstring(res, 2, hashhex, PSYNC_LHASH_DIGEST_HEXLEN);
psync_sql_run_free(res);
}
void psync_get_random_seed(unsigned char *seed, const void *addent, size_t aelen, int fast){
static unsigned char lastseed[PSYNC_LHASH_DIGEST_LEN];
psync_lhash_ctx hctx;
struct timespec tm;
psync_stat_t st;
char *home;
void *ptr;
psync_uint_t i, j;
int64_t i64;
pthread_t threadid;
unsigned char lsc[64][PSYNC_LHASH_DIGEST_LEN];
#if defined(P_OS_POSIX)
debug(D_NOTICE, "in");
struct utsname un;
struct statvfs stfs;
char **env;
pid_t pid;
psync_nanotime(&tm);
psync_lhash_init(&hctx);
psync_lhash_update(&hctx, &tm, sizeof(tm));
if (likely_log(!uname(&un)))
psync_lhash_update(&hctx, &un, sizeof(un));
pid=getpid();
psync_lhash_update(&hctx, &pid, sizeof(pid));
if (!statvfs("/", &stfs))
psync_lhash_update(&hctx, &stfs, sizeof(stfs));
for (env=environ; *env!=NULL; env++)
psync_lhash_update(&hctx, *env, strlen(*env));
#if defined(_POSIX_TIMERS) && _POSIX_TIMERS>0 && defined(_POSIX_MONOTONIC_CLOCK)
if (likely_log(!clock_gettime(CLOCK_MONOTONIC, &tm)))
psync_lhash_update(&hctx, &tm, sizeof(tm));
#endif
#if defined(P_OS_LINUX)
psync_add_file_to_seed("/dev/urandom", &hctx, PSYNC_HASH_DIGEST_LEN);
#else
psync_add_file_to_seed("/dev/random", &hctx, PSYNC_HASH_DIGEST_LEN);
#endif
#elif defined(P_OS_WINDOWS)
SYSTEM_INFO si;
OSVERSIONINFO osvi;
CURSORINFO ci;
PROCESSENTRY32 pe;
THREADENTRY32 te;
MODULEENTRY32 me;
MEMORYSTATUSEX ms;
LARGE_INTEGER li;
TCHAR ib[1024];
DWORD ibc;
HCRYPTPROV cprov;
HANDLE pr;
debug(D_NOTICE, "in");
psync_nanotime(&tm);
psync_lhash_init(&hctx);
psync_lhash_update(&hctx, &tm, sizeof(tm));
if (CryptAcquireContext(&cprov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)){
if (CryptGenRandom(cprov, PSYNC_HASH_DIGEST_LEN, lsc[0]))
psync_lhash_update(&hctx, lsc[0], PSYNC_HASH_DIGEST_LEN);
CryptReleaseContext(cprov, 0);
}
if ((pr=CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0))!=INVALID_HANDLE_VALUE){
pe.dwSize=sizeof(pe);
if (Process32First(pr, &pe))
do {
psync_lhash_update(&hctx, &pe, sizeof(pe));
} while(Process32Next(pr, &pe));
te.dwSize=sizeof(te);
if (Thread32First(pr, &te))
do {
psync_lhash_update(&hctx, &te, sizeof(te));
} while(Thread32Next(pr, &te));
me.dwSize=sizeof(me);
if (Module32First(pr, &me))
do {
psync_lhash_update(&hctx, &me, sizeof(me));
} while(Module32Next(pr, &me));
CloseHandle(pr);
}
ms.dwLength=sizeof(ms);
if (GlobalMemoryStatusEx(&ms))
psync_lhash_update(&hctx, &ms, sizeof(ms));
ci.cbSize=sizeof(ci);
if (GetCursorInfo(&ci))
psync_lhash_update(&hctx, &ci, sizeof(ci));
GetSystemInfo(&si);
psync_lhash_update(&hctx, &si, sizeof(si));
ibc=ARRAY_SIZE(ib);
if (GetComputerName(ib, &ibc))
psync_lhash_update(&hctx, ib, sizeof(TCHAR)*ibc);
ibc=ARRAY_SIZE(ib);
if (GetUserName(ib, &ibc))
psync_lhash_update(&hctx, ib, sizeof(TCHAR)*ibc);
memset(&osvi, 0, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize=sizeof(OSVERSIONINFO);
if (GetVersionEx(&osvi))
psync_lhash_update(&hctx, &osvi, sizeof(osvi));
ibc=GetCurrentProcessId();
psync_lhash_update(&hctx, &ibc, sizeof(ibc));
ibc=GetTickCount();
psync_lhash_update(&hctx, &ibc, sizeof(ibc));
if (QueryPerformanceCounter(&li))
psync_lhash_update(&hctx, &li, sizeof(li));
#endif
#if defined(P_OS_LINUX)
psync_get_random_seed_linux(&hctx);
#endif
threadid=pthread_self();
psync_lhash_update(&hctx, &threadid, sizeof(threadid));
ptr=(void *)&ptr;
psync_lhash_update(&hctx, &ptr, sizeof(ptr));
ptr=(void *)psync_get_random_seed;
psync_lhash_update(&hctx, &ptr, sizeof(ptr));
ptr=(void *)pthread_self;
psync_lhash_update(&hctx, &ptr, sizeof(ptr));
ptr=(void *)malloc;
psync_lhash_update(&hctx, &ptr, sizeof(ptr));
ptr=(void *)&lastseed;
psync_lhash_update(&hctx, &ptr, sizeof(ptr));
home=psync_get_home_dir();
if (home){
i64=psync_get_free_space_by_path(home);
psync_lhash_update(&hctx, &i64, sizeof(i64));
psync_lhash_update(&hctx, home, strlen(home));
if (likely_log(!psync_stat(home, &st)))
psync_lhash_update(&hctx, &st, sizeof(st));
psync_free(home);
}
if (!fast){
debug(D_NOTICE, "db in");
psync_get_random_seed_from_db(&hctx);
debug(D_NOTICE, "db out");
}
if (aelen)
psync_lhash_update(&hctx, addent, aelen);
debug(D_NOTICE, "adding bulk data");
for (i=0; i<ARRAY_SIZE(lsc); i++){
memcpy(&lsc[i], lastseed, PSYNC_LHASH_DIGEST_LEN);
for (j=0; j<PSYNC_LHASH_DIGEST_LEN; j++)
lsc[i][j]^=(unsigned char)i;
}
for (j=fast?3:0; j<5; j++){
for (i=0; i<100; i++){
psync_lhash_update(&hctx, &i, sizeof(i));
psync_lhash_update(&hctx, &j, sizeof(j));
psync_lhash_update(&hctx, lsc, sizeof(lsc));
}
psync_nanotime(&tm);
psync_lhash_update(&hctx, &tm, sizeof(&tm));
}
psync_lhash_final(seed, &hctx);
memcpy(lastseed, seed, PSYNC_LHASH_DIGEST_LEN);
debug(D_NOTICE, "storing in db");
psync_store_seed_in_db(seed);
debug(D_NOTICE, "out");
}
static int psync_wait_socket_writable_microsec(psync_socket_t sock, long sec, long usec){
fd_set wfds;
struct timeval tv;
int res;
tv.tv_sec=sec;
tv.tv_usec=usec;
FD_ZERO(&wfds);
FD_SET(sock, &wfds);
res=select(sock+1, NULL, &wfds, NULL, &tv);
if (res==1)
return 0;
if (res==0)
psync_sock_set_err(P_TIMEDOUT);
return SOCKET_ERROR;
}
#define psync_wait_socket_writable(sock, sec) psync_wait_socket_writable_microsec(sock, sec, 0)
int psync_wait_socket_write_timeout(psync_socket_t sock){
return psync_wait_socket_writable(sock, PSYNC_SOCK_WRITE_TIMEOUT);
}
static int psync_wait_socket_readable_microsec(psync_socket_t sock, long sec, long usec){
fd_set rfds;
struct timeval tv;
#if IS_DEBUG
struct timespec start, end;
unsigned long msec;
#endif
int res;
tv.tv_sec=sec;
tv.tv_usec=usec;
FD_ZERO(&rfds);
FD_SET(sock, &rfds);
#if IS_DEBUG
psync_nanotime(&start);
#endif
res=select(sock+1, &rfds, NULL, NULL, &tv);
if (res==1){
#if IS_DEBUG
psync_nanotime(&end);
msec=(end.tv_sec-start.tv_sec)*1000+end.tv_nsec/1000000-start.tv_nsec/1000000;
if (msec>=30000)
debug(D_WARNING, "got response from socket after %lu milliseconds", msec);
else if (msec>=5000)
debug(D_NOTICE, "got response from socket after %lu milliseconds", msec);
#endif
return 0;
}
if (res==0){
if (sec)
debug(D_WARNING, "socket read timeouted on %ld seconds", sec);
psync_sock_set_err(P_TIMEDOUT);
}
else
debug(D_WARNING, "select returned %d", res);
return SOCKET_ERROR;
}
#define psync_wait_socket_readable(sock, sec) psync_wait_socket_readable_microsec(sock, sec, 0)