summaryrefslogtreecommitdiff
path: root/openvpn/gentoo/openvpn.init
blob: 99fa8b287c2bec7bcc291e4a13772b0c51f8f17e (plain) (blame)
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
#!/sbin/runscript

# OpenVPN start/stop script
# Adapted to Gentoo by James Yonan

# Originally Contributed to the OpenVPN project by
# Douglas Keller <doug@voidstar.dyndns.org>
# 2002.05.15

# This script does the following:
#
# - Starts an openvpn process for each .conf file it finds in
#   /etc/openvpn.
#
# - If /etc/openvpn/xxx.sh exists for a xxx.conf file then it executes
#   it before starting openvpn (useful for doing openvpn --mktun...).

# - In addition to start/stop you can do:
#
#   service openvpn reload - SIGHUP
#   service openvpn reopen - SIGUSR1
#   service openvpn status - SIGUSR2

# Location of openvpn binary
openvpn=/usr/local/sbin/openvpn

# PID directory
piddir=/var/run/openvpn

# Our working directory (.conf files should be here)
work=/etc/openvpn

# Our options
opts="start stop restart condrestart"

depend() {
    need net
    use dns
}

start() {
    ebegin "Starting OpenVPN"

    # Load the TUN/TAP module
    /sbin/modprobe tun >/dev/null 2>&1

    if [ ! -d  $piddir ]; then
	mkdir $piddir
    fi

    cd $work

    # Start every .conf in $work and run .sh if exists
    local errors=0
    local successes=0
    local retstatus=0
    for c in `/bin/ls *.conf 2>/dev/null`; do
	bn=${c%%.conf}
	if [ -f "$bn.sh" ]; then
	    . $bn.sh
	fi
	rm -f $piddir/$bn.pid
	$openvpn --daemon openvpn-$bn --writepid $piddir/$bn.pid --config $c --cd $work
	if [ $? = 0 ]; then
	    successes=1
	else
	    errors=1
	fi
    done

    # Decide status based on errors/successes.
    # If at least one tunnel succeeded, we return success.
    # If some tunnels succeeded and some failed, we return
    #   success but give a warning.
    if [ $successes = 1 ]; then
	if [ $errors = 1 ]; then
	    ewarn "Note: At least one OpenVPN tunnel failed to start"
	fi
    else
	retstatus=1
	if [ $errors = 0 ]; then
	    ewarn "Note: No OpenVPN configuration files were found in $work"
	fi
    fi
    eend $retstatus "Error starting OpenVPN"
}

stop() {
    ebegin "Stopping OpenVPN"
    for pidf in `/bin/ls $piddir/*.pid 2>/dev/null`; do
	if [ -s $pidf ]; then
	    kill `cat $pidf` >/dev/null 2>&1
	fi
	rm -f $pidf
    done
    eend 0
}

# this should really be in runscript.sh
started() {
    if [ -L "${svcdir}/started/${myservice}" ]; then
	return 1
    else
	return 0
    fi
}

# attempt to restart ONLY if we are already started
condrestart() {
    started || restart
}