File: proxy.tcl

package info (click to toggle)
amsn 0.98.3-2
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 33,876 kB
  • ctags: 10,292
  • sloc: tcl: 117,923; ansic: 32,173; cpp: 17,387; xml: 6,643; objc: 1,251; sh: 667; makefile: 544; perl: 215; python: 126
file content (1177 lines) | stat: -rw-r--r-- 36,952 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
# proxy.tcl --
#
#	This file defines various procedures which implement a
#	Proxy access system. Code originally by Dave Mifsud,
#	converted to namespace and improved by D. Emilio Grimaldo T.
#	SOCKS5 support (integration) is experimental!!!
#

::Version::setSubversionId {$Id: proxy.tcl 11886 2010-01-11 01:43:13Z kakaroto $}

package provide Proxy 0.1
package require http
package require SASL::NTLM;
package require uri;
package require base64;

# This should be converted to a proper package, to use with package require
source socks.tcl	;# SOCKS5 proxy support

#the framework for connections. You create an instance of this object only,
#never the other proxy objects directly

proc globalGotNexusReply { proxy token {total 0} {current 0} } {
	if {![catch {$proxy cget -name}]} {
		$proxy GotNexusReply $token $total $current
	} else {
		::http::cleanup $token
	}
}

proc globalGotAuthReply { proxy str token } {
	if {![catch {$proxy cget -name}]} {
		$proxy GotAuthReply $str $token
	} else {
		::http::cleanup $token
	}
}

proc globalWrite { proxy name {msg ""} } {
	if {![catch {$proxy cget -name}]} {
		$proxy write $name $msg
	}
}

#The only way to get HTTP proxy + SSL to work...
#http://wiki.tcl.tk/2627
#helped by patthoyts autoproxy!
proc HTTPsecureSocket { args } {
	set phost [::http::config -proxyhost]
	set pport [::http::config -proxyport]
	upvar host thost
	upvar port tport

	# if a proxy has been configured
	if {[string length $phost] && [string length $pport]} {
		#TODO: make async: set socket [socket -async $phost $pport]
		# create the socket to the proxy
		set socket [socket -async $phost $pport]
		fconfigure $socket -buffering line -translation crlf
		puts $socket "CONNECT $thost:$tport HTTP/1.0"
        	puts $socket "Host: $thost"
	        puts $socket "User-Agent: [http::config -useragent]"
		puts $socket "Content-Length: 0"
	        puts $socket "Proxy-Connection: Keep-Alive"
	        puts $socket "Connection: Keep-Alive"
		puts $socket "Cache-Control: no-cache"
		puts $socket "Pragma: no-cache"
		if { [::config::getKey proxyauthenticate] } {
			set proxy_user [::config::getKey proxyuser]
			set proxy_pass [::config::getKey proxypass]
			set auth [string map {"\n" "" } [base64::encode ${proxy_user}:${proxy_pass}]]
			puts $socket "Proxy-Authorization: Basic $auth"
		}
		puts $socket ""
		#flush $socket

		set reply ""
		while {[gets $socket r] > 0} {
			lappend reply $r
		}

		set result [lindex $reply 0]

		# be sure there's a valid response code
		# We use a regexp because of some (or maybe only one) proxy returning "HTTP/1.0  200 .." with two spaces, 
		# so the split makes the code the 3rd argument not the second, and $code becomes empty. 
		# refer to http://amsn.sf.net/forums/viewtopic.php?t=1030
		if {! [regexp {^HTTP/1\.[01] +2[0-9][0-9]} $result]} {
			return -code error $result
		}

		# now add tls to the socket and return it
		fconfigure $socket -blocking 1 -buffering none -translation binary

		::tls::import $socket

		# We need to foce the handshake while the socket is blocking for tls to actually work
		::tls::handshake $socket
		
		fconfigure $socket -blocking 0 -buffering none -translation binary
		return $socket

	}

	# if not proxifying, just create a tls socket directly
	return [::tls::socket $thost $tport]
}

proc SOCKSsecureSocket { args } {
	set phost [::http::config -proxyhost]
	set pport [::http::config -proxyport]
	upvar host thost
	upvar port tport
	# if a proxy has been configured
	if {[string length $phost] && [string length $pport]} {
		#TODO: make async: set socket [socket -async $phost $pport]
		# create the socket to the proxy
		set socket [socket -async $phost $pport]

		set proxy_authenticate [expr [::config::getKey proxyauthenticate] == 1 ? 1 : 0]
		set proxy_user [::config::getKey proxyuser]
		set proxy_pass [::config::getKey proxypass]
		if {[catch {set res [::Socks5::Init $socket $thost $tport $proxy_authenticate $proxy_user $proxy_pass]} res] } {
			catch {close $socket}
		}
		if { $res != "OK" } {
			return -code error $res
		}

		# now add tls to the socket and return it
		fconfigure $socket -blocking 1 -buffering none -translation binary

		::tls::import $socket

		# We need to foce the handshake while the socket is blocking for tls to actually work
		::tls::handshake $socket
		
		fconfigure $socket -blocking 0 -buffering none -translation binary
		return $socket

	}

	# if not proxifying, just create a tls socket directly
	return [::tls::socket $thost $tport]
}

