summaryrefslogtreecommitdiff
path: root/plugins/CopyEngine/Ultracopier-Spec/TransferThread.cpp
blob: 9cbad5a28a3328cae37f18412dd548f373849cc0 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
//presume bug linked as multple paralelle inode to resume after "overwrite"
//then do overwrite node function to not re-set the file name

#include "TransferThread.h"
#include <string>
#include <dirent.h>
#include <limits.h>
#ifdef WIDESTRING
#include <locale>
//#include <codecvt>
#endif

#ifdef Q_OS_WIN32
#include <accctrl.h>
#include <aclapi.h>
#endif

#include "../../../cpp11addition.h"

TransferThread::TransferThread() :
    mode(Ultracopier::CopyMode::Copy),
    transfer_stat                   (TransferStat_Idle),
    doRightTransfer                 (false),
    #ifdef ULTRACOPIER_PLUGIN_RSYNC
    rsync                           (false),
    #endif
    keepDate                        (false),
    mkFullPath                      (false),
    stopIt                          (false),
    fileExistsAction                (FileExists_NotSet),
    alwaysDoFileExistsAction        (FileExists_NotSet),
    needSkip                        (false),
    needRemove                      (false),
    deletePartiallyTransferredFiles (true),
    renameTheOriginalDestination    (false),
    writeError                      (false),
    readError                       (false),
    havePermission                  (false),
    haveTransferTime                (false)
{
    id=0;
    renameRegex=std::regex("^(.*)(\\.[a-zA-Z0-9]+)$");
    #ifdef Q_OS_WIN32
        regRead=std::regex("^[a-zA-Z]:");
    #endif
    transferSize                    = 0;//external set by ListThread

    #ifndef Q_OS_UNIX
    PSecurityD=NULL;
    dacl=NULL;
    #endif
    #ifdef Q_OS_Win32
    stopItWin=0;
    #endif
    //if not QThread
    run();
}

TransferThread::~TransferThread()
{
    #ifdef Q_OS_WIN32
    stopItWin=1;
    #endif
    stopIt=true;
    //else cash without this disconnect
    //disconnect(&readThread);
    //disconnect(&writeThread);
    #ifndef Q_OS_UNIX
    if(PSecurityD!=NULL)
    {
        free(PSecurityD);
        PSecurityD=NULL;
    }
    if(dacl!=NULL)
    {
        //free(dacl);
        dacl=NULL;
    }
    #endif
}

void TransferThread::run()
{
    moveToThread(this);

    //ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+QStringLiteral("] start: ")+QString::number((qint64)QThread::currentThreadId())));
    transfer_stat			= TransferStat_Idle;
    stopIt                  = false;
    fileExistsAction        = FileExists_NotSet;
    alwaysDoFileExistsAction= FileExists_NotSet;

    #ifdef ULTRACOPIER_PLUGIN_DEBUG
    if(!connect(&driveManagement,&DriveManagement::debugInformation,this,                   &TransferThread::debugInformation,	Qt::QueuedConnection))
        abort();
    #endif
}

TransferStat TransferThread::getStat() const
{
    return transfer_stat;
}

#ifdef WIDESTRING
INTERNALTYPEPATH TransferThread::stringToInternalString(const std::string& utf8)
{
    /* buggy on MXE
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
    return converter.from_bytes(utf8);*/
    return QString::fromUtf8(utf8.data(),utf8.size()).toStdWString();
    //return widen(utf8);
}

std::string TransferThread::internalStringTostring(const INTERNALTYPEPATH& utf16)
{
    /* buggy on MXE
    std::wstring_convert<std::codecvt_utf8<wchar_t>> conv1;
    return conv1.to_bytes(utf16);*/
    const QByteArray &data=QString::fromStdWString(utf16).toUtf8();
    return std::string(data.constData(),data.size());
    //return narrow(utf16);
}
#else
std::string TransferThread::stringToInternalString(const std::string& utf8)
{
    return utf8;
}

std::string TransferThread::internalStringTostring(const std::string& utf16)
{
    return utf16;
}
#endif

bool TransferThread::setFiles(const INTERNALTYPEPATH& source, const int64_t &size, const INTERNALTYPEPATH& destination, const Ultracopier::CopyMode &mode)
{
    if(transfer_stat!=TransferStat_Idle)
    {
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Critical,"["+std::to_string(id)+("] already used, source: ")+
                                 TransferThread::internalStringTostring(source)+", destination: "+TransferThread::internalStringTostring(destination));
        return false;
    }
    //to prevent multiple file alocation into ListThread::doNewActions_inode_manipulation()
    transfer_stat			= TransferStat_PreOperation;
    //emit pushStat(stat,transferId);
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] start, source: "+TransferThread::internalStringTostring(source)+", destination: "+TransferThread::internalStringTostring(destination));
    this->source                    = source;
    this->destination               = destination;
    this->mode                      = mode;
    this->size                      = size;
    stopIt                          = false;
    #ifdef Q_OS_WIN32
    stopItWin=0;
    #endif
    fileExistsAction                = FileExists_NotSet;
    canStartTransfer                = false;
    sended_state_preOperationStopped= false;
    fileContentError                = false;
    writeError                      = false;
    readError                       = false;
    haveTransferTime                = false;
    canStartTransfer                = false;
    resetExtraVariable();
    emit internalStartPreOperation();
    startTransferTime.restart();
    return true;
}

