backing up
[vsorcdistro/.git] / ryu / build / lib.linux-armv7l-2.7 / ryu / lib / snortlib.py
1 # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16
17 import os
18 import logging
19 import six
20
21 from ryu.lib import hub, alert
22 from ryu.base import app_manager
23 from ryu.controller import event
24
25
26 BUFSIZE = alert.AlertPkt._ALERTPKT_SIZE
27 SOCKFILE = "/tmp/snort_alert"
28
29
30 class EventAlert(event.EventBase):
31     def __init__(self, msg):
32         super(EventAlert, self).__init__()
33         self.msg = msg
34
35
36 class SnortLib(app_manager.RyuApp):
37
38     def __init__(self):
39         super(SnortLib, self).__init__()
40         self.name = 'snortlib'
41         self.config = {'unixsock': True}
42         self._set_logger()
43         self.sock = None
44         self.nwsock = None
45
46     def set_config(self, config):
47         assert isinstance(config, dict)
48         self.config = config
49
50     def start_socket_server(self):
51         if not self.config.get('unixsock'):
52
53             if self.config.get('port') is None:
54                 self.config['port'] = 51234
55
56             self._start_recv_nw_sock(self.config.get('port'))
57         else:
58             self._start_recv()
59
60         self.logger.info(self.config)
61
62     def _recv_loop(self):
63         self.logger.info("Unix socket start listening...")
64         while True:
65             data = self.sock.recv(BUFSIZE)
66             msg = alert.AlertPkt.parser(data)
67             if msg:
68                 self.send_event_to_observers(EventAlert(msg))
69
70     def _start_recv(self):
71         if os.path.exists(SOCKFILE):
72             os.unlink(SOCKFILE)
73
74         self.sock = hub.socket.socket(hub.socket.AF_UNIX,
75                                       hub.socket.SOCK_DGRAM)
76         self.sock.bind(SOCKFILE)
77         hub.spawn(self._recv_loop)
78
79     def _start_recv_nw_sock(self, port):
80
81         self.nwsock = hub.socket.socket(hub.socket.AF_INET,
82                                         hub.socket.SOCK_STREAM)
83         self.nwsock.setsockopt(hub.socket.SOL_SOCKET,
84                                hub.socket.SO_REUSEADDR, 1)
85         self.nwsock.bind(('0.0.0.0', port))
86         self.nwsock.listen(5)
87
88         hub.spawn(self._accept_loop_nw_sock)
89
90     def _accept_loop_nw_sock(self):
91         self.logger.info("Network socket server start listening...")
92         while True:
93             conn, addr = self.nwsock.accept()
94             self.logger.info("Connected with %s", addr[0])
95             hub.spawn(self._recv_loop_nw_sock, conn, addr)
96
97     def _recv_loop_nw_sock(self, conn, addr):
98         buf = six.binary_type()
99         while True:
100             ret = conn.recv(BUFSIZE)
101             if len(ret) == 0:
102                 self.logger.info("Disconnected from %s", addr[0])
103                 break
104
105             buf += ret
106             while len(buf) >= BUFSIZE:
107                 # self.logger.debug("Received buffer size: %d", len(buf))
108                 data = buf[:BUFSIZE]
109                 msg = alert.AlertPkt.parser(data)
110                 if msg:
111                     self.send_event_to_observers(EventAlert(msg))
112                 buf = buf[BUFSIZE:]
113
114     def _set_logger(self):
115         """change log format."""
116         self.logger.propagate = False
117         hdl = logging.StreamHandler()
118         fmt_str = '[snort][%(levelname)s] %(message)s'
119         hdl.setFormatter(logging.Formatter(fmt_str))
120         self.logger.addHandler(hdl)