-
Notifications
You must be signed in to change notification settings - Fork 106
/
ftn_bso.js
2310 lines (1983 loc) · 69.4 KB
/
ftn_bso.js
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
/* jslint node: true */
'use strict';
// ENiGMA½
const MessageScanTossModule = require('../msg_scan_toss_module.js').MessageScanTossModule;
const Config = require('../config.js').config;
const ftnMailPacket = require('../ftn_mail_packet.js');
const ftnUtil = require('../ftn_util.js');
const Address = require('../ftn_address.js');
const Log = require('../logger.js').log;
const ArchiveUtil = require('../archive_util.js');
const msgDb = require('../database.js').dbs.message;
const Message = require('../message.js');
const TicFileInfo = require('../tic_file_info.js');
const Errors = require('../enig_error.js').Errors;
const FileEntry = require('../file_entry.js');
const scanFile = require('../file_base_area.js').scanFile;
const getFileAreaByTag = require('../file_base_area.js').getFileAreaByTag;
const getDescFromFileName = require('../file_base_area.js').getDescFromFileName;
const copyFileWithCollisionHandling = require('../file_util.js').copyFileWithCollisionHandling;
const getAreaStorageDirectoryByTag = require('../file_base_area.js').getAreaStorageDirectoryByTag;
const isValidStorageTag = require('../file_base_area.js').isValidStorageTag;
const User = require('../user.js');
// deps
const moment = require('moment');
const _ = require('lodash');
const paths = require('path');
const async = require('async');
const fs = require('graceful-fs');
const later = require('later');
const temptmp = require('temptmp').createTrackedSession('ftn_bso');
const assert = require('assert');
const sane = require('sane');
const fse = require('fs-extra');
const iconv = require('iconv-lite');
const uuidV4 = require('uuid/v4');
exports.moduleInfo = {
name : 'FTN BSO',
desc : 'BSO style message scanner/tosser for FTN networks',
author : 'NuSkooler',
};
/*
:TODO:
* Support (approx) max bundle size
* Validate packet passwords!!!!
=> secure vs insecure landing areas
*/
exports.getModule = FTNMessageScanTossModule;
const SCHEDULE_REGEXP = /(?:^|or )?(@watch\:|@immediate)([^\0]+)?$/;
function FTNMessageScanTossModule() {
MessageScanTossModule.call(this);
const self = this;
this.archUtil = ArchiveUtil.getInstance();
if(_.has(Config, 'scannerTossers.ftn_bso')) {
this.moduleConfig = Config.scannerTossers.ftn_bso;
}
this.getDefaultNetworkName = function() {
if(this.moduleConfig.defaultNetwork) {
return this.moduleConfig.defaultNetwork.toLowerCase();
}
const networkNames = Object.keys(Config.messageNetworks.ftn.networks);
if(1 === networkNames.length) {
return networkNames[0].toLowerCase();
}
};
this.getDefaultZone = function(networkName) {
if(_.isNumber(Config.messageNetworks.ftn.networks[networkName].defaultZone)) {
return Config.messageNetworks.ftn.networks[networkName].defaultZone;
}
// non-explicit: default to local address zone
const networkLocalAddress = Config.messageNetworks.ftn.networks[networkName].localAddress;
if(networkLocalAddress) {
const addr = Address.fromString(networkLocalAddress);
return addr.zone;
}
};
/*
this.isDefaultDomainZone = function(networkName, address) {
const defaultNetworkName = this.getDefaultNetworkName();
return(networkName === defaultNetworkName && address.zone === this.moduleConfig.defaultZone);
};
*/
this.getNetworkNameByAddress = function(remoteAddress) {
return _.findKey(Config.messageNetworks.ftn.networks, network => {
const localAddress = Address.fromString(network.localAddress);
return !_.isUndefined(localAddress) && localAddress.isEqual(remoteAddress);
});
};
this.getNetworkNameByAddressPattern = function(remoteAddressPattern) {
return _.findKey(Config.messageNetworks.ftn.networks, network => {
const localAddress = Address.fromString(network.localAddress);
return !_.isUndefined(localAddress) && localAddress.isPatternMatch(remoteAddressPattern);
});
};
this.getLocalAreaTagByFtnAreaTag = function(ftnAreaTag) {
ftnAreaTag = ftnAreaTag.toUpperCase(); // always compare upper
return _.findKey(Config.messageNetworks.ftn.areas, areaConf => {
return areaConf.tag.toUpperCase() === ftnAreaTag;
});
};
this.getExportType = function(nodeConfig) {
return _.isString(nodeConfig.exportType) ? nodeConfig.exportType.toLowerCase() : 'crash';
};
/*
this.getSeenByAddresses = function(messageSeenBy) {
if(!_.isArray(messageSeenBy)) {
messageSeenBy = [ messageSeenBy ];
}
let seenByAddrs = [];
messageSeenBy.forEach(sb => {
seenByAddrs = seenByAddrs.concat(ftnUtil.parseAbbreviatedNetNodeList(sb));
});
return seenByAddrs;
};
*/
this.messageHasValidMSGID = function(msg) {
return _.isString(msg.meta.FtnKludge.MSGID) && msg.meta.FtnKludge.MSGID.length > 0;
};
/*
this.getOutgoingEchoMailPacketDir = function(networkName, destAddress) {
let dir = this.moduleConfig.paths.outbound;
if(!this.isDefaultDomainZone(networkName, destAddress)) {
const hexZone = `000${destAddress.zone.toString(16)}`.substr(-3);
dir = paths.join(dir, `${networkName.toLowerCase()}.${hexZone}`);
}
return dir;
};
*/
this.getOutgoingEchoMailPacketDir = function(networkName, destAddress) {
networkName = networkName.toLowerCase();
let dir = this.moduleConfig.paths.outbound;
const defaultNetworkName = this.getDefaultNetworkName();
const defaultZone = this.getDefaultZone(networkName);
let zoneExt;
if(defaultZone !== destAddress.zone) {
zoneExt = '.' + `000${destAddress.zone.toString(16)}`.substr(-3);
} else {
zoneExt = '';
}
if(defaultNetworkName === networkName) {
dir = paths.join(dir, `outbound${zoneExt}`);
} else {
dir = paths.join(dir, `${networkName}${zoneExt}`);
}
return dir;
};
this.getOutgoingPacketFileName = function(basePath, messageId, isTemp, fileCase) {
//
// Generating an outgoing packet file name comes with a few issues:
// * We must use DOS 8.3 filenames due to legacy systems that receive
// the packet not understanding LFNs
// * We need uniqueness; This is especially important with packets that
// end up in bundles and on the receiving/remote system where conflicts
// with other systems could also occur
//
// There are a lot of systems in use here for the name:
// * HEX CRC16/32 of data
// * HEX UNIX timestamp
// * Mystic at least at one point, used Hex8(day of month + seconds past midnight + hundredths of second)
// See https://groups.google.com/forum/#!searchin/alt.bbs.mystic/netmail$20filename/alt.bbs.mystic/m1xLnY8i1pU/YnG2excdl6MJ
// * SBBSEcho uses DDHHMMSS - see https://github.com/ftnapps/pkg-sbbs/blob/master/docs/fidonet.txt
// * We already have a system for 8-character serial number gernation that is
// used for e.g. in FTS-0009.001 MSGIDs... let's use that!
//
const name = ftnUtil.getMessageSerialNumber(messageId);
const ext = (true === isTemp) ? 'pk_' : 'pkt';
let fileName = `${name}.${ext}`;
if('upper' === fileCase) {
fileName = fileName.toUpperCase();
}
return paths.join(basePath, fileName);
};
this.getOutgoingFlowFileExtension = function(destAddress, flowType, exportType, fileCase) {
let ext;
switch(flowType) {
case 'mail' : ext = `${exportType.toLowerCase()[0]}ut`; break;
case 'ref' : ext = `${exportType.toLowerCase()[0]}lo`; break;
case 'busy' : ext = 'bsy'; break;
case 'request' : ext = 'req'; break;
case 'requests' : ext = 'hrq'; break;
}
if('upper' === fileCase) {
ext = ext.toUpperCase();
}
return ext;
};
this.getOutgoingFlowFileName = function(basePath, destAddress, flowType, exportType, fileCase) {
let basename;
const ext = self.getOutgoingFlowFileExtension(
destAddress,
flowType,
exportType,
fileCase
);
if(destAddress.point) {
} else {
//
// Use |destAddress| nnnnNNNN.??? where nnnn is dest net and NNNN is dest
// node. This seems to match what Mystic does
//
basename =
`0000${destAddress.net.toString(16)}`.substr(-4) +
`0000${destAddress.node.toString(16)}`.substr(-4);
}
if('upper' === fileCase) {
basename = basename.toUpperCase();
}
return paths.join(basePath, `${basename}.${ext}`);
};
this.flowFileAppendRefs = function(filePath, fileRefs, directive, cb) {
const appendLines = fileRefs.reduce( (content, ref) => {
return content + `${directive}${ref}\n`;
}, '');
fs.appendFile(filePath, appendLines, err => {
cb(err);
});
};
this.getOutgoingBundleFileName = function(basePath, sourceAddress, destAddress, cb) {
//
// Base filename is constructed as such:
// * If this |destAddress| is *not* a point address, we use NNNNnnnn where
// NNNN is 0 padded hex of dest net - source net and and nnnn is 0 padded
// hex of dest node - source node.
// * If |destAddress| is a point, NNNN becomes 0000 and nnnn becomes 'p' +
// 3 digit 0 padded hex point
//
// Extension is dd? where dd is Su...Mo and ? is 0...Z as collisions arise
//
let basename;
if(destAddress.point) {
const pointHex = `000${destAddress.point}`.substr(-3);
basename = `0000p${pointHex}`;
} else {
basename =
`0000${Math.abs(sourceAddress.net - destAddress.net).toString(16)}`.substr(-4) +
`0000${Math.abs(sourceAddress.node - destAddress.node).toString(16)}`.substr(-4);
}
//
// We need to now find the first entry that does not exist starting
// with dd0 to ddz
//
const EXT_SUFFIXES = '0123456789abcdefghijklmnopqrstuvwxyz'.split('');
let fileName = `${basename}.${moment().format('dd').toLowerCase()}`;
async.detectSeries(EXT_SUFFIXES, (suffix, callback) => {
const checkFileName = fileName + suffix;
fs.stat(paths.join(basePath, checkFileName), err => {
callback(null, (err && 'ENOENT' === err.code) ? true : false);
});
}, (err, finalSuffix) => {
if(finalSuffix) {
return cb(null, paths.join(basePath, fileName + finalSuffix));
}
return cb(new Error('Could not acquire a bundle filename!'));
});
};
this.prepareMessage = function(message, options) {
//
// Set various FTN kludges/etc.
//
const localAddress = new Address(options.network.localAddress); // ensure we have an Address obj not a string version
message.meta.FtnProperty = message.meta.FtnProperty || {};
message.meta.FtnKludge = message.meta.FtnKludge || {};
message.meta.FtnProperty.ftn_orig_node = localAddress.node;
message.meta.FtnProperty.ftn_orig_network = localAddress.net;
message.meta.FtnProperty.ftn_cost = 0;
// tear line and origin can both go in EchoMail & NetMail
message.meta.FtnProperty.ftn_tear_line = ftnUtil.getTearLine();
message.meta.FtnProperty.ftn_origin = ftnUtil.getOrigin(localAddress);
let ftnAttribute = ftnMailPacket.Packet.Attribute.Local; // message from our system
if(self.isNetMailMessage(message)) {
// These should be set for Private/NetMail already
assert(_.isNumber(parseInt(message.meta.FtnProperty.ftn_dest_node)));
assert(_.isNumber(parseInt(message.meta.FtnProperty.ftn_dest_network)));
ftnAttribute |= ftnMailPacket.Packet.Attribute.Private;
//
// NetMail messages need a FRL-1005.001 "Via" line
// http://ftsc.org/docs/frl-1005.001
//
// :TODO: We need to do this when FORWARDING NetMail
/*
if(_.isString(message.meta.FtnKludge.Via)) {
message.meta.FtnKludge.Via = [ message.meta.FtnKludge.Via ];
}
message.meta.FtnKludge.Via = message.meta.FtnKludge.Via || [];
message.meta.FtnKludge.Via.push(ftnUtil.getVia(options.network.localAddress));
*/
//
// We need to set INTL, and possibly FMPT and/or TOPT
// See http://retro.fidoweb.ru/docs/index=ftsc&doc=FTS-4001&enc=mac
//
message.meta.FtnKludge.INTL = ftnUtil.getIntl(options.destAddress, localAddress);
if(_.isNumber(localAddress.point) && localAddress.point > 0) {
message.meta.FtnKludge.FMPT = localAddress.point;
}
if(_.isNumber(options.destAddress.point) && options.destAddress.point > 0) {
message.meta.FtnKludge.TOPT = options.destAddress.point;
}
} else {
// We need to set some destination info for EchoMail
message.meta.FtnProperty.ftn_dest_node = options.destAddress.node;
message.meta.FtnProperty.ftn_dest_network = options.destAddress.net;
//
// Set appropriate attribute flag for export type
//
switch(this.getExportType(options.nodeConfig)) {
case 'crash' : ftnAttribute |= ftnMailPacket.Packet.Attribute.Crash; break;
case 'hold' : ftnAttribute |= ftnMailPacket.Packet.Attribute.Hold; break;
// :TODO: Others?
}
//
// EchoMail requires some additional properties & kludges
//
message.meta.FtnProperty.ftn_area = Config.messageNetworks.ftn.areas[message.areaTag].tag;
//
// When exporting messages, we should create/update SEEN-BY
// with remote address(s) we are exporting to.
//
const seenByAdditions =
[ `${localAddress.net}/${localAddress.node}` ].concat(Config.messageNetworks.ftn.areas[message.areaTag].uplinks);
message.meta.FtnProperty.ftn_seen_by =
ftnUtil.getUpdatedSeenByEntries(message.meta.FtnProperty.ftn_seen_by, seenByAdditions);
//
// And create/update PATH for ourself
//
message.meta.FtnKludge.PATH = ftnUtil.getUpdatedPathEntries(message.meta.FtnKludge.PATH, localAddress);
}
message.meta.FtnProperty.ftn_attr_flags = ftnAttribute;
//
// Additional kludges
//
// Check for existence of MSGID as we may already have stored it from a previous
// export that failed to finish
//
if(!message.meta.FtnKludge.MSGID) {
message.meta.FtnKludge.MSGID = ftnUtil.getMessageIdentifier(
message,
localAddress,
message.isPrivate() // true = isNetMail
);
}
message.meta.FtnKludge.TZUTC = ftnUtil.getUTCTimeZoneOffset();
//
// According to FSC-0046:
//
// "When a Conference Mail processor adds a TID to a message, it may not
// add a PID. An existing TID should, however, be replaced. TIDs follow
// the same format used for PIDs, as explained above."
//
message.meta.FtnKludge.TID = ftnUtil.getProductIdentifier();
//
// Determine CHRS and actual internal encoding name. If the message has an
// explicit encoding set, use it. Otherwise, try to preserve any CHRS/encoding already set.
//
let encoding = options.nodeConfig.encoding || Config.scannerTossers.ftn_bso.packetMsgEncoding || 'utf8';
const explicitEncoding = _.get(message.meta, 'System.explicit_encoding');
if(explicitEncoding) {
encoding = explicitEncoding;
} else if(message.meta.FtnKludge.CHRS) {
const encFromChars = ftnUtil.getEncodingFromCharacterSetIdentifier(message.meta.FtnKludge.CHRS);
if(encFromChars) {
encoding = encFromChars;
}
}
//
// Ensure we ended up with something useable. If not, back to utf8!
//
if(!iconv.encodingExists(encoding)) {
Log.debug( { encoding : encoding }, 'Unknown encoding. Falling back to utf8');
encoding = 'utf8';
}
options.encoding = encoding; // save for later
message.meta.FtnKludge.CHRS = ftnUtil.getCharacterSetIdentifierByEncoding(encoding);
};
this.setReplyKludgeFromReplyToMsgId = function(message, cb) {
//
// Look up MSGID kludge for |message.replyToMsgId|, if any.
// If found, we can create a REPLY kludge with the previously
// discovered MSGID.
//
if(0 === message.replyToMsgId) {
return cb(null); // nothing to do
}
Message.getMetaValuesByMessageId(message.replyToMsgId, 'FtnKludge', 'MSGID', (err, msgIdVal) => {
if(!err) {
assert(_.isString(msgIdVal), 'Expected string but got ' + (typeof msgIdVal) + ' (' + msgIdVal + ')');
// got a MSGID - create a REPLY
message.meta.FtnKludge.REPLY = msgIdVal;
}
cb(null); // this method always passes
});
};
// check paths, Addresses, etc.
this.isAreaConfigValid = function(areaConfig) {
if(!areaConfig || !_.isString(areaConfig.tag) || !_.isString(areaConfig.network)) {
return false;
}
if(_.isString(areaConfig.uplinks)) {
areaConfig.uplinks = areaConfig.uplinks.split(' ');
}
return (_.isArray(areaConfig.uplinks));
};
this.hasValidConfiguration = function() {
if(!_.has(this, 'moduleConfig.nodes') || !_.has(Config, 'messageNetworks.ftn.areas')) {
return false;
}
// :TODO: need to check more!
return true;
};
this.parseScheduleString = function(schedStr) {
if(!schedStr) {
return; // nothing to parse!
}
let schedule = {};
const m = SCHEDULE_REGEXP.exec(schedStr);
if(m) {
schedStr = schedStr.substr(0, m.index).trim();
if('@watch:' === m[1]) {
schedule.watchFile = m[2];
} else if('@immediate' === m[1]) {
schedule.immediate = true;
}
}
if(schedStr.length > 0) {
const sched = later.parse.text(schedStr);
if(-1 === sched.error) {
schedule.sched = sched;
}
}
// return undefined if we couldn't parse out anything useful
if(!_.isEmpty(schedule)) {
return schedule;
}
};
this.getAreaLastScanId = function(areaTag, cb) {
const sql =
`SELECT area_tag, message_id
FROM message_area_last_scan
WHERE scan_toss = "ftn_bso" AND area_tag = ?
LIMIT 1;`;
msgDb.get(sql, [ areaTag ], (err, row) => {
return cb(err, row ? row.message_id : 0);
});
};
this.setAreaLastScanId = function(areaTag, lastScanId, cb) {
const sql =
`REPLACE INTO message_area_last_scan (scan_toss, area_tag, message_id)
VALUES ("ftn_bso", ?, ?);`;
msgDb.run(sql, [ areaTag, lastScanId ], err => {
return cb(err);
});
};
this.getNodeConfigByAddress = function(addr) {
addr = _.isString(addr) ? Address.fromString(addr) : addr;
// :TODO: sort wildcard nodes{} entries by most->least explicit according to FTN hierarchy
return _.find(this.moduleConfig.nodes, (node, nodeAddrWildcard) => {
return addr.isPatternMatch(nodeAddrWildcard);
});
};
// :TODO: deprecate this in favor of getNodeConfigByAddress()
this.getNodeConfigKeyByAddress = function(uplink) {
const nodeKey = _.filter(Object.keys(this.moduleConfig.nodes), addr => {
return Address.fromString(addr).isPatternMatch(uplink);
})[0];
return nodeKey;
};
this.exportNetMailMessagePacket = function(message, exportOpts, cb) {
//
// For NetMail, we always create a *single* packet per message.
//
async.series(
[
function generalPrep(callback) {
self.prepareMessage(message, exportOpts);
return self.setReplyKludgeFromReplyToMsgId(message, callback);
},
function createPacket(callback) {
const packet = new ftnMailPacket.Packet();
const packetHeader = new ftnMailPacket.PacketHeader(
exportOpts.network.localAddress,
exportOpts.destAddress,
exportOpts.nodeConfig.packetType
);
packetHeader.password = exportOpts.nodeConfig.packetPassword || '';
// use current message ID for filename seed
exportOpts.pktFileName = self.getOutgoingPacketFileName(
self.exportTempDir,
message.messageId,
false, // createTempPacket=false
exportOpts.fileCase
);
const ws = fs.createWriteStream(exportOpts.pktFileName);
packet.writeHeader(ws, packetHeader);
packet.getMessageEntryBuffer(message, exportOpts, (err, msgBuf) => {
if(err) {
return callback(err);
}
ws.write(msgBuf);
packet.writeTerminator(ws);
ws.end();
ws.once('finish', () => {
return callback(null);
});
});
}
],
err => {
return cb(err);
}
);
};
this.exportMessagesByUuid = function(messageUuids, exportOpts, cb) {
//
// This method has a lot of madness going on:
// - Try to stuff messages into packets until we've hit the target size
// - We need to wait for write streams to finish before proceeding in many cases
// or data will be cut off when closing and creating a new stream
//
let exportedFiles = [];
let currPacketSize = self.moduleConfig.packetTargetByteSize;
let packet;
let ws;
let remainMessageBuf;
let remainMessageId;
const createTempPacket = !_.isString(exportOpts.nodeConfig.archiveType) || 0 === exportOpts.nodeConfig.archiveType.length;
function finalizePacket(cb) {
packet.writeTerminator(ws);
ws.end();
ws.once('finish', () => {
return cb(null);
});
}
async.each(messageUuids, (msgUuid, nextUuid) => {
let message = new Message();
async.series(
[
function finalizePrevious(callback) {
if(packet && currPacketSize >= self.moduleConfig.packetTargetByteSize) {
return finalizePacket(callback);
} else {
callback(null);
}
},
function loadMessage(callback) {
message.load( { uuid : msgUuid }, err => {
if(err) {
return callback(err);
}
// General preperation
self.prepareMessage(message, exportOpts);
self.setReplyKludgeFromReplyToMsgId(message, err => {
callback(err);
});
});
},
function createNewPacket(callback) {
if(currPacketSize >= self.moduleConfig.packetTargetByteSize) {
packet = new ftnMailPacket.Packet();
const packetHeader = new ftnMailPacket.PacketHeader(
exportOpts.network.localAddress,
exportOpts.destAddress,
exportOpts.nodeConfig.packetType);
packetHeader.password = exportOpts.nodeConfig.packetPassword || '';
// use current message ID for filename seed
const pktFileName = self.getOutgoingPacketFileName(
self.exportTempDir,
message.messageId,
createTempPacket,
exportOpts.fileCase
);
exportedFiles.push(pktFileName);
ws = fs.createWriteStream(pktFileName);
currPacketSize = packet.writeHeader(ws, packetHeader);
if(remainMessageBuf) {
currPacketSize += packet.writeMessageEntry(ws, remainMessageBuf);
remainMessageBuf = null;
}
}
callback(null);
},
function appendMessage(callback) {
packet.getMessageEntryBuffer(message, exportOpts, (err, msgBuf) => {
if(err) {
return callback(err);
}
currPacketSize += msgBuf.length;
if(currPacketSize >= self.moduleConfig.packetTargetByteSize) {
remainMessageBuf = msgBuf; // save for next packet
remainMessageId = message.messageId;
} else {
ws.write(msgBuf);
}
return callback(null);
});
},
function storeStateFlags0Meta(callback) {
message.persistMetaValue('System', 'state_flags0', Message.StateFlags0.Exported.toString(), err => {
callback(err);
});
},
function storeMsgIdMeta(callback) {
//
// We want to store some meta as if we had imported
// this message for later reference
//
if(message.meta.FtnKludge.MSGID) {
message.persistMetaValue('FtnKludge', 'MSGID', message.meta.FtnKludge.MSGID, err => {
callback(err);
});
} else {
callback(null);
}
}
],
err => {
nextUuid(err);
}
);
}, err => {
if(err) {
cb(err);
} else {
async.series(
[
function terminateLast(callback) {
if(packet) {
return finalizePacket(callback);
} else {
callback(null);
}
},
function writeRemainPacket(callback) {
if(remainMessageBuf) {
// :TODO: DRY this with the code above -- they are basically identical
packet = new ftnMailPacket.Packet();
const packetHeader = new ftnMailPacket.PacketHeader(
exportOpts.network.localAddress,
exportOpts.destAddress,
exportOpts.nodeConfig.packetType);
packetHeader.password = exportOpts.nodeConfig.packetPassword || '';
// use current message ID for filename seed
const pktFileName = self.getOutgoingPacketFileName(
self.exportTempDir,
remainMessageId,
createTempPacket,
exportOpts.filleCase
);
exportedFiles.push(pktFileName);
ws = fs.createWriteStream(pktFileName);
packet.writeHeader(ws, packetHeader);
ws.write(remainMessageBuf);
return finalizePacket(callback);
} else {
callback(null);
}
}
],
err => {
cb(err, exportedFiles);
}
);
}
});
};
this.getNetMailRoute = function(dstAddr) {
//
// messageNetworks.ftn.netMail.routes{} full|wildcard -> full adddress lookup
//
const routes = _.get(Config, 'messageNetworks.ftn.netMail.routes');
if(!routes) {
return;
}
return _.find(routes, (route, addrWildcard) => {
return dstAddr.isPatternMatch(addrWildcard);
});
/*
const route = _.find(routes, (route, addrWildcard) => {
return dstAddr.isPatternMatch(addrWildcard);
});
if(route && route.address) {
return Address.fromString(route.address);
}
*/
};
this.getAcceptableNetMailNetworkInfoFromAddress = function(dstAddr, cb) {
//
// Attempt to find an acceptable network configuration using the following
// lookup order (most to least explicit config):
//
// 1) Routes: messageNetworks.ftn.netMail.routes{} -> scannerTossers.ftn_bso.nodes{} -> config
// - Where we send may not be where dstAddress is (it's routed!)
// 2) Direct to nodes: scannerTossers.ftn_bso.nodes{} -> config
// - Where we send is direct to dstAddr
//
// In both cases, attempt to look up Zone:Net/* to discover local "from" network/address
// falling back to Config.scannerTossers.ftn_bso.defaultNetwork
//
const route = this.getNetMailRoute(dstAddr);
let routeAddress;
let networkName;
if(route) {
routeAddress = Address.fromString(route.address);
networkName = route.network;
} else {
routeAddress = dstAddr;
}
networkName = networkName ||
this.getNetworkNameByAddressPattern(`${routeAddress.zone}:${routeAddress.net}/*`) ||
Config.scannerTossers.ftn_bso.defaultNetwork
;
const config = _.find(this.moduleConfig.nodes, (node, nodeAddrWildcard) => {
return routeAddress.isPatternMatch(nodeAddrWildcard);
}) || {
packetType : '2+',
encoding : Config.scannerTossers.ftn_bso.packetMsgEncoding,
};
return cb(
config ? null : Errors.DoesNotExist(`No configuration found for ${dstAddr.toString()}`),
config, routeAddress, networkName
);
};
this.exportNetMailMessagesToUplinks = function(messagesOrMessageUuids, cb) {
// for each message/UUID, find where to send the thing
async.each(messagesOrMessageUuids, (msgOrUuid, nextMessageOrUuid) => {
const exportOpts = {};
const message = new Message();
async.series(
[
function loadMessage(callback) {
if(_.isString(msgOrUuid)) {
message.load( { uuid : msgOrUuid }, err => {
return callback(err, message);
});
} else {
return callback(null, msgOrUuid);
}
},
function discoverUplink(callback) {
const dstAddr = new Address(message.meta.System[Message.SystemMetaNames.RemoteToUser]);
return self.getAcceptableNetMailNetworkInfoFromAddress(dstAddr, (err, config, routeAddress, networkName) => {
if(err) {
return callback(err);
}
exportOpts.nodeConfig = config;
exportOpts.destAddress = routeAddress;
exportOpts.fileCase = config.fileCase || 'lower';
exportOpts.network = Config.messageNetworks.ftn.networks[networkName];
exportOpts.networkName = networkName;
exportOpts.outgoingDir = self.getOutgoingEchoMailPacketDir(exportOpts.networkName, exportOpts.destAddress);
exportOpts.exportType = self.getExportType(config);
if(!exportOpts.network) {
return callback(Errors.DoesNotExist(`No configuration found for network ${networkName}`));
}
return callback(null);
});
},
function createOutgoingDir(callback) {
// ensure outgoing NetMail directory exists
return fse.mkdirs(exportOpts.outgoingDir, callback);
},
function exportPacket(callback) {
return self.exportNetMailMessagePacket(message, exportOpts, callback);
},
function moveToOutgoing(callback) {
const newExt = exportOpts.fileCase === 'lower' ? '.pkt' : '.PKT';
exportOpts.exportedToPath = paths.join(
exportOpts.outgoingDir,
`${paths.basename(exportOpts.pktFileName, paths.extname(exportOpts.pktFileName))}${newExt}`
);
return fse.move(exportOpts.pktFileName, exportOpts.exportedToPath, callback);
},
function prepareFloFile(callback) {
const flowFilePath = self.getOutgoingFlowFileName(
exportOpts.outgoingDir,
exportOpts.destAddress,
'ref',
exportOpts.exportType,
exportOpts.fileCase
);
return self.flowFileAppendRefs(flowFilePath, [ exportOpts.exportedToPath ], '^', callback);
},
function storeStateFlags0Meta(callback) {
return message.persistMetaValue('System', 'state_flags0', Message.StateFlags0.Exported.toString(), callback);
},
function storeMsgIdMeta(callback) {
// Store meta as if we had imported this message -- for later reference
if(message.meta.FtnKludge.MSGID) {
return message.persistMetaValue('FtnKludge', 'MSGID', message.meta.FtnKludge.MSGID, callback);
}
return callback(null);
}
],
err => {
if(err) {
Log.warn( { error :err.message }, 'Error exporting message' );
}
return nextMessageOrUuid(null);
}
);
}, err => {
return cb(err);
});
};
this.exportEchoMailMessagesToUplinks = function(messageUuids, areaConfig, cb) {
async.each(areaConfig.uplinks, (uplink, nextUplink) => {
const nodeConfigKey = self.getNodeConfigKeyByAddress(uplink);
if(!nodeConfigKey) {
return nextUplink();
}
const exportOpts = {
nodeConfig : self.moduleConfig.nodes[nodeConfigKey],
network : Config.messageNetworks.ftn.networks[areaConfig.network],
destAddress : Address.fromString(uplink),
networkName : areaConfig.network,
fileCase : self.moduleConfig.nodes[nodeConfigKey].fileCase || 'lower',
};
if(_.isString(exportOpts.network.localAddress)) {
exportOpts.network.localAddress = Address.fromString(exportOpts.network.localAddress);
}
const outgoingDir = self.getOutgoingEchoMailPacketDir(exportOpts.networkName, exportOpts.destAddress);
const exportType = self.getExportType(exportOpts.nodeConfig);
async.waterfall(
[
function createOutgoingDir(callback) {
fse.mkdirs(outgoingDir, err => {
callback(err);
});
},
function exportToTempArea(callback) {
self.exportMessagesByUuid(messageUuids, exportOpts, callback);
},
function createArcMailBundle(exportedFileNames, callback) {
if(self.archUtil.haveArchiver(exportOpts.nodeConfig.archiveType)) {
// :TODO: support bundleTargetByteSize:
//
// Compress to a temp location then we'll move it in the next step
//
// Note that we must use the *final* output dir for getOutgoingBundleFileName()
// as it checks for collisions in bundle names!
//
self.getOutgoingBundleFileName(outgoingDir, exportOpts.network.localAddress, exportOpts.destAddress, (err, bundlePath) => {
if(err) {
return callback(err);
}
// adjust back to temp path
const tempBundlePath = paths.join(self.exportTempDir, paths.basename(bundlePath));
self.archUtil.compressTo(
exportOpts.nodeConfig.archiveType,