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
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
|
// ---------------------------------------------------------------------------80
// ICQ plugin for Miranda Instant Messenger
// ________________________________________
//
// Copyright © 2000-2001 Richard Hughes, Roland Rabien, Tristan Van de Vreede
// Copyright © 2001-2002 Jon Keating, Richard Hughes
// Copyright © 2002-2004 Martin Öberg, Sam Kothari, Robert Rainwater
// Copyright © 2004-2010 Joe Kucera
// Copyright © 2012-2018 Miranda NG team
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// -----------------------------------------------------------------------------
// DESCRIPTION:
//
// OSCAR File-Transfers implementation
// -----------------------------------------------------------------------------
#include "stdafx.h"
struct oscarthreadstartinfo
{
int type;
int incoming;
MCONTACT hContact;
HNETLIBCONN hConnection;
DWORD dwRemoteIP;
oscar_filetransfer *ft;
oscar_listener *listener;
};
// small utility function
extern void NormalizeBackslash(char* path);
//
// Common functions
/////////////////////////////
char* FindFilePathContainer(const char **files, int iFile, char *szContainer)
{
const char *szThisFile = files[iFile];
char *szFileName = (char*)ExtractFileName(szThisFile);
szContainer[0] = '\0';
if (szThisFile != szFileName) { // find an earlier subdirectory to be used as a container
for (int i = iFile - 1; i >= 0; i--) {
size_t len = mir_strlen(files[i]);
if (!_strnicmp(files[i], szThisFile, len) && (szThisFile[len] == '\\' || szThisFile[len] == '/')) {
const char *pszLastBackslash;
if (((pszLastBackslash = strrchr(files[i], '\\')) == nullptr) &&
((pszLastBackslash = strrchr(files[i], '/')) == nullptr)) {
mir_strcpy(szContainer, files[i]);
}
else {
len = pszLastBackslash - files[i] + 1;
null_strcpy(szContainer, szThisFile + len, szFileName - szThisFile - len);
}
}
}
}
return szFileName;
}
//
// Utility functions
/////////////////////////////
oscar_filetransfer* CIcqProto::CreateOscarTransfer()
{
oscar_filetransfer *ft = (oscar_filetransfer*)SAFE_MALLOC(sizeof(oscar_filetransfer));
ft->ft_magic = FT_MAGIC_OSCAR; // Setup signature
// Init members
ft->fileId = -1;
{
mir_cslock l(oftMutex);
m_arFileTransfers.insert(ft);
}
NetLog_Direct("OFT: FT struct %p created", ft);
return ft;
}
filetransfer* CIcqProto::CreateIcqFileTransfer()
{
filetransfer *ft = (filetransfer*)SAFE_MALLOC(sizeof(filetransfer));
ft->ft_magic = FT_MAGIC_ICQ;
{
mir_cslock l(oftMutex);
m_arFileTransfers.insert(ft);
}
NetLog_Direct("FT struct %p created", ft);
return ft;
}
int CIcqProto::IsValidFileTransfer(basic_filetransfer *ft)
{
mir_cslock l(oftMutex);
return m_arFileTransfers.indexOf(ft) != -1;
}
int CIcqProto::IsValidOscarTransfer(basic_filetransfer *ft)
{
mir_cslock l(oftMutex);
return m_arFileTransfers.indexOf(ft) != -1 && ft->ft_magic == FT_MAGIC_OSCAR;
}
oscar_filetransfer* CIcqProto::FindOscarTransfer(MCONTACT hContact, DWORD dwID1, DWORD dwID2)
{
mir_cslock l(oftMutex);
for (auto &it : m_arFileTransfers) {
if (it->ft_magic == FT_MAGIC_OSCAR) {
oscar_filetransfer *oft = (oscar_filetransfer*)it;
if (oft->hContact == hContact && oft->pMessage.dwMsgID1 == dwID1 && oft->pMessage.dwMsgID2 == dwID2)
return oft;
}
}
return nullptr;
}
// Release file transfer structure
void CIcqProto::SafeReleaseFileTransfer(basic_filetransfer **bft)
{
mir_cslock l(oftMutex);
// Check for filetransfer validity
int idx = m_arFileTransfers.indexOf(*bft);
if (idx == -1)
return;
if (*bft) {
if ((*bft)->ft_magic == FT_MAGIC_ICQ) { // release ICQ filetransfer structure and its contents
filetransfer *ift = (filetransfer*)(*bft);
SAFE_FREE(&ift->szFilename);
SAFE_FREE(&ift->szDescription);
SAFE_FREE(&ift->szSavePath);
SAFE_FREE(&ift->szThisSubdir);
if (ift->pszFiles) {
for (int i = 0; i < (int)ift->dwFileCount; i++) {
// szThisFile can be a duplicate of pszFiles[i]
if (ift->szThisFile == ift->pszFiles[i])
ift->szThisFile = nullptr;
SAFE_FREE(&ift->pszFiles[i]);
}
SAFE_FREE((void**)&ift->pszFiles);
}
SAFE_FREE(&ift->szThisFile);
// Invalidate transfer
m_arFileTransfers.remove(idx);
NetLog_Direct("FT struct %p released", bft);
// Release memory
SAFE_FREE((void**)bft);
}
else if ((*bft)->ft_magic == FT_MAGIC_OSCAR) { // release oscar filetransfer structure and its contents
oscar_filetransfer *oft = (oscar_filetransfer*)(*bft);
// If connected, close connection
if (oft->connection)
CloseOscarConnection(oft->connection);
// Release oscar listener
if (oft->listener)
ReleaseOscarListener((oscar_listener**)&oft->listener);
// Release cookie
if (oft->dwCookie)
FreeCookie(oft->dwCookie);
// Release all dynamic members
SAFE_FREE(&oft->rawFileName);
SAFE_FREE(&oft->szSavePath);
SAFE_FREE(&oft->szThisFile);
SAFE_FREE(&oft->szThisPath);
SAFE_FREE(&oft->szDescription);
if (oft->files) {
for (int i = 0; i < oft->wFilesCount; i++)
SAFE_FREE(&oft->files[i].szFile);
SAFE_FREE((void**)&oft->files);
}
if (oft->files_list)
SAFE_FREE((void**)&oft->files_list);
if (oft->file_containers) {
for (int i = 0; i < oft->containerCount; i++)
SAFE_FREE(&oft->file_containers[i]);
SAFE_FREE((void**)&oft->file_containers);
}
if (oft->fileId != -1)
_close(oft->fileId);
// Invalidate transfer
m_arFileTransfers.remove(idx);
NetLog_Direct("OFT: FT struct %p released", bft);
// Release memory
SAFE_FREE((void**)bft);
}
}
}
// Calculate oft checksum of buffer
// --------------------------------
// Information was gathered from Gaim's sources, thanks
//
DWORD oft_calc_checksum(int offset, const BYTE *buffer, int len, DWORD dwChecksum)
{
DWORD checksum = (dwChecksum >> 16) & 0xffff;
for (int i = 0; i < len; i++) {
WORD val = buffer[i];
if (((i + offset) & 1) == 0)
val = val << 8;
if (checksum < val)
checksum -= val + 1;
else // simulate carry
checksum -= val;
}
checksum = ((checksum & 0x0000ffff) + (checksum >> 16));
checksum = ((checksum & 0x0000ffff) + (checksum >> 16));
return checksum << 16;
}
DWORD oft_calc_file_checksum(int hFile, __int64 maxSize)
{
BYTE buf[OFT_BUFFER_SIZE];
int bytesRead;
__int64 offset = 0;
DWORD dwCheck = 0xFFFF0000;
_lseek(hFile, 0, SEEK_SET);
bytesRead = _read(hFile, buf, (maxSize < sizeof(buf)) ? maxSize : (unsigned)sizeof(buf));
if (bytesRead == -1)
return dwCheck;
while (bytesRead) {
dwCheck = oft_calc_checksum((int)offset, buf, bytesRead, dwCheck);
offset += bytesRead;
bytesRead = _read(hFile, buf, sizeof(buf));
if (bytesRead + offset > maxSize) bytesRead = (int)(maxSize - offset);
}
_lseek(hFile, 0, SEEK_SET); // back to beginning
return dwCheck;
}
oscar_listener* CIcqProto::CreateOscarListener(oscar_filetransfer *ft, NETLIBNEWCONNECTIONPROC_V2 handler)
{
oscar_listener *listener = (oscar_listener*)SAFE_MALLOC(sizeof(oscar_listener));
if (listener) {
listener->ppro = this;
listener->ft = ft;
if (listener->hBoundPort = NetLib_BindPort(handler, listener, &listener->wPort, nullptr))
return listener; // Success
SAFE_FREE((void**)&listener);
}
return nullptr; // Failure
}
void CIcqProto::ReleaseOscarListener(oscar_listener **pListener)
{
oscar_listener *listener = *pListener;
if (listener) { // Close listening port
if (listener->hBoundPort) {
Netlib_CloseHandle(listener->hBoundPort);
listener->hBoundPort = nullptr;
}
NetLog_Direct("Oscar listener on port %d released.", listener->wPort);
}
SAFE_FREE((void**)pListener);
}
//
// Miranda FT interface handlers & services
/////////////////////////////
void CIcqProto::handleRecvServMsgOFT(BYTE *buf, size_t wLen, DWORD dwUin, char *szUID, DWORD dwID1, DWORD dwID2, WORD wCommand)
{
MCONTACT hContact = HContactFromUID(dwUin, szUID, nullptr);
if (wCommand == 0) { // this is OFT request
oscar_tlv_chain* chain = readIntoTLVChain(&buf, wLen, 0);
if (chain) {
WORD wAckType = chain->getWord(0x0A, 1);
if (wAckType == 1) { // This is first request in this OFT
oscar_filetransfer *ft = CreateOscarTransfer();
char *pszFileName = nullptr;
char *pszDescription = nullptr;
debugLogA("This is a file request");
// This TLV chain may contain the following TLVs:
// TLV(A): Acktype 0x0001 - file request / abort request
// 0x0002 - file ack
// TLV(F): Unknown
// TLV(E): Language ?
// TLV(2): Proxy IP
// TLV(16): Proxy IP Check
// TLV(3): External IP
// TLV(4): Internal IP
// TLV(5): Port
// TLV(17): Port Check
// TLV(10): Proxy Flag
// TLV(D): Charset of User Message
// TLV(C): User Message (ICQ_COOL_FT)
// TLV(2711): FT info
// TLV(2712): Charset of file name
// init filetransfer structure
ft->pMessage.dwMsgID1 = dwID1;
ft->pMessage.dwMsgID2 = dwID2;
ft->bUseProxy = chain->getTLV(0x10, 1) ? 1 : 0;
ft->dwProxyIP = chain->getDWord(0x02, 1);
ft->dwRemoteInternalIP = chain->getDWord(0x03, 1);
ft->dwRemoteExternalIP = chain->getDWord(0x04, 1);
ft->wRemotePort = chain->getWord(0x05, 1);
ft->wReqNum = wAckType;
{ // User Message
oscar_tlv* tlv = chain->getTLV(0x0C, 1);
if (tlv) { // parse User Message
BYTE* tBuf = tlv->pData;
pszDescription = (char*)_alloca(tlv->wLen + 2);
unpackString(&tBuf, (char*)pszDescription, tlv->wLen);
pszDescription[tlv->wLen] = '\0';
pszDescription[tlv->wLen + 1] = '\0';
{ // apply User Message encoding
oscar_tlv *charset = chain->getTLV(0x0D, 1);
char *str = pszDescription;
char *bTag, *eTag;
if (charset) { // decode charset
char *szEnc = (char*)_alloca(charset->wLen + 1);
null_strcpy(szEnc, (char*)charset->pData, charset->wLen);
str = ApplyEncoding((char*)pszDescription, szEnc);
}
else str = null_strdup(str);
// eliminate HTML tags
pszDescription = EliminateHtml(str, mir_strlen(str));
bTag = strstrnull(pszDescription, "<DESC>");
if (bTag) { // take special Description - ICQJ's extension
eTag = strstrnull(bTag, "</DESC>");
if (eTag) {
*eTag = '\0';
str = null_strdup(bTag + 6);
SAFE_FREE(&pszDescription);
pszDescription = str;
}
}
else {
bTag = strstrnull(pszDescription, "<FS>");
if (bTag) { // take only <FS> - Description tag if present
eTag = strstrnull(bTag, "</FS>");
if (eTag) {
*eTag = '\0';
str = null_strdup(bTag + 4);
SAFE_FREE(&pszDescription);
pszDescription = str;
}
}
}
}
}
if (!mir_strlen(pszDescription)) {
SAFE_FREE(&pszDescription);
pszDescription = ICQTranslateUtf(LPGEN("No description given"));
}
}
{ // parse File Transfer Info block
oscar_tlv* tlv = chain->getTLV(0x2711, 1);
// sanity check
if (!tlv || tlv->wLen < 8) {
debugLogA("Error: Malformed file request");
// release structures
SafeReleaseFileTransfer((basic_filetransfer**)&ft);
SAFE_FREE(&pszDescription);
return;
}
BYTE *tBuf = tlv->pData;
size_t tLen = tlv->wLen;
WORD wFlag;
unpackWord(&tBuf, &wFlag); // FT flag
unpackWord(&tBuf, &ft->wFilesCount);
unpackDWord(&tBuf, (DWORD*)&ft->qwTotalSize);
tLen -= 8;
// Filename / Directory Name
if (tLen) { // some filename specified, unpack
size_t wFilenameLength = tLen - 1;
pszFileName = (char*)_alloca(tLen);
unpackString(&tBuf, (char*)pszFileName, wFilenameLength);
pszFileName[wFilenameLength] = '\0';
}
else if (ft->wFilesCount == 1) // give some generic file name
pszFileName = "unnamed_file";
else // or empty directory name
pszFileName = "";
// apply Filename / Directory Name encoding
oscar_tlv* charset = chain->getTLV(0x2712, 1);
if (charset) {
char* szEnc = (char*)_alloca(charset->wLen + 1);
null_strcpy(szEnc, (char*)charset->pData, charset->wLen);
pszFileName = ApplyEncoding(pszFileName, szEnc);
}
else pszFileName = ansi_to_utf8(pszFileName);
if (ft->wFilesCount == 1) { // Filename - use for DB event
char *szFileName = (char*)_alloca(mir_strlen(pszFileName) + 1);
mir_strcpy(szFileName, pszFileName);
SAFE_FREE(&pszFileName);
pszFileName = szFileName;
}
else { // Save Directory name for future use
ft->szThisPath = pszFileName;
// for multi-file transfer we do not display "folder" name, but create only a simple notice
pszFileName = (char*)_alloca(64);
char tmp[64];
mir_snprintf(pszFileName, 64, ICQTranslateUtfStatic(LPGEN("%d Files"), tmp, _countof(tmp)), ft->wFilesCount);
}
}
// Total Size TLV (ICQ 6 and AIM 6)
{
oscar_tlv *tlv = chain->getTLV(0x2713, 1);
if (tlv && tlv->wLen >= 8) {
BYTE *tBuf = tlv->pData;
unpackQWord(&tBuf, &ft->qwTotalSize);
}
}
int bAdded;
ft->hContact = HContactFromUID(dwUin, szUID, &bAdded);
ft->fileId = -1;
// Send chain event
char *szBlob = (char*)_alloca(sizeof(DWORD) + mir_strlen(pszFileName) + mir_strlen(pszDescription) + 2);
*(PDWORD)szBlob = 0;
mir_strcpy(szBlob + sizeof(DWORD), pszFileName);
mir_strcpy(szBlob + sizeof(DWORD) + mir_strlen(pszFileName) + 1, pszDescription);
wchar_t* ptszFileName = mir_utf8decodeW(pszFileName);
PROTORECVFILE pre = { 0 };
pre.dwFlags = PRFF_UNICODE;
pre.fileCount = 1;
pre.timestamp = time(nullptr);
pre.descr.w = mir_utf8decodeW(pszDescription);
pre.files.w = &ptszFileName;
pre.lParam = (LPARAM)ft;
ProtoChainRecvFile(ft->hContact, &pre);
mir_free(pre.descr.w);
mir_free(ptszFileName);
}
else if (wAckType == 2) { // First attempt failed, reverse requested
oscar_filetransfer *ft = FindOscarTransfer(hContact, dwID1, dwID2);
if (ft) {
NetLog_Direct("OFT: Redirect received (%d)", wAckType);
ft->wReqNum = wAckType;
if (ft->flags & OFTF_SENDING) {
ReleaseOscarListener((oscar_listener**)&ft->listener);
ft->bUseProxy = chain->getTLV(0x10, 1) ? 1 : 0;
ft->dwProxyIP = chain->getDWord(0x02, 1);
ft->dwRemoteInternalIP = chain->getDWord(0x03, 1);
ft->dwRemoteExternalIP = chain->getDWord(0x04, 1);
ft->wRemotePort = chain->getWord(0x05, 1);
OpenOscarConnection(hContact, ft, ft->bUseProxy ? OCT_PROXY_RECV : OCT_REVERSE);
}
else { // Just sanity
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, (HANDLE)ft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&ft);
}
}
else debugLogA("Error: Invalid request, no such transfer");
}
else if (wAckType == 3) { // Transfering thru proxy, join tunnel
oscar_filetransfer *ft = FindOscarTransfer(hContact, dwID1, dwID2);
if (ft) { // release possible previous listener
NetLog_Direct("OFT: Redirect received (%d)", wAckType);
ft->wReqNum = wAckType;
ReleaseOscarListener((oscar_listener**)&ft->listener);
ft->bUseProxy = chain->getTLV(0x10, 1) ? 1 : 0;
ft->dwProxyIP = chain->getDWord(0x02, 1);
ft->wRemotePort = chain->getWord(0x05, 1);
if (ft->bUseProxy && ft->dwProxyIP) // Init proxy connection
OpenOscarConnection(hContact, ft, OCT_PROXY_RECV);
else // try Stage 4
OpenOscarConnection(hContact, ft, OCT_PROXY);
}
else debugLogA("Error: Invalid request, no such transfer");
}
else if (wAckType == 4) {
oscar_filetransfer *ft = FindOscarTransfer(hContact, dwID1, dwID2);
if (ft) {
NetLog_Direct("OFT: Redirect received (%d)", wAckType);
ft->wReqNum = wAckType;
ft->bUseProxy = chain->getTLV(0x10, 1) ? 1 : 0;
ft->dwProxyIP = chain->getDWord(0x02, 1);
ft->wRemotePort = chain->getWord(0x05, 1);
if (ft->bUseProxy && ft->dwProxyIP) // Init proxy connection
OpenOscarConnection(hContact, ft, OCT_PROXY_RECV);
else
debugLogA("Error: Invalid request, IP missing.");
}
else debugLogA("Error: Invalid request, no such transfer");
}
else debugLogA("Error: Uknown Stage %d request", wAckType);
disposeChain(&chain);
}
else debugLogA("Error: Missing TLV chain in OFT request");
}
else if (wCommand == 1) { // transfer cancelled/aborted
oscar_filetransfer *ft = FindOscarTransfer(hContact, dwID1, dwID2);
if (ft) {
debugLogA("OFT: File transfer cancelled by %s", strUID(dwUin, szUID));
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, (HANDLE)ft, 0);
// Notify user, that the FT was cancelled // TODO: new ACKRESULT_?
icq_LogMessage(LOG_ERROR, LPGEN("The file transfer was aborted by the other user."));
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&ft);
}
else debugLogA("Error: Invalid request, no such transfer");
}
else if (wCommand == 2) { // transfer accepted - connection established
oscar_filetransfer *ft = FindOscarTransfer(hContact, dwID1, dwID2);
if (ft) {
NetLog_Direct("OFT: Session established.");
// Init connection
if (ft->flags & OFTF_SENDING) {
if (ft->connection && ft->connection->status == OCS_CONNECTED) {
if (!(ft->flags & OFTF_FILE_REQUEST_SENT)) {
ft->flags |= OFTF_FILE_REQUEST_SENT;
// proceed with first file
oft_sendPeerInit(ft->connection);
}
}
ft->flags |= OFTF_INITIALIZED; // accept was received
}
else debugLogA("Warning: Received invalid rendezvous accept");
}
else debugLogA("Error: Invalid request, no such transfer");
}
else debugLogA("Error: Unknown wCommand=0x%x in OFT request", wCommand);
}
void CIcqProto::handleRecvServResponseOFT(BYTE *buf, size_t wLen, DWORD dwUin, char *szUID, void* ft)
{
if (wLen < 2)
return;
size_t wDataLen;
unpackWord(&buf, &wDataLen);
if (wDataLen == 2) {
oscar_filetransfer *oft = (oscar_filetransfer*)ft;
WORD wStatus;
unpackWord(&buf, &wStatus);
switch (wStatus) {
case 1:
// FT denied (icq5)
debugLogA("OFT: File transfer denied by %s", strUID(dwUin, szUID));
ProtoBroadcastAck(oft->hContact, ACKTYPE_FILE, ACKRESULT_DENIED, (HANDLE)oft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&oft);
break;
case 4: // Proxy error
icq_LogMessage(LOG_ERROR, LPGEN("The file transfer failed: Proxy error"));
ProtoBroadcastAck(oft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, (HANDLE)oft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&oft);
break;
case 5: // Invalid request
icq_LogMessage(LOG_ERROR, LPGEN("The file transfer failed: Invalid request"));
ProtoBroadcastAck(oft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, (HANDLE)oft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&oft);
break;
case 6: // Proxy Failed (IP = 0)
icq_LogMessage(LOG_ERROR, LPGEN("The file transfer failed: Proxy unavailable"));
ProtoBroadcastAck(oft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, (HANDLE)oft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&oft);
break;
default:
debugLogA("OFT: Uknown request response code 0x%x", wStatus);
ProtoBroadcastAck(oft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, (HANDLE)oft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&oft);
}
}
}
// This function is called from the Netlib when someone is connecting to our oscar_listener
static void oft_newConnectionReceived(HNETLIBCONN hNewConnection, DWORD dwRemoteIP, void *pExtra)
{
oscarthreadstartinfo *otsi = (oscarthreadstartinfo*)SAFE_MALLOC(sizeof(oscarthreadstartinfo));
oscar_listener *listener = (oscar_listener*)pExtra;
otsi->type = listener->ft->flags & OFTF_SENDING ? OCT_NORMAL : OCT_REVERSE;
otsi->incoming = 1;
otsi->hConnection = hNewConnection;
otsi->dwRemoteIP = dwRemoteIP;
otsi->listener = listener;
// Start a new thread for the incomming connection
listener->ppro->ForkThread((CIcqProto::MyThreadFunc)&CIcqProto::oft_connectionThread, otsi);
}
static char* oftGetFileContainer(oscar_filetransfer* oft, const char** files, int iFile)
{
char szPath[MAX_PATH];
FindFilePathContainer(files, iFile, szPath);
char *szPathUtf = ansi_to_utf8(szPath);
int i;
// try to find existing container
for (i = 0; i < oft->containerCount; i++)
if (!mir_strcmp(szPathUtf, oft->file_containers[i])) {
SAFE_FREE((void**)&szPathUtf);
return oft->file_containers[i];
}
// create new container
i = oft->containerCount++;
oft->file_containers = (char**)SAFE_REALLOC(oft->file_containers, (sizeof(char*) * oft->containerCount));
oft->file_containers[i] = szPathUtf;
return oft->file_containers[i];
}
HANDLE CIcqProto::oftInitTransfer(MCONTACT hContact, DWORD dwUin, char* szUid, const wchar_t** files, const wchar_t* pszDesc)
{
int i, filesCount;
struct _stati64 statbuf;
// Initialize filetransfer struct
debugLogA("Init file send");
oscar_filetransfer *ft = CreateOscarTransfer();
ft->hContact = hContact;
ft->pMessage.bMessageType = MTYPE_FILEREQ;
InitMessageCookie(&ft->pMessage);
for (filesCount = 0; files[filesCount]; filesCount++);
ft->files = (oft_file_record *)SAFE_MALLOC(sizeof(oft_file_record) * filesCount);
ft->files_list = (char**)SAFE_MALLOC(sizeof(wchar_t *) * filesCount);
ft->qwTotalSize = 0;
char **filesUtf = (char**)SAFE_MALLOC(sizeof(char *) * filesCount);
for (i = 0; i < filesCount; i++) filesUtf[i] = FileNameToUtf(files[i]);
// Prepare files arrays
for (i = 0; i < filesCount; i++) {
if (_wstat64(files[i], &statbuf))
debugLogA("IcqSendFile() was passed invalid filename \"%s\"", files[i]);
else {
if (!(statbuf.st_mode & _S_IFDIR)) { // take only files
ft->files[ft->wFilesCount].szFile = ft->files_list[ft->wFilesCount] = null_strdup(filesUtf[i]);
ft->files[ft->wFilesCount].szContainer = oftGetFileContainer(ft, (LPCSTR*)filesUtf, i);
ft->wFilesCount++;
ft->qwTotalSize += statbuf.st_size;
}
}
}
for (i = 0; i < filesCount; i++)
SAFE_FREE(&filesUtf[i]);
SAFE_FREE((void**)&filesUtf);
if (!ft->wFilesCount) { // found no valid files to send
icq_LogMessage(LOG_ERROR, LPGEN("Failed to Initialize File Transfer. No valid files were specified."));
// Notify UI
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, (HANDLE)ft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&ft);
return nullptr; // Failure
}
#ifdef __GNUC__
#define OSCAR_MAX_SIZE 0x100000000ULL
#else
#define OSCAR_MAX_SIZE 0x100000000
#endif
if (ft->qwTotalSize >= OSCAR_MAX_SIZE && ft->wFilesCount > 1) { // file larger than 4GB can be send only as single
icq_LogMessage(LOG_ERROR, LPGEN("The files are too big to be sent at once. Files bigger than 4 GB can be sent only separately."));
// Notify UI
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, (HANDLE)ft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&ft);
return nullptr; // Failure
}
debugLogA("OFT: Found %d files.", ft->wFilesCount);
ft->szDescription = make_utf8_string(pszDesc);
ft->flags = OFTF_SENDING;
ft->fileId = -1;
ft->iCurrentFile = 0;
ft->dwCookie = AllocateCookie(CKT_FILE, ICQ_MSG_SRV_SEND, hContact, ft);
// Init oscar fields
{
ft->wEncrypt = 0;
ft->wCompress = 0;
ft->wPartsCount = 1;
ft->wPartsLeft = 1;
mir_strcpy(ft->rawIDString, "Cool FileXfer");
ft->bHeaderFlags = 0x20;
ft->bNameOff = 0x1C;
ft->bSizeOff = 0x11;
ft->dwRecvForkCheck = 0xFFFF0000;
ft->dwThisForkCheck = 0xFFFF0000;
ft->dwRecvFileCheck = 0xFFFF0000;
}
// Send file transfer request
{
char *pszFiles;
if (ft->wFilesCount == 1) { // transfering single file, give filename
pszFiles = (char*)ExtractFileName(ft->files[0].szFile);
}
else { // check if transfering one directory
char *szFirstDiv, *szFirstDir = ft->file_containers[0];
size_t nFirstDirLen;
// default is no root dir
pszFiles = "";
if ((szFirstDiv = strstrnull(szFirstDir, "\\")) || (szFirstDiv = strstrnull(szFirstDir, "/")))
nFirstDirLen = szFirstDiv - szFirstDir;
else
nFirstDirLen = mir_strlen(szFirstDir);
if (nFirstDirLen) { // got root dir from first container, check if others are only sub-dirs
for (i = 0; i < ft->containerCount; i++) {
if (_strnicmp((char*)ft->file_containers[i], (char*)szFirstDir, nFirstDirLen)) {
szFirstDir = nullptr;
break;
}
}
if (szFirstDir) { // fine, we are sending only one directory
pszFiles = szFirstDir;
if (szFirstDiv) szFirstDiv[0] = '\0';
nFirstDirLen++; // include backslash
// cut all files container by root dir - it is transferred as root separately
for (i = 0; i < ft->wFilesCount; i++)
ft->files[i].szContainer += nFirstDirLen;
}
}
}
// Create listener
ft->listener = CreateOscarListener(ft, oft_newConnectionReceived);
// Send packet
if (ft->listener) {
oft_sendFileRequest(dwUin, szUid, ft, pszFiles, getDword("RealIP", 0));
}
else { // try stage 1 proxy
ft->szThisFile = null_strdup(pszFiles);
OpenOscarConnection(hContact, ft, OCT_PROXY_INIT);
}
}
return ft; // Success
}
HANDLE CIcqProto::oftFileAllow(MCONTACT hContact, HANDLE hTransfer, const wchar_t *szPath)
{
oscar_filetransfer *ft = (oscar_filetransfer*)hTransfer;
DWORD dwUin;
uid_str szUid;
if (getContactUid(hContact, &dwUin, &szUid))
return nullptr; // Invalid contact
if (!IsValidOscarTransfer(ft))
return nullptr; // Invalid transfer
ft->szSavePath = make_utf8_string(szPath);
if (ft->szThisPath) { // Append Directory name to the save path, when transfering a directory
ft->szSavePath = (char*)SAFE_REALLOC(ft->szSavePath, mir_strlen(ft->szSavePath) + mir_strlen(ft->szThisPath) + 4);
NormalizeBackslash(ft->szSavePath);
mir_strcat(ft->szSavePath, ft->szThisPath);
NormalizeBackslash(ft->szSavePath);
}
NetLog_Direct("OFT: Request accepted, saving to '%s'.", ft->szSavePath);
// Create cookie
ft->dwCookie = AllocateCookie(CKT_FILE, ICQ_MSG_SRV_SEND, hContact, ft);
OpenOscarConnection(hContact, ft, ft->bUseProxy ? OCT_PROXY_RECV : OCT_NORMAL);
return hTransfer; // Success
}
DWORD CIcqProto::oftFileDeny(MCONTACT hContact, HANDLE hTransfer, const wchar_t*)
{
oscar_filetransfer *ft = (oscar_filetransfer*)hTransfer;
DWORD dwUin;
uid_str szUid;
if (getContactUid(hContact, &dwUin, &szUid))
return 1; // Invalid contact
if (!IsValidOscarTransfer(ft))
return 1; // Invalid transfer
if (ft->hContact != hContact)
return 1; // Bad contact or hTransfer
NetLog_Direct("OFT: Request denied.");
oft_sendFileDeny(dwUin, szUid, ft);
// Release structure
SafeReleaseFileTransfer((basic_filetransfer**)&ft);
return 0; // Success
}
DWORD CIcqProto::oftFileCancel(MCONTACT hContact, HANDLE hTransfer)
{
oscar_filetransfer* ft = (oscar_filetransfer*)hTransfer;
DWORD dwUin;
uid_str szUid;
if (getContactUid(hContact, &dwUin, &szUid))
return 1; // Invalid contact
if (!IsValidOscarTransfer(ft))
return 1; // Invalid transfer
if (ft->hContact != hContact)
return 1; // Bad contact or hTransfer
NetLog_Direct("OFT: Transfer cancelled.");
oft_sendFileCancel(dwUin, szUid, ft);
ProtoBroadcastAck(hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
// Release structure
SafeReleaseFileTransfer((basic_filetransfer**)&ft);
return 0; // Success
}
void CIcqProto::oftFileResume(oscar_filetransfer *ft, int action, const wchar_t *szFilename)
{
int openFlags;
if (ft->connection == nullptr)
return;
oscar_connection *oc = ft->connection;
NetLog_Direct("OFT: Resume Transfer, Action: %d, FileName: '%s'", action, szFilename);
switch (action) {
case FILERESUME_RESUME:
openFlags = _O_BINARY | _O_RDWR;
break;
case FILERESUME_OVERWRITE:
openFlags = _O_BINARY | _O_CREAT | _O_TRUNC | _O_WRONLY;
ft->qwFileBytesDone = 0;
break;
case FILERESUME_SKIP:
openFlags = _O_BINARY | _O_WRONLY;
ft->qwFileBytesDone = ft->qwThisFileSize;
break;
case FILERESUME_RENAME:
openFlags = _O_BINARY | _O_CREAT | _O_TRUNC | _O_WRONLY;
SAFE_FREE(&ft->szThisFile);
ft->szThisFile = make_utf8_string(szFilename);
ft->qwFileBytesDone = 0;
break;
default: // workaround for bug in Miranda Core
if (ft->resumeAction == FILERESUME_RESUME)
openFlags = _O_BINARY | _O_RDWR;
else { // default to overwrite
openFlags = _O_BINARY | _O_CREAT | _O_TRUNC | _O_WRONLY;
ft->qwFileBytesDone = 0;
}
}
ft->resumeAction = action;
ft->fileId = OpenFileUtf(ft->szThisFile, openFlags, _S_IREAD | _S_IWRITE);
if (ft->fileId == -1) {
NetLog_Direct("OFT: errno=%d", errno);
icq_LogMessage(LOG_ERROR, LPGEN("Your file receive has been aborted because Miranda could not open the destination file in order to write to it. You may be trying to save to a read-only folder."));
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&oc->ft);
return;
}
if (action == FILERESUME_RESUME)
ft->qwFileBytesDone = _lseeki64(ft->fileId, 0, SEEK_END);
else
_lseeki64(ft->fileId, ft->qwFileBytesDone, SEEK_SET);
ft->qwBytesDone += ft->qwFileBytesDone;
if (action == FILERESUME_RESUME) { // use smart-resume
oc->status = OCS_RESUME;
ft->dwRecvFileCheck = oft_calc_file_checksum(ft->fileId, ft->qwFileBytesDone);
_lseek(ft->fileId, 0, SEEK_END);
NetLog_Direct("OFT: Starting Smart-Resume");
sendOFT2FramePacket(oc, OFT_TYPE_RESUMEREQUEST);
return;
}
if (action == FILERESUME_SKIP) // we are skipping the file, send "we are done"
oc->status = OCS_NEGOTIATION;
else { // Send "we are ready"
oc->status = OCS_DATA;
ft->flags |= OFTF_FILE_RECEIVING;
sendOFT2FramePacket(oc, OFT_TYPE_READY);
}
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
if (!ft->qwThisFileSize || action == FILERESUME_SKIP) { // if the file is empty we will not receive any data
BYTE buf;
oft_handleFileData(oc, &buf, 0);
}
}
static void oft_buildProtoFileTransferStatus(oscar_filetransfer* ft, PROTOFILETRANSFERSTATUS* pfts)
{
memset(pfts, 0, sizeof(PROTOFILETRANSFERSTATUS));
pfts->hContact = ft->hContact;
pfts->flags = PFTS_UTF + ((ft->flags & OFTF_SENDING) ? PFTS_SENDING : PFTS_RECEIVING);
if (ft->flags & OFTF_SENDING)
pfts->pszFiles.a = ft->files_list;
else
pfts->pszFiles.a = nullptr; /* FIXME */
pfts->totalFiles = ft->wFilesCount;
pfts->currentFileNumber = ft->iCurrentFile;
pfts->totalBytes = ft->qwTotalSize;
pfts->totalProgress = ft->qwBytesDone;
pfts->szWorkingDir.a = ft->szThisPath;
pfts->szCurrentFile.a = ft->szThisFile;
pfts->currentFileSize = ft->qwThisFileSize;
pfts->currentFileTime = ft->dwThisFileDate;
pfts->currentFileProgress = ft->qwFileBytesDone;
}
void CIcqProto::CloseOscarConnection(oscar_connection *oc)
{
mir_cslock l(oftMutex);
if (oc) {
oc->type = OCT_CLOSING;
if (oc->hConnection) // we need this for Netlib handle consistency
NetLib_CloseConnection(&oc->hConnection, FALSE);
}
}
/////////////////////////////////////////////////////////////////////////////////////////
void CIcqProto::OpenOscarConnection(MCONTACT hContact, oscar_filetransfer *ft, int type)
{
oscarthreadstartinfo *otsi = (oscarthreadstartinfo*)SAFE_MALLOC(sizeof(oscarthreadstartinfo));
otsi->hContact = hContact;
otsi->type = type;
otsi->ft = ft;
ForkThread((MyThreadFunc)&CIcqProto::oft_connectionThread, otsi);
}
int CIcqProto::CreateOscarProxyConnection(oscar_connection *oc)
{
// inform UI
ProtoBroadcastAck(oc->ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTPROXY, oc->ft, 0);
NETLIBOPENCONNECTION nloc = { 0 };
nloc.szHost = OSCAR_PROXY_HOST;
nloc.wPort = getWord("OscarPort", m_bSecureConnection ? DEFAULT_SERVER_PORT_SSL : DEFAULT_SERVER_PORT);
if (nloc.wPort == 0)
nloc.wPort = RandRange(1024, 65535);
if (m_bGatewayMode)
nloc.flags |= NLOCF_HTTPGATEWAY;
oc->hConnection = NetLib_OpenConnection(m_hNetlibUser, "Proxy ", &nloc);
if (!oc->hConnection) // proxy connection failed
return 0;
oc->type = OCT_PROXY;
oc->status = OCS_PROXY;
oc->ft->connection = oc;
// init proxy
proxy_sendInitTunnel(oc);
return 1; // Success
}
void __cdecl CIcqProto::oft_connectionThread(oscarthreadstartinfo *otsi)
{
oscar_connection oc = { 0 };
oscar_listener *source;
Thread_SetName("ICQ: oft_connectionThread");
oc.hContact = otsi->hContact;
oc.hConnection = otsi->hConnection;
oc.type = otsi->type;
oc.incoming = otsi->incoming;
oc.ft = otsi->ft;
source = otsi->listener;
if (oc.incoming) {
if (IsValidOscarTransfer(source->ft)) {
oc.ft = source->ft;
oc.ft->dwRemoteExternalIP = otsi->dwRemoteIP;
oc.hContact = oc.ft->hContact;
oc.ft->connection = &oc;
oc.status = OCS_CONNECTED;
}
else { // FT is already over, kill listener
NetLog_Direct("Received unexpected connection, closing.");
CloseOscarConnection(&oc);
ReleaseOscarListener(&source);
SAFE_FREE((void**)&otsi);
return;
}
}
SAFE_FREE((void**)&otsi);
if (oc.hContact) // Load contact information
getContactUid(oc.hContact, &oc.dwUin, &oc.szUid);
// Load local IP information
oc.dwLocalExternalIP = getDword("IP", 0);
oc.dwLocalInternalIP = getDword("RealIP", 0);
if (!oc.incoming) { // create outgoing connection
if (oc.type == OCT_NORMAL || oc.type == OCT_REVERSE) { // create outgoing connection to peer
NETLIBOPENCONNECTION nloc = { 0 };
IN_ADDR addr = { 0 }, addr2 = { 0 };
if (oc.ft->dwRemoteExternalIP == oc.dwLocalExternalIP && oc.ft->dwRemoteInternalIP)
addr.S_un.S_addr = htonl(oc.ft->dwRemoteInternalIP);
else if (oc.ft->dwRemoteExternalIP) {
addr.S_un.S_addr = htonl(oc.ft->dwRemoteExternalIP);
// for different internal, try it also (for LANs with multiple external IP, VPNs, etc.)
if (oc.ft->dwRemoteInternalIP != oc.ft->dwRemoteExternalIP)
addr2.S_un.S_addr = htonl(oc.ft->dwRemoteInternalIP);
}
else // try LAN
addr.S_un.S_addr = htonl(oc.ft->dwRemoteInternalIP);
// Inform UI that we will attempt to connect
ProtoBroadcastAck(oc.ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTING, oc.ft, 0);
if (!addr.S_un.S_addr && oc.type == OCT_NORMAL) { // IP to connect to is empty, request reverse
oscar_listener* listener = CreateOscarListener(oc.ft, oft_newConnectionReceived);
if (listener) { // we got listening port, fine send request
oc.ft->listener = listener;
// notify UI
ProtoBroadcastAck(oc.ft->hContact, ACKTYPE_FILE, ACKRESULT_LISTENING, oc.ft, 0);
oft_sendFileRedirect(oc.dwUin, oc.szUid, oc.ft, oc.dwLocalInternalIP, listener->wPort, FALSE);
return;
}
if (!CreateOscarProxyConnection(&oc)) { // normal connection failed, notify peer, wait for error or stage 3 proxy
oft_sendFileRedirect(oc.dwUin, oc.szUid, oc.ft, 0, 0, FALSE);
// stage 3 can follow
return;
}
}
else if (addr.S_un.S_addr && oc.ft->wRemotePort) {
nloc.szHost = inet_ntoa(addr);
nloc.wPort = oc.ft->wRemotePort;
nloc.timeout = 8; // 8 secs to connect
oc.hConnection = NetLib_OpenConnection(m_hDirectNetlibUser, oc.type == OCT_REVERSE ? "Reverse " : nullptr, &nloc);
if (!oc.hConnection && addr2.S_un.S_addr) { // first address failed, try second one if available
nloc.szHost = inet_ntoa(addr2);
oc.hConnection = NetLib_OpenConnection(m_hDirectNetlibUser, oc.type == OCT_REVERSE ? "Reverse " : nullptr, &nloc);
}
if (!oc.hConnection) {
if (oc.type == OCT_NORMAL) { // connection failed, try reverse
oscar_listener* listener = CreateOscarListener(oc.ft, oft_newConnectionReceived);
if (listener) { // we got listening port, fine send request
oc.ft->listener = listener;
// notify UI that we await connection
ProtoBroadcastAck(oc.ft->hContact, ACKTYPE_FILE, ACKRESULT_LISTENING, oc.ft, 0);
oft_sendFileRedirect(oc.dwUin, oc.szUid, oc.ft, oc.dwLocalInternalIP, listener->wPort, FALSE);
return;
}
}
if (!CreateOscarProxyConnection(&oc)) { // proxy connection failed, notify peer, wait for error or stage 4 proxy
oft_sendFileRedirect(oc.dwUin, oc.szUid, oc.ft, 0, 0, FALSE);
// stage 3 or stage 4 can follow
return;
}
}
else {
oc.status = OCS_CONNECTED;
// ack normal connection
oc.ft->connection = &oc;
// acknowledge OFT - connection is ready
oft_sendFileAccept(oc.dwUin, oc.szUid, oc.ft);
// signal UI
ProtoBroadcastAck(oc.ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTED, oc.ft, 0);
}
}
else { // try proxy, stage 3 (sending)
if (!CreateOscarProxyConnection(&oc)) { // proxy connection failed, notify peer, wait for error or stage 4 proxy
oft_sendFileRedirect(oc.dwUin, oc.szUid, oc.ft, 0, 0, FALSE);
// stage 4 can follow
return;
}
}
}
else if (oc.type == OCT_PROXY_RECV) { // stage 2 & stage 4
if (oc.ft->dwProxyIP && oc.ft->wRemotePort) { // create proxy connection, join tunnel
NETLIBOPENCONNECTION nloc = { 0 };
IN_ADDR addr = { 0 };
// inform UI that we will connect to file proxy
ProtoBroadcastAck(oc.ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTPROXY, oc.ft, 0);
addr.S_un.S_addr = htonl(oc.ft->dwProxyIP);
nloc.szHost = inet_ntoa(addr);
nloc.wPort = getWord("OscarPort", m_bSecureConnection ? DEFAULT_SERVER_PORT_SSL : DEFAULT_SERVER_PORT);
if (nloc.wPort == 0)
nloc.wPort = RandRange(1024, 65535);
if (m_bGatewayMode)
nloc.flags |= NLOCF_HTTPGATEWAY;
oc.hConnection = NetLib_OpenConnection(m_hNetlibUser, "Proxy ", &nloc);
if (!oc.hConnection) { // proxy connection failed, we are out of possibilities
ProtoBroadcastAck(oc.ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, oc.ft, 0);
// notify the other side, that we failed
oft_sendFileResponse(oc.dwUin, oc.szUid, oc.ft, 0x04);
// Release structure
SafeReleaseFileTransfer((basic_filetransfer**)&oc.ft);
return;
}
oc.status = OCS_PROXY;
oc.ft->connection = &oc;
// Join proxy tunnel
proxy_sendJoinTunnel(&oc, oc.ft->wRemotePort);
}
else // stage 2 failed (empty IP)
{ // try stage 3, or send response error 0x06
if (!CreateOscarProxyConnection(&oc)) {
oft_sendFileResponse(oc.dwUin, oc.szUid, oc.ft, 0x06);
// notify UI
ProtoBroadcastAck(oc.ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, oc.ft, 0);
// Release structure
SafeReleaseFileTransfer((basic_filetransfer**)&oc.ft);
return;
}
}
}
else if (oc.type == OCT_PROXY) { // stage 4
if (!CreateOscarProxyConnection(&oc)) { // proxy connection failed, we are out of possibilities
ProtoBroadcastAck(oc.ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, oc.ft, 0);
// notify the other side, that we failed
oft_sendFileResponse(oc.dwUin, oc.szUid, oc.ft, 0x06);
// Release structure
SafeReleaseFileTransfer((basic_filetransfer**)&oc.ft);
return;
}
}
else if (oc.type == OCT_PROXY_INIT) { // stage 1
if (!CreateOscarProxyConnection(&oc)) { // We failed to init transfer, notify UI
icq_LogMessage(LOG_ERROR, LPGEN("Failed to Initialize File Transfer. Unable to bind local port and File proxy unavailable."));
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&oc.ft);
return;
}
else
oc.type = OCT_PROXY_INIT;
}
}
if (!oc.hConnection) { // one more sanity check
NetLog_Direct("Error: No OFT connection.");
return;
}
if (oc.status != OCS_PROXY) { // Connected, notify FT UI
ProtoBroadcastAck(oc.ft->hContact, ACKTYPE_FILE, ACKRESULT_INITIALISING, oc.ft, 0);
// send init OFT frame - just for different order of packets (just like Trillian)
if (oc.status == OCS_CONNECTED && (oc.ft->flags & OFTF_SENDING) && ((oc.ft->flags & OFTF_INITIALIZED) || oc.type == OCT_REVERSE) && !(oc.ft->flags & OFTF_FILE_REQUEST_SENT)) {
oc.ft->flags |= OFTF_FILE_REQUEST_SENT;
// proceed with first file
oft_sendPeerInit(&oc);
}
}
HANDLE hPacketRecver = Netlib_CreatePacketReceiver(oc.hConnection, 8192);
NETLIBPACKETRECVER packetRecv = {};
// Packet receiving loop
while (oc.hConnection) {
packetRecv.dwTimeout = oc.wantIdleTime ? 0 : 120000;
int recvResult = Netlib_GetMorePackets(hPacketRecver, &packetRecv);
if (!recvResult) {
NetLog_Direct("Clean closure of oscar socket (%p)", oc.hConnection);
break;
}
if (recvResult == SOCKET_ERROR) {
if (GetLastError() == ERROR_TIMEOUT) { // TODO: this will not work on some systems
if (oc.wantIdleTime) { // here we want to send file data packets
oft_sendFileData(&oc);
}
else if (oc.status != OCS_WAITING) {
NetLog_Direct("Connection timeouted, closing.");
break;
}
}
else if (oc.type != OCT_CLOSING || GetLastError() != 87) { // log only significant errors, not "connection killed by us"
NetLog_Direct("Abortive closure of oscar socket (%p) (%d)", oc.hConnection, GetLastError());
break;
}
}
if (oc.type == OCT_CLOSING)
packetRecv.bytesUsed = packetRecv.bytesAvailable;
else
packetRecv.bytesUsed = oft_handlePackets(&oc, packetRecv.buffer, packetRecv.bytesAvailable);
}
// End of packet receiving loop
NetLib_SafeCloseHandle(&hPacketRecver);
CloseOscarConnection(&oc);
// Clean up
{
mir_cslock l(oftMutex);
if (m_arFileTransfers.indexOf(oc.ft) != -1)
oc.ft->connection = nullptr; // release link
}
// Give server some time for abort/cancel to arrive
SleepEx(1000, TRUE);
// Error handling
if (IsValidOscarTransfer(oc.ft)) {
if (oc.status == OCS_DATA) {
ProtoBroadcastAck(oc.hContact, ACKTYPE_FILE, ACKRESULT_FAILED, oc.ft, 0);
icq_LogMessage(LOG_ERROR, LPGEN("Connection lost during file transfer."));
// Release structure
SafeReleaseFileTransfer((basic_filetransfer**)&oc.ft);
}
else if (oc.status == OCS_NEGOTIATION) {
ProtoBroadcastAck(oc.hContact, ACKTYPE_FILE, ACKRESULT_FAILED, oc.ft, 0);
icq_LogMessage(LOG_ERROR, LPGEN("File transfer negotiation failed for unknown reason."));
// Release structure
SafeReleaseFileTransfer((basic_filetransfer**)&oc.ft);
}
}
}
void CIcqProto::sendOscarPacket(oscar_connection *oc, icq_packet *packet)
{
if (oc->hConnection) {
int nResult = Netlib_Send(oc->hConnection, (const char*)packet->pData, packet->wLen, 0);
if (nResult == SOCKET_ERROR) {
NetLog_Direct("Oscar %p socket error: %d, closing", oc->hConnection, GetLastError());
CloseOscarConnection(oc);
}
}
SAFE_FREE((void**)&packet->pData);
}
int CIcqProto::oft_handlePackets(oscar_connection *oc, BYTE *buf, size_t len)
{
size_t bytesUsed = 0;
while (len > 0) {
if (oc->status == OCS_DATA && (oc->ft->flags & OFTF_FILE_RECEIVING))
return oft_handleFileData(oc, buf, len);
if (oc->status == OCS_PROXY)
return oft_handleProxyData(oc, buf, len);
if (len < 6)
break;
BYTE *pBuf = buf;
DWORD dwHead;
unpackDWord(&pBuf, &dwHead);
if (dwHead != 0x4F465432) { // bad packet
NetLog_Direct("OFT: Received invalid packet (dwHead = 0x%x).", dwHead);
CloseOscarConnection(oc);
break;
}
size_t datalen;
unpackWord(&pBuf, &datalen);
if (len < datalen) // wait for whole packet
break;
WORD datatype;
unpackWord(&pBuf, &datatype);
#ifdef _DEBUG
NetLog_Direct("OFT2: Type %u, Length %u bytes", datatype, datalen);
#endif
handleOFT2FramePacket(oc, datatype, pBuf, datalen-8);
/* Increase pointers so we can check for more data */
buf += datalen;
len -= datalen;
bytesUsed += datalen;
}
return (int)bytesUsed;
}
int CIcqProto::oft_handleProxyData(oscar_connection *oc, BYTE *buf, size_t len)
{
oscar_filetransfer *ft = oc->ft;
size_t datalen, bytesUsed = 0;
while (len > 2) {
BYTE *pBuf = buf;
unpackWord(&pBuf, &datalen);
datalen += 2;
if (len < datalen)
break; // packet is not complete
if (datalen < 12) { // malformed packet
CloseOscarConnection(oc);
break;
}
pBuf += 2; // packet version
WORD wCommand;
unpackWord(&pBuf, &wCommand);
pBuf += 6;
// handle packet
switch (wCommand) {
case 0x01: // Error
WORD wError;
char* szError;
unpackWord(&pBuf, &wError);
switch (wError) {
case 0x0D:
szError = "Bad request";
break;
case 0x0E:
szError = "Malformed packet";
break;
case 0x10:
szError = "Initial request timeout";
break;
case 0x1A:
szError = "Accept period timeout";
break;
case 0x1C:
szError = "Invalid data";
break;
default:
szError = "Unknown";
}
// Notify peer
oft_sendFileResponse(oc->dwUin, oc->szUid, oc->ft, 0x06);
debugLogA("Proxy Error: %s (0x%x)", szError, wError);
// Notify UI
ProtoBroadcastAck(oc->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, oc->ft, 0);
// Release structure
SafeReleaseFileTransfer((basic_filetransfer**)&oc->ft);
break;
case 0x03: // Tunnel created
WORD wCode;
DWORD dwIP;
unpackWord(&pBuf, &wCode);
unpackDWord(&pBuf, &dwIP);
if (oc->type == OCT_PROXY_INIT) { // Proxy ready, send Stage 1 Request
ft->bUseProxy = 1;
ft->wRemotePort = wCode;
ft->dwProxyIP = dwIP;
oft_sendFileRequest(oc->dwUin, oc->szUid, ft, ft->szThisFile, 0);
SAFE_FREE(&ft->szThisFile);
// Notify UI
ProtoBroadcastAck(oc->hContact, ACKTYPE_FILE, ACKRESULT_INITIALISING, oc->ft, 0);
}
else {
debugLogA("Proxy Tunnel ready, notify peer.");
oft_sendFileRedirect(oc->dwUin, oc->szUid, ft, dwIP, wCode, TRUE);
}
break;
case 0x05: // Connection ready
oc->status = OCS_CONNECTED; // connection ready to send packets
// Notify UI
ProtoBroadcastAck(oc->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTED, oc->ft, 0);
// signal we are ready
if (oc->type == OCT_PROXY_RECV) {
oft_sendFileAccept(oc->dwUin, oc->szUid, ft);
if (ft->flags & OFTF_SENDING) // connection is ready for transfer (sending only)
ft->flags |= OFTF_INITIALIZED;
}
debugLogA("Proxy Tunnel established");
if ((ft->flags & OFTF_INITIALIZED) && (ft->flags & OFTF_SENDING) && !(ft->flags & OFTF_FILE_REQUEST_SENT)) {
ft->flags |= OFTF_FILE_REQUEST_SENT;
// proceed with first file
oft_sendPeerInit(ft->connection);
}
break;
default:
debugLogA("Unknown proxy command 0x%x", wCommand);
}
buf += datalen;
len -= datalen;
bytesUsed += datalen;
}
return (int)bytesUsed;
}
int CIcqProto::oft_handleFileData(oscar_connection *oc, BYTE *buf, size_t len)
{
oscar_filetransfer *ft = oc->ft;
size_t dwLen = len, bytesUsed = 0;
// do not accept more data than expected
if (ft->qwThisFileSize - ft->qwFileBytesDone < dwLen)
dwLen = (int)(ft->qwThisFileSize - ft->qwFileBytesDone);
if (ft->fileId == -1) { // something went terribly bad
CloseOscarConnection(oc);
return 0;
}
_write(ft->fileId, buf, (unsigned)dwLen);
// update checksum
ft->dwRecvFileCheck = oft_calc_checksum((int)ft->qwFileBytesDone, buf, (unsigned)dwLen, ft->dwRecvFileCheck);
bytesUsed += dwLen;
ft->qwBytesDone += dwLen;
ft->qwFileBytesDone += dwLen;
// notify FT UI of our progress, at most every 700ms - do not be faster than Miranda
if (GetTickCount() > ft->dwLastNotify + 700 || ft->qwFileBytesDone == ft->qwThisFileSize) {
PROTOFILETRANSFERSTATUS pfts;
oft_buildProtoFileTransferStatus(ft, &pfts);
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&pfts);
ft->dwLastNotify = GetTickCount();
}
if (ft->qwFileBytesDone == ft->qwThisFileSize) {
/* EOF */
ft->flags &= ~OFTF_FILE_RECEIVING;
_close(ft->fileId);
ft->fileId = -1;
if (ft->resumeAction != FILERESUME_SKIP && ft->dwRecvFileCheck != ft->dwThisFileCheck) {
NetLog_Direct("Error: File checksums does not match!");
// Notify UI
char *pszMsg = ICQTranslateUtf(LPGEN("The checksum of file \"%s\" does not match, the file is probably damaged."));
char szBuf[MAX_PATH];
mir_snprintf(szBuf, pszMsg, ExtractFileName(ft->szThisFile));
icq_LogMessage(LOG_ERROR, szBuf);
SAFE_FREE(&pszMsg);
}
// keep transfer going (icq6 ignores checksums completely)
else if (ft->resumeAction == FILERESUME_SKIP)
NetLog_Direct("OFT: File receive skipped.");
else
NetLog_Direct("OFT: File received successfully.");
if ((DWORD)(ft->iCurrentFile + 1) == ft->wFilesCount) {
ft->bHeaderFlags = 0x01; // the whole process is over
// ack received file
sendOFT2FramePacket(oc, OFT_TYPE_DONE);
oc->type = OCT_CLOSING;
NetLog_Direct("File Transfer completed successfully.");
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_SUCCESS, ft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&ft);
}
else { // ack received file
sendOFT2FramePacket(oc, OFT_TYPE_DONE);
oc->status = OCS_NEGOTIATION;
}
}
return (int)bytesUsed;
}
void CIcqProto::handleOFT2FramePacket(oscar_connection *oc, WORD datatype, BYTE *pBuffer, size_t wLen)
{
oscar_filetransfer *ft = oc->ft;
DWORD dwID1;
DWORD dwID2;
if (wLen < 232) { // allow shorter packets, but at least with filename
NetLog_Direct("Error: Malformed OFT2 Frame, ignoring.");
return;
}
unpackLEDWord(&pBuffer, &dwID1);
wLen -= 4;
unpackLEDWord(&pBuffer, &dwID2);
wLen -= 4;
if (datatype == OFT_TYPE_REQUEST && !(ft->flags & OFTF_FILE_REQUEST_RECEIVED)) { // first request does not contain MsgIDs we need to send them in ready packet
dwID1 = ft->pMessage.dwMsgID1;
dwID2 = ft->pMessage.dwMsgID2;
}
if (ft->pMessage.dwMsgID1 != dwID1 || ft->pMessage.dwMsgID2 != dwID2) { // this is not the right packet - bad Message IDs
NetLog_Direct("Error: Invalid Packet Cookie, closing.");
CloseOscarConnection(oc);
return;
}
switch (datatype) {
case OFT_TYPE_REQUEST:
{ // Sender ready
if (ft->flags & OFTF_SENDING) { // just sanity check - this is only for receiving client
NetLog_Direct("Error: Invalid Packet, closing.");
CloseOscarConnection(oc);
return;
}
// Read Frame data
if (!(ft->flags & OFTF_FILE_REQUEST_RECEIVED)) {
unpackWord(&pBuffer, &ft->wEncrypt);
unpackWord(&pBuffer, &ft->wCompress);
unpackWord(&pBuffer, &ft->wFilesCount);
}
else
pBuffer += 6;
unpackWord(&pBuffer, &ft->wFilesLeft);
ft->iCurrentFile = ft->wFilesCount - ft->wFilesLeft;
if (!(ft->flags & OFTF_FILE_REQUEST_RECEIVED))
unpackWord(&pBuffer, &ft->wPartsCount);
else
pBuffer += 2;
unpackWord(&pBuffer, &ft->wPartsLeft);
if (!(ft->flags & OFTF_FILE_REQUEST_RECEIVED)) { // just check it
DWORD dwSize;
unpackDWord(&pBuffer, &dwSize);
if (dwSize != (DWORD)ft->qwTotalSize) { // the 32bits does not match, use them as full size
ft->qwTotalSize = dwSize;
debugLogA("Warning: Invalid total size.");
}
}
else pBuffer += 4;
// this allows us to receive single >4GB file correctly
DWORD dwSize;
unpackDWord(&pBuffer, &dwSize);
if (dwSize == (DWORD)ft->qwTotalSize && ft->wFilesCount == 1)
ft->qwThisFileSize = ft->qwTotalSize;
else
ft->qwThisFileSize = dwSize;
unpackDWord(&pBuffer, &ft->dwThisFileDate);
unpackDWord(&pBuffer, &ft->dwThisFileCheck);
unpackDWord(&pBuffer, &ft->dwRecvForkCheck);
unpackDWord(&pBuffer, &ft->dwThisForkSize);
unpackDWord(&pBuffer, &ft->dwThisFileCreation);
unpackDWord(&pBuffer, &ft->dwThisForkCheck);
pBuffer += 4; // File Bytes Done
unpackDWord(&pBuffer, &ft->dwRecvFileCheck);
if (!(ft->flags & OFTF_FILE_REQUEST_RECEIVED))
unpackString(&pBuffer, ft->rawIDString, 32);
else
pBuffer += 32;
unpackByte(&pBuffer, &ft->bHeaderFlags);
unpackByte(&pBuffer, &ft->bNameOff);
unpackByte(&pBuffer, &ft->bSizeOff);
if (!(ft->flags & OFTF_FILE_REQUEST_RECEIVED)) {
unpackString(&pBuffer, (char*)ft->rawDummy, 69);
unpackString(&pBuffer, (char*)ft->rawMacInfo, 16);
}
else pBuffer += 85;
unpackWord(&pBuffer, &ft->wEncoding);
unpackWord(&pBuffer, &ft->wSubEncoding);
ft->cbRawFileName = wLen - 176;
SAFE_FREE((void**)&ft->rawFileName); // release previous buffers
SAFE_FREE(&ft->szThisFile);
ft->rawFileName = (char*)SAFE_MALLOC(ft->cbRawFileName + 2);
unpackString(&pBuffer, ft->rawFileName, ft->cbRawFileName);
// Prepare file
if (ft->wEncoding == 2) // UCS-2 encoding
ft->szThisFile = ApplyEncoding(ft->rawFileName, "unicode-2-0");
else
ft->szThisFile = ansi_to_utf8(ft->rawFileName);
// convert dir markings to normal backslashes
for (size_t i = 0; i < mir_strlen(ft->szThisFile); i++)
if (ft->szThisFile[i] == 0x01)
ft->szThisFile[i] = '\\';
ft->flags |= OFTF_FILE_REQUEST_RECEIVED; // First Frame Processed
NetLog_Direct("File '%s', %I64u Bytes", ft->szThisFile, ft->qwThisFileSize);
{ // Prepare Path Information
char *szFile = strrchr(ft->szThisFile, '\\');
SAFE_FREE(&ft->szThisPath); // release previous path
if (szFile) {
ft->szThisPath = ft->szThisFile;
szFile[0] = '\0'; // split that strings
ft->szThisFile = null_strdup(szFile + 1);
// no cheating with paths
if (!IsValidRelativePath(ft->szThisPath)) {
NetLog_Direct("Invalid path information");
break;
}
}
else ft->szThisPath = null_strdup("");
}
/* no cheating with paths */
if (!IsValidRelativePath(ft->szThisFile)) {
NetLog_Direct("Invalid path information");
break;
}
char *szFullPath = (char*)SAFE_MALLOC(mir_strlen(ft->szSavePath) + mir_strlen(ft->szThisPath) + mir_strlen(ft->szThisFile) + 3);
mir_strcpy(szFullPath, ft->szSavePath);
NormalizeBackslash(szFullPath);
mir_strcat(szFullPath, ft->szThisPath);
NormalizeBackslash(szFullPath);
// make sure the dest dir exists
if (MakeDirUtf(szFullPath))
NetLog_Direct("Failed to create destination directory!");
mir_strcat(szFullPath, ft->szThisFile);
// we joined the full path to dest file
SAFE_FREE(&ft->szThisFile);
ft->szThisFile = szFullPath;
ft->qwFileBytesDone = 0;
/* file resume */
PROTOFILETRANSFERSTATUS pfts;
oft_buildProtoFileTransferStatus(ft, &pfts);
if (ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_FILERESUME, ft, (LPARAM)&pfts)) {
oc->status = OCS_WAITING;
break; /* UI supports resume: it will call PS_FILERESUME */
}
ft->fileId = OpenFileUtf(ft->szThisFile, _O_BINARY | _O_CREAT | _O_TRUNC | _O_WRONLY, _S_IREAD | _S_IWRITE);
#ifdef _DEBUG
NetLog_Direct("OFT: OpenFileUtf(%s, %u) returned %u", ft->szThisFile, _O_BINARY | _O_CREAT | _O_TRUNC | _O_WRONLY, ft->fileId);
#endif
if (ft->fileId == -1) {
#ifdef _DEBUG
NetLog_Direct("OFT: errno=%d", errno);
#endif
icq_LogMessage(LOG_ERROR, LPGEN("Your file receive has been aborted because Miranda could not open the destination file in order to write to it. You may be trying to save to a read-only folder."));
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&oc->ft);
return;
}
// Send "we are ready"
oc->status = OCS_DATA;
ft->flags |= OFTF_FILE_RECEIVING;
sendOFT2FramePacket(oc, OFT_TYPE_READY);
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
if (!ft->qwThisFileSize) { // if the file is empty we will not receive any data
BYTE buf;
oft_handleFileData(oc, &buf, 0);
}
return;
}
case OFT_TYPE_READY:
case OFT_TYPE_RESUMEACK:
// Receiver is ready
oc->status = OCS_DATA;
oc->wantIdleTime = 1;
ft->flags |= OFTF_FILE_SENDING;
NetLog_Direct("OFT: Receiver ready.");
break;
case OFT_TYPE_RESUMEREQUEST:
// Receiver wants to resume file transfer from point
if (!(ft->flags & OFTF_SENDING)) { // just sanity check - this is only for sending client
NetLog_Direct("Error: Invalid Packet, closing.");
CloseOscarConnection(oc);
return;
}
{
DWORD dwResumeCheck, dwResumeOffset, dwFileCheck;
// Read Resume Frame data
pBuffer += 44;
unpackDWord(&pBuffer, &dwResumeOffset);
unpackDWord(&pBuffer, &dwResumeCheck);
dwFileCheck = oft_calc_file_checksum(ft->fileId, dwResumeOffset);
if (dwFileCheck == dwResumeCheck && dwResumeOffset <= ft->qwThisFileSize) { // resume seems ok
ft->qwFileBytesDone = dwResumeOffset;
ft->qwBytesDone += dwResumeOffset;
_lseek(ft->fileId, dwResumeOffset, SEEK_SET);
NetLog_Direct("OFT: Resume request, ready.");
}
else
NetLog_Direct("OFT: Resume request, restarting.");
// Ready for resume
sendOFT2FramePacket(oc, OFT_TYPE_RESUMEREADY);
}
break;
case OFT_TYPE_RESUMEREADY:
// Process Smart-resume reply
if (ft->flags & OFTF_SENDING) { // just sanity check - this is only for receiving client
NetLog_Direct("Error: Invalid Packet, closing.");
CloseOscarConnection(oc);
return;
}
{
DWORD dwResumeOffset, dwResumeCheck;
// Read Resume Reply data
pBuffer += 44;
unpackDWord(&pBuffer, &dwResumeOffset);
unpackDWord(&pBuffer, &dwResumeCheck);
if (ft->qwFileBytesDone != dwResumeOffset) {
ft->qwBytesDone -= (ft->qwFileBytesDone - dwResumeOffset);
ft->qwFileBytesDone = dwResumeOffset;
if (dwResumeOffset)
ft->dwRecvFileCheck = dwResumeCheck;
else // Restarted resume (data mismatch)
ft->dwRecvFileCheck = 0xFFFF0000;
}
_lseek(ft->fileId, dwResumeOffset, SEEK_SET);
if (ft->qwThisFileSize != ft->qwFileBytesDone)
NetLog_Direct("OFT: Resuming from offset %u.", dwResumeOffset);
// Prepare to receive data
oc->status = OCS_DATA;
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
// Ready for receive
sendOFT2FramePacket(oc, OFT_TYPE_RESUMEACK);
if (ft->qwThisFileSize == ft->qwFileBytesDone) { // all data already processed
BYTE buf;
oft_handleFileData(oc, &buf, 0);
}
}
break;
case OFT_TYPE_DONE:
// File done
oc->status = OCS_NEGOTIATION;
oc->wantIdleTime = 0;
ft->flags &= ~OFTF_FILE_SENDING;
NetLog_Direct("OFT: File sent successfully.");
#ifdef _DEBUG
NetLog_Direct("OFT: _close(%u)", ft->fileId);
#endif
_close(ft->fileId); // FIXME: this needs fix for "skip file" feature
ft->fileId = -1;
ft->iCurrentFile++;
// continue with next file
oft_sendPeerInit(oc);
break;
default:
NetLog_Direct("Error: Uknown OFT frame type 0x%x", datatype);
}
}
//
// Proxy packets
/////////////////////////////
void CIcqProto::proxy_sendInitTunnel(oscar_connection *oc)
{
icq_packet packet;
size_t wLen = 39 + getUINLen(m_dwLocalUIN);
packet.wLen = WORD(wLen);
init_generic_packet(&packet, 2);
packWord(&packet, WORD(wLen));
packWord(&packet, OSCAR_PROXY_VERSION);
packWord(&packet, 0x02); // wCommand
packDWord(&packet, 0); // Unknown
packWord(&packet, 0); // Flags?
packUIN(&packet, m_dwLocalUIN);
packLEDWord(&packet, oc->ft->pMessage.dwMsgID1);
packLEDWord(&packet, oc->ft->pMessage.dwMsgID2);
packDWord(&packet, 0x00010010); // TLV(1)
packGUID(&packet, MCAP_FILE_TRANSFER);
sendOscarPacket(oc, &packet);
}
void CIcqProto::proxy_sendJoinTunnel(oscar_connection *oc, WORD wPort)
{
icq_packet packet;
size_t wLen = 41 + getUINLen(m_dwLocalUIN);
packet.wLen = WORD(wLen);
init_generic_packet(&packet, 2);
packWord(&packet, WORD(wLen));
packWord(&packet, OSCAR_PROXY_VERSION);
packWord(&packet, 0x04); // wCommand
packDWord(&packet, 0); // Unknown
packWord(&packet, 0); // Flags?
packUIN(&packet, m_dwLocalUIN);
packWord(&packet, wPort);
packLEDWord(&packet, oc->ft->pMessage.dwMsgID1);
packLEDWord(&packet, oc->ft->pMessage.dwMsgID2);
packDWord(&packet, 0x00010010); // TLV(1)
packGUID(&packet, MCAP_FILE_TRANSFER);
sendOscarPacket(oc, &packet);
}
//
// Direct packets
/////////////////////////////
void CIcqProto::oft_sendFileData(oscar_connection *oc)
{
oscar_filetransfer *ft = oc->ft;
BYTE buf[OFT_BUFFER_SIZE];
if (ft->fileId == -1)
return;
int bytesRead = _read(ft->fileId, buf, sizeof(buf));
if (bytesRead == -1)
return;
if (!bytesRead) { //
oc->wantIdleTime = 0;
return;
}
if ((DWORD)bytesRead > (ft->qwThisFileSize - ft->qwFileBytesDone)) { // do not send more than expected, limit to known size
bytesRead = (DWORD)(ft->qwThisFileSize - ft->qwFileBytesDone);
oc->wantIdleTime = 0;
}
if (bytesRead) {
icq_packet packet;
packet.wLen = bytesRead;
init_generic_packet(&packet, 0);
packBuffer(&packet, buf, bytesRead); // we are sending raw data
sendOscarPacket(oc, &packet);
ft->qwBytesDone += bytesRead;
ft->qwFileBytesDone += bytesRead;
}
if (GetTickCount() > ft->dwLastNotify + 700 || oc->wantIdleTime == 0 || ft->qwFileBytesDone == ft->qwThisFileSize) { // notify only once a while or after last data packet sent
PROTOFILETRANSFERSTATUS pfts;
oft_buildProtoFileTransferStatus(ft, &pfts);
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&pfts);
ft->dwLastNotify = GetTickCount();
}
}
void CIcqProto::oft_sendPeerInit(oscar_connection *oc)
{
mir_cslock l(oftMutex);
// prepare init frame
oscar_filetransfer *ft = oc->ft;
if (ft->iCurrentFile >= (int)ft->wFilesCount) { // All files done, great!
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_SUCCESS, ft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&oc->ft);
return;
}
SAFE_FREE(&ft->szThisFile);
ft->szThisFile = null_strdup(ft->files[ft->iCurrentFile].szFile);
struct _stati64 statbuf;
if (FileStatUtf(ft->szThisFile, &statbuf)) {
icq_LogMessage(LOG_ERROR, LPGEN("Your file transfer has been aborted because one of the files that you selected to send is no longer readable from the disk. You may have deleted or moved it."));
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&oc->ft);
return;
}
// create full relative filename
char* szThisContainer = ft->files[ft->iCurrentFile].szContainer;
char *pszThisFileName = (char*)SAFE_MALLOC(mir_strlen(ft->szThisFile) + mir_strlen(szThisContainer) + 4);
mir_strcpy(pszThisFileName, szThisContainer);
NormalizeBackslash(pszThisFileName);
mir_strcat(pszThisFileName, ExtractFileName(ft->szThisFile));
// convert backslashes to dir markings
for (size_t i = 0; i < mir_strlen(pszThisFileName); i++)
if (pszThisFileName[i] == '\\' || pszThisFileName[i] == '/')
pszThisFileName[i] = 0x01;
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
ft->fileId = OpenFileUtf(ft->szThisFile, _O_BINARY | _O_RDONLY, 0);
if (ft->fileId == -1) {
NetLog_Direct("OFT: error opening file %s, errno=%d", ft->szThisFile, errno);
SAFE_FREE((void**)&pszThisFileName);
icq_LogMessage(LOG_ERROR, LPGEN("Your file transfer has been aborted (error=%d), because one of the files that you selected to send is no longer readable from the disk. You may have deleted or moved it."));
ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
// Release transfer
SafeReleaseFileTransfer((basic_filetransfer**)&oc->ft);
return;
}
ft->qwThisFileSize = statbuf.st_size;
ft->dwThisFileDate = statbuf.st_mtime;
ft->dwThisFileCreation = statbuf.st_ctime;
ft->dwThisFileCheck = oft_calc_file_checksum(ft->fileId, ft->qwThisFileSize);
ft->qwFileBytesDone = 0;
ft->dwRecvFileCheck = 0xFFFF0000;
SAFE_FREE((void**)&ft->rawFileName);
if (IsUSASCII(pszThisFileName, mir_strlen(pszThisFileName))) {
ft->wEncoding = 0; // ascii
ft->cbRawFileName = WORD(mir_strlen(pszThisFileName) + 1);
if (ft->cbRawFileName < 64)
ft->cbRawFileName = 64;
ft->rawFileName = (char*)SAFE_MALLOC(ft->cbRawFileName);
mir_strcpy(ft->rawFileName, (char*)pszThisFileName);
SAFE_FREE((void**)&pszThisFileName);
}
else {
ft->wEncoding = 2; // ucs-2
WCHAR *pwsThisFile = make_unicode_string(pszThisFileName);
SAFE_FREE((void**)&pszThisFileName);
ft->cbRawFileName = WORD(mir_wstrlen(pwsThisFile) * sizeof(WCHAR)) + 2;
if (ft->cbRawFileName < 64)
ft->cbRawFileName = 64;
ft->rawFileName = (char*)SAFE_MALLOC(ft->cbRawFileName);
// convert to LE ordered string
BYTE *pwsThisFileBuf = (BYTE*)pwsThisFile; // need this - unpackWideString moves the address!
unpackWideString(&pwsThisFileBuf, (WCHAR*)ft->rawFileName, mir_wstrlen(pwsThisFile) * sizeof(WCHAR));
SAFE_FREE((void**)&pwsThisFile);
}
ft->wFilesLeft = WORD(ft->wFilesCount - ft->iCurrentFile);
sendOFT2FramePacket(oc, OFT_TYPE_REQUEST);
}
void CIcqProto::sendOFT2FramePacket(oscar_connection *oc, WORD datatype)
{
oscar_filetransfer *ft = oc->ft;
icq_packet packet;
packet.wLen = WORD(192 + ft->cbRawFileName);
init_generic_packet(&packet, 0);
// Basic Oscar Frame
packDWord(&packet, 0x4F465432); // Magic
packWord(&packet, packet.wLen);
packWord(&packet, datatype);
// Cookie
packLEDWord(&packet, ft->pMessage.dwMsgID1);
packLEDWord(&packet, ft->pMessage.dwMsgID2);
packWord(&packet, ft->wEncrypt);
packWord(&packet, ft->wCompress);
packWord(&packet, ft->wFilesCount);
packWord(&packet, ft->wFilesLeft);
packWord(&packet, ft->wPartsCount);
packWord(&packet, ft->wPartsLeft);
packDWord(&packet, (DWORD)ft->qwTotalSize);
packDWord(&packet, (DWORD)ft->qwThisFileSize);
packDWord(&packet, ft->dwThisFileDate);
packDWord(&packet, ft->dwThisFileCheck);
packDWord(&packet, ft->dwRecvForkCheck);
packDWord(&packet, ft->dwThisForkSize);
packDWord(&packet, ft->dwThisFileCreation);
packDWord(&packet, ft->dwThisForkCheck);
packDWord(&packet, (DWORD)ft->qwFileBytesDone);
packDWord(&packet, ft->dwRecvFileCheck);
packBuffer(&packet, (LPBYTE)ft->rawIDString, 32);
packByte(&packet, ft->bHeaderFlags);
packByte(&packet, ft->bNameOff);
packByte(&packet, ft->bSizeOff);
packBuffer(&packet, ft->rawDummy, 69);
packBuffer(&packet, ft->rawMacInfo, 16);
packWord(&packet, ft->wEncoding);
packWord(&packet, ft->wSubEncoding);
packBuffer(&packet, (LPBYTE)ft->rawFileName, ft->cbRawFileName);
sendOscarPacket(oc, &packet);
}
|