Subversion Repositories Koakuma

Rev

Rev 5 | Rev 9 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3 nishi 1
# $Id: rpc.tcl 8 2024-10-01 23:05:34Z nishi $
4 nishi 2
package require http
3
package require base64
4
package require term::ansi::ctrl::unix
5
 
8 nishi 6
catch {
7
	package require tls
8
	::http::register https 443 ::tls::socket
9
}
10
 
11
set RPC_URL "http://127.0.0.1/koakuma/rpc"
12
if { [info exists "env(KOAKUMA_RPC)"] } {
13
	set RPC_URL "$env(KOAKUMA_RPC)"
14
}
15
set RPC_URL "[regsub {/+$} "$RPC_URL" ""]"
16
 
4 nishi 17
namespace eval rpc {
18
	proc require-auth {} {
19
		global RPC_URL
20
		set tok [::http::geturl "$RPC_URL"]
21
		set code [::http::ncode $tok]
22
		::http::cleanup $tok
23
		if { $code == 401 } {
24
			return 1
25
		} elseif { $code == 403 } {
26
			return -1
27
		} else {
28
			return 0
29
		}
30
	}
31
	set username ""
32
	set password ""
33
	proc ask-auth {} {
5 nishi 34
		global username
35
		global password
4 nishi 36
		puts -nonewline "Username: "
37
		flush stdout
5 nishi 38
		set ::rpc::username "[gets stdin]"
4 nishi 39
		puts -nonewline "Password: "
40
		flush stdout
41
		exec stty -echo
5 nishi 42
		set ::rpc::password "[gets stdin]"
4 nishi 43
		exec stty echo
44
		puts ""
45
 
46
		set headers ""
47
		lappend headers "Authorization"
5 nishi 48
		lappend headers "Basic [::base64::encode -wrapchar "" "$::rpc::username:$::rpc::password"]"
4 nishi 49
 
50
		global RPC_URL
51
		set tok [::http::geturl "$RPC_URL" -headers $headers]
52
		set code [::http::ncode $tok]
53
		::http::cleanup $tok
54
 
55
		if { $code == 200 } {
56
			return 1
57
		}
58
		return 0
59
	}
5 nishi 60
	proc send {path content} {
61
		set headers ""
62
		global RPC_URL
63
		if { "$::rpc::username" != "" } {
64
			lappend headers "Authorization"
65
			lappend headers "Basic [::base64::encode -wrapchar "" "$::rpc::username:$::rpc::password"]"
66
		}
67
		set tok [::http::geturl "$RPC_URL$path" -headers $headers -type "application/json" -query "$content"]
68
		set code [::http::ncode $tok]
69
		set body "[::http::data $tok]"
70
		::http::cleanup $tok
71
		lappend result "$code"
72
		lappend result "$body"
73
		return $result
74
	}
4 nishi 75
}