Add custom EXI buffer management
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / NetconfEXICodec.java
1 /*
2  * Copyright (c) 2014, 2015 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.netconf.nettyutil.handler;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.cache.CacheBuilder;
13 import com.google.common.cache.CacheLoader;
14 import com.google.common.cache.LoadingCache;
15 import org.opendaylight.netconf.nettyutil.handler.exi.EXIParameters;
16 import org.opendaylight.netconf.shaded.exificient.core.EXIFactory;
17 import org.opendaylight.netconf.shaded.exificient.core.exceptions.EXIException;
18 import org.opendaylight.netconf.shaded.exificient.main.api.sax.SAXEncoder;
19 import org.xml.sax.EntityResolver;
20 import org.xml.sax.InputSource;
21
22 public final class NetconfEXICodec {
23     /**
24      * OpenEXI does not allow us to directly prevent resolution of external entities. In order
25      * to prevent XXE attacks, we reuse a single no-op entity resolver.
26      */
27     private static final EntityResolver ENTITY_RESOLVER = (publicId, systemId) -> new InputSource();
28
29     /**
30      * Since we have a limited number of options we can have, instantiating a weak cache
31      * will allow us to reuse instances where possible.
32      */
33     private static final LoadingCache<EXIParameters, NetconfEXICodec> CODECS =
34             CacheBuilder.newBuilder().weakValues().build(new CacheLoader<EXIParameters, NetconfEXICodec>() {
35                 @Override
36                 public NetconfEXICodec load(final EXIParameters key) {
37                     return new NetconfEXICodec(key.getFactory());
38                 }
39             });
40
41     private final ThreadLocalSAXFactory exiFactory;
42
43     private NetconfEXICodec(final EXIFactory exiFactory) {
44         this.exiFactory = new ThreadLocalSAXFactory(requireNonNull(exiFactory));
45     }
46
47     public static NetconfEXICodec forParameters(final EXIParameters parameters) {
48         return CODECS.getUnchecked(parameters);
49     }
50
51     ThreadLocalSAXDecoder getReader() throws EXIException {
52         final ThreadLocalSAXDecoder reader = exiFactory.createEXIReader();
53         reader.setEntityResolver(ENTITY_RESOLVER);
54         return reader;
55     }
56
57     SAXEncoder getWriter() throws EXIException {
58         return exiFactory.createEXIWriter();
59     }
60 }