11import logging
22
33from telegram import Update , NullHandler
4- from future .utils import bytes_to_native_str as n
4+ from future .utils import bytes_to_native_str
55from threading import Lock
66import json
77try :
1414logging .getLogger (__name__ ).addHandler (H )
1515
1616
17+ class _InvalidPost (Exception ):
18+
19+ def __init__ (self , http_code ):
20+ self .http_code = http_code
21+ super (_InvalidPost , self ).__init__ ()
22+
23+
1724class WebhookServer (BaseHTTPServer .HTTPServer , object ):
1825 def __init__ (self , server_address , RequestHandlerClass , update_queue ,
1926 webhook_path ):
@@ -63,12 +70,15 @@ def do_GET(self):
6370
6471 def do_POST (self ):
6572 self .logger .debug ("Webhook triggered" )
66- if self .path == self .server .webhook_path and \
67- 'content-type' in self .headers and \
68- 'content-length' in self .headers and \
69- self .headers ['content-type' ] == 'application/json' :
70- json_string = \
71- n (self .rfile .read (int (self .headers ['content-length' ])))
73+ try :
74+ self ._validate_post ()
75+ clen = self ._get_content_len ()
76+ except _InvalidPost as e :
77+ self .send_error (e .http_code )
78+ self .end_headers ()
79+ else :
80+ buf = self .rfile .read (clen )
81+ json_string = bytes_to_native_str (buf )
7282
7383 self .send_response (200 )
7484 self .end_headers ()
@@ -80,6 +90,20 @@ def do_POST(self):
8090 update .update_id )
8191 self .server .update_queue .put (update )
8292
83- else :
84- self .send_error (403 )
85- self .end_headers ()
93+ def _validate_post (self ):
94+ if not (self .path == self .server .webhook_path and
95+ 'content-type' in self .headers and
96+ self .headers ['content-type' ] == 'application/json' ):
97+ raise _InvalidPost (403 )
98+
99+ def _get_content_len (self ):
100+ clen = self .headers .get ('content-length' )
101+ if clen is None :
102+ raise _InvalidPost (411 )
103+ try :
104+ clen = int (clen )
105+ except ValueError :
106+ raise _InvalidPost (403 )
107+ if clen < 0 :
108+ raise _InvalidPost (403 )
109+ return clen
0 commit comments