那么,这将是一个相当模糊的话题,但我会试一试,也许有人会知道答案。
我正在为Transmission BitTorrent客户端编写一个远程Node.js客户端。使用JSON对象通过RPC处理通信。
我的代码(用CoffeeScript编写,如果这是一个问题我也可以提供相同的JavaScript代码,只是不想让这个问题太长而无法阅读),重要的部分:
runRemoteCommand: (params) ->
# convert JSON object to string
params = JSON.stringify params #, null, " "
# set request options
options =
host: @config.host
port: @config.port
path: @config.rpcPath
auth: "#{@config.username}:#{@config.password}"
headers:
'Content-Type': 'application/json'
'Content-Length': params.length
method: 'GET'
# we don't know the session id yet
sessionId = false
# wrapped in a function so it could be run two times, not really a finished solution
run = () =>
# If the session id is provided, set the header, as in 2.3.1 of the specs
if sessionId
options.headers["X-Transmission-Session-Id"] = sessionId
# define the request object and a callback for the response
request = @http.get options, (response) =>
# log everything for debug purposes
console.log "STATUS: #{response.statusCode}"
console.log "HEADERS: #{JSON.stringify response.headers}"
response.setEncoding 'utf8'
response.on "data", (data) =>
console.log "BODY: #{data}"
# if status code is 409, use provided session id
if response.statusCode == 409
sessionId = response.headers["x-transmission-session-id"]
console.log "sessionId: #{sessionId}"
# running it immediately sometimes caused the remote server to provide a 501 error, so I gave it a timeout
setTimeout run, 5000
# no output here
request.on "error", (e) =>
console.log "ERROR: #{e}"
# actually send the request
request.write params
request.end()
# run our function
run()
params
变量定义为:
params =
"arguments":
"filename": link
"method": "torrent-add"
"tag": 6667
在我设置有效的会话ID之前,一切正常。在第一次调用run
函数时,我得到以下输出(将其格式化为更加方便眼睛):
状态:409
头:
{ "server":"Transmission", "x-transmission-session-id":"io4dOLm8Q33aSCEULW0iv74SeewJ3w1tP21L7qkdS4QktIkR", "date":"Wed, 04 Apr 2012 08:37:37 GMT", "content-length":"580", "content-type":"text/html; charset=ISO-8859-1" }
的sessionId: io4dOLm8Q33aSCEULW0iv74SeewJ3w1tP21L7qkdS4QktIkR
BODY:
409: 冲突
您的请求的会话ID无效 标题。
要解决此问题,请按以下步骤操作:
- 阅读时 响应,获取其X-Transmission-Session-Id标头并记住它
- 将更新的标题添加到您的外发请求中
- 当您收到此消息时 409错误消息,重新发送您的请求与更新 标题
此要求已添加以帮助防止CSRF 攻击。
X-Transmission-Session-Id: io4dOLm8Q33aSCEULW0iv74SeewJ3w1tP21L7qkdS4QktIkR
当没有提供会话ID时,远程服务器应该返回的是什么。但是,在标头中设置会话ID后,服务器不会响应。第二个run
调用被触发并发送请求(通过放置一些有用的console.log
确认),但响应回调永远不会被触发。我没有收到远程服务器的响应,我的应用程序冻结等待。
我很确定错误是在我这边,而不是在服务器上,因为当连接到同一个远程会话时,一个开箱即用的远程客户端工作正常。
我是否正确执行了请求?特别是JSON部分?
我编写了一个小的PHP脚本来测试JSON编码的请求是否正常,并将其用作“假”远程传输。这是:
$ headers = apache_request_headers();
// Simulate transmission's behavior
if (!isset($headers['X-Transmission-Session-Id'])) {
header("HTTP/1.0 409 Conflict");
header("X-Transmission-Session-Id: test");
}
print_r($headers);
// Is there a nicer way to get the raw request?
print_r(file_get_contents('php://input'));
而且,就个人而言,我认为此测试输出的数据没有任何错误。返回409状态代码后,Node.js应用程序正确分配请求的会话ID。第一个print_r
打印一个数组:
Array
(
[Content-type] => application/json
[Content-length] => 152
[X-Transmission-Session-Id] => test
[Host] => tp.localhost
[Connection] => keep-alive
)
第二个打印一个字符串,这是一个格式正确的JSON字符串(仅此而已):
{
"arguments": {
"filename": "http://link-to-torrent"
},
"method": "torrent-add",
"tag": 6667
}
我真的看不出我做错了什么。我使用同一个远程服务器测试的某些第三方客户端可以正常工作。
答案 0 :(得分:1)
Havng同样的问题我已经完成了这门课程。我正在考虑更好的方法做一个getData,方法。但它确实有效。
http = require "http"
_ = require "underscore"
class Connect
constructor: (@login, @password, @host='127.0.0.1', @port=9091, @headers={}) ->
getData: (params)->
key = "x-transmission-session-id"
options = {
host: @host
port: @port
path: '/transmission/rpc',
method: 'POST',
headers: @headers || {},
auth: "#{ @login }:#{ @password }"
}
_.extend options, params || {}
req = http.request(options, (res)=>
if res.statusCode == 401
console.log "Auth errror"
else if res.statusCode == 409
auth_header={}
auth_header[key] = res.headers[key]
_.extend @headers, auth_header
@getData(params)
else if res.statusCode == 200
res.setEncoding 'utf8'
res.on('data', (chunk)->
#here should be an emmit of data
console.log chunk
)
else
console.log "Error #{ res.statusCode }"
)
req.write('data\n')
req.write('data\n')
req.end()
connector = new Connect "transmission", "password"
connector.getData()
答案 1 :(得分:0)
好吧,我能够使用mikeal's request来解决问题 - 但不能解决 - 这也简化了我的代码。最新版本如下:
runRemoteCommand: (params, callback = false) =>
options =
uri: @uri
method: "POST"
json: params
if @sessionId
options.headers =
"X-Transmission-Session-Id": @sessionId
request options, (error, response, body) =>
retVal =
success: false
end = true
if error
retVal.message = "An error occured: #{error}"
else
switch response.statusCode
when 409
if response.headers["x-transmission-session-id"]
@sessionId = response.headers["x-transmission-session-id"]
end = false
@.runRemoteCommand params, callback
else
retVal.message = "Session id not present"
when 200
retVal.success = true
retVal.response = body
else retVal.message = "Error, code: #{response.statusCode}"
callback retVal if end && callback
我暂时不接受这个答案,因为我仍然不知道“原始”版本有什么问题。
答案 2 :(得分:0)
#!/bin/bash
#-----------------------------------------------------------------------
#
DEBUG=0
HOST="192.168.1.65"
PORT="8181"
TRURL="http://$HOST:$PORT/transmission/rpc"
USER="admin"
PASSWORD="password1"
XTSID=""
#-------------------------------------
#
function getSID ()
{
local S="$1"
S=${S##*X-Transmission-Session-Id: }
S=${S%%</code>*}
echo $S
}
#-------------------------------------
function getData ()
{
local REQUEST="$1"
local RET=$(curl --silent -H "X-Transmission-Session-Id: $XTSID" \
-H "Content-type: application/json" \
-X POST \
-d "$REQUEST" \
--user $USER:$PASSWORD $TRURL)
((DEBUG)) && echo $XTSID
if [[ "$RET" =~ "409: Conflict" ]]
then
XTSID=$(getSID "$RET")
((DEBUG)) && echo "XTSID $XTSID"
RET=$(curl --silent -H "X-Transmission-Session-Id: $XTSID" \
-H "Content-type: application/json" \
-X POST \
-d "$REQUEST" \
--user $USER:$PASSWORD $TRURL)
fi
echo $RET
}
#-------------------------------------
R='{"method":"session-stats"}'
RET=$(getData "$R")
echo $RET