1#!/usr/bin/env python
2#
3# BitBake Toaster Implementation
4#
5# Copyright (C) 2015 Intel Corporation
6#
7# SPDX-License-Identifier: GPL-2.0-only
8#
9
10"""Custom management command checksocket."""
11
12import errno
13import socket
14
15from django.core.management.base import BaseCommand, CommandError
16from django.utils.encoding import force_text
17
18DEFAULT_ADDRPORT = "0.0.0.0:8000"
19
20class Command(BaseCommand):
21    """Custom management command."""
22
23    help = 'Check if Toaster can listen on address:port'
24
25    def add_arguments(self, parser):
26        parser.add_argument('addrport', nargs='?', default=DEFAULT_ADDRPORT,
27                            help='ipaddr:port to check, %s by default' % \
28                                 DEFAULT_ADDRPORT)
29
30    def handle(self, *args, **options):
31        addrport = options['addrport']
32        if ':' not in addrport:
33            raise CommandError('Invalid addr:port specified: %s' % addrport)
34        splitted = addrport.split(':')
35        try:
36            splitted[1] = int(splitted[1])
37        except ValueError:
38            raise CommandError('Invalid port specified: %s' % splitted[1])
39        self.stdout.write('Check if toaster can listen on %s' % addrport)
40        try:
41            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
42            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
43            sock.bind(tuple(splitted))
44        except (socket.error, OverflowError) as err:
45            errors = {
46                errno.EACCES: 'You don\'t have permission to access port %s' \
47                              % splitted[1],
48                errno.EADDRINUSE: 'Port %s is already in use' % splitted[1],
49                errno.EADDRNOTAVAIL: 'IP address can\'t be assigned to',
50            }
51            if hasattr(err, 'errno') and err.errno in errors:
52                errtext = errors[err.errno]
53            else:
54                errtext = force_text(err)
55            raise CommandError(errtext)
56
57        self.stdout.write("OK")
58