void TransferThread::setFileRename(const std::string &nameForRename)
{
    if(transfer_stat!=TransferStat_PreOperation)
    {
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Critical,"["+std::to_string(id)+("] already used, source: ")+
                                 TransferThread::internalStringTostring(source)+(", destination: ")+TransferThread::internalStringTostring(destination));
        return;
    }
    if(QString::fromStdString(nameForRename).contains(QRegularExpression(QStringLiteral("[/\\\\\\*]"))))
    {
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Critical,"["+std::to_string(id)+("] can't use this kind of name, internal error"));
        emit errorOnFile(destination,tr("Try rename with using special characters").toStdString());
        return;
    }
    #ifdef WIDESTRING
    std::string::size_type n=destination.rfind(L'/');
    #else
    std::string::size_type n=destination.rfind('/');
    #endif
    #ifdef Q_OS_WIN32
    const std::wstring::size_type n2=destination.rfind(L'\\');
    if(n2>n && (n2!=std::wstring::npos || n==std::wstring::npos))
        n=n2;
    #endif
    #ifdef WIDESTRING
    if(n != std::wstring::npos)
    #else
    if(n != std::string::npos)
    #endif
    {
        INTERNALTYPEPATH destinationPath=destination.substr(0,n);//+1
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] nameForRename: "+nameForRename+", destinationPath: "+internalStringTostring(destinationPath));
        if(stringEndsWith(destinationPath,'/')
        #ifdef Q_OS_WIN32
                || stringEndsWith(destinationPath,'\\')
        #endif
                )
            destination=destinationPath+TransferThread::stringToInternalString(nameForRename);
        else
            destination=destinationPath+TransferThread::stringToInternalString("/")+TransferThread::stringToInternalString(nameForRename);
    }
    else
        destination=TransferThread::stringToInternalString(nameForRename);

    /*why all this code?
    if(!renameTheOriginalDestination)
        destination=destination+TransferThread::stringToInternalString("/")+TransferThread::stringToInternalString(nameForRename);
    else
    {
        //INTERNALTYPEPATH tempDestination=destination;
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Information,"["+std::to_string(id)+"] rename "+TransferThread::internalStringTostring(destination)+
                                 ": to: "+TransferThread::internalStringTostring(destination)+"/"+nameForRename);
        if(!rename(destination,(destination+TransferThread::stringToInternalString("/")+TransferThread::stringToInternalString(nameForRename))))
        {
            if(!is_file(destination))
            {
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] source not exists "+TransferThread::internalStringTostring(destination)+
                                         ": destination: "+TransferThread::internalStringTostring(destination)+", error: "+std::to_string(errno));
                emit errorOnFile(destination,tr("File not found").toStdString());
                return;
            }
            else
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] unable to do real move "+TransferThread::internalStringTostring(destination)+
                                         ": "+TransferThread::internalStringTostring(destination)+", error: "+std::to_string(errno));
            emit errorOnFile(destination,"errno: "+std::string(strerror(errno)));
            return;
        }
        if(source==destination)
            source=destination+TransferThread::stringToInternalString("/")+TransferThread::stringToInternalString(nameForRename);
        destination=tempDestination;
    }*/
    fileExistsAction	= FileExists_NotSet;
    resetExtraVariable();
    emit internalStartPreOperation();
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] destination is: "+TransferThread::internalStringTostring(destination));
}

bool TransferThread::rename(const INTERNALTYPEPATH &source, const INTERNALTYPEPATH &destination)
{
    #ifdef Q_OS_WIN32
    return MoveFileExW(
                        TransferThread::toFinalPath(source).c_str(),
                        TransferThread::toFinalPath(destination).c_str(),
                        MOVEFILE_REPLACE_EXISTING);
    #else
    return ::rename(TransferThread::internalStringTostring(source).c_str(),
                    TransferThread::internalStringTostring(destination).c_str())==0;
    #endif
}

void TransferThread::setAlwaysFileExistsAction(const FileExistsAction &action)
{
    //ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+QStringLiteral("] action to do always: ")+QString::number(action)));
    alwaysDoFileExistsAction=action;
}

void TransferThread::resetExtraVariable()
{
    sended_state_preOperationStopped=false;
    writeError                  = false;
    readError                   = false;
    needRemove                  = false;
    needSkip                    = false;
    retry                       = false;
    havePermission              = false;
}

bool TransferThread::isSame()
{
    //check if source and destination is not the same
    //source.absoluteFilePath()==destination.absoluteFilePath() not work is source don't exists
    if(source==destination)
    {
        #ifdef ULTRACOPIER_PLUGIN_DEBUG
        if(!is_file(destination))
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] start source: "+TransferThread::internalStringTostring(source)+" not exists");
        if(is_symlink(source))
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] start source: "+TransferThread::internalStringTostring(source)+" isSymLink");
        if(is_symlink(destination))
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] start destination: "+TransferThread::internalStringTostring(destination)+" isSymLink");
        #endif
        if(fileExistsAction==FileExists_NotSet && alwaysDoFileExistsAction==FileExists_Skip)
        {
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] is same but skip");
            transfer_stat=TransferStat_Idle;
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] transfer_stat=TransferStat_Idle");
            emit postOperationStopped();
            //quit
            return true;
        }
        if(checkAlwaysRename())
            return false;
        emit fileAlreadyExists(source,destination,true);
        return true;
    }
    return false;
}

