2 * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.netconf.nettyutil.handler;
11 import static java.util.Objects.requireNonNull;
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;
25 public final class NetconfEXICodec {
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.
30 private static final EntityResolver ENTITY_RESOLVER = (publicId, systemId) -> new InputSource();
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.
36 private static final LoadingCache<EXIParameters, NetconfEXICodec> CODECS =
37 CacheBuilder.newBuilder().weakValues().build(new CacheLoader<EXIParameters, NetconfEXICodec>() {
39 public NetconfEXICodec load(final EXIParameters key) {
40 return new NetconfEXICodec(key.getFactory());
44 private final SAXFactory exiFactory;
46 private NetconfEXICodec(final EXIFactory exiFactory) {
47 this.exiFactory = new SAXFactory(requireNonNull(exiFactory));
50 public static NetconfEXICodec forParameters(final EXIParameters parameters) {
51 return CODECS.getUnchecked(parameters);
54 XMLReader getReader() throws EXIException {
55 final XMLReader reader = exiFactory.createEXIReader();
56 reader.setEntityResolver(ENTITY_RESOLVER);
60 SAXEncoder getWriter() throws EXIException {
61 final SAXEncoder writer = exiFactory.createEXIWriter();