Merge "Fix Main 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.util.ArrayList;
29 import java.util.Collection;
30 import java.util.List;
31
32 import javax.servlet.ServletConfig;
33 import javax.servlet.ServletException;
34 import javax.servlet.http.HttpServletRequest;
35 import javax.servlet.http.HttpServletResponse;
36
37 import org.json.JSONArray;
38 import org.json.JSONObject;
39 import org.json.JSONTokener;
40 import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;
41 import org.onap.dmaap.datarouter.provisioning.beans.Feed;
42 import org.onap.dmaap.datarouter.provisioning.beans.IngressRoute;
43 import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;
44 import org.onap.dmaap.datarouter.provisioning.utils.*;
45
46 import com.att.eelf.configuration.EELFLogger;
47 import com.att.eelf.configuration.EELFManager;
48
49 /**
50  * This servlet handles redirects for the <publishURL> on the provisioning server,
51  * which is generated by the provisioning server to handle a particular subscriptions to a feed.
52  * See the <b>File Publishing and Delivery API</b> document for details on how these methods
53  * should be invoked.
54  *
55  * @author Robert Eby
56  * @version $Id: PublishServlet.java,v 1.8 2014/03/12 19:45:41 eby Exp $
57  */
58 @SuppressWarnings("serial")
59 public class PublishServlet extends BaseServlet {
60     private int next_node;
61     private String provstring;
62     private List<IngressRoute> irt;
63     //Adding EELF Logger Rally:US664892
64     private static EELFLogger eelflogger = EELFManager.getInstance().getLogger("org.onap.dmaap.datarouter.provisioning.PublishServlet");
65     private static final Object lock = new Object();
66
67
68     @Override
69     public void init(ServletConfig config) throws ServletException {
70         super.init(config);
71         next_node = 0;
72         provstring = "";
73         irt = new ArrayList<IngressRoute>();
74
75     }
76     @Override
77     public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
78         setIpAndFqdnForEelf("doDelete");
79         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
80         redirect(req, resp);
81     }
82     @Override
83     public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
84         setIpAndFqdnForEelf("doGet");
85         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
86         redirect(req, resp);
87     }
88     @Override
89     public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
90         setIpAndFqdnForEelf("doPut");
91         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
92         redirect(req, resp);
93     }
94     @Override
95     public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
96         setIpAndFqdnForEelf("doPost");
97         eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));
98         redirect(req, resp);
99
100     }
101     private void redirect(HttpServletRequest req, HttpServletResponse resp)  {
102         try {
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         } catch (IOException ioe) {
138             intlogger.error("IOException" + ioe.getMessage());
139
140         }
141     }
142     private String getRedirectNode(int feedid, HttpServletRequest req) {
143         // Check to see if the IRT needs to be updated
144         Poker p = Poker.getPoker();
145         String s = p.getProvisioningString();
146         synchronized (lock) {
147             if (irt == null || (s.length() != provstring.length()) || !s.equals(provstring)) {
148                 // Provisioning string has changed -- update the IRT
149                 provstring = s;
150                 JSONObject jo = new JSONObject(new JSONTokener(provstring));
151                 JSONArray ja = jo.getJSONArray("ingress");
152                 List<IngressRoute> newlist = new ArrayList<IngressRoute>();
153                 for (int i = 0; i < ja.length(); i++) {
154                     IngressRoute iroute = new IngressRoute(ja.getJSONObject(i));
155                     newlist.add(iroute);
156                 }
157                 irt = newlist;
158             }
159         }
160
161         // Look in IRT for next node
162         for (IngressRoute route : irt) {
163             if (route.matches(feedid, req)) {
164                 // pick a node at random from the list
165                 Collection<String> nodes = route.getNodes();
166                 String[] arr = nodes.toArray(new String[0]);
167                 long id = System.currentTimeMillis() % arr.length;
168                 String node = arr[(int) id];
169                 intlogger.info("Redirecting to "+node+" because of route "+route);
170                 return node;
171             }
172         }
173
174         // No IRT rule matches, do round robin of all active nodes
175         String[] nodes = getNodes();
176         if (next_node >= nodes.length)    // The list of nodes may have grown/shrunk
177             next_node = 0;
178         return nodes[next_node++];
179     }
180     private int checkPath(HttpServletRequest req) {
181         String path = req.getPathInfo();
182         if (path == null || path.length() < 2)
183             return -1;
184         path = path.substring(1);
185         int ix = path.indexOf('/');
186         if (ix < 0 || ix == path.length()-1)
187             return -2;
188         try {
189             int feedid = Integer.parseInt(path.substring(0, ix));
190             if (!Feed.isFeedValid(feedid))
191                 return -1;
192             return feedid;
193         } catch (NumberFormatException e) {
194             return -1;
195         }
196     }
197 }