bool TransferThread::destinationExists()
{
    //check if destination exists
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] "+QStringLiteral("overwrite: %1, alwaysDoFileExistsAction: %2, readError: %3, writeError: %4")
                             .arg(fileExistsAction)
                             .arg(alwaysDoFileExistsAction)
                             .arg(readError)
                             .arg(writeError)
                             .toStdString()
                             );
    if(alwaysDoFileExistsAction==FileExists_Overwrite || readError || writeError
            #ifdef ULTRACOPIER_PLUGIN_RSYNC
            || rsync
            #endif
            )
        return false;

    bool destinationExists=false;
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] time to first FS access");
    destinationExists=is_file(destination);
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] finish first FS access: "+std::to_string(destinationExists));
    if(destinationExists)
    {
        if(fileExistsAction==FileExists_NotSet && alwaysDoFileExistsAction==FileExists_Skip)
        {
            transfer_stat=TransferStat_Idle;
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] transfer_stat=TransferStat_Idle");
            emit postOperationStopped();
            //quit
            return true;
        }
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] FS access");
        if(checkAlwaysRename())
            return false;
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] FS access");
        if(is_file(source))
        {
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] FS access");
            if(fileExistsAction==FileExists_OverwriteIfNewer || (fileExistsAction==FileExists_NotSet && alwaysDoFileExistsAction==FileExists_OverwriteIfNewer))
            {
                const int64_t &sm=readFileMDateTime(source);
                const int64_t &sd=readFileMDateTime(destination);
                if(sm==-1)
                {
                    #ifndef Q_OS_WIN32
                    const int e=errno;
                    emit errorOnFile(source,"Unable to read modification time: "+std::string(strerror(e))+" ("+std::to_string(e)+")");
                    #else
                    emit errorOnFile(source,"Unable to read modification time: "+GetLastErrorStdStr());
                    #endif
                    return true;
                }
                if(sd==-1)
                {
                    #ifndef Q_OS_WIN32
                    const int e=errno;
                    emit errorOnFile(destination,"Unable to read modification time: "+std::string(strerror(e))+" ("+std::to_string(e)+")");
                    #else
                    emit errorOnFile(destination,"Unable to read modification time: "+GetLastErrorStdStr());
                    #endif
                    return true;
                }
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] readFileMDateTime(source): "+std::to_string(sm));
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] readFileMDateTime(destination): "+std::to_string(sd));
                if(sm>sd || sm==-1 || sd==-1)
                    return false;
                else
                {
                    transfer_stat=TransferStat_Idle;
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] transfer_stat=TransferStat_Idle;");
                    emit postOperationStopped();
                    return true;
                }
            }
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] FS access");
            if(fileExistsAction==FileExists_OverwriteIfOlder || (fileExistsAction==FileExists_NotSet && alwaysDoFileExistsAction==FileExists_OverwriteIfOlder))
            {
                const int64_t &sm=readFileMDateTime(source);
                const int64_t &sd=readFileMDateTime(destination);
                if(sm==-1)
                {
                    #ifndef Q_OS_WIN32
                    const int e=errno;
                    emit errorOnFile(source,"Unable to read modification time: "+std::string(strerror(e))+" ("+std::to_string(e)+")");
                    #else
                    emit errorOnFile(source,"Unable to read modification time: "+GetLastErrorStdStr());
                    #endif
                    return true;
                }
                if(sd==-1)
                {
                    #ifndef Q_OS_WIN32
                    const int e=errno;
                    emit errorOnFile(destination,"Unable to read modification time: "+std::string(strerror(e))+" ("+std::to_string(e)+")");
                    #else
                    emit errorOnFile(destination,"Unable to read modification time: "+GetLastErrorStdStr());
                    #endif
                    return true;
                }
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] readFileMDateTime(source): "+std::to_string(sm));
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] readFileMDateTime(destination): "+std::to_string(sd));
                if(sm<sd/* || sm==-1 || sd==-1*/)
                    return false;
                else
                {
                    transfer_stat=TransferStat_Idle;
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] transfer_stat=TransferStat_Idle;");
                    emit postOperationStopped();
                    return true;
                }
            }
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] FS access");
            if(fileExistsAction==FileExists_OverwriteIfNotSameMdate || (fileExistsAction==FileExists_NotSet && alwaysDoFileExistsAction==FileExists_OverwriteIfNotSameMdate))
            {
                const int64_t &sm=readFileMDateTime(source);
                const int64_t &sd=readFileMDateTime(destination);
                if(sm==-1)
                {
                    #ifndef Q_OS_WIN32
                    const int e=errno;
                    emit errorOnFile(source,"Unable to read modification time: "+std::string(strerror(e))+" ("+std::to_string(e)+")");
                    #else
                    emit errorOnFile(source,"Unable to read modification time: "+GetLastErrorStdStr());
                    #endif
                    return true;
                }
                if(sd==-1)
                {
                    #ifndef Q_OS_WIN32
                    const int e=errno;
                    emit errorOnFile(destination,"Unable to read modification time: "+std::string(strerror(e))+" ("+std::to_string(e)+")");
                    #else
                    emit errorOnFile(destination,"Unable to read modification time: "+GetLastErrorStdStr());
                    #endif
                    return true;
                }
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] readFileMDateTime(source): "+std::to_string(sm));
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] readFileMDateTime(destination): "+std::to_string(sd));
                if(sm!=sd || sm==-1 || sd==-1)
                    return false;
                else
                {
                    transfer_stat=TransferStat_Idle;
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] transfer_stat=TransferStat_Idle;");
                    emit postOperationStopped();
                    return true;
                }
            }
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] FS access");
            if(fileExistsAction==FileExists_OverwriteIfNotSameSize || (fileExistsAction==FileExists_NotSet && alwaysDoFileExistsAction==FileExists_OverwriteIfNotSameMdate))
            {
                if(file_stat_size(source)!=file_stat_size(destination))
                    return false;
                else
                {
                    transfer_stat=TransferStat_Idle;
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] transfer_stat=TransferStat_Idle;");
                    emit postOperationStopped();
                    return true;
                }
            }
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] FS access");
            if(fileExistsAction==FileExists_OverwriteIfNotSameSizeAndDate || (fileExistsAction==FileExists_NotSet && alwaysDoFileExistsAction==FileExists_OverwriteIfNotSameMdate))
            {
                const int64_t &sm=readFileMDateTime(source);
                const int64_t &sd=readFileMDateTime(destination);
                if(sm==-1)
                {
                    #ifndef Q_OS_WIN32
                    const int e=errno;
                    emit errorOnFile(source,"Unable to read modification time: "+std::string(strerror(e))+" ("+std::to_string(e)+")");
                    #else
                    emit errorOnFile(source,"Unable to read modification time: "+GetLastErrorStdStr());
                    #endif
                    return true;
                }
                if(sd==-1)
                {
                    #ifndef Q_OS_WIN32
                    const int e=errno;
                    emit errorOnFile(destination,"Unable to read modification time: "+std::string(strerror(e))+" ("+std::to_string(e)+")");
                    #else
                    emit errorOnFile(destination,"Unable to read modification time: "+GetLastErrorStdStr());
                    #endif
                    return true;
                }
                if(sm!=sd || file_stat_size(source)!=file_stat_size(destination))
                    return false;
                else
                {
                    transfer_stat=TransferStat_Idle;
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] transfer_stat=TransferStat_Idle;");
                    emit postOperationStopped();
                    return true;
                }
            }
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] FS access");
        }
        else
        {
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] FS access");
            if(fileExistsAction!=FileExists_NotSet)
            {
                transfer_stat=TransferStat_Idle;
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] transfer_stat=TransferStat_Idle;");
                emit postOperationStopped();
                return true;
            }
        }
        if(fileExistsAction==FileExists_NotSet)
        {
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] FS access");
            emit fileAlreadyExists(source,destination,false);
            return true;
        }
    }
    return false;
}

/** \example
 * /dir1/dir2/file -> file
 * /file -> file
 * /dir1/dir2/ -> dir2
 * /dir1/ -> dir1
 * / -> root */
#ifdef Q_OS_WIN32
std::string TransferThread::resolvedName(std::string inode)
#else
std::string TransferThread::resolvedName(const std::string &inode)
#endif
{
    #ifdef Q_OS_WIN32
    stringreplaceAll(inode,"\\","/");
    #endif
    const std::string::size_type &lastPos=inode.rfind('/');
    if(lastPos == std::string::npos || (lastPos==0 && inode.size()==1))
        return "root";
    if((lastPos+1)!=inode.size())
        return inode.substr(lastPos+1);
    if(inode.size()==1)
        return "root";
    const std::string::size_type &previousLastPos=inode.rfind('/',inode.size()-2);
    if((lastPos-2)==previousLastPos || previousLastPos == std::string::npos)
        return "root";
    return inode.substr(previousLastPos+1,lastPos-previousLastPos-1);
}

