Merge "Fix NodeServlet Vulnerabilities"
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / PublishServlet.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
4  * * ===========================================================================
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * * ===========================================================================
7  * * Licensed under the Apache License, Version 2.0 (the "License");
8  * * you may not use this file except in compliance with the License.
9  * * You may obtain a copy of the License at
10  * *
11  *  *      http://www.apache.org/licenses/LICENSE-2.0
12  * *
13  *  * Unless required by applicable law or agreed to in writing, software
14  * * distributed under the License is distributed on an "AS IS" BASIS,
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * * See the License for the specific language governing permissions and
17  * * limitations under the License.
18  * * ============LICENSE_END====================================================
19  * *
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23
24
25 package org.onap.dmaap.datarouter.provisioning;
26
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.List;
32 import java.util.Properties;
33
34 import javax.servlet.ServletConfig;
35 import javax.servlet.ServletException;
36 import javax.servlet.http.HttpServletRequest;
37 import javax.servlet.http.HttpServletResponse;
38
39 import org.json.JSONArray;
40 import org.json.JSONObject;
41 import org.json.JSONTokener;
42 import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;
43 import org.onap.dmaap.datarouter.provisioning.beans.Feed;
44 import org.onap.dmaap.datarouter.provisioning.beans.IngressRoute;
45 import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;
46 import org.onap.dmaap.datarouter.provisioning.utils.*;
47
48 import com.att.eelf.configuration.EELFLogger;
49 import com.att.eelf.configuration.EELFManager;
50
51 /**
52  * This servlet handles redirects for the <publishURL> on the provisioning server,
53  * which is generated by the provisioning server to handle a particular subscriptions to a feed.
54  * See the <b>File Publishing and Delivery API</b> document for details on how these methods
55  * should be invoked.
56  *
57  * @author Robert Eby
58  * @version $Id: PublishServlet.java,v 1.8 2014/03/12 19:45:41 eby Exp $
59  */
60 @SuppressWarnings("serial")
61 public class PublishServlet extends BaseServlet {
62     private int next_node;
63     private String provstring;
64     private List<IngressRoute> irt;
65     //Adding EELF Logger Rally:US664892
66     private static EELFLogger eelflogger = EELFManager.getInstance().getLogger("org.onap.dmaap.datarouter.provisioning.PublishServlet");
67     private static final Object lock = new Object();
68
69
70     @Override
71     public void init(ServletConfig config) throws ServletException {
72         super.init(config);
73         next_node = 0;
74         provstring = "";
75         irt = new ArrayList<IngressRoute>();
76
77     }
78     @Override
79     public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
80         setIpAndFqdnForEelf("doDelete");
81         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
82         redirect(req, resp);
83     }
84     @Override
85     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
86         setIpAndFqdnForEelf("doGet");
87         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
88         redirect(req, resp);
89     }
90     @Override
91     public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
92         setIpAndFqdnForEelf("doPut");
93         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
94         redirect(req, resp);
95     }
96     @Override
97     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
98         setIpAndFqdnForEelf("doPost");
99         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));
100         redirect(req, resp);
101     }
102     private void redirect(HttpServletRequest req, HttpServletResponse resp) throws IOException {
103         String[] nodes = getNodes();
104         if (nodes == null || nodes.length == 0) {
105             resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "There are no nodes defined in the DR network.");
106         } else {
107             EventLogRecord elr = new EventLogRecord(req);
108             int feedid = checkPath(req);
109             if (feedid < 0) {
110                 String message = (feedid == -1)
111                     ? "Invalid request - Missing or bad feed number."
112                     : "Invalid request - Missing file ID.";
113                 elr.setMessage(message);
114                 elr.setResult(HttpServletResponse.SC_NOT_FOUND);
115                 eventlogger.info(elr);
116
117                 resp.sendError(HttpServletResponse.SC_NOT_FOUND, message);
118             } else {
119                 // Generate new URL
120                 String nextnode = getRedirectNode(feedid, req);
121                 nextnode = nextnode+":"+DB.HTTPS_PORT;
122                 String newurl = "https://" + nextnode + "/publish" + req.getPathInfo();
123                 String qs = req.getQueryString();
124                 if (qs != null)
125                     newurl += "?" + qs;
126
127                 // Log redirect in event log
128                 String message = "Redirected to: "+newurl;
129                 elr.setMessage(message);
130                 elr.setResult(HttpServletResponse.SC_MOVED_PERMANENTLY);
131                 eventlogger.info(elr);
132
133                 resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
134                 resp.setHeader("Location", newurl);
135             }
136         }
137     }
138     private String getRedirectNode(int feedid, HttpServletRequest req) {
139         // Check to see if the IRT needs to be updated
140         Poker p = Poker.getPoker();
141         String s = p.getProvisioningString();
142         synchronized (lock) {
143             if (irt == null || (s.length() != provstring.length()) || !s.equals(provstring)) {
144                 // Provisioning string has changed -- update the IRT
145                 provstring = s;
146                 JSONObject jo = new JSONObject(new JSONTokener(provstring));
147                 JSONArray ja = jo.getJSONArray("ingress");
148                 List<IngressRoute> newlist = new ArrayList<IngressRoute>();
149                 for (int i = 0; i < ja.length(); i++) {
150                     IngressRoute iroute = new IngressRoute(ja.getJSONObject(i));
151                     newlist.add(iroute);
152                 }
153                 irt = newlist;
154             }
155         }
156
157         // Look in IRT for next node
158         for (IngressRoute route : irt) {
159             if (route.matches(feedid, req)) {
160                 // pick a node at random from the list
161                 Collection<String> nodes = route.getNodes();
162                 String[] arr = nodes.toArray(new String[0]);
163                 long id = System.currentTimeMillis() % arr.length;
164                 String node = arr[(int) id];
165                 intlogger.info("Redirecting to "+node+" because of route "+route);
166                 return node;
167             }
168         }
169
170         // No IRT rule matches, do round robin of all active nodes
171         String[] nodes = getNodes();
172         if (next_node >= nodes.length)    // The list of nodes may have grown/shrunk
173             next_node = 0;
174         return nodes[next_node++];
175     }
176     private int checkPath(HttpServletRequest req) {
177         String path = req.getPathInfo();
178         if (path == null || path.length() < 2)
179             return -1;
180         path = path.substring(1);
181         int ix = path.indexOf('/');
182         if (ix < 0 || ix == path.length()-1)
183             return -2;
184         try {
185             int feedid = Integer.parseInt(path.substring(0, ix));
186             if (!Feed.isFeedValid(feedid))
187                 return -1;
188             return feedid;
189         } catch (NumberFormatException e) {
190             return -1;
191         }
192     }
193 }