Subversion Repositories Koakuma

Rev

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