#ifdef Q_OS_WIN32
std::wstring TransferThread::resolvedName(std::wstring inode)
#else
std::wstring TransferThread::resolvedName(const std::wstring &inode)
#endif
{
    #ifdef Q_OS_WIN32
    stringreplaceAll(inode,L"\\",L"/");
    #endif
    const std::wstring::size_type &lastPos=inode.rfind(L'/');
    if(lastPos == std::wstring::npos || (lastPos==0 && inode.size()==1))
        return L"root";
    if((lastPos+1)!=inode.size())
        return inode.substr(lastPos+1);
    if(inode.size()==1)
        return L"root";
    const std::wstring::size_type &previousLastPos=inode.rfind(L'/',inode.size()-2);
    if((lastPos-2)==previousLastPos || previousLastPos == std::wstring::npos)
        return L"root";
    return inode.substr(previousLastPos+1,lastPos-previousLastPos-1);
}

INTERNALTYPEPATH TransferThread::getSourcePath() const
{
    return source;
}

INTERNALTYPEPATH TransferThread::getDestinationPath() const
{
    return destination;
}

Ultracopier::CopyMode TransferThread::getMode() const
{
    return mode;
}

//return true if has been renamed
bool TransferThread::checkAlwaysRename()
{
    if(alwaysDoFileExistsAction==FileExists_Rename)
    {
        INTERNALTYPEPATH newDestination=destination;
        std::string fileName=resolvedName(TransferThread::internalStringTostring(newDestination));
        std::string suffix;
        std::string newFileName;
        //resolv the suffix
        if(std::regex_match(fileName,renameRegex))
        {
            suffix=fileName;
            suffix=std::regex_replace(suffix,renameRegex,"$2");
            fileName=std::regex_replace(fileName,renameRegex,"$1");
        }
        //resolv the new name
        int num=1;
        do
        {
            if(num==1)
            {
                if(firstRenamingRule.empty())
                    newFileName=tr("%name% - copy%suffix%").toStdString();
                else
                    newFileName=firstRenamingRule;
            }
            else
            {
                if(otherRenamingRule.empty())
                    newFileName=tr("%name% - copy (%number%)%suffix%").toStdString();
                else
                    newFileName=otherRenamingRule;
                stringreplaceAll(newFileName,"%number%",std::to_string(num));
            }
            stringreplaceAll(newFileName,"%name%",fileName);
            stringreplaceAll(newFileName,"%suffix%",suffix);
            newDestination=FSabsolutePath(newDestination);
            if(!stringEndsWith(newDestination,'/')
                #ifdef Q_OS_WIN32
                    && !stringEndsWith(destination,'\\')
                #endif
                    )
                newDestination+=TransferThread::stringToInternalString("/");
            newDestination+=TransferThread::stringToInternalString(newFileName);
            num++;
        }
        while(is_file(newDestination));
        if(!renameTheOriginalDestination)
            destination=newDestination;
        else
        {
            if(rename(destination.c_str(),newDestination.c_str())!=0)
            {
                if(!is_file(destination))
                {
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] source not exists "+TransferThread::internalStringTostring(destination)+
                                             ": destination: "+TransferThread::internalStringTostring(newDestination)+", error: "+std::to_string(errno));
                    emit errorOnFile(destination,tr("File not found").toStdString());
                    readError=true;
                    return true;
                }
                else
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] unable to do real move "+TransferThread::internalStringTostring(destination)+
                                             ": "+TransferThread::internalStringTostring(newDestination)+", error: "+std::to_string(errno));
                readError=true;
                emit errorOnFile(destination,std::string(strerror(errno))+", errno: "+std::string(strerror(errno)));
                return true;
            }
        }
        return true;
    }
    return false;
}

/// \warning not check if path have double //, if have do bug return failed
/// \warning check mkpath() call should not exists because only existing dest is allowed now
#ifdef Q_OS_UNIX
bool TransferThread::mkpath(const INTERNALTYPEPATH &path, const mode_t &mode)
#else
bool TransferThread::mkpath(const INTERNALTYPEPATH &path)
#endif
{
    #ifdef Q_OS_WIN32
    if(!mkdir(path))
        if(errno==EEXIST)
            return true;

    printf("%i",errno);
    #ifndef WIDESTRING
    #error if windows, WIDESTRING need be enabled
    #endif
    //use reverse method to performance, more complex to code but less system call/fs call
    std::wstring::size_type previouspos=path.size();
    std::wstring::size_type lastpos=std::string::npos;

    const wchar_t *pathC=path.c_str();
    wchar_t pathCedit[32000];
    wcscpy(pathCedit,pathC);
    std::vector<std::wstring::size_type> pathSplit;
    pathSplit.push_back(path.size());
    do
    {
        lastpos=path.rfind(L'/',previouspos-1);
        if(lastpos == std::wstring::npos)
            return false;

        while(pathC[lastpos-1]==L'/')
            if(lastpos>0)
                lastpos--;
            else
                return false;

        //buggy case?
        #ifdef Q_OS_UNIX
        if(lastpos<2)
            return false;
        #else
        if(lastpos<4)
            return false;
        #endif

        pathCedit[lastpos]=L'\0';
        previouspos=lastpos;

        errno=0;
        if(!mkdir(pathCedit))
            if(errno!=EEXIST && errno!=ENOENT)
                return false;
        //here errno can be: EEXIST, ENOENT, 0
        if(errno==ENOENT)
            pathSplit.push_back(lastpos);
    } while(lastpos>0 && errno==ENOENT);

    do
    {
        wcscpy(pathCedit,pathC);
        lastpos=pathSplit.back();
        pathSplit.pop_back();
        pathCedit[lastpos]=L'\0';
        #ifdef Q_OS_UNIX
        if(mkdir(pathCedit, mode)==-1)
        #else
        if(!mkdir(pathCedit))
        #endif
            if(errno!=EEXIST)
                return false;
    } while(!pathSplit.empty());
    return true;
    #else
    char pathC[PATH_MAX];
    strcpy(pathC,TransferThread::internalStringTostring(path).c_str());
    if(!mkdir(path))
        if(errno==EEXIST)
            return true;

    printf("%i",errno);
    //use reverse method to performance, more complex to code but less system call/fs call
    std::string::size_type previouspos=path.size();
    std::string::size_type lastpos=std::string::npos;

    char pathCedit[PATH_MAX];
    strcpy(pathCedit,pathC);
    std::vector<std::string::size_type> pathSplit;
    pathSplit.push_back(path.size());
    do
    {
        lastpos=path.rfind('/',previouspos-1);
        if(lastpos == std::string::npos)
            return false;

        while(pathC[lastpos-1]=='/')
            if(lastpos>0)
                lastpos--;
            else
                return false;

        //buggy case?
        #ifdef Q_OS_UNIX
        if(lastpos<2)
            return false;
        #else
        if(lastpos<4)
            return false;
        #endif

        pathCedit[lastpos]='\0';
        previouspos=lastpos;

        errno=0;
        #ifdef Q_OS_UNIX
        if(::mkdir(pathCedit, mode)==-1)
        #else
        if(::mkdir(pathCedit)==-1)
        #endif
            if(errno!=EEXIST && errno!=ENOENT)
                return false;
        //here errno can be: EEXIST, ENOENT, 0
        if(errno==ENOENT)
            pathSplit.push_back(lastpos);
    } while(lastpos>0 && errno==ENOENT);

    do
    {
        strcpy(pathCedit,pathC);
        lastpos=pathSplit.back();
        pathSplit.pop_back();
        pathCedit[lastpos]='\0';
        #ifdef Q_OS_UNIX
        if(::mkdir(pathCedit, mode)==-1)
        #else
        if(::mkdir(pathCedit)==-1)
        #endif
            if(errno!=EEXIST)
                return false;
    } while(!pathSplit.empty());
    return true;
    #endif
}

