Bug 3106 - Untangle directories
[bgpcep.git] / pcep / impl / src / main / java / org / opendaylight / protocol / pcep / impl / AbstractPCEPSessionNegotiator.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.pcep.impl;
9
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import io.netty.channel.Channel;
13 import io.netty.handler.ssl.SslHandler;
14 import io.netty.util.concurrent.Promise;
15 import java.util.concurrent.Future;
16 import java.util.concurrent.TimeUnit;
17 import java.util.concurrent.TimeoutException;
18 import javax.net.ssl.SSLContext;
19 import javax.net.ssl.SSLEngine;
20 import org.opendaylight.controller.config.yang.pcep.impl.Tls;
21 import org.opendaylight.protocol.framework.AbstractSessionNegotiator;
22 import org.opendaylight.protocol.pcep.impl.spi.Util;
23 import org.opendaylight.protocol.pcep.impl.tls.SslContextFactory;
24 import org.opendaylight.protocol.pcep.spi.PCEPErrors;
25 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Keepalive;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.KeepaliveBuilder;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.OpenBuilder;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Pcerr;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Starttls;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.StarttlsBuilder;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.OpenMessage;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.keepalive.message.KeepaliveMessageBuilder;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.message.OpenMessageBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcep.error.object.ErrorObject;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcerr.message.pcerr.message.error.type.SessionCase;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.start.tls.message.StartTlsMessageBuilder;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * Abstract PCEP session negotiator. Takes care of basic handshake without implementing a specific policy. Policies need
44  * to be provided by a specific subclass.
45  */
46 public abstract class AbstractPCEPSessionNegotiator extends AbstractSessionNegotiator<Message, PCEPSessionImpl> {
47     /**
48      * Unified KeepWait and OpenWait timer expiration, in seconds.
49      */
50     public static final int FAIL_TIMER_VALUE = 60;
51
52     /**
53      * PCEP session negotiation state transitions are described in RFC5440. Simplification the two timers (KeepWait and
54      * OpenWait) are merged into a FailTimer, as they are mutually exclusive, have the same timeout value and their
55      * action is to terminate negotiation. This timer is restarted between state transitions and runs in all states
56      * except Idle and Finished.
57      */
58     @VisibleForTesting
59     public enum State {
60         /**
61          * Negotiation has not begun. It will be activated once we are asked to provide our initial proposal, at which
62          * point we move into OpenWait state.
63          */
64         IDLE,
65         /**
66          * Waiting for the peer's StartTLS message
67          */
68         START_TLS_WAIT,
69         /**
70          * Waiting for the peer's OPEN message.
71          */
72         OPEN_WAIT,
73         /**
74          * Waiting for the peer's KEEPALIVE message.
75          */
76         KEEP_WAIT,
77         /**
78          * Negotiation has completed.
79          */
80         FINISHED,
81     }
82
83     private static final Logger LOG = LoggerFactory.getLogger(AbstractPCEPSessionNegotiator.class);
84     private static final Keepalive KEEPALIVE = new KeepaliveBuilder().setKeepaliveMessage(new KeepaliveMessageBuilder().build()).build();
85
86     private volatile boolean localOK, openRetry, remoteOK;
87     private volatile State state = State.IDLE;
88     private Future<?> failTimer;
89     private Open localPrefs;
90     private Open remotePrefs;
91     private Tls tlsConfiguration;
92
93     protected AbstractPCEPSessionNegotiator(final Promise<PCEPSessionImpl> promise, final Channel channel) {
94         super(promise, channel);
95     }
96
97     /**
98      * Get the initial session parameters proposal.
99      *
100      * @return Session parameters proposal.
101      */
102     protected abstract Open getInitialProposal();
103
104     /**
105      * Get the revised session parameters proposal based on the feedback the peer has provided to us.
106      *
107      * @param suggestion Peer-provided suggested session parameters
108      * @return Session parameters proposal, or null if peers session parameters preclude us from suggesting anything
109      */
110     protected abstract Open getRevisedProposal(Open suggestion);
111
112     /**
113      * Check whether a peer-provided session parameters proposal is acceptable.
114      *
115      * @param proposal peer-proposed session parameters
116      * @return true if the proposal is acceptable, false otherwise
117      */
118     protected abstract boolean isProposalAcceptable(Open proposal);
119
120     /**
121      * Given a peer-provided session parameters proposal which we found unacceptable, provide a counter-proposal. The
122      * requirement is that the isProposalAcceptable() method has to return true when presented with this proposal.
123      *
124      * @param proposal unacceptable peer proposal
125      * @return our counter-proposal, or null if there is no way to negotiate an acceptable proposal
126      */
127     protected abstract Open getCounterProposal(Open proposal);
128
129     /**
130      * Create the protocol session.
131      *
132      * @param channel Underlying channel.
133      * @param localPrefs Session preferences proposed by us and accepted by the peer.
134      * @param remotePrefs Session preferences proposed by the peer and accepted by us.
135      * @return New protocol session.
136      */
137     protected abstract PCEPSessionImpl createSession(Channel channel, Open localPrefs, Open remotePrefs);
138
139     /**
140      * Sends PCEP Error Message with one PCEPError.
141      *
142      * @param value
143      */
144     private void sendErrorMessage(final PCEPErrors value) {
145
146         this.sendMessage(Util.createErrorMessage(value, null));
147     }
148
149     private void scheduleFailTimer() {
150         this.failTimer = this.channel.eventLoop().schedule(new Runnable() {
151             @Override
152             public void run() {
153                 switch (AbstractPCEPSessionNegotiator.this.state) {
154                 case FINISHED:
155                 case IDLE:
156                     break;
157                 case START_TLS_WAIT:
158                     sendErrorMessage(PCEPErrors.STARTTLS_TIMER_EXP);
159                     negotiationFailed(new TimeoutException("StartTLSWait timer expired"));
160                     AbstractPCEPSessionNegotiator.this.state = State.FINISHED;
161                 case KEEP_WAIT:
162                     sendErrorMessage(PCEPErrors.NO_MSG_BEFORE_EXP_KEEPWAIT);
163                     negotiationFailed(new TimeoutException("KeepWait timer expired"));
164                     AbstractPCEPSessionNegotiator.this.state = State.FINISHED;
165                     break;
166                 case OPEN_WAIT:
167                     sendErrorMessage(PCEPErrors.NO_OPEN_BEFORE_EXP_OPENWAIT);
168                     negotiationFailed(new TimeoutException("OpenWait timer expired"));
169                     AbstractPCEPSessionNegotiator.this.state = State.FINISHED;
170                     break;
171                 default:
172                     break;
173                 }
174             }
175         }, FAIL_TIMER_VALUE, TimeUnit.SECONDS);
176     }
177
178     @Override
179     protected final void startNegotiation() {
180         Preconditions.checkState(this.state == State.IDLE);
181         if (this.tlsConfiguration != null) {
182             this.sendMessage(new StarttlsBuilder().setStartTlsMessage(new StartTlsMessageBuilder().build()).build());
183             this.state = State.START_TLS_WAIT;
184             scheduleFailTimer();
185             LOG.info("Started TLS connection negotiation with peer {}", this.channel);
186         } else {
187             startNegotiationWithOpen();
188         }
189     }
190
191     private void startNegotiationWithOpen() {
192         this.localPrefs = getInitialProposal();
193         final OpenMessage m = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.OpenBuilder().setOpenMessage(
194                 new OpenMessageBuilder().setOpen(this.localPrefs).build()).build();
195         this.sendMessage(m);
196         this.state = State.OPEN_WAIT;
197         scheduleFailTimer();
198
199         LOG.info("PCEP session with {} started, sent proposal {}", this.channel, this.localPrefs);
200     }
201
202     private boolean handleMessageKeepWait(final Message msg) {
203         if (msg instanceof Keepalive) {
204             this.localOK = true;
205             if (this.remoteOK) {
206                 LOG.info("PCEP peer {} completed negotiation", this.channel);
207                 negotiationSuccessful(createSession(this.channel, this.localPrefs, this.remotePrefs));
208                 this.state = State.FINISHED;
209             } else {
210                 scheduleFailTimer();
211                 this.state = State.OPEN_WAIT;
212                 LOG.debug("Channel {} moved to OpenWait state with localOK=1", this.channel);
213             }
214             return true;
215         } else if (msg instanceof Pcerr) {
216             final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcerr.message.PcerrMessage err = ((Pcerr) msg).getPcerrMessage();
217             if (err.getErrorType() == null) {
218                 final ErrorObject obj = err.getErrors().get(0).getErrorObject();
219                 LOG.warn("Unexpected error received from PCC: type {} value {}", obj.getType(), obj.getValue());
220                 negotiationFailed(new IllegalStateException("Unexpected error received from PCC."));
221                 this.state = State.IDLE;
222                 return true;
223             }
224             this.localPrefs = getRevisedProposal(((SessionCase) err.getErrorType()).getSession().getOpen());
225             if (this.localPrefs == null) {
226                 sendErrorMessage(PCEPErrors.PCERR_NON_ACC_SESSION_CHAR);
227                 negotiationFailed(new IllegalStateException("Peer suggested unacceptable retry proposal"));
228                 this.state = State.FINISHED;
229                 return true;
230             }
231             this.sendMessage(new OpenBuilder().setOpenMessage(new OpenMessageBuilder().setOpen(this.localPrefs).build()).build());
232             if (!this.remoteOK) {
233                 this.state = State.OPEN_WAIT;
234             }
235             scheduleFailTimer();
236             return true;
237         }
238         return false;
239     }
240
241     private boolean handleMessageOpenWait(final Message msg) {
242         if (!(msg instanceof org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Open)) {
243             return false;
244         }
245         final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.message.OpenMessage o = ((org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Open) msg).getOpenMessage();
246         final Open open = o.getOpen();
247         if (isProposalAcceptable(open)) {
248             this.sendMessage(KEEPALIVE);
249             this.remotePrefs = open;
250             this.remoteOK = true;
251             if (this.localOK) {
252                 negotiationSuccessful(createSession(this.channel, this.localPrefs, this.remotePrefs));
253                 LOG.info("PCEP peer {} completed negotiation", this.channel);
254                 this.state = State.FINISHED;
255             } else {
256                 scheduleFailTimer();
257                 this.state = State.KEEP_WAIT;
258                 LOG.debug("Channel {} moved to KeepWait state with remoteOK=1", this.channel);
259             }
260             return true;
261         }
262         if (this.openRetry) {
263             sendErrorMessage(PCEPErrors.SECOND_OPEN_MSG);
264             negotiationFailed(new IllegalStateException("OPEN renegotiation failed"));
265             this.state = State.FINISHED;
266             return true;
267         }
268         final Open newPrefs = getCounterProposal(open);
269         if (newPrefs == null) {
270             sendErrorMessage(PCEPErrors.NON_ACC_NON_NEG_SESSION_CHAR);
271             negotiationFailed(new IllegalStateException("Peer sent unacceptable session parameters"));
272             this.state = State.FINISHED;
273             return true;
274         }
275         this.sendMessage(Util.createErrorMessage(PCEPErrors.NON_ACC_NEG_SESSION_CHAR, newPrefs));
276         this.openRetry = true;
277         this.state = this.localOK ? State.OPEN_WAIT : State.KEEP_WAIT;
278         scheduleFailTimer();
279         return true;
280     }
281
282     private boolean handleMessageStartTlsWait(final Message msg) {
283         if (msg instanceof Starttls) {
284             final SslContextFactory sslFactory = new SslContextFactory(this.tlsConfiguration);
285             final SSLContext sslContext = sslFactory.getServerContext();
286             if (sslContext == null) {
287                 this.sendErrorMessage(PCEPErrors.NOT_POSSIBLE_WITHOUT_TLS);
288                 negotiationFailed(new IllegalStateException("Failed to establish a TLS connection."));
289                 this.state = State.FINISHED;
290                 return true;
291             }
292             final SSLEngine engine = sslContext.createSSLEngine();
293             engine.setNeedClientAuth(true);
294             engine.setUseClientMode(false);
295             this.channel.pipeline().addFirst(new SslHandler(engine));
296             LOG.info("PCEPS TLS connection with peer: {} established succesfully.", this.channel);
297             startNegotiationWithOpen();
298             return true;
299         } else if (! (msg instanceof Pcerr)) {
300             this.sendErrorMessage(PCEPErrors.NON_STARTTLS_MSG_RCVD);
301             negotiationFailed(new IllegalStateException("Unexpected message recieved."));
302             this.state = State.FINISHED;
303             return true;
304         }
305         return false;
306     }
307
308     @Override
309     protected final void handleMessage(final Message msg) {
310         this.failTimer.cancel(false);
311
312         LOG.debug("Channel {} handling message {} in state {}", this.channel, msg, this.state);
313
314         switch (this.state) {
315         case FINISHED:
316         case IDLE:
317             throw new IllegalStateException("Unexpected handleMessage in state " + this.state);
318         case START_TLS_WAIT:
319             if (handleMessageStartTlsWait(msg)) {
320                 return;
321             }
322             break;
323         case KEEP_WAIT:
324             if (handleMessageKeepWait(msg)) {
325                 return;
326             }
327             break;
328         case OPEN_WAIT:
329             if (handleMessageOpenWait(msg)) {
330                 return;
331             }
332             break;
333         default:
334             break;
335         }
336         LOG.warn("Channel {} in state {} received unexpected message {}", this.channel, this.state, msg);
337         sendErrorMessage(PCEPErrors.NON_OR_INVALID_OPEN_MSG);
338         negotiationFailed(new Exception("Illegal message encountered"));
339         this.state = State.FINISHED;
340     }
341
342     @VisibleForTesting
343     State getState() {
344         return this.state;
345     }
346
347     public void setTlsConfiguration(final Tls tlsConfiguration) {
348         this.tlsConfiguration = tlsConfiguration;
349     }
350 }