proc SOCKSSocket { args } {
	set phost [::http::config -proxyhost]
	set pport [::http::config -proxyport]
	upvar host thost
	upvar port tport
	# if a proxy has been configured
	if {[string length $phost] && [string length $pport]} {
		#TODO: make async: set socket [socket -async $phost $pport]
		# create the socket to the proxy
		set socket [socket -async $phost $pport]

		set proxy_authenticate [expr [::config::getKey proxyauthenticate] == 1 ? 1 : 0]
		set proxy_user [::config::getKey proxyuser]
		set proxy_pass [::config::getKey proxypass]
		if {[catch {set res [::Socks5::Init $socket $thost $tport $proxy_authenticate $proxy_user $proxy_pass]} res] } {
			catch {close $socket}
		}
		if { $res != "OK" } {
			return -code error $res
		}

		return $socket

	}

	# if not proxifying, just create a socket directly
	return [socket -async $thost $tport]
}

####################################################
# All NTLM stuff adapted from autoproxy
####################################################

proc NTLMsecureSocket { args } {

  upvar host thost
  upvar port tport

  set s [NTLMauthenticate $thost $tport]
  return [::tls::import $socket]

}

proc NTLMsocket { args } {

  upvar host thost
  upvar port tport

  return [::autoproxy::NTLMauthenticate $thost $tport]

}


proc NTLMCallback { context command args } {

    switch -exact -- $command {
        username    { return [::config::getKey proxyuser] }
        password { return [::config::getKey proxypass] }
        realm    { return "" }
        hostname { return [info host] }
        default  { return -code error unxpected }

}

proc NTLMauthenticate { thost tport } {

  variable options
  set phost $options(proxy_host)
  set pport $options(proxy_port)

  set s [socket $phost $pport]
  fconfigure $s -blocking 1 -buffering line -translation crlf

  set ctx [SASL::new -mechanism NTLM -callback [namespace origin NTLMCallback]]
  while {1} {
    set more_steps [SASL::step $ctx $challenge]
    set response [SASL::response $ctx]
    #puts "----"
    #puts "Sending NTLM message to proxy"
    #puts "NTLM key: [base64::encode -wrapchar {} $response]"
    puts $s "CONNECT $thost:$tport HTTP/1.1\nHost: $phost\nProxy-Connection: Keep-Alive\nConnection: Keep-Alive\nCache-Control: no-cache\nPragma: no-cache\nProxy-Authorization: NTLM [base64::encode -wrapchar {} $response]\n"
    #puts "----"
    if {!$more_steps} {break}
    #puts "Handling proxy reply"

    set response {}
    while {[set line [gets $s]] ne "" } {
      append response $line\r\n
      # break if headers done
      if {$line == ""} {
        break
      }
    }
    set length {}
    regexp {Content-Length: ([0-9]*)} $response -> length
    #puts "response length: $length"
    # puts $response
    if {$length eq {} } {
      set body [read $s]
    } else {
      set body [read $s [expr $length-1] ]
    }
    # puts $body
    regexp {Proxy-Authenticate: NTLM (.*)\r\n} $response -> challenge
    #puts "Server challenge: $challenge"
    set challenge [base64::decode $challenge]
   }
   #puts "Handshake completed"
   #puts "----"

   SASL::cleanup $ctx

   puts $socket ""
   set reply ""
   while {[gets $socket r] > 0} {
      lappend reply $r
   }

   set result [lindex $reply 0]
   if {! [regexp {^HTTP/1\.[01] +2[0-9][0-9]} $result]} {
      return -code error $result
   }

   fconfigure $s -translation binary -buffering none -blocking 0
   return $s

}

}

::snit::type Proxy {

	delegate method * to proxy

	constructor {args} {
		if {[::config::getKey connectiontype] == "direct" } {
			install proxy using ProxyDirect %AUTO% -name $self
		} elseif {[::config::getKey connectiontype] == "http" } {
			install proxy using ProxyHTTP %AUTO% -name $self -direct 1
		} elseif { [::config::getKey connectiontype] == "proxy" && [::config::getKey proxytype] == "http" && 
			   [::config::getKey http_proxy_use_gateway 1]} {
			install proxy using ProxyHTTP %AUTO% -name $self -direct 0
		} elseif { [::config::getKey connectiontype] == "proxy" && [::config::getKey proxytype] == "http" && 
			   ![::config::getKey http_proxy_use_gateway 1]} {
			install proxy using ProxyDirect %AUTO% -name $self
		} elseif { [::config::getKey connectiontype] == "proxy" && [::config::getKey proxytype] == "socks5" } {
			install proxy using ProxyDirect %AUTO% -name $self
		} else {
			::config::setKey connectiontype "direct"
			install proxy using ProxyDirect %AUTO% -name $self
		}

		$self configurelist $args
	}

	destructor {
		catch { $proxy destroy }
	}
}