#ifdef Q_OS_UNIX
bool TransferThread::mkdir(const INTERNALTYPEPATH &file_path, const mode_t &mode)
#else
bool TransferThread::mkdir(const INTERNALTYPEPATH &file_path)
#endif
{
#ifdef Q_OS_WIN32
    const bool r = CreateDirectory(TransferThread::toFinalPath(file_path).c_str(),NULL);
    const DWORD &t=GetLastError();
    if(!r)
    {
        if(t==183/*is_dir(file_path) performance impact*/)
            errno=EEXIST;
        else if(t==3/*is_dir(file_path) performance impact*/)
            errno=ENOENT;
        else
            errno=t;
    }
    return r;
#else
    #ifdef Q_OS_UNIX
    return ::mkdir(TransferThread::internalStringTostring(file_path).c_str(),mode)==0;
    #else
    return ::mkdir(TransferThread::internalStringTostring(file_path).c_str())==0;
    #endif
#endif
}

bool TransferThread::canBeMovedDirectly() const
{
    if(mode!=Ultracopier::Move)
    {
        ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] mode!=Ultracopier::Move");
        return false;
    }
    return is_symlink(source) || driveManagement.isSameDrive(
                TransferThread::internalStringTostring(destination),
                TransferThread::internalStringTostring(source)
                );
}

bool TransferThread::canBeCopiedDirectly() const
{
    return is_symlink(source);
}

//set the copy info and options before runing
void TransferThread::setRightTransfer(const bool doRightTransfer)
{
    this->doRightTransfer=doRightTransfer;
}

/// \brief set buffer
void TransferThread::setBuffer(const bool buffer)
{
    Q_UNUSED(buffer);
}

/*void TransferThread::setBufferSize(const int parallelBuffer,const int serialBuffer)
{
    writeThread->setBufferSize(const int parallelBuffer,const int serialBuffer);
}*/

//set keep date
void TransferThread::setKeepDate(const bool keepDate)
{
    this->keepDate=keepDate;
}

bool TransferThread::doFilePostOperation()
{
    //do operation needed by copy
    //set the time if no write thread used

    if(/*not implied by is_symlink, exist can be false because symlink dest not exists*/
            !exists(destination) && !is_symlink(destination))
    {
        if(!stopIt)
            if(/*true when the destination have been remove but not the symlink:*/!is_symlink(source))
            {
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] Unable to change the date: File not found");
                emit errorOnFile(destination,tr("Unable to change the date").toStdString()+": "+tr("File not found").toStdString());
                return false;
            }
    }
    else
    {
        if(doRightTransfer)
        {
            //should be never used but...
            /*source.refresh();
            if(source.exists())*/
            if(havePermission)
            {
                if(!writeDestinationFilePermissions(destination))
                {
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] Unable to set the destination file permission");
                    //emit errorOnFile(destination,tr("Unable to set the destination file permission"));
                    //return false;
                }
            }
            else
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] Try doRightTransfer when source not exists");
        }
        //date at end because previous change can touch the file
        if(doTheDateTransfer)
        {
            if(!writeDestinationFileDateTime(destination))
            {
                if(!is_file(destination))
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] Unable to change the date (is not a file)");
                else
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] Unable to change the date");
                /* error with virtual folder under windows */
                #ifndef Q_OS_WIN32
                if(keepDate)
                {
                    emit errorOnFile(destination,tr("Unable to change the date").toStdString());
                    return false;
                }
                #endif
            }
            /*else -> need be done at source m time read
            {
                #ifndef Q_OS_WIN32
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] read the destination time: "+destination.lastModified().toString().toStdString());
                if(destination.lastModified()<ULTRACOPIER_PLUGIN_MINIMALYEAR_TIMESTAMPS)
                {
                    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] read the destination time lower than min time: "+destination.lastModified().toString().toStdString());
                    if(keepDate)
                    {
                        emit errorOnFile(destination,tr("Unable to change the date").toStdString());
                        return false;
                    }
                }
                #endif
            }*/
        }

    }
    if(stopIt)
        return false;

    return true;
}

//////////////////////////////////////////////////////////////////
///////////////////////// Normal event ///////////////////////////
//////////////////////////////////////////////////////////////////

