@@ -23,6 +23,7 @@ import (
2323 "github.com/kost/tty2web/pkg/homedir"
2424 "github.com/kost/tty2web/pkg/randomstring"
2525 "github.com/kost/tty2web/webtty"
26+ "github.com/kost/tty2web/tlshelp"
2627 "github.com/kost/httpexecute"
2728 "github.com/kost/regeorgo"
2829)
@@ -126,6 +127,23 @@ func (server *Server) Run(ctx context.Context, options ...RunOption) error {
126127
127128 srvErr := make (chan error , 1 )
128129
130+ if server .options .EnableTLS {
131+ crtFile := homedir .Expand (server .options .TLSCrtFile )
132+ keyFile := homedir .Expand (server .options .TLSKeyFile )
133+ log .Printf ("TLS crt file: " + crtFile )
134+ log .Printf ("TLS key file: " + keyFile )
135+ cer , err := tls .LoadX509KeyPair (crtFile ,keyFile )
136+ if err != nil {
137+ log .Printf ("Error loading TLS key and crt file %s and %s: %v. Generating random one!" , crtFile , keyFile , err )
138+
139+ cer , err = tlshelp .GetRandomTLS (2048 )
140+ if err != nil {
141+ return errors .Wrapf (err , "error generating and failed to load tls cert and key `%s` and `%s`" , crtFile , keyFile )
142+ }
143+ }
144+ config := & tls.Config {Certificates : []tls.Certificate {cer }}
145+ srv .TLSConfig = config
146+ }
129147 if server .options .Dns != "" {
130148 go func () {
131149 session , err = DnsConnectSocks (server .options .Dns , server .options .DnsKey , server .options .DnsDelay )
@@ -134,7 +152,11 @@ func (server *Server) Run(ctx context.Context, options ...RunOption) error {
134152 srvErr <- err
135153 return
136154 }
137- err = srv .Serve (session )
155+ if server .options .EnableTLS {
156+ err = srv .ServeTLS (session , "" , "" )
157+ } else {
158+ err = srv .Serve (session )
159+ }
138160 if err != nil {
139161 srvErr <- err
140162 }
@@ -160,12 +182,7 @@ func (server *Server) Run(ctx context.Context, options ...RunOption) error {
160182 }
161183 go func () {
162184 if server .options .EnableTLS {
163- crtFile := homedir .Expand (server .options .TLSCrtFile )
164- keyFile := homedir .Expand (server .options .TLSKeyFile )
165- log .Printf ("TLS crt file: " + crtFile )
166- log .Printf ("TLS key file: " + keyFile )
167-
168- err = srv .ServeTLS (listener , crtFile , keyFile )
185+ err = srv .ServeTLS (listener , "" , "" )
169186 } else {
170187 err = srv .Serve (listener )
171188 }
@@ -181,7 +198,11 @@ func (server *Server) Run(ctx context.Context, options ...RunOption) error {
181198 srvErr <- err
182199 return
183200 }
184- err = srv .Serve (session )
201+ if server .options .EnableTLS {
202+ err = srv .ServeTLS (session , "" , "" )
203+ } else {
204+ err = srv .Serve (session )
205+ }
185206 if err != nil {
186207 srvErr <- err
187208 }
0 commit comments