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