int64_t TransferThread::readFileMDateTime(const INTERNALTYPEPATH &source)
{
    //ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"readFileDateTime("+source+")");
    /** Why not do it with Qt? Because it not support setModificationTime(), and get the time with Qt, that's mean use local time where in C is UTC time */
    #ifdef Q_OS_UNIX
        struct stat info;
        if(stat(TransferThread::internalStringTostring(source).c_str(),&info)!=0)
            return -1;
        #ifdef Q_OS_MAC
        return info.st_mtimespec.tv_sec;
        #else
        return info.st_mtim.tv_sec;
        #endif
    #else
        #ifdef Q_OS_WIN32
            HANDLE hFileSouce = CreateFileW(TransferThread::toFinalPath(source).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
            if(hFileSouce == INVALID_HANDLE_VALUE)
                return -1;
            FILETIME ftCreate, ftAccess, ftWrite;
            if(!GetFileTime(hFileSouce, &ftCreate, &ftAccess, &ftWrite))
            {
                CloseHandle(hFileSouce);
                //ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] unable to get the file time: "+TransferThread::GetLastErrorStdStr());
                return -1;
            }
            CloseHandle(hFileSouce);
            const int64_t UNIX_TIME_START = 0x019DB1DED53E8000; //January 1, 1970 (start of Unix epoch) in "ticks"
            const int64_t TICKS_PER_SECOND = 10000000; //a tick is 100ns
            LARGE_INTEGER li;
            li.LowPart  = ftWrite.dwLowDateTime;
            li.HighPart = ftWrite.dwHighDateTime;
            return (li.QuadPart - UNIX_TIME_START) / TICKS_PER_SECOND;
        #else
            return -1;
        #endif
    #endif
    return -1;
}

//fonction to read the file date time
bool TransferThread::readSourceFileDateTime(const INTERNALTYPEPATH &source)
{
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] readFileDateTime("+TransferThread::internalStringTostring(source)+")");
    /** Why not do it with Qt? Because it not support setModificationTime(), and get the time with Qt, that's mean use local time where in C is UTC time */
    #ifdef Q_OS_UNIX
        struct stat info;
        if(stat(TransferThread::internalStringTostring(source).c_str(),&info)!=0)
            return false;
        #ifdef Q_OS_MAC
        time_t ctime=info.st_ctimespec.tv_sec;
        time_t actime=info.st_atimespec.tv_sec;
        time_t modtime=info.st_mtimespec.tv_sec;
        //this function avalaible on unix and mingw
        butime.actime=actime;
        butime.modtime=modtime;
        #else
        time_t ctime=info.st_ctim.tv_sec;
        time_t actime=info.st_atim.tv_sec;
        time_t modtime=info.st_mtim.tv_sec;
        //this function avalaible on unix and mingw
        butime.actime=actime;
        butime.modtime=modtime;
        #endif
        if((uint64_t)modtime<ULTRACOPIER_PLUGIN_MINIMALYEAR_TIMESTAMPS)
        {
            ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] the sources is older to copy the time: "+TransferThread::internalStringTostring(source));
            return false;
        }
        Q_UNUSED(ctime);
        return true;
    #else
        #ifdef Q_OS_WIN32
            HANDLE hFileSouce = CreateFileW(TransferThread::toFinalPath(source).c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
            if(hFileSouce == INVALID_HANDLE_VALUE)
            {
                //ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] open failed to read: "+QString::fromWCharArray(filePath).toStdString()+", error: "+TransferThread::GetLastErrorStdStr());
                return false;
            }
            FILETIME ftCreate, ftAccess, ftWrite;
            if(!GetFileTime(hFileSouce, &ftCreate, &ftAccess, &ftWrite))
            {
                CloseHandle(hFileSouce);
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] unable to get the file time");
                return false;
            }
            this->ftCreate=ftCreate;
            this->ftAccess=ftAccess;
            this->ftWrite=ftWrite;
            CloseHandle(hFileSouce);
            const uint64_t modtime=(uint64_t)ftWrite.dwLowDateTime + ((uint64_t)2^32 * (uint64_t)ftWrite.dwHighDateTime);
            if(modtime<ULTRACOPIER_PLUGIN_MINIMALYEAR_TIMESTAMPS)
            {
                //ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] the sources is older to copy the time: "+source+": "+source.lastModified().toString().toStdString());
                return false;
            }
            return true;
        #else
            return false;
        #endif
    #endif
    return false;
}

bool TransferThread::writeDestinationFileDateTime(const INTERNALTYPEPATH &destination)
{
    ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Notice,"["+std::to_string(id)+"] writeFileDateTime("+TransferThread::internalStringTostring(destination)+")");
    /** Why not do it with Qt? Because it not support setModificationTime(), and get the time with Qt, that's mean use local time where in C is UTC time */
    #ifdef Q_OS_UNIX
        return utime(TransferThread::internalStringTostring(destination).c_str(),&butime)==0;
    #else
        #ifdef Q_OS_WIN32
            HANDLE hFileDestination = CreateFileW(TransferThread::toFinalPath(destination).c_str(), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
            if(hFileDestination == INVALID_HANDLE_VALUE)
            {
                //ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] open failed to write: "+QString::fromWCharArray(filePath).toStdString()+", error: "+TransferThread::GetLastErrorStdStr());
                return false;
            }
            FILETIME ftCreate, ftAccess, ftWrite;
            ftCreate=this->ftCreate;
            ftAccess=this->ftAccess;
            ftWrite=this->ftWrite;
            if(!SetFileTime(hFileDestination, &ftCreate, &ftAccess, &ftWrite))
            {
                CloseHandle(hFileDestination);
                ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] unable to set the file time");
                return false;
            }
            CloseHandle(hFileDestination);
            return true;
        #else
            return false;
        #endif
    #endif
    return false;
}

bool TransferThread::readSourceFilePermissions(const INTERNALTYPEPATH &source)
{
    #ifdef Q_OS_UNIX
    if(stat(TransferThread::internalStringTostring(source).c_str(), &permissions)!=0)
        return false;
    else
        return true;
    #else
    HANDLE hFile = CreateFileW(source.c_str(), GENERIC_READ ,
            FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
    if (hFile == INVALID_HANDLE_VALUE) {
      ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] CreateFile() failed. Error: INVALID_HANDLE_VALUE: "+TransferThread::GetLastErrorStdStr());
      return false;
    }
    DWORD lasterror = GetSecurityInfo(hFile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
                                NULL, NULL, &dacl, NULL, &PSecurityD);
    if (lasterror != ERROR_SUCCESS) {
      ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] GetSecurityInfo() failed. Error"+std::to_string(lasterror));
      return false;
    }
    CloseHandle(hFile);
    return true;
    #endif
}

bool TransferThread::writeDestinationFilePermissions(const INTERNALTYPEPATH &destination)
{
    #ifdef Q_OS_UNIX
    if(chmod(TransferThread::internalStringTostring(destination).c_str(), permissions.st_mode)!=0)
        return false;
    if(chown(TransferThread::internalStringTostring(destination).c_str(), permissions.st_uid, permissions.st_gid)!=0)
        return false;
    return true;
    #else
    HANDLE hFile = CreateFileW(destination.c_str(),READ_CONTROL | WRITE_OWNER | WRITE_DAC | ACCESS_SYSTEM_SECURITY,0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
    if (hFile == INVALID_HANDLE_VALUE) {
      ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] CreateFile() failed. Error: INVALID_HANDLE_VALUE: "+TransferThread::GetLastErrorStdStr());
      return false;
    }
    DWORD lasterror = SetSecurityInfo(hFile, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION , NULL, NULL, dacl, NULL);
    if (lasterror != ERROR_SUCCESS) {
      ULTRACOPIER_DEBUGCONSOLE(Ultracopier::DebugLevel_Warning,"["+std::to_string(id)+"] SetSecurityInfo() failed. Error"+std::to_string(lasterror));
      return false;
    }
    CloseHandle(hFile);
    if(PSecurityD!=NULL)
    {
        //free(PSecurityD);//crash on some NAS, it's why is commented, http://forum-ultracopier.first-world.info/viewtopic.php?f=8&t=903&p=3689#p3689
        PSecurityD=NULL;
    }
    if(dacl!=NULL)
    {
        //free(dacl);
        dacl=NULL;
    }
    return true;
    #endif
}

