-
Notifications
You must be signed in to change notification settings - Fork 3
/
XMWebUIPlugin.java
5416 lines (5283 loc) · 237 KB
/
XMWebUIPlugin.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
/*
* Created on Sep 16, 2009
* Created by Paul Gardner
*
* Copyright 2009 Vuze, Inc. All rights reserved.
*
* 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; version 2 of the License only.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
package org.klomp.snark.rpc;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static com.aelitis.azureus.plugins.xmwebui.TransmissionVars.*;
import net.i2p.CoreVersion;
import net.i2p.I2PAppContext;
import net.i2p.data.Base32;
import net.i2p.data.Base64;
import net.i2p.data.Destination;
import net.i2p.servlet.RequestWrapper;
import net.i2p.util.Log;
import net.i2p.util.SecureFile;
import org.gudy.azureus2.plugins.download.DownloadException;
import org.klomp.snark.BitField;
import org.klomp.snark.I2PSnarkUtil;
import org.klomp.snark.MagnetURI;
import org.klomp.snark.MetaInfo;
import org.klomp.snark.Peer;
import org.klomp.snark.PeerID;
import org.klomp.snark.Snark;
import org.klomp.snark.SnarkManager;
import org.klomp.snark.Storage;
import org.klomp.snark.TrackerClient;
import org.klomp.snark.bencode.BEncoder;
import org.json.simple.JsonObject;
@SuppressWarnings({
"unchecked",
"rawtypes"
})
/**
* Mapping of Vuze to i2psnark classes:
* Torrent :: MetaInfo
* Download :: Snark
* DownloadManager :: SnarkManager
*
*
*
*/
public class
XMWebUIPlugin {
private static final boolean IS_5101_PLUS = true;
/**
* 5: No longer xml escapes strings when user agent does not start with "Mozilla/"
*/
private static final int VUZE_RPC_VERSION = 5;
public static final int DEFAULT_PORT = 9091;
private static final Properties defaults = new Properties();
static {
//System.setProperty( "az.xmwebui.skip.ssl.hack", "true" );
defaults.put( WebPlugin.PR_DISABLABLE, Boolean.TRUE);
defaults.put( WebPlugin.PR_ENABLE, Boolean.TRUE);
defaults.put( WebPlugin.PR_PORT, Integer.valueOf(DEFAULT_PORT));
defaults.put( WebPlugin.PR_ROOT_DIR, "transmission/web" );
defaults.put( WebPlugin.PR_ENABLE_KEEP_ALIVE, Boolean.TRUE);
defaults.put( WebPlugin.PR_HIDE_RESOURCE_CONFIG, Boolean.TRUE);
defaults.put( WebPlugin.PR_PAIRING_SID, "xmwebui" );
}
private static final String SEARCH_PREFIX = "/psearch";
private static final int SEARCH_TIMEOUT = 60*1000;
private static final long SEARCH_AUTOREMOVE_TIMEOUT = 60 * 1000 * 60l;
private boolean view_mode;
private final boolean trace_param;
private final boolean hide_ln_param = true;
//private TorrentAttribute t_id;
private Map<Long,RecentlyRemovedData> recently_removed = new HashMap<Long,RecentlyRemovedData>();
//private Set<Long> stubbifying = new HashSet<Long>();
private Map<String, String> ip_to_session_id = new HashMap<String, String>();
private final String az_mode = "core";
private static final String az_version = "5.7.5.1";
private boolean check_ids_outstanding = true;
private Map<String,Map<Long,String>> session_torrent_info_cache = new HashMap<String,Map<Long,String>>();
//private Object lifecycle_lock = new Object();
//private int lifecycle_state = 0;
//private boolean update_in_progress;
private Object json_rpc_client; // Object during transition to core support
private Object json_server_method_lock = new Object();
private transient Map<String,Object> json_server_methods = new HashMap<String, Object>(); // Object during transition to core support
private final boolean logtofile_param = false;
//private LoggerChannel log;
//private long lastVerserverCheck;
private final I2PAppContext _context;
private final Log _log;
private final SnarkManager _manager;
private final I2PSnarkUtil _util;
public
XMWebUIPlugin(I2PAppContext ctx, SnarkManager mgr) {
_context = ctx;
_manager = mgr;
_util = mgr.util();
_log = ctx.logManager().getLog(getClass());
// must be set before start
trace_param = _log.shouldDebug();
initialize();
}
private void
initialize()
{
/****
log = plugin_interface.getLogger().getChannel( "xmwebui" );
defaults.put(PR_LOG, log);
plugin_interface.getUtilities().getLocaleUtilities().integrateLocalisedMessageBundle(
"com.aelitis.azureus.plugins.xmwebui.internat.Messages" );
t_id = plugin_interface.getTorrentManager().getPluginAttribute( "xmui.dl.id" );
BasicPluginConfigModel config = getConfigModel();
int port = plugin_interface.getPluginconfig().getPluginIntParameter( WebPlugin.CONFIG_PORT, CONFIG_PORT_DEFAULT );
config.addLabelParameter2( "xmwebui.blank" );
config.addHyperlinkParameter2( "xmwebui.openui", "http://127.0.0.1:" + port + "/" );
config.addLabelParameter2( "xmwebui.blank" );
//hide_ln_param = config.addBooleanParameter2( "xmwebui.hidelownoise", "xmwebui.hidelownoise", true );
//trace_param = config.addBooleanParameter2( "xmwebui.trace", "xmwebui.trace", false );
//logtofile_param = config.addBooleanParameter2( "xmwebui.logtofile", "xmwebui.logtofile", false );
changeLogToFile(logtofile_param.getValue());
logtofile_param.addConfigParameterListener(new ConfigParameterListener() {
public void configParameterChanged(ConfigParameter param) {
changeLogToFile(logtofile_param.getValue());
}
});
ConfigParameter mode_parameter = plugin_interface.getPluginconfig().getPluginParameter( WebPlugin.CONFIG_MODE );
if ( mode_parameter == null ) {
view_mode = true;
checkViewMode();
} else {
mode_parameter.addConfigParameterListener(
new ConfigParameterListener()
{
public void
configParameterChanged(
ConfigParameter param )
{
setViewMode();
}
});
setViewMode();
}
_manager.addListener( this );
_manager.addSnarkListener(
new SnarkListener()
{
public void
downloadStubEventOccurred(
SnarkEvent event )
throws DownloadException
{
int event_type = event.getEventType();
List<Snark> stubs = event.getSnarks();
synchronized( recently_removed ) {
if ( event_type == SnarkEvent.DSE_STUB_WILL_BE_ADDED ) {
for ( Snark stub: stubs ) {
try {
long id = destubbify( stub ).getLongAttribute( t_id );
stubbifying.add( id );
stub.setLongAttribute( t_id, id );
} catch( Throwable e ) {
Debug.out( e );
}
}
} else if ( event_type == SnarkEvent.DSE_STUB_ADDED || event_type == SnarkEvent.DSE_STUB_WILL_BE_REMOVED ) {
for ( Snark stub: stubs ) {
long id = stub.getLongAttribute( t_id );
stubbifying.remove( id );
}
}
}
}
}, false );
if ( IS_5101_PLUS ) {
json_rpc_client =
new Utilities.JSONClient() {
public void
serverRegistered(
JSONServer server )
{
List<String> methods = server.getSupportedMethods();
//System.out.println( "Registering methods: " + server.getName() + " -> " + methods );
synchronized( json_server_method_lock ) {
Map<String,Object> new_methods = new HashMap<String, Object>( json_server_methods );
for ( String method: methods ) {
new_methods.put( method, server );
}
json_server_methods = new_methods;
}
}
public void
serverUnregistered(
JSONServer server )
{
List<String> methods = server.getSupportedMethods();
//System.out.println( "Unregistering methods: " + server.getName() + " -> " + methods );
synchronized( json_server_method_lock ) {
Map<String,Object> new_methods = new HashMap<String, Object>( json_server_methods );
for ( String method: methods ) {
new_methods.remove( method );
}
json_server_methods = new_methods;
}
}
};
plugin_interface.getUtilities().registerJSONRPCClient((Utilities.JSONClient)json_rpc_client );
}
****/
}
/****
protected void changeLogToFile(boolean logToFile) {
if (log != null) {
if (logToFile) {
log.setDiagnostic(1024l * 1024l, true);
} else {
// no way of turning off :(
}
}
}
****/
private void
checkViewMode()
{
if ( view_mode ) {
return;
}
/****
PluginConfig pc = plugin_interface.getPluginconfig();
{
String data_dir = pc.getCoreStringParameter( PluginConfig.CORE_PARAM_STRING_DEFAULT_SAVE_PATH );
boolean data_bad = false;
if ( data_dir == null || data_dir.length() == 0 ) {
data_bad = true;
} else {
File dir = new File( data_dir );
if ( !dir.exists()) {
dir.mkdirs();
}
data_bad = !dir.canWrite();
}
if ( data_bad ) {
_log.error(_t( "xmwebui.error.data_path" ));
}
}
if ( !pc.getUnsafeBooleanParameter( "Save Snark Files" )) {
_log.error(_t( "xmwebui.error.torrent_path" ));
} else {
String torrent_dir = pc.getUnsafeStringParameter( "General_sDefaultTorrent_Directory" );
boolean torrent_bad = false;
if ( torrent_dir == null || torrent_dir.length() == 0 ) {
torrent_bad = true;
} else {
File dir = new File( torrent_dir );
if ( !dir.exists()) {
dir.mkdirs();
}
torrent_bad = !dir.canWrite();
}
if ( torrent_bad ) {
_log.error(_t( "xmwebui.error.torrent_path" ));
}
}
****/
}
protected void
setupServer()
{
}
public void
unload()
{
//_manager.removeListener( this );
if ( IS_5101_PLUS ) {
if ( json_rpc_client != null ) {
//plugin_interface.getUtilities().unregisterJSONRPCClient((Utilities.JSONClient)json_rpc_client);
json_rpc_client = null;
}
json_server_methods.clear();
}
}
protected void
setViewMode()
{
/****
String mode_str = plugin_interface.getPluginconfig().getPluginStringParameter( WebPlugin.CONFIG_MODE, WebPlugin.CONFIG_MODE_DEFAULT );
view_mode = !mode_str.equalsIgnoreCase( WebPlugin.CONFIG_MODE_FULL );
****/
checkViewMode();
}
public File
getResourceDir()
{
return( new File( _manager.getDataDir(), "transmission" + File.separator + "web" ));
}
public void
downloadAdded(
Snark download )
{
}
// @see org.gudy.azureus2.plugins.download.SnarkManagerListener#downloadRemoved(org.gudy.azureus2.plugins.download.Download)
public void
downloadRemoved(
Snark download )
{
addRecentlyRemoved( download );
}
private void
addRecentlyRemoved(
Snark download )
{
synchronized( recently_removed ) {
long id = getID( download, false );
if ( id > 0 /* && !stubbifying.contains( id ) */ ) {
if ( !recently_removed.containsKey( id )) {
recently_removed.put( id, new RecentlyRemovedData( id ));
}
}
}
}
private boolean
handleRecentlyRemoved(
String session_id,
Map args,
Map result )
{
Object ids = args.get( "ids" );
if ( ids != null && ids instanceof String && ((String)ids).equals( "recently-active" )) {
synchronized( recently_removed ) {
if ( recently_removed.size() > 0 ) {
long now = _context.clock().now();
Iterator<RecentlyRemovedData> it = recently_removed.values().iterator();
List<Long> removed = new ArrayList<Long>();
while( it.hasNext()) {
RecentlyRemovedData rrd = it.next();
if ( !rrd.hasSession( session_id )) {
removed.add( rrd.getID());
}
if ( now - rrd.getCreateTime() > 60*1000 ) {
it.remove();
}
}
if ( removed.size() > 0 ) {
//System.out.println( "Reporting removed to " + session_id + ": " + removed );
result.put( "removed", removed );
}
}
}
return( true );
} else {
return( false );
}
}
public boolean
generateSupport(HttpServletRequest request, HttpServletResponse response) throws IOException {
boolean logit = trace_param;
if (logit) {
log("-> " + request.getMethod() + ' ' + request.getServletPath());
String qs = request.getQueryString();
if (qs != null)
log( "-> query: " + qs);
for (Enumeration<String> en = request.getHeaderNames(); en.hasMoreElements(); ) {
// cgi params overwrite JSON POST data map values
String hdr = en.nextElement();
String val = request.getHeader(hdr);
log( "-> header: " + hdr + " = " + val);
}
}
if (/*request.getInputStream().available() == 0 && */ "chunked".equals(request.getHeader("transfer-encoding"))) {
response.setStatus( 415 );
return true;
}
try {
String session_id = getSessionID( request );
// Set cookie just in case client is looking for one..
response.setHeader( "Set-Cookie", "X-Transmission-Session-Id=" + session_id + "; path=/; HttpOnly" );
// This is the actual spec for massing session-id
response.setHeader("X-Transmission-Session-Id", session_id );
if (!isSessionValid(request)) {
//log("Header:\n" + request.getHeader());
log("409: " + request.getServletPath());
response.setContentType( "text/plain; charset=UTF-8" );
response.setStatus( 409 );
response.getOutputStream().write("You_didn_t_set_the_X-Transmission-Session-Id".getBytes());
return true;
}
if (!request.getMethod().equals("POST")) {
// Sonarr does a GET for testing and to get the 409, shouldn't go past here
response.setContentType("text/plain; charset=UTF-8");
response.setStatus(200);
return true;
}
String session_id_plus = session_id;
// XXX getHeaders() keys are lowercase.. this line always null?
String tid = request.getHeader( "X-XMRPC-Tunnel-ID" );
if ( tid != null ) {
session_id_plus += "/" + tid;
}
String url = request.getServletPath();
if (url.endsWith("/"))
url = url.substring(0, url.length() - 1);
//System.out.println( "Header: " + request.getHeader() );
if (url.equals("/web/transmission/rpc") || url.equals("/rpc")) {
LineNumberReader lnr;
String enc = request.getHeader("content-encoding");
if (enc != null && logit)
log( "-> encoding: " + enc );
Map request_json = null;
// http://www.jsonrpc.org/historical/json-rpc-over-http.html
// Content-Type SHOULD be 'application/json-rpc' but MAY be 'application/json' or 'application/jsonrequest'
if (!"application/x-www-form-urlencoded".equals(request.getHeader("content-type"))) {
if ("gzip".equals(enc)) {
GZIPInputStream gzipIS = new GZIPInputStream(request.getInputStream());
lnr = new LineNumberReader( new InputStreamReader( gzipIS, "UTF-8" ));
} else {
lnr = new LineNumberReader( new InputStreamReader( request.getInputStream(), "UTF-8" ));
}
StringBuilder request_json_str = new StringBuilder(2048);
while( true ) {
String line = lnr.readLine();
if ( line == null ) {
break;
}
request_json_str.append( line );
}
if ( logit ) {
log( "-> " + request_json_str );
}
request_json = JSONUtils.decodeJSON( request_json_str.toString());
}
for (Enumeration<String> en = request.getParameterNames(); en.hasMoreElements(); ) {
// cgi params overwrite JSON POST data map values
String param = en.nextElement();
String val = request.getParameter(param);
if (logit)
log( "-> param: " + param + " = " + val);
if (param.startsWith("{")) {
// json in body, but with x-www-form-urlencoded content-type (transmission-remote)
request_json = JSONUtils.decodeJSON(param);
} else if (param.equals("json")) {
// debugging?
request_json = JSONUtils.decodeJSON(val);
} else {
if (request_json == null)
request_json = new HashMap(4);
// cgi params or standard form
request_json.put(param, val);
}
}
Map response_json = processRequest( request, session_id_plus, request_json );
String response_json_str = JSONUtils.encodeToJSON( response_json );
if ( logit ) {
log( "<- " + response_json_str.length() );
log( "<- " + response_json_str );
}
response.setContentType( "application/json; charset=UTF-8" );
PrintWriter pw = new PrintWriter( new OutputStreamWriter( response.getOutputStream(), "UTF-8" ));
pw.println( response_json_str );
pw.flush();
//response.setGZIP( true );
return( true );
/* example code to relay a stream
} else if ( url.startsWith( "/vuze/test.mkv" )) {
Map headers = request.getHeaders();
OutputStream os = response.getRawOutputStream();
Socket sock = new Socket( "127.0.0.1", 46409 );
OutputStream sos = sock.getOutputStream();
String req = "GET /Content/test.mkv HTTP/1.1\r\n";
String range = (String)headers.get( "range" );
if ( range != null ) {
req += "Range: " + range + "\r\n";
}
req += "\r\n";
sos.write( req.getBytes( "ISO-8859-1"));
sos.flush();
InputStream is = sock.getInputStream();
byte[] buffer = new byte[256*1024];
while( true ) {
int len = is.read( buffer );
if ( len <= 0 ) {
break;
}
os.write( buffer, 0, len );
}
return( true );
*/
/****
} else if ( url.startsWith( "/vuze/resource?json=" )) {
Map request_json = JSONUtils.decodeJSON( UrlUtils.decode( url.substring( url.indexOf( '?' ) + 6 )));
return( processResourceRequest( request, response, request_json ));
****/
} else if (url.equals("/web/transmission/upload") || url.equals("/upload")) {
if ( logit ) {
log( "upload request" );
}
checkUpdatePermissions();
RequestWrapper rw = new RequestWrapper(request);
boolean add_stopped = Boolean.parseBoolean(rw.getParameter("paused"));
try {
int num_found = 0;
for ( Enumeration<String> en = rw.getParameterNames(); en.hasMoreElements(); ) {
String field_name = en.nextElement();
if ( field_name.equalsIgnoreCase( "torrent_file" ) || field_name.equalsIgnoreCase( "torrent_files[]" )) {
num_found++;
String torrent_file_name = rw.getParameter( "filename" );
if ( torrent_file_name == null ) {
throw( new IOException( "upload filename missing" ));
}
InputStream tis = rw.getInputStream(field_name);
MetaInfo torrent;
try {
torrent = new MetaInfo( tis );
} catch( Throwable e ) {
throw( new IOException( "Failed to deserialise torrent file", e));
}
try {
Snark download = addTorrent( torrent, null, add_stopped, null );
response.setContentType( "text/xml; charset=UTF-8" );
response.getOutputStream().write( "<h1>200: OK</h1>".getBytes());
return( true );
} catch( Throwable e ) {
throw( new IOException("Failed to add torrent", e));
}
}
}
if ( num_found == 0 ) {
log( "No torrents found in upload request" );
}
return( true );
} finally {
// nothing
}
} else if ( url.startsWith( "/web/transmission/web")) {
response.setStatus( 301 );
response.setHeader( "Location", "/transmission/web/" );
return( true );
} else {
log( "404: " + url);
return( false );
}
} catch( PermissionDeniedException e ) {
log( "401", e );
response.setStatus( 401 );
return( true );
} catch( IOException e ) {
if ( logit ) {
log( "Processing failed", e );
e.printStackTrace();
}
throw( e );
} catch( Throwable e ) {
if ( logit ) {
log( "Processing failed", e );
e.printStackTrace();
}
throw( new IOException( "Processing failed", e));
}
}
private String
getCookie(
String cookies,
String cookie_id)
{
if ( cookies == null ) {
return null;
}
String[] cookie_list = cookies.split( ";" );
for ( String cookie: cookie_list ) {
String[] bits = cookie.split( "=" );
if ( bits.length == 2 ) {
if ( bits[0].trim().equals( cookie_id )) {
return bits[1].trim();
}
}
}
return null;
}
private boolean
isSessionValid(
HttpServletRequest request)
{
//if (!request.getServletPath().startsWith("/transmission/")) {
// return true;
//}
// tunnel requests are already strongly authenticated and session based
//String tunnel = request.getHeader( "x-vuze-is-tunnel" );
//if ( tunnel != null && tunnel.equalsIgnoreCase( "true" )) {
// return true;
//}
String session_id = getSessionID(request);
String header_session_id = request.getHeader(
"X-Transmission-Session-Id");
if (header_session_id == null) {
header_session_id = request.getHeader(
"x-transmission-session-id");
}
if (header_session_id == null) {
header_session_id = getCookie(
request.getHeader("cookie"),
"X-Transmission-Session-Id");
}
//System.out.println("header_session_id=" + header_session_id);
if (header_session_id == null) {
return false;
}
return (header_session_id.equals(session_id));
}
private String
getSessionID(
HttpServletRequest request)
{
String clientAddress = request.getRemoteAddr();
synchronized (ip_to_session_id) {
String session_id = ip_to_session_id.get(clientAddress);
if (session_id == null) {
session_id = Double.toHexString(_context.random().nextDouble());
ip_to_session_id.put(clientAddress, session_id);
}
return session_id;
}
}
private static final Object add_torrent_lock = new Object();
protected Snark
addTorrent(
final MetaInfo torrent,
File download_dir,
boolean add_stopped,
final DownloadWillBeAddedListener listener)
throws DownloadException
{
synchronized( add_torrent_lock ) {
final SnarkManager dm = _manager;
Snark download = dm.getTorrentByInfoHash( torrent.getInfoHash() );
if ( download == null ) {
if (listener != null) {
/****
dm.addDownloadWillBeAddedListener(new DownloadWillBeAddedListener() {
public void initialised(Snark dlAdding) {
boolean b = Arrays.equals(dlAdding.getInfoHash(), torrent.getInfoHash());
if (b) {
dm.removeDownloadWillBeAddedListener(this);
listener.initialised(dlAdding);
}
}
});
****/
}
try {
boolean success = dm.addTorrent( torrent, null, null, download_dir, add_stopped );
if (success)
download = dm.getTorrentByInfoHash(torrent.getInfoHash());
} catch (IOException ioe) {
throw new DownloadException("Failed to add", ioe);
}
// particularly necessary for the android client as untidy closedown is common
//AzureusCoreFactory.getSingleton().saveState();
}
return( download );
}
}
protected void
checkUpdatePermissions()
throws IOException
{
if ( view_mode ) {
log( "permission denied" );
throw( new PermissionDeniedException());
}
}
protected Map
processRequest(
HttpServletRequest wp_request,
String session_id,
Map request )
throws IOException
{
Map response = new HashMap();
if (request == null) {
response.put( "result", "error: Bad or missing JSON string");
return response;
}
String method = (String) request.get("method");
if ( method == null ) {
response.put("result", "error: 'method' missing");
} else {
Map args = (Map) request.get("arguments");
if ( args == null ) {
args = Collections.emptyMap();
}
try {
Map result = processRequest( wp_request, session_id, method, args );
if ( result != null ) {
response.put( "arguments", result );
}
response.put( "result", "success" );
} catch( PermissionDeniedException e ) {
log("permission denied", e);
response.put( "result", "error: permission denied " + e );
} catch( TextualException e ) {
response.put( "result", e.getMessage());
} catch( Throwable e ) {
log("processRequest", e);
response.put( "result", "error: " + e );
}
}
Object tag = request.get( "tag" );
if ( tag != null ) {
response.put( "tag", tag );
}
return( response );
}
private static Number getNumber(
Object val)
{
return getNumber(val, 0);
}
private static Number getNumber(
Object val,
Number defaultNumber)
{
if (val instanceof Number) {
return (Number) val;
}
if (val instanceof String) {
NumberFormat format = NumberFormat.getInstance();
try {
Number number = format.parse((String) val);
return number;
} catch (ParseException e) {
return defaultNumber;
}
}
return defaultNumber;
}
protected Map
processRequest(
HttpServletRequest request,
String session_id,
String method,
Map args )
throws Exception
{
boolean save_core_state = false;
try {
Map result = new HashMap();
// https://trac.transmissionbt.com/browser/trunk/extras/rpc-spec.txt
// to get 271 working with this backend change remote.js RPC _Root to be
// _Root : './transmission/rpc',
if (false) {
/****
if ( method.equals( "session-set" )) {
try {
method_Session_Set(args, result);
} finally {
// assume something important was changed and persist it now
COConfigurationManager.save();
}
****/
} else if ( method.equals( "session-get" ) ) {
method_Session_Get(args, result);
} else if ( method.equals( "session-stats" )) {
method_Session_Stats(args, result);
} else if ( method.equals( "torrent-add" )) {
String agent = request.getHeader("User-Agent");
boolean xmlEscape = agent != null && agent.startsWith("Mozilla/");
method_Torrent_Add(args, result, xmlEscape);
// this is handled within the torrent-add method: save_core_state = true;
} else if ( method.equals( "torrent-start-all" )) {
checkUpdatePermissions();
_manager.startAllTorrents();
save_core_state = true;
} else if ( method.equals( "torrent-stop-all" )) {
checkUpdatePermissions();
_manager.stopAllTorrents(false);
save_core_state = true;
} else if ( method.equals( "torrent-start" )) {
method_Torrent_Start(args, result);
save_core_state = true;
} else if ( method.equals( "torrent-start-now" )) {
// RPC v14
method_Torrent_Start_Now(args, result);
save_core_state = true;
} else if ( method.equals( "torrent-stop" )) {
method_Torrent_Stop(args, result);
save_core_state = true;
} else if ( method.equals( "torrent-verify" )) {
method_Torrent_Verify(args, result);
} else if ( method.equals( "torrent-remove" )) {
// RPC v3
method_Torrent_Remove(args, result);
save_core_state = true;
/****
} else if ( method.equals( "torrent-set" )) {
method_Torrent_Set( session_id, args, result);
****/
} else if ( method.equals( "torrent-get" )) {
method_Torrent_Get(request, session_id, args, result);
/****
} else if ( method.equals( "torrent-reannounce" )) {
// RPC v5
method_Torrent_Reannounce(args, result);
} else if ( method.equals( "torrent-set-location" )) {
// RPC v6
method_Torrent_Set_Location(args, result);
} else if ( method.equals( "blocklist-update" )) {
// RPC v5
method_Blocklist_Update(args, result);
****/
} else if ( method.equals( "session-close" )) {
// RPC v12
synchronized (ip_to_session_id) {
ip_to_session_id.remove(session_id);
}
/****
} else if ( method.equals( "queue-move-top" )) {
// RPC v14
method_Queue_Move_Top(args, result);
} else if ( method.equals( "queue-move-up" )) {
// RPC v14
method_Queue_Move_Up(args, result);
} else if ( method.equals( "queue-move-down" )) {
// RPC v14
method_Queue_Move_Down(args, result);
} else if ( method.equals( "queue-move-bottom" )) {
// RPC v14
method_Queue_Move_Bottom(args, result);
*/
} else if ( method.equals( "free-space" )) {
// RPC v15
method_Free_Space(args, result);
/*
} else if ( method.equals( "torrent-rename-path" )) {
// RPC v15
method_Torrent_Rename_Path(args, result);
*/
} else if ( method.equals( "tags-get-list" )) {
// Vuze RPC v3
method_Tags_Get_List(args, result);
/*
} else if ( method.equals( "tags-lookup-start" )) {
method_Tags_Lookup_Start(args, result);
} else if ( method.equals( "tags-lookup-get-results" )) {
method_Tags_Lookup_Get_Results(args, result);
} else if ( method.equals( "subscription-get" )) {
method_Subscription_Get(args, result);
} else if ( method.equals( "subscription-add" )) {
method_Subscription_Add(args, result);
} else if ( method.equals( "subscription-set" )) {
method_Subscription_Set(args, result);
} else if ( method.equals( "subscription-remove" )) {
method_Subscription_Remove(args, result);
} else if ( method.equals( "vuze-search-start" )) {
method_Vuze_Search_Start(args, result);
} else if ( method.equals( "vuze-search-get-results" )) {
method_Vuze_Search_Get_Results(args, result);
} else if ( method.equals( "vuze-config-set" )) {
method_Vuze_Config_Set(args, result);
} else if ( method.equals( "vuze-config-get" )) {
method_Vuze_Config_Get(args, result);
} else if ( method.equals( "vuze-lifecycle" )) {
processVuzeLifecycle( args, result );
} else if ( method.equals( "vuze-pairing" )) {
if ( IS_5101_PLUS ) {
processVuzePairing( args, result );
} else {
throw( new IOException( "Client version too old!" ));
}
} else if ( method.equals( "vuze-torrent-get" )) {
processVuzeTorrentGet( request, args, result );
} else if ( method.equals( "vuze-file-add" )) {
processVuzeFileAdd( args, result );
****/
} else {
/****
if ( IS_5101_PLUS ) {
Utilities.JSONServer server = (Utilities.JSONServer)json_server_methods.get( method );
if ( server != null ) {
return( server.call( method, args ));
}
}
****/
if ( trace_param ) {
log( "unhandled method: " + method);
}
throw new TextualException("unsupported method: " + method);
}
return( result );
} finally {
if ( save_core_state ) {
// particularly necessary for the android client as untidy closedown is common
//AzureusCoreFactory.getSingleton().saveState();
}
}
}
/****
private void method_Vuze_Config_Get(Map args, Map result) {
List listKeys = MapUtils.getMapList(args, "keys", Collections.EMPTY_LIST);
for (Object key : listKeys) {
String keyString = key.toString();
if (ignoreConfigKey(keyString)) {
continue;
}
Object val = COConfigurationManager.getParameter(keyString);
if (val instanceof byte[]) {
// Place parsed string in key's value, B64 of bytes in key + ".B64"
String valString;
byte[] bytes = (byte[]) val;
try {
valString = new String(bytes, "UTF-8");
} catch (Throwable e) {
valString = new String(bytes);
}
result.put(key, valString);
try {
result.put(key + ".B64", new String(Base64.encode(bytes), "utf8"));
} catch (UnsupportedEncodingException e) {
}
} else {
result.put(key, val);
}