]> git.basschouten.com Git - openhab-addons.git/blob
86e223feb38f9f314e8692b7b2b130712b6d3b47
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.snmp.internal;
14
15 import java.io.IOException;
16 import java.util.ArrayList;
17 import java.util.HashSet;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Set;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.binding.snmp.internal.config.SnmpServiceConfiguration;
25 import org.openhab.binding.snmp.internal.types.SnmpAuthProtocol;
26 import org.openhab.binding.snmp.internal.types.SnmpPrivProtocol;
27 import org.openhab.core.config.core.Configuration;
28 import org.osgi.service.component.annotations.Activate;
29 import org.osgi.service.component.annotations.Component;
30 import org.osgi.service.component.annotations.Deactivate;
31 import org.osgi.service.component.annotations.Modified;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.snmp4j.CommandResponder;
35 import org.snmp4j.PDU;
36 import org.snmp4j.Snmp;
37 import org.snmp4j.Target;
38 import org.snmp4j.event.ResponseListener;
39 import org.snmp4j.mp.MPv3;
40 import org.snmp4j.security.Priv3DES;
41 import org.snmp4j.security.SecurityModels;
42 import org.snmp4j.security.SecurityProtocols;
43 import org.snmp4j.security.USM;
44 import org.snmp4j.security.UsmUser;
45 import org.snmp4j.smi.OctetString;
46 import org.snmp4j.smi.UdpAddress;
47 import org.snmp4j.transport.DefaultUdpTransportMapping;
48
49 /**
50  * The {@link SnmpServiceImpl} implements SnmpService
51  * handlers.
52  *
53  * @author Jan N. Klug - Initial contribution
54  */
55
56 @NonNullByDefault
57 @Component(configurationPid = "binding.snmp", service = SnmpService.class)
58 public class SnmpServiceImpl implements SnmpService {
59     private final Logger logger = LoggerFactory.getLogger(SnmpServiceImpl.class);
60
61     private @NonNullByDefault({}) SnmpServiceConfiguration config;
62     private @Nullable Snmp snmp;
63     private @Nullable DefaultUdpTransportMapping transport;
64
65     private final List<CommandResponder> listeners = new ArrayList<>();
66     private final Set<UserEntry> userEntries = new HashSet<>();
67
68     @Activate
69     public SnmpServiceImpl(Map<String, Object> config) {
70         SecurityProtocols.getInstance().addDefaultProtocols();
71         SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());
72
73         OctetString localEngineId = new OctetString(MPv3.createLocalEngineID());
74         USM usm = new USM(SecurityProtocols.getInstance(), localEngineId, 0);
75         SecurityModels.getInstance().addSecurityModel(usm);
76
77         modified(config);
78     }
79
80     @Modified
81     protected void modified(Map<String, Object> config) {
82         this.config = new Configuration(config).as(SnmpServiceConfiguration.class);
83         try {
84             shutdownSnmp();
85
86             final DefaultUdpTransportMapping transport;
87
88             if (this.config.port > 0) {
89                 transport = new DefaultUdpTransportMapping(new UdpAddress(this.config.port), true);
90             } else {
91                 transport = new DefaultUdpTransportMapping();
92             }
93
94             SecurityProtocols.getInstance().addDefaultProtocols();
95             SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());
96
97             final Snmp snmp = new Snmp(transport);
98             listeners.forEach(snmp::addCommandResponder);
99             snmp.listen();
100
101             // re-add user entries
102             userEntries.forEach(u -> addUser(snmp, u));
103
104             this.snmp = snmp;
105             this.transport = transport;
106
107             logger.debug("initialized SNMP at {}", transport.getAddress());
108         } catch (IOException e) {
109             logger.warn("could not open SNMP instance on port {}: {}", this.config.port, e.getMessage());
110         }
111     }
112
113     @SuppressWarnings("unused")
114     @Deactivate
115     public void deactivate() {
116         try {
117             shutdownSnmp();
118         } catch (IOException e) {
119             logger.info("could not end SNMP: {}", e.getMessage());
120         }
121     }
122
123     private void shutdownSnmp() throws IOException {
124         DefaultUdpTransportMapping transport = this.transport;
125         if (transport != null) {
126             transport.close();
127             this.transport = null;
128         }
129         Snmp snmp = this.snmp;
130         if (snmp != null) {
131             snmp.close();
132             this.snmp = null;
133         }
134     }
135
136     @Override
137     public void addCommandResponder(CommandResponder listener) {
138         Snmp snmp = this.snmp;
139         if (snmp != null) {
140             snmp.addCommandResponder(listener);
141         }
142         listeners.add(listener);
143     }
144
145     @Override
146     public void removeCommandResponder(CommandResponder listener) {
147         Snmp snmp = this.snmp;
148         if (snmp != null) {
149             snmp.removeCommandResponder(listener);
150         }
151         listeners.remove(listener);
152     }
153
154     @Override
155     public void send(PDU pdu, Target target, @Nullable Object userHandle, ResponseListener listener)
156             throws IOException {
157         Snmp snmp = this.snmp;
158         if (snmp != null) {
159             snmp.send(pdu, target, userHandle, listener);
160             logger.trace("send {} to {}", pdu, target);
161         } else {
162             logger.warn("SNMP service not initialized, can't send {} to {}", pdu, target);
163         }
164     }
165
166     @Override
167     public void addUser(String userName, SnmpAuthProtocol snmpAuthProtocol, @Nullable String authPassphrase,
168             SnmpPrivProtocol snmpPrivProtocol, @Nullable String privPassphrase, byte[] engineId) {
169         UsmUser usmUser = new UsmUser(new OctetString(userName),
170                 authPassphrase != null ? snmpAuthProtocol.getOid() : null,
171                 authPassphrase != null ? new OctetString(authPassphrase) : null,
172                 privPassphrase != null ? snmpPrivProtocol.getOid() : null,
173                 privPassphrase != null ? new OctetString(privPassphrase) : null);
174         OctetString securityNameOctets = new OctetString(userName);
175
176         UserEntry userEntry = new UserEntry(securityNameOctets, new OctetString(engineId), usmUser);
177         userEntries.add(userEntry);
178
179         Snmp snmp = this.snmp;
180         if (snmp != null) {
181             addUser(snmp, userEntry);
182         }
183     }
184
185     private static void addUser(Snmp snmp, UserEntry userEntry) {
186         snmp.getUSM().addUser(userEntry.securityName, userEntry.engineId, userEntry.user);
187     }
188
189     private static class UserEntry {
190         public OctetString securityName;
191         public OctetString engineId;
192         public UsmUser user;
193
194         public UserEntry(OctetString securityName, OctetString engineId, UsmUser user) {
195             this.securityName = securityName;
196             this.engineId = engineId;
197             this.user = user;
198         }
199     }
200 }