//retry after error
void TransferThread::putAtBottom()
{
    emit tryPutAtBottom();
}

#ifdef ULTRACOPIER_PLUGIN_RSYNC
/// \brief set rsync
void TransferThread::setRsync(const bool rsync)
{
    this->rsync=rsync;
}
#endif

#ifdef ULTRACOPIER_PLUGIN_DEBUG
//to set the id
void TransferThread::setId(int id)
{
    this->id=id;
}
#endif

void TransferThread::setRenamingRules(const std::string &firstRenamingRule, const std::string &otherRenamingRule)
{
    this->firstRenamingRule=firstRenamingRule;
    this->otherRenamingRule=otherRenamingRule;
}

void TransferThread::setDeletePartiallyTransferredFiles(const bool &deletePartiallyTransferredFiles)
{
    this->deletePartiallyTransferredFiles=deletePartiallyTransferredFiles;
}

void TransferThread::setRenameTheOriginalDestination(const bool &renameTheOriginalDestination)
{
    this->renameTheOriginalDestination=renameTheOriginalDestination;
}

void TransferThread::set_updateMount()
{
    driveManagement.tryUpdate();
}

bool TransferThread::is_symlink(const INTERNALTYPEPATH &filename)
{
    #ifdef Q_OS_WIN32
    WIN32_FILE_ATTRIBUTE_DATA fileInfo;
    BOOL r = GetFileAttributesExW(TransferThread::toFinalPath(filename).c_str(), GetFileExInfoStandard, &fileInfo);
    if(r != FALSE)
    {
        return fileInfo.dwFileAttributes != INVALID_FILE_ATTRIBUTES &&
           (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT);
    }
    else
        return false;
    #else
    return is_symlink(TransferThread::internalStringTostring(filename).c_str());
    #endif
}

bool TransferThread::is_symlink(const char * const filename)
{
    #ifdef Q_OS_WIN32
    WIN32_FILE_ATTRIBUTE_DATA fileInfo;
    BOOL r = GetFileAttributesExA(TransferThread::toFinalPath(filename).c_str(), GetFileExInfoStandard, &fileInfo);
    if(r != FALSE)
    {
        return fileInfo.dwFileAttributes != INVALID_FILE_ATTRIBUTES &&
           (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT);
    }
    else
        return false;
    #else
    struct stat p_statbuf;
    if (lstat(filename, &p_statbuf) < 0)
        //if error or file not exists, considere as regular file
        return false;
    if (S_ISLNK(p_statbuf.st_mode))
        return true;
    #endif
    return false;
}

bool TransferThread::is_file(const INTERNALTYPEPATH &filename)
{
    #ifdef Q_OS_WIN32
    DWORD dwAttrib = GetFileAttributesW(TransferThread::toFinalPath(filename).c_str());
    return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
           (dwAttrib & FILE_ATTRIBUTE_NORMAL || dwAttrib & FILE_ATTRIBUTE_ARCHIVE)
            );
    #else
    return is_file(TransferThread::internalStringTostring(filename).c_str());
    #endif
}

bool TransferThread::is_file(const char * const filename)
{
    #ifdef Q_OS_WIN32
    DWORD dwAttrib = GetFileAttributesA(TransferThread::toFinalPath(filename).c_str());
    return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
           (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
    #else
    struct stat p_statbuf;
    if (lstat(filename, &p_statbuf) < 0)
        //if error or file not exists, considere as regular file
        return false;
    if (S_ISREG(p_statbuf.st_mode))
        return true;
    return false;
    #endif
}

bool TransferThread::is_dir(const INTERNALTYPEPATH &filename)
{
    #ifdef Q_OS_WIN32
    DWORD dwAttrib = GetFileAttributesW(TransferThread::toFinalPath(filename).c_str());
    return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
            (dwAttrib & FILE_ATTRIBUTE_DIRECTORY) &&
            !(dwAttrib & FILE_ATTRIBUTE_REPARSE_POINT));
    #else
    return is_dir(TransferThread::internalStringTostring(filename).c_str());
    #endif
}

bool TransferThread::is_dir(const char * const filename)
{
    #ifdef Q_OS_WIN32
    DWORD dwAttrib = GetFileAttributesA(TransferThread::toFinalPath(filename).c_str());
    return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
           (dwAttrib & FILE_ATTRIBUTE_DIRECTORY) &&
            !(dwAttrib & FILE_ATTRIBUTE_REPARSE_POINT));
    #else
    struct stat p_statbuf;
    if (lstat(filename, &p_statbuf) < 0)
        //if error or file not exists, considere as regular file
        return false;
    if (S_ISDIR(p_statbuf.st_mode))
        return true;
    return false;
    #endif
}

bool TransferThread::exists(const INTERNALTYPEPATH &filename)
{
    #ifdef Q_OS_WIN32
    DWORD dwAttrib = GetFileAttributesW(TransferThread::toFinalPath(filename).c_str());
    return dwAttrib != INVALID_FILE_ATTRIBUTES;
    #else
    return exists(TransferThread::internalStringTostring(filename).c_str());
    #endif
}

bool TransferThread::exists(const char * const filename)
{
    #ifdef Q_OS_WIN32
    DWORD dwAttrib = GetFileAttributesA(TransferThread::toFinalPath(filename).c_str());
    return dwAttrib != INVALID_FILE_ATTRIBUTES;
    #else
    struct stat p_statbuf;
    if (lstat(filename, &p_statbuf) < 0)
        //if error or file not exists, considere as regular file
        return false;
    #endif
    return true;
}

int64_t TransferThread::file_stat_size(const INTERNALTYPEPATH &filename)
{
    #ifdef Q_OS_WIN32
    WIN32_FILE_ATTRIBUTE_DATA fileInfo;
    BOOL r = GetFileAttributesExW(TransferThread::toFinalPath(filename).c_str(), GetFileExInfoStandard, &fileInfo);
    if(r == FALSE)
        return -1;
    int64_t size=fileInfo.nFileSizeHigh;
    size<<=32;
    size|=fileInfo.nFileSizeLow;
    return size;
    #else
    return file_stat_size(TransferThread::internalStringTostring(filename).c_str());
    #endif
}

int64_t TransferThread::file_stat_size(const char * const filename)
{
    #ifdef Q_OS_WIN32
    WIN32_FILE_ATTRIBUTE_DATA fileInfo;
    BOOL r = GetFileAttributesExA(TransferThread::toFinalPath(filename).c_str(), GetFileExInfoStandard, &fileInfo);
    if(r == FALSE)
        return -1;
    int64_t size=fileInfo.nFileSizeHigh;
    size<<=32;
    size|=fileInfo.nFileSizeLow;
    return size;
    #else
    struct stat p_statbuf;
    if (stat(filename, &p_statbuf) < 0)
        //if error or file not exists, considere as regular file
        return -1;
    if (lstat(filename, &p_statbuf) < 0)
        //if error or file not exists, considere as regular file
        return -1;
    return p_statbuf.st_size;
    #endif
}

