-
-
Notifications
You must be signed in to change notification settings - Fork 135
/
Session.java
1140 lines (996 loc) · 41.6 KB
/
Session.java
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
package com.frostwire.jlibtorrent;
import com.frostwire.jlibtorrent.alerts.*;
import com.frostwire.jlibtorrent.plugins.Plugin;
import com.frostwire.jlibtorrent.plugins.SwigPlugin;
import com.frostwire.jlibtorrent.swig.*;
import com.frostwire.jlibtorrent.swig.session_handle.options_t;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* The session holds all state that spans multiple torrents. Among other
* things it runs the network loop and manages all torrents. Once it's
* created, the session object will spawn the main thread that will do all
* the work. The main thread will be idle as long it doesn't have any
* torrents to participate in.
* <p/>
* This class belongs to a middle logical layer of abstraction. It's a wrapper
* of the underlying swig session object (from libtorrent), but it does not
* expose all the raw features, not expose a very high level interface
* like {@link com.frostwire.jlibtorrent.DHT DHT} or
* {@link com.frostwire.jlibtorrent.Downloader Downloader}.
*
* @author gubatron
* @author aldenml
*/
public final class Session extends SessionHandle {
private static final Logger LOG = Logger.getLogger(Session.class);
private static final long REQUEST_STATS_RESOLUTION_MILLIS = 1000;
private static final long ALERTS_LOOP_WAIT_MILLIS = 500;
private static final LruCache<String, byte[]> MAGNET_CACHE = new LruCache<String, byte[]>(50);
private static final Object MAGNET_LOCK = new Object();
private final session s;
private final JavaStat stat;
private final SessionStats stats;
private long lastStatsRequestTime;
private long lastStatSecondTick;
private final SparseArray<ArrayList<AlertListener>> listeners;
private final SparseArray<AlertListener[]> listenerSnapshots;
private boolean running;
private final LinkedList<SwigPlugin> plugins;
/**
* The flag alert_mask is always set to all_categories.
*
* @param settings
* @param logging
*/
public Session(SettingsPack settings, boolean logging, AlertListener listener) {
super(createSession(settings, logging));
this.s = (session) super.s;
this.stat = new JavaStat();
this.stats = new SessionStats(stat);
this.listeners = new SparseArray<ArrayList<AlertListener>>();
this.listenerSnapshots = new SparseArray<AlertListener[]>();
if (listener != null) {
addListener(listener);
}
this.running = true;
alertsLoop();
for (Pair<String, Integer> router : defaultRouters()) {
s.add_dht_router(router.to_string_int_pair());
}
this.plugins = new LinkedList<SwigPlugin>();
}
public Session() {
this(new SettingsPack(), false, null);
}
/**
* This constructor allow you to specify the listen interfaces in the
* same format libtorrent accepts. Like for example, IPv4+IPv6 in the
* first available port: "0.0.0.0:0,[::]:0"
*
* @param interfaces
* @param logging
* @param listener
*/
public Session(String interfaces, boolean logging, AlertListener listener) {
this(createSettings(interfaces), logging, listener);
}
public session getSwig() {
return s;
}
public void addListener(AlertListener listener) {
modifyListeners(true, listener);
}
public void removeListener(AlertListener listener) {
modifyListeners(false, listener);
}
/**
* You add torrents through the add_torrent() function where you give an
* object with all the parameters. The add_torrent() overloads will block
* until the torrent has been added (or failed to be added) and returns
* an error code and a torrent_handle. In order to add torrents more
* efficiently, consider using async_add_torrent() which returns
* immediately, without waiting for the torrent to add. Notification of
* the torrent being added is sent as add_torrent_alert.
* <p/>
* The overload that does not take an error_code throws an exception on
* error and is not available when building without exception support.
* The torrent_handle returned by add_torrent() can be used to retrieve
* information about the torrent's progress, its peers etc. It is also
* used to abort a torrent.
* <p/>
* If the torrent you are trying to add already exists in the session (is
* either queued for checking, being checked or downloading)
* ``add_torrent()`` will throw libtorrent_exception which derives from
* ``std::exception`` unless duplicate_is_error is set to false. In that
* case, add_torrent() will return the handle to the existing torrent.
* <p/>
* all torrent_handles must be destructed before the session is destructed!
*
* @param ti
* @param saveDir
* @param priorities
* @param resumeFile
* @return
*/
public TorrentHandle addTorrent(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile) {
return addTorrentSupport(ti, saveDir, priorities, resumeFile, false);
}
/**
* You add torrents through the add_torrent() function where you give an
* object with all the parameters. The add_torrent() overloads will block
* until the torrent has been added (or failed to be added) and returns
* an error code and a torrent_handle. In order to add torrents more
* efficiently, consider using async_add_torrent() which returns
* immediately, without waiting for the torrent to add. Notification of
* the torrent being added is sent as add_torrent_alert.
* <p/>
* The overload that does not take an error_code throws an exception on
* error and is not available when building without exception support.
* The torrent_handle returned by add_torrent() can be used to retrieve
* information about the torrent's progress, its peers etc. It is also
* used to abort a torrent.
* <p/>
* If the torrent you are trying to add already exists in the session (is
* either queued for checking, being checked or downloading)
* ``add_torrent()`` will throw libtorrent_exception which derives from
* ``std::exception`` unless duplicate_is_error is set to false. In that
* case, add_torrent() will return the handle to the existing torrent.
* <p/>
* all torrent_handles must be destructed before the session is destructed!
*
* @param torrent
* @param saveDir
* @param resumeFile
* @return
*/
public TorrentHandle addTorrent(File torrent, File saveDir, File resumeFile) {
return addTorrent(new TorrentInfo(torrent), saveDir, null, resumeFile);
}
/**
* You add torrents through the add_torrent() function where you give an
* object with all the parameters. The add_torrent() overloads will block
* until the torrent has been added (or failed to be added) and returns
* an error code and a torrent_handle. In order to add torrents more
* efficiently, consider using async_add_torrent() which returns
* immediately, without waiting for the torrent to add. Notification of
* the torrent being added is sent as add_torrent_alert.
* <p/>
* The overload that does not take an error_code throws an exception on
* error and is not available when building without exception support.
* The torrent_handle returned by add_torrent() can be used to retrieve
* information about the torrent's progress, its peers etc. It is also
* used to abort a torrent.
* <p/>
* If the torrent you are trying to add already exists in the session (is
* either queued for checking, being checked or downloading)
* ``add_torrent()`` will throw libtorrent_exception which derives from
* ``std::exception`` unless duplicate_is_error is set to false. In that
* case, add_torrent() will return the handle to the existing torrent.
* <p/>
* all torrent_handles must be destructed before the session is destructed!
*
* @param torrent
* @param saveDir
* @return
*/
public TorrentHandle addTorrent(File torrent, File saveDir) {
return addTorrent(torrent, saveDir, null);
}
/**
* In order to add torrents more efficiently, consider using this which returns
* immediately, without waiting for the torrent to add. Notification of
* the torrent being added is sent as {@link com.frostwire.jlibtorrent.alerts.AddTorrentAlert}.
* <p/>
* If the torrent you are trying to add already exists in the session (is
* either queued for checking, being checked or downloading)
* ``add_torrent()`` will throw libtorrent_exception which derives from
* ``std::exception`` unless duplicate_is_error is set to false. In that
* case, add_torrent() will return the handle to the existing torrent.
*
* @param ti
* @param saveDir
* @param priorities
* @param resumeFile
*/
public void asyncAddTorrent(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile) {
addTorrentSupport(ti, saveDir, priorities, resumeFile, true);
}
/**
* You add torrents through the add_torrent() function where you give an
* object with all the parameters. The add_torrent() overloads will block
* until the torrent has been added (or failed to be added) and returns
* an error code and a torrent_handle. In order to add torrents more
* efficiently, consider using async_add_torrent() which returns
* immediately, without waiting for the torrent to add. Notification of
* the torrent being added is sent as add_torrent_alert.
* <p/>
* The overload that does not take an error_code throws an exception on
* error and is not available when building without exception support.
* The torrent_handle returned by add_torrent() can be used to retrieve
* information about the torrent's progress, its peers etc. It is also
* used to abort a torrent.
* <p/>
* If the torrent you are trying to add already exists in the session (is
* either queued for checking, being checked or downloading)
* ``add_torrent()`` will throw libtorrent_exception which derives from
* ``std::exception`` unless duplicate_is_error is set to false. In that
* case, add_torrent() will return the handle to the existing torrent.
* <p/>
* all torrent_handles must be destructed before the session is destructed!
*
* @param torrent
* @param saveDir
* @param resumeFile
*/
public void asyncAddTorrent(File torrent, File saveDir, File resumeFile) {
asyncAddTorrent(new TorrentInfo(torrent), saveDir, null, resumeFile);
}
/**
* You add torrents through the add_torrent() function where you give an
* object with all the parameters. The add_torrent() overloads will block
* until the torrent has been added (or failed to be added) and returns
* an error code and a torrent_handle. In order to add torrents more
* efficiently, consider using async_add_torrent() which returns
* immediately, without waiting for the torrent to add. Notification of
* the torrent being added is sent as add_torrent_alert.
* <p/>
* The overload that does not take an error_code throws an exception on
* error and is not available when building without exception support.
* The torrent_handle returned by add_torrent() can be used to retrieve
* information about the torrent's progress, its peers etc. It is also
* used to abort a torrent.
* <p/>
* If the torrent you are trying to add already exists in the session (is
* either queued for checking, being checked or downloading)
* ``add_torrent()`` will throw libtorrent_exception which derives from
* ``std::exception`` unless duplicate_is_error is set to false. In that
* case, add_torrent() will return the handle to the existing torrent.
* <p/>
* all torrent_handles must be destructed before the session is destructed!
*
* @param torrent
* @param saveDir
*/
public void asyncAddTorrent(File torrent, File saveDir) {
asyncAddTorrent(torrent, saveDir, null);
}
/**
* This method will close all peer connections associated with the torrent and tell the
* tracker that we've stopped participating in the swarm. This operation cannot fail.
* When it completes, you will receive a torrent_removed_alert.
* <p/>
* The optional second argument options can be used to delete all the files downloaded
* by this torrent. To do so, pass in the value session::delete_files. The removal of
* the torrent is asyncronous, there is no guarantee that adding the same torrent immediately
* after it was removed will not throw a libtorrent_exception exception. Once the torrent
* is deleted, a torrent_deleted_alert is posted.
*
* @param th
*/
public void removeTorrent(TorrentHandle th, Options options) {
s.remove_torrent(th.getSwig(), options.getSwig());
}
/**
* This method will close all peer connections associated with the torrent and tell the
* tracker that we've stopped participating in the swarm. This operation cannot fail.
* When it completes, you will receive a torrent_removed_alert.
*
* @param th
*/
public void removeTorrent(TorrentHandle th) {
if (th.isValid()) {
s.remove_torrent(th.getSwig());
}
}
/**
* Applies the settings specified by the settings pack {@code sp}. This is an
* asynchronous operation that will return immediately and actually apply
* the settings to the main thread of libtorrent some time later.
*
* @param sp
*/
public void applySettings(SettingsPack sp) {
s.apply_settings(sp.getSwig());
}
/**
* In case you want to destruct the session asynchronously, you can
* request a session destruction proxy. If you don't do this, the
* destructor of the session object will block while the trackers are
* contacted. If you keep one ``session_proxy`` to the session when
* destructing it, the destructor will not block, but start to close down
* the session, the destructor of the proxy will then synchronize the
* threads. So, the destruction of the session is performed from the
* ``session`` destructor call until the ``session_proxy`` destructor
* call. The ``session_proxy`` does not have any operations on it (since
* the session is being closed down, no operations are allowed on it).
* The only valid operation is calling the destructor::
*
* @return
*/
public SessionProxy abort() {
running = false;
return new SessionProxy(s.abort());
}
/**
* Pausing the session has the same effect as pausing every torrent in
* it, except that torrents will not be resumed by the auto-manage
* mechanism.
*/
public void pause() {
s.pause();
}
/**
* Resuming will restore the torrents to their previous paused
* state. i.e. the session pause state is separate from the torrent pause
* state. A torrent is inactive if it is paused or if the session is
* paused.
*/
public void resume() {
s.resume();
}
public boolean isPaused() {
return s.is_paused();
}
/**
* returns the port we ended up listening on. Since you
* just pass a port-range to the constructor and to ``listen_on()``, to
* know which port it ended up using, you have to ask the session using
* this function.
*
* @return
*/
public int getListenPort() {
return s.listen_port();
}
public int getSslListenPort() {
return s.ssl_listen_port();
}
/**
* will tell you whether or not the session has
* successfully opened a listening port. If it hasn't, this function will
* return false, and then you can use ``listen_on()`` to make another
* attempt.
*
* @return
*/
public boolean isListening() {
return s.is_listening();
}
/**
* Loads and saves all session settings, including dht settings,
* encryption settings and proxy settings. {@link #saveState()}
* internally writes all keys to an {@link entry} that's passed in,
* which needs to either not be initialized, or initialized as a dictionary.
* <p/>
* The {@code flags} arguments passed in to this method can be used to
* filter which parts of the session state to save. By default, all state
* is saved (except for the individual torrents).
* See {@link com.frostwire.jlibtorrent.swig.session_handle.save_state_flags_t}
*
* @return
*/
public byte[] saveState(long flags) {
entry e = new entry();
s.save_state(e);
return Vectors.byte_vector2bytes(e.bencode());
}
/**
* Same as calling {@link #saveState(long)} with all save state flags.
*
* @return
* @see #saveState(long)
*/
public byte[] saveState() {
entry e = new entry();
s.save_state(e);
return Vectors.byte_vector2bytes(e.bencode());
}
/**
* Loads and saves all session settings, including dht_settings,
* encryption settings and proxy settings. ``save_state`` writes all keys
* to the ``entry`` that's passed in, which needs to either not be
* initialized, or initialized as a dictionary.
* <p/>
* ``load_state`` expects a lazy_entry which can be built from a bencoded
* buffer with lazy_bdecode().
* <p/>
* The ``flags`` arguments passed in to ``save_state`` can be used to
* filter which parts of the session state to save. By default, all state
* is saved (except for the individual torrents). see save_state_flags_t
*
* @param data
*/
public void loadState(byte[] data) {
byte_vector buffer = Vectors.bytes2byte_vector(data);
bdecode_node n = new bdecode_node();
error_code ec = new error_code();
int ret = bdecode_node.bdecode(buffer, n, ec);
if (ret == 0) {
s.load_state(n);
} else {
LOG.error("failed to decode torrent: " + ec.message());
}
}
/**
* This functions instructs the session to post the state_update_alert,
* containing the status of all torrents whose state changed since the
* last time this function was called.
* <p/>
* Only torrents who has the state subscription flag set will be
* included. This flag is on by default. See add_torrent_params.
* the ``flags`` argument is the same as for torrent_handle::status().
* see torrent_handle::status_flags_t.
*
* @param flags
*/
public void postTorrentUpdates(TorrentHandle.StatusFlags flags) {
s.post_torrent_updates(flags.getSwig());
}
/**
* This functions instructs the session to post the state_update_alert,
* containing the status of all torrents whose state changed since the
* last time this function was called.
* <p/>
* Only torrents who has the state subscription flag set will be
* included.
*/
public void postTorrentUpdates() {
s.post_torrent_updates();
}
/**
* This function will post a {@link com.frostwire.jlibtorrent.alerts.SessionStatsAlert} object, containing a
* snapshot of the performance counters from the internals of libtorrent.
* To interpret these counters, query the session via
* session_stats_metrics().
*/
public void postSessionStats() {
s.post_session_stats();
}
/**
* This will cause a dht_stats_alert to be posted.
*/
public void postDHTStats() {
s.post_dht_stats();
}
/**
* Looks for a torrent with the given info-hash. In
* case there is such a torrent in the session, a torrent_handle to that
* torrent is returned.
* <p/>
* In case the torrent cannot be found, a null is returned.
*
* @param infoHash
* @return
*/
public TorrentHandle findTorrent(Sha1Hash infoHash) {
torrent_handle th = s.find_torrent(infoHash.swig());
return th != null && th.is_valid() ? new TorrentHandle(th) : null;
}
/**
* Returns a list of torrent handles to all the
* torrents currently in the session.
*
* @return
*/
public List<TorrentHandle> getTorrents() {
torrent_handle_vector v = s.get_torrents();
long size = v.size();
List<TorrentHandle> l = new ArrayList<TorrentHandle>((int) size);
for (int i = 0; i < size; i++) {
l.add(new TorrentHandle(v.get(i)));
}
return l;
}
// starts/stops UPnP, NATPMP or LSD port mappers they are stopped by
// default These functions are not available in case
// ``TORRENT_DISABLE_DHT`` is defined. ``start_dht`` starts the dht node
// and makes the trackerless service available to torrents. The startup
// state is optional and can contain nodes and the node id from the
// previous session. The dht node state is a bencoded dictionary with the
// following entries:
//
// nodes
// A list of strings, where each string is a node endpoint encoded in
// binary. If the string is 6 bytes long, it is an IPv4 address of 4
// bytes, encoded in network byte order (big endian), followed by a 2
// byte port number (also network byte order). If the string is 18
// bytes long, it is 16 bytes of IPv6 address followed by a 2 bytes
// port number (also network byte order).
//
// node-id
// The node id written as a readable string as a hexadecimal number.
//
// ``dht_state`` will return the current state of the dht node, this can
// be used to start up the node again, passing this entry to
// ``start_dht``. It is a good idea to save this to disk when the session
// is closed, and read it up again when starting.
//
// If the port the DHT is supposed to listen on is already in use, and
// exception is thrown, ``asio::error``.
//
// ``stop_dht`` stops the dht node.
//
// ``add_dht_node`` adds a node to the routing table. This can be used if
// your client has its own source of bootstrapping nodes.
//
// ``set_dht_settings`` sets some parameters availavle to the dht node.
// See dht_settings for more information.
//
// ``is_dht_running()`` returns true if the DHT support has been started
// and false
// otherwise.
void setDHTSettings(DhtSettings settings) {
s.set_dht_settings(settings.swig());
}
public boolean isDHTRunning() {
return s.is_dht_running();
}
/**
* takes a host name and port pair. That endpoint will be
* pinged, and if a valid DHT reply is received, the node will be added to
* the routing table.
*
* @param node
*/
public void addDHTNode(Pair<String, Integer> node) {
s.add_dht_node(node.to_string_int_pair());
}
/**
* adds the given endpoint to a list of DHT router nodes.
* If a search is ever made while the routing table is empty, those nodes will
* be used as backups. Nodes in the router node list will also never be added
* to the regular routing table, which effectively means they are only used
* for bootstrapping, to keep the load off them.
* <p/>
* An example routing node that you could typically add is
* ``router.bittorrent.com``.
*
* @param node
*/
public void addDHTRouter(Pair<String, Integer> node) {
s.add_dht_router(node.to_string_int_pair());
}
/**
* Query the DHT for an immutable item at the target hash.
* the result is posted as a {@link DhtImmutableItemAlert}.
*
* @param target
*/
public void dhtGetItem(Sha1Hash target) {
s.dht_get_item(target.swig());
}
/**
* Query the DHT for a mutable item under the public key {@code key}.
* this is an ed25519 key. The {@code salt} argument is optional and may be left
* as an empty string if no salt is to be used.
* <p/>
* if the item is found in the DHT, a {@link DhtMutableItemAlert} is
* posted.
*
* @param key
* @param salt
*/
public void dhtGetItem(byte[] key, byte[] salt) {
s.dht_get_item(Vectors.bytes2byte_vector(key), Vectors.bytes2byte_vector(salt));
}
/**
* Store the given bencoded data as an immutable item in the DHT.
* the returned hash is the key that is to be used to look the item
* up agan. It's just the sha-1 hash of the bencoded form of the
* structure.
*
* @param entry
* @return
*/
public Sha1Hash dhtPutItem(Entry entry) {
return new Sha1Hash(s.dht_put_item(entry.getSwig()));
}
// store an immutable item. The ``key`` is the public key the blob is
// to be stored under. The optional ``salt`` argument is a string that
// is to be mixed in with the key when determining where in the DHT
// the value is to be stored. The callback function is called from within
// the libtorrent network thread once we've found where to store the blob,
// possibly with the current value stored under the key.
// The values passed to the callback functions are:
//
// entry& value
// the current value stored under the key (may be empty). Also expected
// to be set to the value to be stored by the function.
//
// boost::array<char,64>& signature
// the signature authenticating the current value. This may be zeroes
// if there is currently no value stored. The functon is expected to
// fill in this buffer with the signature of the new value to store.
// To generate the signature, you may want to use the
// ``sign_mutable_item`` function.
//
// boost::uint64_t& seq
// current sequence number. May be zero if there is no current value.
// The function is expected to set this to the new sequence number of
// the value that is to be stored. Sequence numbers must be monotonically
// increasing. Attempting to overwrite a value with a lower or equal
// sequence number will fail, even if the signature is correct.
//
// std::string const& salt
// this is the salt that was used for this put call.
//
// Since the callback function ``cb`` is called from within libtorrent,
// it is critical to not perform any blocking operations. Ideally not
// even locking a mutex. Pass any data required for this function along
// with the function object's context and make the function entirely
// self-contained. The only reason data blobs' values are computed
// via a function instead of just passing in the new value is to avoid
// race conditions. If you want to *update* the value in the DHT, you
// must first retrieve it, then modify it, then write it back. The way
// the DHT works, it is natural to always do a lookup before storing and
// calling the callback in between is convenient.
public void dhtPutItem(byte[] publicKey, byte[] privateKey, Entry entry, byte[] salt) {
s.dht_put_item(Vectors.bytes2byte_vector(publicKey),
Vectors.bytes2byte_vector(privateKey),
entry.getSwig(),
Vectors.bytes2byte_vector(salt));
}
public void dhtGetPeers(Sha1Hash infoHash) {
s.dht_get_peers(infoHash.swig());
}
public void dhtAnnounce(Sha1Hash infoHash, int port, int flags) {
s.dht_announce(infoHash.swig(), port, flags);
}
public void dhtAnnounce(Sha1Hash infoHash) {
s.dht_announce(infoHash.swig());
}
public void dhtDirectRequest(UdpEndpoint endp, Entry entry) {
s.dht_direct_request(endp.swig(), entry.getSwig());
}
public void addExtension(Plugin p) {
SwigPlugin sp = new SwigPlugin(p);
s.add_swig_extension(sp);
plugins.add(sp);
}
/**
* add_port_mapping adds a port forwarding on UPnP and/or NAT-PMP,
* whichever is enabled. The return value is a handle referring to the
* port mapping that was just created. Pass it to delete_port_mapping()
* to remove it.
*
* @param t
* @param externalPort
* @param localPort
* @return
*/
public int addPortMapping(ProtocolType t, int externalPort, int localPort) {
return s.add_port_mapping(t.getSwig(), externalPort, localPort);
}
public void deletePortMapping(int handle) {
s.delete_port_mapping(handle);
}
public SessionStats getStats() {
return stats;
}
public SettingsPack getSettingsPack() {
return new SettingsPack(s.get_settings());
}
// You add torrents through the add_torrent() function where you give an
// object with all the parameters. The add_torrent() overloads will block
// until the torrent has been added (or failed to be added) and returns
// an error code and a torrent_handle. In order to add torrents more
// efficiently, consider using async_add_torrent() which returns
// immediately, without waiting for the torrent to add. Notification of
// the torrent being added is sent as add_torrent_alert.
//
// The overload that does not take an error_code throws an exception on
// error and is not available when building without exception support.
// The torrent_handle returned by add_torrent() can be used to retrieve
// information about the torrent's progress, its peers etc. It is also
// used to abort a torrent.
//
// If the torrent you are trying to add already exists in the session (is
// either queued for checking, being checked or downloading)
// ``add_torrent()`` will throw libtorrent_exception which derives from
// ``std::exception`` unless duplicate_is_error is set to false. In that
// case, add_torrent() will return the handle to the existing torrent.
//
// all torrent_handles must be destructed before the session is destructed!
public TorrentHandle addTorrent(AddTorrentParams params, ErrorCode ec) {
return new TorrentHandle(s.add_torrent(params.getSwig(), ec.getSwig()));
}
public void asyncAddTorrent(AddTorrentParams params) {
s.async_add_torrent(params.getSwig());
}
/**
* @param uri
* @param timeout in seconds
* @return
*/
public byte[] fetchMagnet(String uri, int timeout) {
add_torrent_params p = add_torrent_params.create_instance_disabled_storage();
error_code ec = new error_code();
libtorrent.parse_magnet_uri(uri, p, ec);
if (ec.value() != 0) {
throw new IllegalArgumentException(ec.message());
}
final sha1_hash info_hash = p.getInfo_hash();
String sha1 = info_hash.to_hex();
byte[] data = MAGNET_CACHE.get(sha1);
if (data != null) {
return data;
}
boolean add;
torrent_handle th;
synchronized (MAGNET_LOCK) {
th = s.find_torrent(info_hash);
if (th != null && th.is_valid()) {
// we have a download with the same info-hash, let's wait
add = false;
} else {
add = true;
}
if (add) {
p.setName("fetch_magnet:" + uri);
p.setSave_path("fetch_magnet/" + uri);
long flags = p.get_flags();
flags &= ~add_torrent_params.flags_t.flag_auto_managed.swigValue();
p.set_flags(flags);
ec.clear();
th = s.add_torrent(p, ec);
th.resume();
}
}
int n = 0;
do {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// ignore
}
data = MAGNET_CACHE.get(sha1);
if (data != null) {
break; // aldenml: this in one of those cases in which "break" is more clear to me
}
n++;
} while (n < timeout);
synchronized (MAGNET_LOCK) {
if (add && th != null && th.is_valid()) {
s.remove_torrent(th);
}
}
return data;
}
@Override
protected void finalize() throws Throwable {
this.running = false;
super.finalize();
}
private void fireAlert(Alert<?> a, int type) {
AlertListener[] listeners = listenerSnapshots.get(type);
if (listeners != null) {
for (int i = 0; i < listeners.length; i++) {
try {
AlertListener l = listeners[i];
if (l != null) {
l.alert(a);
}
} catch (Throwable e) {
LOG.warn("Error calling alert listener", e);
}
}
}
}
private TorrentHandle addTorrentSupport(TorrentInfo ti, File saveDir, Priority[] priorities, File resumeFile, boolean async) {
String savePath = null;
if (saveDir != null) {
savePath = saveDir.getAbsolutePath();
} else if (resumeFile == null) {
throw new IllegalArgumentException("Both saveDir and resumeFile can't be null at the same time");
}
add_torrent_params p = add_torrent_params.create_instance();
p.set_ti(ti.getSwig());
if (savePath != null) {
p.setSave_path(savePath);
}
if (priorities != null) {
byte_vector v = new byte_vector();
for (int i = 0; i < priorities.length; i++) {
v.push_back((byte) priorities[i].getSwig());
}
p.set_file_priorities(v);
}
p.setStorage_mode(storage_mode_t.storage_mode_sparse);
long flags = p.get_flags();
flags &= ~add_torrent_params.flags_t.flag_auto_managed.swigValue();
if (resumeFile != null) {
try {
byte[] data = Files.bytes(resumeFile);
p.set_resume_data(Vectors.bytes2byte_vector(data));
flags |= add_torrent_params.flags_t.flag_use_resume_save_path.swigValue();
} catch (Throwable e) {
LOG.warn("Unable to set resume data", e);
}
}
p.set_flags(flags);
if (async) {
s.async_add_torrent(p);
return null;
} else {
error_code ec = new error_code();
torrent_handle th = s.add_torrent(p, ec);
return new TorrentHandle(th);
}
}
private void alertsLoop() {
Runnable r = new Runnable() {
@Override
public void run() {
alert_ptr_vector vector = new alert_ptr_vector();
high_resolution_clock.duration max_wait = libtorrent.to_milliseconds(ALERTS_LOOP_WAIT_MILLIS);
while (running) {
alert ptr = s.wait_for_alert(max_wait);
if (ptr != null) {
s.pop_alerts(vector);
long size = vector.size();
for (int i = 0; i < size; i++) {
alert swigAlert = vector.get(i);
int type = swigAlert.type();
Alert<?> alert = null;
if (type == AlertType.SESSION_STATS.getSwig()) {
alert = Alerts.cast(swigAlert);
updateSessionStat((SessionStatsAlert) alert);
}
if (type == AlertType.METADATA_RECEIVED.getSwig()) {
alert = Alerts.cast(swigAlert);
saveMagnetData((MetadataReceivedAlert) alert);
}
if (listeners.indexOfKey(type) >= 0) {
if (alert == null) {
alert = Alerts.cast(swigAlert);
}
fireAlert(alert, type);
}
if (type != AlertType.SESSION_STATS.getSwig() &&
listeners.indexOfKey(-1) >= 0) {
if (alert == null) {
alert = Alerts.cast(swigAlert);
}
fireAlert(alert, -1);
}
}
vector.clear();
}
long now = System.currentTimeMillis();
if ((now - lastStatsRequestTime) >= REQUEST_STATS_RESOLUTION_MILLIS) {
lastStatsRequestTime = now;
postSessionStats();
}
}
}
};
Thread t = new Thread(r, "Session-alertsLoop");
t.setDaemon(true);
t.start();
}
private void modifyListeners(boolean adding, AlertListener listener) {
if (listener != null) {
int[] types = listener.types();
//all alert-type including listener
if (types == null) {
modifyListeners(adding, -1, listener);
} else {
for (int i = 0; i < types.length; i++) {
if (types[i] == -1) {
throw new IllegalArgumentException("Type can't be the key of all (-1)");
}
modifyListeners(adding, types[i], listener);
}
}
}