::snit::type ProxyDirect {

	option -name
	variable http_idlist
	variable sockErr

	method checkSocketErrors { sock } {
		fileevent $sock writable {}
		set sockErr [fconfigure $sock -err]
	}

	#Called to write some data to the connection
	method write { sb data } {

		set sb_sock [$sb cget -sock]
		if {[catch {puts -nonewline $sb_sock "$data"} res]} {
			status_log "::DirectConnectin::Write: SB $sb problem when writing to the socket: $res...\n" red
			return -1
		} else {
			return 0
		}

	}

	#Called to close the given connection
	method finish {sb} {

		set sock [$sb cget -sock]

		catch {
			fileevent $sock readable ""
			fileevent $sock writable ""
		}

		if {[catch {close $sock}]} {
			return -1
		} else {
			return 0
		}
	}

	#Called to stablish the given connection.
	#The "server" field in the sb data must be set to server:port
	method connect {sb} {
	
		if { [$sb cget -proxy_host] != ""} {
			#We connect through SOCKS socket
			set tmp_serv [$sb cget -proxy_host]
			set tmp_port [$sb cget -proxy_port]
			set proxy_serv [lindex [$sb cget -server] 0]
			set proxy_port [lindex [$sb cget -server] 1]
			if {[$sb cget -proxy_authenticate] == 1 } {
				set proxy_authenticate 1
				set proxy_user [$sb cget -proxy_user]
				set proxy_password [$sb cget -proxy_password]
			} else {
				set proxy_authenticate 0
				set proxy_user ""
				set proxy_password ""
			}
		} else {
			#We connect directly
			set tmp_serv [lindex [$sb cget -server] 0]
			set tmp_port [lindex [$sb cget -server] 1]
		}
		if { [catch {set sock [socket -async $tmp_serv $tmp_port]} res ] } {
			$sb configure -error_msg $res
			return -1
		}

		#set sockErr ""
		#fileevent $sock writable [list $self checkSocketErrors $sock]
		#tkwait variable [myvar sockErr]
		#if { $sockErr == "" } {
			$sb configure -sock $sock
                	if { [$sb cget -proxy_host] != ""} {
	                        if { [::config::getKey proxytype] == "http"} {
	                                set res [$self ConnectHTTP $sock $proxy_serv $proxy_port $proxy_authenticate $proxy_user $proxy_password]
	                                if { $res != "OK" } {
	                                        $sb configure -error_msg $res
	                                        return -1
	                                }
	                        } else {
	                                set res [::Socks5::Init $sock $proxy_serv $proxy_port $proxy_authenticate $proxy_user $proxy_password]
	                                if { $res != "OK" } {
	                                        $sb configure -error_msg $res
	                                        return -1
	                                }
	                        }
	                }
	                fconfigure $sock -buffering none -translation binary -blocking 0
	                fileevent $sock readable [list $sb receivedData]
	                set connected_command [$sb cget -connected]
	                lappend connected_command $sock
	                fileevent $sock writable $connected_command
			return 0
		#} else {
		#	$sb configure -error_msg $sockErr
		#	return -1
		#}
	}

	method ConnectHTTP {sck addr port auth user pass} {

		set http_idlist(stat,$sck) 0
		set http_idlist(data,$sck) ""

		
		set msg "CONNECT ${addr}:${port} HTTP/1.0\r\n"
		append msg "Host: ${addr}:${port}\r\n"
		append msg "User-Agent: [http::config -useragent]\r\n"
		append msg "Content-Length: 0\r\n"
		append msg "Proxy-Connection: Keep-Alive\r\n"
		append msg "Connection: Keep-Alive\r\n"
		append msg "Pragma: no-cache\r\n"
		append msg "Cache-Control: no-cache\r\n"
		if {$auth} {
			set basic [base64::encode "${user}:${pass}"]
			append msg "Proxy-Authorization: Basic $basic\r\n"
		}
		append msg "\r\n"
		
		status_log "sending $msg" blue
		fconfigure $sck -translation {binary binary} -blocking 0
		fileevent $sck readable [list $self ReceivedHTTPResponse $sck]

		puts -nonewline $sck "$msg"
		flush $sck


		status_log "HTTP going into tkwait\n"
		tkwait variable [myvar http_idlist(stat,$sck)]

		fileevent $sck readable {}
		set data [set http_idlist(data,$sck)]
		unset http_idlist(stat,$sck)
		unset http_idlist(data,$sck)
		if {[eof $sck]} {
			catch {close $sck}
			status_log "ERROR:Connection closed with HTTP Server!"
			return "ERROR:Connection closed with HTTP Server!"
		}

		if { ([string range $data 9 11] != "200") && ([string range $data 9 11] != "100")} {
			catch {close $sck}
			status_log "HTTP Proxy answered non 200 : $data" red
			return "ERROR: Proxy answered non 200"
		} else {
			fconfigure $sck -translation {auto auto}
			status_log "HTTP: OK"
			return "OK"
		}
	}
	method ReceivedHTTPResponse { sck } {
		if { [catch {set http_idlist(data,$sck) [read $sck]} res] } {
			status_log "Error when reading from http server : $res"
		}

		incr http_idlist(stat,$sck)
	}

	method authInit {} {
		global login_passport_url

		set proxy_host [ns cget -proxy_host]
		set proxy_port [ns cget -proxy_port]
		if {$proxy_host == "" } {
			::http::config -proxyhost ""
		} else {
			if { $proxy_port == "" } {
				set proxy_port 1080
			}
			::http::config -proxyhost $proxy_host -proxyport $proxy_port
		}

		if { [::config::getKey proxytype] == "http"} {
			if { [::config::getKey proxyauthmethod] == "ntlm" } {
				status_log "registering ntlm socket"
				::http::config -proxyhost ""
				if { [catch {http::register http 80 NTLMsocket} res]} {
					MSN::logout
	                                MSN::reconnect "Proxy returned error: $res"
        	                        return -1
				}
				status_log "registering ntlm secure socket "
                	        if { [catch {http::register https 443 NTLMsecureSocket} res]} {
                        	        MSN::logout
                                	MSN::reconnect "Proxy returned error: $res"
                               	 return -1
	                        }
			} else {
	                        status_log "registering http secure socket "
	                        if { [catch {http::register https 443 HTTPsecureSocket} res]} {
	                                MSN::logout
	                                MSN::reconnect "Proxy returned error: $res"
	                                return -1
	                        }
			}
		} else {
			# http://wiki.tcl.tk/2627 :(
			if { [catch {http::register https 443 SOCKSsecureSocket} res]} {
				MSN::logout
				MSN::reconnect "Proxy returned error: $res"
				return -1
			}
		}

#		if { [::config::getKey nossl] == 1 } {
#			#If we can't use ssl, avoid getting url from nexus
#			set login_passport_url "https://login.passport.com/login2.srf"
#		} else {
			#Contact nexus to get login url
			set login_passport_url 0
			degt_protocol $self

			after 0 "catch {::http::geturl [list https://nexus.passport.com/rdr/pprdr.asp] -timeout 5000 -command {globalGotNexusReply $self}}"
#		}
	}

	method authenticate {str url} {
		set head [list Authorization "Passport1.4 OrgVerb=GET,OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,sign-in=[::config::getKey login],pwd=[urlencode $::password],${str}"]
		#if { [::config::getKey nossl] == 1 || ([::config::getKey connectiontype] != "direct" && [::config::getKey connectiontype] != "http") } {
		#	set url [string map { https:// http:// } $url]
		#}
#		if { [::config::getKey nossl] == 1 } {
#			set url [string map { https:// http:// } $url]
#		}
		status_log "::DirectConnection::authenticate: Getting $url\n" blue
		if { [catch {::http::geturl $url -command "globalGotAuthReply $self [list $str]" -headers $head}] } {
			eval [ns cget -autherror_handler]
			#msnp9_auth_error
		}

	}


	method GotNexusReply {token {total 0} {current 0}} {

		global login_passport_url
		if { [::http::status $token] != "ok" || [::http::ncode $token ] != 200 } {
			#Nexus connection failed, so let's just set login URL manually
			set loginurl "https://login.live.com/login2.srf"
			status_log "gotNexusReply: error in nexus reply, getting url manually\n" red
		} else {
			#We got reply from nexus. Extract login URL
			upvar #0 $token state

			set index [expr {[lsearch $state(meta) "PassportURLs"]+1}]
			set values [split [lindex $state(meta) $index] ","]
			set index [lsearch $values "DALogin=*"]
			set loginurl "https://[string range [lindex $values $index] 8 end]"
			status_log "gotNexusReply: loginurl=$loginurl\n" green
		}
		::http::cleanup $token

		#If $login_passport_url == 0, we got login url before authentication took place
		if { $login_passport_url == 0 } {
			#Set loginurl (will be used in authentication), and rest in peace
			set login_passport_url $loginurl
			status_log "gotNexusReply: finished before authentication took place\n" green
		} else {
			#Authentication is waiting for us to get this url!! Do authentication inmediatly
			status_log "gotNexusReply: authentication was waiting for me, so I'll do it\n" green
			$self authenticate $login_passport_url $loginurl
		}

	}

	method GotAuthReply { str token } {
		if { [::http::status $token] != "ok" } {
			::http::cleanup $token
			status_log "$self GotAuthReply error: [::http::error]\n"
			eval [ns cget -autherror_handler]
			#msnp9_auth_error
			return
		}

		upvar #0 $token state

		if { [::http::ncode $token] == 200 } {
			#Authentication done correctly
			set index [expr {[lsearch $state(meta) "Authentication-Info"]+1}]
			set values [split [lindex $state(meta) $index] ","]
			set index [lsearch $values "from-PP=*"]
			set value [string range [lindex $values $index] 9 end-1]
			status_log "::DirectConnection::GotAuthReply 200 Ticket= $value\n" green

			set command [list [ns cget -ticket_handler] $value]
			eval $command
			#msnp9_authenticate $value

		} elseif {[::http::ncode $token] == 302} {
			#Redirected to another URL, try again
			set index [expr {[lsearch $state(meta) "Location"]+1}]
			set url [lindex $state(meta) $index]
			status_log "::DirectConnection::GotAuthReply 302: Forward to $url\n" green
			$self authenticate $str $url
		} elseif {[::http::ncode $token] == 401} {
			#msnp9_userpass_error
			eval [ns cget -passerror_handler]
		} else {
			eval [ns cget -autherror_handler]
			#msnp9_auth_error
		}
		::http::cleanup $token

	}
}