bool TransferThread::entryInfoList(const INTERNALTYPEPATH &path,std::vector<INTERNALTYPEPATH> &list)
{
    std::vector<dirent_uc> listTemp;
    if(!TransferThread::entryInfoList(path,listTemp))
        return false;
    for(const dirent_uc &u : listTemp)
        list.push_back(u.d_name);
    return true;
}

bool TransferThread::rmdir(const INTERNALTYPEPATH &path)
{
    #ifdef Q_OS_WIN32
    return RemoveDirectoryW(TransferThread::toFinalPath(path).c_str());
    #else
    return ::rmdir(TransferThread::internalStringTostring(path).c_str())==0;
    #endif
}

#ifdef Q_OS_UNIX
bool TransferThread::entryInfoList(const INTERNALTYPEPATH &path,std::vector<dirent_uc> &list)
{
    DIR *dp;
    struct dirent *ep;
    dp=opendir(TransferThread::internalStringTostring(path).c_str());
    if(dp!=NULL)
    {
        do {
            ep=readdir(dp);
            if(ep!=NULL)
            {
                const std::string name(ep->d_name);
                if(name!="." && name!="..")
                {
                    dirent_uc tempValue;
                    #if defined(__HAIKU__)
                    struct stat sp;
                    memset(&sp,0,sizeof(sp));
                    if(stat((TransferThread::internalStringTostring(path)+"/"+name).c_str(), &sp)==0)
                        tempValue.isFolder=S_ISDIR(sp.st_mode);
                    else
                        return false;
                    #else
                    tempValue.isFolder=ep->d_type==DT_DIR;
                    #endif
                    tempValue.d_name=TransferThread::stringToInternalString(ep->d_name);
                    list.push_back(tempValue);
                }
            }
        } while(ep!=NULL);
        (void) closedir(dp);
        return true;
    }
    return false;
}
#else
bool TransferThread::entryInfoList(const INTERNALTYPEPATH &path,std::vector<dirent_uc> &list)
{
    HANDLE hFind = NULL;
    #ifdef WIDESTRING
    WIN32_FIND_DATAW fdFile;
    if((hFind = FindFirstFileW((TransferThread::toFinalPath(path)+L"\\*").c_str(), &fdFile)) == INVALID_HANDLE_VALUE)
    #else
    WIN32_FIND_DATAA fdFile;
    char finalpath[MAX_PATH];
    strcpy(finalpath,path.c_str());
    strcat(finalpath,"\\*");
    if((hFind = FindFirstFileW(finalpath, &fdFile)) == INVALID_HANDLE_VALUE)
    #endif
        return false;
    do
    {
        #ifdef WIDESTRING
        if(wcscmp(fdFile.cFileName, L".")!=0 && wcscmp(fdFile.cFileName, L"..")!=0)
        #else
        if(strcmp(fdFile.cFileName, ".")!=0 && strcmp(fdFile.cFileName, "..")!=0)
        #endif
        {
            dirent_uc tempValue;
            tempValue.isFolder=
                    (fdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
                    !(fdFile.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
                    ;
            tempValue.d_name=fdFile.cFileName;
            tempValue.size=fdFile.nFileSizeHigh;
            tempValue.size<<=32;
            tempValue.size|=fdFile.nFileSizeLow;
            list.push_back(tempValue);
        }
    }
    while(FindNextFileW(hFind, &fdFile));
    FindClose(hFind);
    return true;
}
#endif

void TransferThread::setMkFullPath(const bool mkFullPath)
{
    this->mkFullPath=mkFullPath;
}

/*int TransferThread::fseeko64(FILE *__stream, uint64_t __off, int __whence)
{
    #if defined(__HAIKU__) || defined(Q_OS_MAC) || defined(ANDROID) || defined(__ANDROID_API__)
    return ::fseeko(__stream,__off,__whence);
    #else
    return ::fseeko64(__stream,__off,__whence);
    #endif
}

int TransferThread::ftruncate64(int __fd, uint64_t __length)
{
    #if defined(__HAIKU__) || defined(Q_OS_MAC) || defined(ANDROID) || defined(__ANDROID_API__)
    return ::ftruncate(__fd,__length);
    #else
    //return ::ftruncate64(__fd,__length);
    return ::ftruncate(__fd,__length);
    #endif
}*/

int64_t TransferThread::transferTime() const
{
    return startTransferTime.elapsed();
}

#ifdef Q_OS_WIN32
std::wstring TransferThread::toFinalPath(std::wstring path)
{
    if(path.size()==2 && path.at(1)==L':')
        path+=L"\\";
    stringreplaceAll(path,L"/",L"\\");
    std::wstring pathW;
    if(path.size()>2 && path.substr(0,2)==L"\\\\")//nas
        pathW=L"\\\\?\\UNC\\"+path.substr(2);
    else
        pathW=L"\\\\?\\"+path;
    return pathW;
}

std::string TransferThread::toFinalPath(std::string path)
{
    if(path.size()==2 && path.at(1)==':')
        path+="\\";
    stringreplaceAll(path,"/","\\");
    std::string pathW;
    if(path.size()>2 && path.substr(0,2)=="\\\\")//nas
        pathW="\\\\?\\UNC\\"+path.substr(2);
    else
        pathW="\\\\?\\"+path;
    return pathW;
}

bool TransferThread::unlink(const std::wstring &path)
{
    return DeleteFileW(TransferThread::toFinalPath(path).c_str()) || RemoveDirectoryW(TransferThread::toFinalPath(path).c_str());
}

std::string TransferThread::GetLastErrorStdStr()
{
  DWORD error = GetLastError();
  if (error)
  {
    LPVOID lpMsgBuf;
    DWORD bufLen = FormatMessageA(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        error,
        MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_DEFAULT),
        (LPSTR) &lpMsgBuf,
        0, NULL );
    if (bufLen)
    {
      std::string result((char *)lpMsgBuf, (int)bufLen);
      LocalFree(lpMsgBuf);
      return result+" ("+std::to_string(error)+")";
    }
    return "1: "+std::to_string(error);
  }
  return "2: "+std::to_string(error);
}
#else
bool TransferThread::unlink(const INTERNALTYPEPATH &path)
{
    return ::unlink(internalStringTostring(path).c_str())==0;
}
#endif