2 # -*- coding: utf-8 -*-
4 VPProxy: HTTP/HLS Stream to HTTP Multiplexing Proxy
6 Based on AceProxy (https://github.com/ValdikSS/AceProxy) design
11 # Monkeypatching and all the stuff
12 gevent.monkey.patch_all()
13 # Startup delay for daemon restart
23 from socket import error as SocketException
24 from socket import SHUT_RDWR
28 from vpconfig import VPConfig
31 import plugins.modules.ipaddr as ipaddr
32 from clientcounter import ClientCounter
33 from plugins.modules.PluginInterface import VPProxyPlugin
42 from apscheduler.schedulers.background import BackgroundScheduler
44 class HTTPHandler(BaseHTTPServer.BaseHTTPRequestHandler):
48 def handle_one_request(self):
50 Add request to requestlist, handle request and remove from the list
52 HTTPHandler.requestlist.append(self)
53 BaseHTTPServer.BaseHTTPRequestHandler.handle_one_request(self)
54 HTTPHandler.requestlist.remove(self)
56 def closeConnection(self):
60 if self.clientconnected:
61 self.clientconnected = False
65 self.connection.shutdown(SHUT_RDWR)
69 def dieWithError(self, errorcode=500):
71 Close connection with error
73 logging.warning("Dying with error")
74 if self.clientconnected:
75 self.send_error(errorcode)
77 self.closeConnection()
79 def proxyReadWrite(self):
81 Read video stream and send it to client
83 logger = logging.getLogger('http_proxyReadWrite')
84 logger.debug("Started")
87 self.streamstate = True
92 if not self.clientconnected:
93 logger.debug("Client is not connected, terminating")
96 VPStuff.vlcclient.mark(self.vlcid)
97 data = self.video.read(4096)
98 if data and self.clientconnected:
99 self.wfile.write(data)
101 logger.warning("Video connection closed")
104 except SocketException:
105 # Video connection dropped
106 logger.warning("Video connection dropped")
109 self.closeConnection()
111 def hangDetector(self):
113 Detect client disconnection while in the middle of something
114 or just normal connection close.
116 logger = logging.getLogger('http_hangDetector')
119 if not self.rfile.read():
124 self.clientconnected = False
125 logger.debug("Client disconnected")
127 self.requestgreenlet.kill()
135 return self.do_GET(headers_only=True)
137 def do_GET(self, headers_only=False):
142 logger = logging.getLogger('http_HTTPHandler')
143 self.clientconnected = True
144 # Don't wait videodestroydelay if error happened
145 self.errorhappened = True
146 # Headers sent flag for fake headers UAs
147 self.headerssent = False
149 self.requestgreenlet = gevent.getcurrent()
150 # Connected client IP address
151 self.clientip = self.request.getpeername()[0]
153 req_headers = self.headers
156 'forwarded-for': req_headers.get('X-Forwarded-For'),
157 'client-agent': req_headers.get('User-Agent'),
161 if VPConfig.firewall:
162 # If firewall enabled
163 self.clientinrange = any(map(lambda i: ipaddr.IPAddress(self.clientip) \
164 in ipaddr.IPNetwork(i), VPConfig.firewallnetranges))
166 if (VPConfig.firewallblacklistmode and self.clientinrange) or \
167 (not VPConfig.firewallblacklistmode and not self.clientinrange):
168 logger.info('Dropping connection from ' + self.clientip + ' due to ' + \
170 self.dieWithError(403) # 403 Forbidden
173 logger.info("Accepted connection from " + self.clientip + " path " + self.path)
176 self.splittedpath = self.path.split('/')
177 self.reqtype = self.splittedpath[1].lower()
178 # If first parameter is 'pid' or 'torrent' or it should be handled
180 if not (self.reqtype in ('get','mp4','ogg','ogv') or self.reqtype in VPStuff.pluginshandlers):
181 self.dieWithError(400) # 400 Bad Request
184 self.dieWithError(400) # 400 Bad Request
187 # Handle request with plugin handler
188 if self.reqtype in VPStuff.pluginshandlers:
190 VPStuff.pluginshandlers.get(self.reqtype).handle(self)
191 except Exception as e:
192 logger.error('Plugin exception: ' + repr(e))
193 logger.error(traceback.format_exc())
196 self.closeConnection()
198 self.handleRequest(headers_only)
200 def handleRequest(self, headers_only):
202 # Limit concurrent connections
203 if 0 < VPConfig.maxconns <= VPStuff.clientcounter.total:
204 logger.debug("Maximum connections reached, can't serve this")
205 self.dieWithError(503) # 503 Service Unavailable
208 # Pretend to work fine with Fake UAs or HEAD request.
209 useragent = self.headers.get('User-Agent')
210 logger.debug("HTTP User Agent:"+useragent)
211 fakeua = useragent and useragent in VPConfig.fakeuas
212 if headers_only or fakeua:
214 logger.debug("Got fake UA: " + self.headers.get('User-Agent'))
215 # Return 200 and exit
216 self.send_response(200)
217 self.send_header("Content-Type", "video/mpeg")
219 self.closeConnection()
222 self.path_unquoted = urllib2.unquote('/'.join(self.splittedpath[2:]))
223 # Make list with parameters
225 for i in xrange(3, 8):
227 self.params.append(int(self.splittedpath[i]))
228 except (IndexError, ValueError):
229 self.params.append('0')
231 # Adding client to clientcounter
232 clients = VPStuff.clientcounter.add(self.reqtype+'/'+self.path_unquoted, self.client_data)
233 # If we are the one client, but sucessfully got vp instance from clientcounter,
234 # then somebody is waiting in the videodestroydelay state
236 # Check if we are first client
237 if VPStuff.clientcounter.get(self.reqtype+'/'+self.path_unquoted)==1:
238 logger.debug("First client, should create VLC session")
239 shouldcreatevp = True
241 logger.debug("Can reuse existing session")
242 shouldcreatevp = False
244 self.vlcid = hashlib.md5(self.reqtype+'/'+self.path_unquoted).hexdigest()
246 # Send fake headers if this User-Agent is in fakeheaderuas tuple
249 "Sending fake headers for " + useragent)
250 self.send_response(200)
251 self.send_header('Cache-Control','no-cache, no-store, must-revalidate');
252 self.send_header('Pragma','no-cache');
253 if self.reqtype in ("ogg","ogv"):
254 self.send_header("Content-Type", "video/ogg")
256 self.send_header("Content-Type", "video/mpeg")
258 # Do not send real headers at all
259 self.headerssent = True
262 self.hanggreenlet = gevent.spawn(self.hangDetector)
263 logger.debug("hangDetector spawned")
267 self.errorhappened = False
270 logger.debug("Got url " + self.path_unquoted)
271 # Force ffmpeg demuxing if set in config
272 if VPConfig.vlcforceffmpeg:
273 self.vlcprefix = 'http/ffmpeg://'
277 logger.info("Starting broadcasting "+self.path)
278 VPStuff.vlcclient.startBroadcast(
279 self.vlcid, self.vlcprefix + self.path_unquoted, VPConfig.vlcmux, VPConfig.vlcpreaccess, self.reqtype)
280 # Sleep a bit, because sometimes VLC doesn't open port in
284 # Building new VLC url
285 self.url = 'http://' + VPConfig.vlchost + \
286 ':' + str(VPConfig.vlcoutport) + '/' + self.vlcid
287 logger.debug("VLC url " + self.url)
289 # Sending client headers to videostream
290 self.video = urllib2.Request(self.url)
291 for key in self.headers.dict:
292 self.video.add_header(key, self.headers.dict[key])
294 self.video = urllib2.urlopen(self.video)
296 # Sending videostream headers to client
297 if not self.headerssent:
298 self.send_response(self.video.getcode())
299 if self.video.info().dict.has_key('connection'):
300 del self.video.info().dict['connection']
301 if self.video.info().dict.has_key('server'):
302 del self.video.info().dict['server']
303 if self.video.info().dict.has_key('transfer-encoding'):
304 del self.video.info().dict['transfer-encoding']
305 if self.video.info().dict.has_key('content-type'):
306 del self.video.info().dict['content-type']
307 if self.video.info().dict.has_key('keep-alive'):
308 del self.video.info().dict['keep-alive']
310 for key in self.video.info().dict:
311 self.send_header(key, self.video.info().dict[key])
313 self.send_header('Cache-Control','no-cache, no-store, must-revalidate');
314 self.send_header('Pragma','no-cache');
316 if self.reqtype=="ogg":
317 self.send_header("Content-Type", "video/ogg")
319 self.send_header("Content-Type", "video/mpeg")
321 # End headers. Next goes video data
323 logger.debug("Headers sent")
324 self.headerssent = True
327 self.proxyReadWrite()
329 # Waiting until hangDetector is joined
330 self.hanggreenlet.join()
331 logger.debug("Request handler finished")
333 except (vpclient.VPException, vlcclient.VlcException, urllib2.URLError) as e:
334 logger.error("Exception: " + repr(e))
335 self.errorhappened = True
337 except gevent.GreenletExit:
338 # hangDetector told us about client disconnection
342 logger.error(traceback.format_exc())
343 self.errorhappened = True
346 logger.debug("END REQUEST")
347 logger.info("Closed connection from " + self.clientip + " path " + self.path)
348 VPStuff.clientcounter.delete(self.reqtype+'/'+self.path_unquoted, self.client_data)
351 class HTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
353 def handle_error(self, request, client_address):
354 # Do not print HTTP tracebacks
358 class VPStuff(object):
360 Inter-class interaction class
364 # taken from http://stackoverflow.com/questions/2699907/dropping-root-permissions-in-python
365 def drop_privileges(uid_name, gid_name='nogroup'):
367 # Get the uid/gid from the name
368 running_uid = pwd.getpwnam(uid_name).pw_uid
369 running_uid_home = pwd.getpwnam(uid_name).pw_dir
370 running_gid = grp.getgrnam(gid_name).gr_gid
372 # Remove group privileges
375 # Try setting the new uid/gid
376 os.setgid(running_gid)
377 os.setuid(running_uid)
379 # Ensure a very conservative umask
380 old_umask = os.umask(077)
382 if os.getuid() == running_uid and os.getgid() == running_gid:
384 os.environ['HOME'] = running_uid_home
389 filename=VPConfig.logpath + 'vphttp.log' if VPConfig.loggingtoafile else None,
390 format='%(asctime)s %(levelname)s %(name)s: %(message)s', datefmt='%d.%m.%Y %H:%M:%S', level=VPConfig.debug)
391 logger = logging.getLogger('INIT')
394 # Trying to change dir (would fail in freezed state)
396 os.chdir(os.path.dirname(os.path.realpath(__file__)))
399 # Creating dict of handlers
400 VPStuff.pluginshandlers = dict()
401 # And a list with plugin instances
402 VPStuff.pluginlist = list()
403 pluginsmatch = glob.glob('plugins/*_plugin.py')
404 sys.path.insert(0, 'plugins')
405 pluginslist = [os.path.splitext(os.path.basename(x))[0] for x in pluginsmatch]
406 for i in pluginslist:
407 plugin = __import__(i)
408 plugname = i.split('_')[0].capitalize()
410 plugininstance = getattr(plugin, plugname)(VPConfig, VPStuff)
411 except Exception as e:
412 logger.error("Cannot load plugin " + plugname + ": " + repr(e))
414 logger.debug('Plugin loaded: ' + plugname)
415 for j in plugininstance.handlers:
416 logger.info("Registering handler '" + j +"'")
417 VPStuff.pluginshandlers[j] = plugininstance
418 VPStuff.pluginlist.append(plugininstance)
420 # Check whether we can bind to the defined port safely
421 if os.getuid() != 0 and VPConfig.httpport <= 1024:
422 logger.error("Cannot bind to port " + str(VPConfig.httpport) + " without root privileges")
425 server = HTTPServer((VPConfig.httphost, VPConfig.httpport), HTTPHandler)
426 logger = logging.getLogger('HTTP')
428 # Dropping root privileges if needed
429 if VPConfig.vpproxyuser and os.getuid() == 0:
430 if drop_privileges(VPConfig.vpproxyuser):
431 logger.info("Dropped privileges to user " + VPConfig.vpproxyuser)
433 logger.error("Cannot drop privileges to user " + VPConfig.vpproxyuser)
436 # Creating ClientCounter
437 VPStuff.clientcounter = ClientCounter()
439 DEVNULL = open(os.devnull, 'wb')
441 # Spawning procedures
442 def spawnVLC(cmd, delay = 0):
444 VPStuff.vlc = psutil.Popen(cmd) #, stdout=DEVNULL, stderr=DEVNULL)
452 VPStuff.vlcclient = vlcclient.VlcClient(
453 host=VPConfig.vlchost, port=VPConfig.vlcport, password=VPConfig.vlcpass,
454 out_port=VPConfig.vlcoutport)
456 except vlcclient.VlcException as e:
459 def isRunning(process):
460 if psutil.version_info[0] >= 2:
461 if process.is_running() and process.status() != psutil.STATUS_ZOMBIE:
463 else: # for older versions of psutil
464 if process.is_running() and process.status != psutil.STATUS_ZOMBIE:
468 def findProcess(name):
469 for proc in psutil.process_iter():
471 pinfo = proc.as_dict(attrs=['pid', 'name'])
472 if pinfo['name'] == name:
474 except psutil.AccessDenied:
477 except psutil.NoSuchProcess:
483 # Trying to close all spawned processes gracefully
484 if isRunning(VPStuff.vlc):
485 if VPStuff.vlcclient:
486 VPStuff.vlcclient.destroy()
488 if isRunning(VPStuff.vlc):
492 # This is what we call to stop the server completely
493 def shutdown(signum = 0, frame = 0):
494 logger.info("Stopping server...")
495 # Closing all client connections
496 for connection in server.RequestHandlerClass.requestlist:
498 # Set errorhappened to prevent waiting for videodestroydelay
499 connection.errorhappened = True
500 connection.closeConnection()
502 logger.warning("Cannot kill a connection!")
504 server.server_close()
507 def _reloadconfig(signum=None, frame=None):
509 Reload configuration file.
514 logger = logging.getLogger('reloadconfig')
516 from vpconfig import VPConfig
517 logger.info('Config reloaded')
519 sched = BackgroundScheduler()
523 VPStuff.vlcclient.clean_streams(VPConfig.videodestroydelay)
525 job = sched.add_job(clean_streams, 'interval', seconds=15)
527 # setting signal handlers
529 gevent.signal(signal.SIGHUP, _reloadconfig)
530 gevent.signal(signal.SIGTERM, shutdown)
531 except AttributeError:
535 VPStuff.vlcProc = VPConfig.vlccmd.split()
536 if spawnVLC(VPStuff.vlcProc, VPConfig.vlcspawntimeout) and connectVLC():
537 logger.info("VLC spawned with pid " + str(VPStuff.vlc.pid))
539 logger.error('Cannot spawn or connect to VLC!')
544 logger.info("Using gevent %s" % gevent.__version__)
545 logger.info("Usig psutil %s" % psutil.__version__)
546 logger.info("Using VLC %s" % VPStuff.vlcclient._vlcver)
547 logger.info("Server started.")
549 if not isRunning(VPStuff.vlc):
551 if spawnVLC(VPStuff.vlcProc, VPConfig.vlcspawntimeout) and connectVLC():
552 logger.info("VLC died, respawned it with pid " + str(VPStuff.vlc.pid))
554 logger.error("Cannot spawn VLC!")
557 # Return to our server tasks
558 server.handle_request()
559 except (KeyboardInterrupt, SystemExit):