#Connection wrapper for HTTP connection or http proxy
::snit::type ProxyHTTP {

	option -direct
	option -name
	option -proxy_queued_data
	option -proxy_session_id
	option -proxy_gateway_ip
	option -proxy_writing
	variable poll_afterids
	variable created_sockets [list]

	constructor {args } {
		array set poll_afterids [list]
		$self configurelist $args
	}

	destructor {
		foreach name [array names poll_afterids]  {
			after cancel [set poll_afterids($name)]
		}
		foreach sock $created_sockets {
			catch {close $sock}
		}
	}

	method write { name {msg ""} } {
#		variable proxy_queued_data
#		variable proxy_session_id
#		variable proxy_gateway_ip
#		variable options(-proxy_writing)

		#Cancel any previous attemp to write or POLL
		after cancel [list $self HTTPPoll $name]
		array unset poll_afterids $name

		after cancel "globalWrite $self $name"

		if {![info exists options(-proxy_queued_data)]} {
			set options(-proxy_queued_data) ""
		}

		if { ![info exists options(-proxy_session_id)]} {
			return -1
		}

		#Kind of mutex here, to avoid race conditions
		set old_proxy_session_id $options(-proxy_session_id)
		set options(-proxy_session_id) ""

		if { $msg != "" } {
			#If msg!="", enqueue it
			set options(-proxy_queued_data) "$options(-proxy_queued_data)$msg"
		}


		#Check if we got the mutex, then write
		if { $old_proxy_session_id != "" } {
			set current_data $options(-proxy_queued_data)
			set size [string length $current_data]
			set strend [expr {$size -1 }]
			set options(-proxy_queued_data) [string replace $options(-proxy_queued_data) 0 $strend]

			if { $options(-direct) } {
				set tmp_data "POST /gateway/gateway.dll?SessionID=$old_proxy_session_id HTTP/1.1\r\n"
			} else {
				set tmp_data "POST http://$options(-proxy_gateway_ip)/gateway/gateway.dll?SessionID=$old_proxy_session_id HTTP/1.1\r\n"
			}
			append tmp_data "Accept: */*\r\n"
			append tmp_data "Content-Type: text/xml; charset=utf-8\r\n"
			append tmp_data "Content-Length: $size\r\n"
			append tmp_data "User-Agent: MSMSGS\r\n"
			append tmp_data "Host: $options(-proxy_gateway_ip)\r\n"
			append tmp_data "Proxy-Connection: Keep-Alive\r\n"
			append tmp_data "Connection: Keep-Alive\r\n"
			append tmp_data "Pragma: no-cache\r\n"
			append tmp_data "Cache-Control: no-cache\r\n"

			if {[$name cget -proxy_authenticate]  == 1 } {
				append tmp_data "Proxy-Authorization: Basic [::base64::encode [$name cget -proxy_user]:[$name cget -proxy_password]]\r\n"
			}


			append tmp_data "\r\n"
			append tmp_data $current_data

			#status_log "::HTTPConnection::Write: PROXY POST Sending: ($name)\n$tmp_data\n" blue
			set options(-proxy_writing) $tmp_data
			if { [catch {puts -nonewline [$name cget -sock] "$tmp_data"} res] } {
				$self connect $name [list $self RetryWrite $name]
				return 0
			}

		} else {

			set options(-proxy_session_id) $old_proxy_session_id
			after 500 "globalWrite $self $name"

		}

		return 0

	}

	method authInit {} {
		#catch {::http::unregister https}

		global tlsinstalled login_passport_url

                #Check if we need to install the TLS module
                if { $tlsinstalled == 0 && [checking_package_tls] == 0} {
                        ::autoupdate::installTLS
                        return -1
                }

                #If SSL is used, register https:// protocol
#                if { [::config::getKey nossl] == 0 } {
#                        http::register https 443 ::tls::socket
#                } else  {
#                        catch {http::unregister https}
#                }


		set proxy_host [ns cget -proxy_host]
		set proxy_port [ns cget -proxy_port]
		if {$proxy_host == "" } {
			::http::config -proxyhost ""
		} else {
			if { $proxy_port == "" } {
				set proxy_port 8080
			}

			::http::config -proxyhost $proxy_host -proxyport $proxy_port
		}

		# http://wiki.tcl.tk/2627 :(
		if { [catch {http::register https 443 HTTPsecureSocket} res]} {
			MSN::logout
			MSN::reconnect "Proxy returned error: $res"
			return -1
		}

#		set ::login_passport_url "https://login.passport.com/login2.srf"
#		        if { [::config::getKey nossl] == 1 } {
                        #If we can't use ssl, avoid getting url from nexus
#                        set login_passport_url "https://login.passport.com/login2.srf"
#                } else {
                        #Contact nexus to get login url
                        set login_passport_url 0
                        degt_protocol $self

			#::http::geturl [list https://nexus.passport.com/rdr/pprdr.asp] -timeout 10000 -command [list globalGotNexusReply $self]
                        if { [catch {::http::geturl https://nexus.passport.com/rdr/pprdr.asp -timeout 10000 -command [list globalGotNexusReply $self]} res]} {
				MSN::logout
				MSN::reconnect "proxy error: $res"
				return -1
			}

#                }
		return 1

	}

	method authenticate {str url} {
		variable proxy_user
		variable proxy_password
		variable proxy_authenticate

		set head [list Authorization "Passport1.4 OrgVerb=GET,OrgURL=http%3A%2F%2Fmessenger%2Emsn%2Ecom,sign-in=[::config::getKey login],pwd=[urlencode $::password],${str}"]
		#if { [::config::getKey nossl] == 1 || ([::config::getKey connectiontype] != "direct" && [::config::getKey connectiontype] != "http") } {
		#	set url [string map { https:// http:// } $url]
		#}
		if {[info exists proxy_authenticate] && $proxy_authenticate  == 1 } {
			lappend head "Proxy-Authorization" "Basic [::base64::encode $proxy_user:$proxy_password]"
		}

		#set url [string map { https:// http:// } $url]
		status_log "::HTTPConnection::authenticate: Getting $url\n" blue
		::http::geturl $url -command "$self GotAuthReply [list $str]" -headers $head
#			eval [ns cget -autherror_handler]
#
	}

        method GotNexusReply {token {total 0} {current 0}} {

                global login_passport_url
                if { [::http::status $token] != "ok" || [::http::ncode $token ] != 200 } {
                        #Nexus connection failed, so let's just set login URL manually
                        set loginurl "https://login.live.com/login2.srf"
                        status_log "gotNexusReply: error in nexus reply, getting url manually\n" red
                } else {
                        #We got reply from nexus. Extract login URL
                        upvar #0 $token state

                        set index [expr {[lsearch $state(meta) "PassportURLs"]+1}]
                        set values [split [lindex $state(meta) $index] ","]
                        set index [lsearch $values "DALogin=*"]
                        set loginurl "https://[string range [lindex $values $index] 8 end]"
                        status_log "gotNexusReply: loginurl=$loginurl\n" green
                }
                ::http::cleanup $token

                #If $login_passport_url == 0, we got login url before authentication took place
                if { $login_passport_url == 0 } {
                        #Set loginurl (will be used in authentication), and rest in peace
                        set login_passport_url $loginurl
                        status_log "gotNexusReply: finished before authentication took place\n" green
                } else {
                        #Authentication is waiting for us to get this url!! Do authentication inmediatly
                        status_log "gotNexusReply: authentication was waiting for me, so I'll do it\n" green
                        $self authenticate $login_passport_url $loginurl
                }

        }

	method GotAuthReply { str token } {
		if { [::http::status $token] != "ok" } {
			::http::cleanup $token
			status_log "::HTTPConnection::GotAuthReply error: [::http::error]\n"
			eval [ns cget -autherror_handler]
			return
		}

		upvar #0 $token state

		if { [::http::ncode $token] == 200 } {
			#Authentication done correctly
			set index [expr {[lsearch $state(meta) "Authentication-Info"]+1}]
			set values [split [lindex $state(meta) $index] ","]
			set index [lsearch $values "from-PP=*"]
			set value [string range [lindex $values $index] 9 end-1]
			status_log "::HTTPConnection::GotAuthReply 200 Ticket= $value\n" green

			set command [list [ns cget -ticket_handler] $value]
			eval $command

		} elseif {[::http::ncode $token] == 302} {
			#Redirected to another URL, try again
			set index [expr {[lsearch $state(meta) "Location"]+1}]
			set url [lindex $state(meta) $index]
			status_log "::HTTPConnection::GotAuthReply 302: Forward to $url\n" green
			$self authenticate $str $url
		} elseif {[::http::ncode $token] == 401} {
			eval [ns cget -passerror_handler]
		} else {
			eval [ns cget -autherror_handler]
		}
		::http::cleanup $token

	}


	#Called to close the given connection
	method finish {name} {

		variable proxy_session_id
#		variable proxy_gateway_ip
		variable proxy_queued_data

		#status_log "Canceling \"$self HTTPPoll $name\""
		after cancel [list $self HTTPPoll $name]
		array unset poll_afterids $name
		
		if {[info exists options(-proxy_session_id)]} {
			unset options(-proxy_session_id)
		}

		if {[info exists options(-proxy_gateway_ip)]} {
			unset options(-proxy_gateway_ip)
		}

		if {[info exists options(-proxy_queued_data)]} {
			unset options(-proxy_queued_data)
		}

		set sock [$name cget -sock]

		catch {
			fileevent $sock readable ""
			fileevent $sock writable ""
		}
		set created_sockets [lreplace $created_sockets [lsearch $created_sockets $sock] [lsearch $created_sockets $sock]]

		if {[catch {close $sock}]} {
			return -1
		} else {
			return 0
		}
	}

	#Called to stablish the given connection.
	#The "server" field in the sb data must be set to server:port
	method connect {sb {connected_handler ""}} {
		variable http_gateway
		variable proxy_user
		variable proxy_password
		variable proxy_authenticate

		#On direct http connection, use gateway directly as proxy
		if { [$sb cget -proxy_host] == ""} {
			set proxy_host [$sb cget -force_gateway_server]
			if {$proxy_host == "" } {
				set proxy_host [::config::getKey start_gateway_server]
			}
			
			set proxy_port 80
		} else {
			set proxy_host [$sb cget -proxy_host]
			set proxy_port [$sb cget -proxy_port]
		}


		if {[$sb cget -proxy_authenticate] == 1 } {
			set proxy_authenticate 1
			set proxy_user [$sb cget -proxy_user]
			set proxy_password [$sb cget -proxy_password]
		}


		if { [catch {set sock [socket -async $proxy_host $proxy_port]} res ] } {
			$sb configure -error_msg $res
			return -1
		}
		lappend created_sockets $sock

		$sb configure -sock $sock
		fconfigure $sock -buffering none -translation {binary binary} -blocking 0

		fileevent $sock readable ""
		if { $connected_handler == "" } {
			fileevent $sock writable [list $self Connected $sb $sock]
		} else {
			fileevent $sock writable $connected_handler
		}
		return 0

	}

	method Connected {sb sock} {

		status_log "::HTTPConnection::Connected: Proxy connected!!\n" green

		fileevent $sock writable {}

		$sb configure -stat "pc"
		set remote_server [lindex [$sb cget -server] 0]
		set remote_port 1863

		set error_msg [fconfigure $sock -error]
		if { $error_msg != "" } {
			$sb configure -error_msg $error_msg
			$sb sockError
			return
		}

		set server "NS"
		if { [string first "SB" $sb] != "-1" } {
			set server "SB"
		}

		if { $options(-direct) } {
			set tmp_data "POST /gateway/gateway.dll?Action=open&Server=$server&IP=$remote_server HTTP/1.1\r\n"
		} else {
			set tmp_data "POST http://[::config::getKey start_gateway_server]/gateway/gateway.dll?Action=open&Server=$server&IP=$remote_server HTTP/1.1\r\n"
		}
	
		append tmp_data "Accept: */*\r\n"
		append tmp_data "Content-Type: text/xml; charset=utf-8\r\n"
		append tmp_data "Content-Length: 0\r\n"
		append tmp_data "User-Agent: MSMSGS\r\n"
		append tmp_data "Host: [::config::getKey start_gateway_server]\r\n"
		append tmp_data "Proxy-Connection: Keep-Alive\r\n"
		append tmp_data "Connection: Keep-Alive\r\n"
		append tmp_data "Pragma: no-cache\r\n"
		append tmp_data "Cache-Control: no-cache\r\n"

		if {[$sb cget -proxy_authenticate] == 1 } {
			append tmp_data "Proxy-Authorization: Basic [::base64::encode [$sb cget -proxy_user]:[$sb cget -proxy_password]]\r\n"
		}
		append tmp_data "\r\n"
		status_log "::HTTPConnection::Connected: PROXY SEND ($sb)\n$tmp_data\n" blue
		if { [catch {puts -nonewline $sock "$tmp_data"} res]} {
			$sb sockError
		}

		fileevent $sock readable [list $self ConnectReply $sb $sock]

	}

	method ConnectReply {sb sock} {
		status_log "::HTTPConnection::ConnectReply\n" green
		$self HTTPRead $sb
		catch {
			fileevent $sock readable [list $self HTTPRead $sb]
			set connected_command [$sb cget -connected]
			lappend connected_command $sock
			fileevent $sock writable $connected_command
		}
	}

	method RetryWrite { name } {
#		variable options(-proxy_writing)
		status_log "Retrying write\n" blue
		catch {fileevent [$name cget -sock] writable ""}
		if { [catch {puts -nonewline [$name cget -sock] $options(-proxy_writing)} res] } {
			$name configure -error_msg $res
			$name sockError
		}
		catch {unset options(-proxy_writing)}
		if { [catch {fileevent [$name cget -sock] readable [list $self HTTPRead $name]} res] } {
			$name configure -error_msg $res
			$name sockError
		}


	}

	method HTTPRead { name } {

		variable proxy_session_id
#		variable proxy_gateway_ip
		variable proxy_data
		variable options

		after cancel [list $self HTTPPoll $name]
		array unset poll_afterids $name

		set sock [$name cget -sock]
		if {[catch {eof $sock} res]} {
			status_log "::HTTPConnection::HTTPRead: Error, closing\n" red
			catch { close $sock }
			$name sockError
		} elseif {[eof $sock]} {
			fileevent $sock readable ""
			fileevent $sock writable ""
			catch { close $sock }
			status_log "::HTTPConnection::HTTPRead: EOF, closing\n" red
			if { [info exists options(-proxy_writing)] } {
				$self connect $name [list $self RetryWrite $name]
				return 0
			} else {
				set poll_afterids($name) [after 2000 [list $self HTTPPoll $name]]
			}
		} else {
			set tmp_data "ERROR READING POST PROXY !!\n"

			catch {gets $sock tmp_data} res

			if { $tmp_data == "" } {
				return
			}

			catch {unset options(-proxy_writing)}

			if { ([string range $tmp_data 9 11] != "200") && ([string range $tmp_data 9 11] != "100")} {
				status_log "::HTTPConnection::HTTPRead: Proxy POST connection closed for $name:\n$tmp_data\n" red
				$name sockError
			} else {

				set headers $tmp_data
				while { $tmp_data != "\r"  } {
					catch {gets $sock tmp_data} res
					set headers "$headers\n$tmp_data"
				}
				set info "[::MSN::GetHeaderValue $headers X-MSN-Messenger]\n"

				set start [expr {[string first "SessionID=" $info] + 10}]
				set end [expr {[string first ";" $info $start]-1}]
				if { $end < 0 } { set end [expr {[string first "\n" $info $start]-1}] }
				set session_id "[string range $info $start $end]"

				set start [expr {[string first "GW-IP=" $info] + 6}]
				set end [expr {[string first ";" $info $start]-1}]
				if { $end < 0 } { set end [expr {[string first "\n" $info $start]-1}] }
				set gateway_ip "[string range $info $start $end]"


				#TODO: Replace everything down here. Reading should be done from ::MSN
				set content_length "[::MSN::GetHeaderValue $headers Content-Length]\n"
				set content_data ""
				if { $content_length > 0 } {
					set content_data [nbread $sock $content_length]
				}

				if {$content_data != "" } {
					catch {$name receivedData $content_data}
				}

				# the handleCommand *could* potentially destroy our own object for some reason...
				# we must be prepared to not crash because of that.
				if { [catch { 
					if { $session_id != ""} {
						#status_log "Scheduling HTTPPoll\n" white
						set poll_afterids($name) [after 2000 [list $self HTTPPoll $name]]
					}
					
					set options(-proxy_gateway_ip) $gateway_ip
					set options(-proxy_session_id) $session_id
				}] } {
					after cancel [list $self HTTPPoll $name]
				}
			}
		}
	}

	method HTTPPoll { name } {
#		variable proxy_session_id
#		variable proxy_gateway_ip
#		variable proxy_queued_data
#		variable options(-proxy_writing)

		array unset poll_afterids $name
		if { ![info exists options(-proxy_session_id)]} {
			return
		}

		#TODO: Race condition!! A write can happen here
		set old_proxy_session_id $options(-proxy_session_id)
		set options(-proxy_session_id) ""

		if { $old_proxy_session_id == ""} {
			status_log "ERROR, RACE CONDITION, THIS SHOULD'T HAPPEN IN HTTPPoll with \"$self HTTPPoll $name\" !!!!!!" white
		} else {
			if { $old_proxy_session_id != ""} {

				if { $options(-direct) } {
					set tmp_data "POST /gateway/gateway.dll?Action=poll&SessionID=$old_proxy_session_id HTTP/1.1\r\n"
				} else {
					set tmp_data "POST http://$options(-proxy_gateway_ip)/gateway/gateway.dll?Action=poll&SessionID=$old_proxy_session_id HTTP/1.1\r\n"
				}
				
				append tmp_data "Accept: */*\r\n"
				append tmp_data "Content-Type: text/xml; charset=utf-8\r\n"
				append tmp_data "Content-Length: 0\r\n"
				append tmp_data "User-Agent: MSMSGS\r\n"
				append tmp_data "Host: $options(-proxy_gateway_ip)\r\n"
				append tmp_data "Proxy-Connection: Keep-Alive\r\n"
				append tmp_data "Connection: Keep-Alive\r\n"
				append tmp_data "Pragma: no-cache\r\n"
				append tmp_data "Cache-Control: no-cache\r\n"
				
				if {[$name cget -proxy_authenticate] == 1 } {
					append tmp_data "Proxy-Authorization: Basic [::base64::encode [$name cget -proxy_user]:[$name cget -proxy_password]]\r\n"
				}

				append tmp_data "\r\n"


				#status_log "PROXY POST polling connection ($name):\n$tmp_data\n" blue
				set options(-proxy_writing) $tmp_data
				if { [catch {puts -nonewline [$name cget -sock] "$tmp_data" } res]} {
					$self connect $name [list $self RetryWrite $name]
					return 0
				}

			}

		}
	}


}