Subversion Repositories Koakuma

Rev

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 17 2024-10-02 07:31:01Z 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 {
17 nishi 19
	set username ""
20
	set password ""
4 nishi 21
	proc require-auth {} {
22
		global RPC_URL
23
		set tok [::http::geturl "$RPC_URL"]
24
		set code [::http::ncode $tok]
25
		::http::cleanup $tok
26
		if { $code == 401 } {
27
			return 1
28
		} elseif { $code == 403 } {
29
			return -1
30
		} else {
31
			return 0
32
		}
33
	}
17 nishi 34
	proc set-username {us} {
35
		global username
36
		set ::rpc::username "$us"
37
	}
38
	proc set-password {pw} {
39
		global password
40
		set ::rpc::password "$pw"
41
	}
4 nishi 42
	proc ask-auth {} {
5 nishi 43
		global username
44
		global password
4 nishi 45
		puts -nonewline "Username: "
46
		flush stdout
5 nishi 47
		set ::rpc::username "[gets stdin]"
4 nishi 48
		puts -nonewline "Password: "
49
		flush stdout
50
		exec stty -echo
5 nishi 51
		set ::rpc::password "[gets stdin]"
4 nishi 52
		exec stty echo
53
		puts ""
54
 
55
		set headers ""
56
		lappend headers "Authorization"
5 nishi 57
		lappend headers "Basic [::base64::encode -wrapchar "" "$::rpc::username:$::rpc::password"]"
4 nishi 58
 
59
		global RPC_URL
60
		set tok [::http::geturl "$RPC_URL" -headers $headers]
61
		set code [::http::ncode $tok]
62
		::http::cleanup $tok
63
 
64
		if { $code == 200 } {
65
			return 1
66
		}
67
		return 0
68
	}
5 nishi 69
	proc send {path content} {
70
		set headers ""
71
		global RPC_URL
72
		if { "$::rpc::username" != "" } {
73
			lappend headers "Authorization"
74
			lappend headers "Basic [::base64::encode -wrapchar "" "$::rpc::username:$::rpc::password"]"
75
		}
76
		set tok [::http::geturl "$RPC_URL$path" -headers $headers -type "application/json" -query "$content"]
77
		set code [::http::ncode $tok]
78
		set body "[::http::data $tok]"
79
		::http::cleanup $tok
80
		lappend result "$code"
81
		lappend result "$body"
82
		return $result
83
	}
11 nishi 84
	proc init {} {
85
		puts -nonewline "Authentication: "
86
		set status [::rpc::require-auth]
87
		if { $status == 1 } {
88
			puts "Required"
89
			if { ![::rpc::ask-auth] } {
90
				puts "Authentication failure"
91
				exit 1
92
			}
93
		} elseif { $status < 0 } {
94
			puts "Got forbidden, cannot continue"
95
			exit 1
96
		} else {
97
			puts "Not required"
98
		}
99
	}
4 nishi 100
}