Fix menu exploding (so that we don't need the id's anymore)
[gigi.git] / src / org / cacert / gigi / Gigi.java
1 package org.cacert.gigi;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5 import java.util.Calendar;
6 import java.util.HashMap;
7 import java.util.LinkedList;
8 import java.util.Map;
9 import java.util.Properties;
10
11 import javax.servlet.ServletException;
12 import javax.servlet.http.HttpServlet;
13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpServletResponse;
15 import javax.servlet.http.HttpSession;
16
17 import org.cacert.gigi.database.DatabaseConnection;
18 import org.cacert.gigi.localisation.Language;
19 import org.cacert.gigi.output.Form.CSRFException;
20 import org.cacert.gigi.output.Menu;
21 import org.cacert.gigi.output.Outputable;
22 import org.cacert.gigi.output.PageMenuItem;
23 import org.cacert.gigi.output.template.Template;
24 import org.cacert.gigi.pages.LoginPage;
25 import org.cacert.gigi.pages.MainPage;
26 import org.cacert.gigi.pages.Page;
27 import org.cacert.gigi.pages.TestSecure;
28 import org.cacert.gigi.pages.Verify;
29 import org.cacert.gigi.pages.account.CertificateAdd;
30 import org.cacert.gigi.pages.account.Certificates;
31 import org.cacert.gigi.pages.account.ChangePasswordPage;
32 import org.cacert.gigi.pages.account.DomainOverview;
33 import org.cacert.gigi.pages.account.MailOverview;
34 import org.cacert.gigi.pages.account.MyDetails;
35 import org.cacert.gigi.pages.error.PageNotFound;
36 import org.cacert.gigi.pages.main.RegisterPage;
37 import org.cacert.gigi.pages.wot.AssurePage;
38 import org.cacert.gigi.util.ServerConstants;
39
40 public class Gigi extends HttpServlet {
41
42     private boolean firstInstanceInited = false;
43
44     public static final String LOGGEDIN = "loggedin";
45
46     public static final String USER = "user";
47
48     private static final long serialVersionUID = -6386785421902852904L;
49
50     private Template baseTemplate;
51
52     private LinkedList<Menu> categories = new LinkedList<Menu>();
53
54     private HashMap<String, Page> pages = new HashMap<String, Page>();
55
56     private HashMap<Page, String> reveresePages = new HashMap<Page, String>();
57
58     private Menu rootMenu;
59
60     private static Gigi instance;
61
62     public Gigi(Properties conf) {
63         if (instance != null) {
64             new IllegalStateException("Multiple Gigi instances!");
65         }
66         instance = this;
67         DatabaseConnection.init(conf);
68     }
69
70     @Override
71     public void init() throws ServletException {
72         if ( !firstInstanceInited) {
73             putPage("/error", new PageNotFound(), null);
74             putPage("/login", new LoginPage("CACert - Login"), "Join CAcert.org");
75             putPage("/", new MainPage("CACert - Home"), null);
76             putPage(ChangePasswordPage.PATH, new ChangePasswordPage(), "My Account");
77             putPage("/secure", new TestSecure(), null);
78             putPage(Verify.PATH, new Verify(), null);
79             putPage(AssurePage.PATH + "/*", new AssurePage(), "CAcert Web of Trust");
80             putPage(Certificates.PATH + "/*", new Certificates(), "Certificates");
81             putPage(MyDetails.PATH, new MyDetails(), "My Account");
82             putPage(RegisterPage.PATH, new RegisterPage(), "Join CAcert.org");
83             putPage(CertificateAdd.PATH, new CertificateAdd(), "Certificates");
84             putPage(MailOverview.DEFAULT_PATH, new MailOverview("My email addresses"), "Certificates");
85             putPage(DomainOverview.PATH, new DomainOverview("Domains"), "Certificates");
86             baseTemplate = new Template(Gigi.class.getResource("Gigi.templ"));
87             rootMenu = new Menu("Main");
88             for (Menu menu : categories) {
89                 menu.prepare();
90                 rootMenu.addItem(menu);
91             }
92             rootMenu.prepare();
93             firstInstanceInited = true;
94         }
95         super.init();
96     }
97
98     private void putPage(String path, Page p, String category) {
99         pages.put(path, p);
100         reveresePages.put(p, path);
101         if (category == null) {
102             return;
103         }
104         Menu m = null;
105         for (Menu menu : categories) {
106             if (menu.getMenuName().equals(category)) {
107                 m = menu;
108                 break;
109             }
110         }
111         if (m == null) {
112             m = new Menu(category);
113             categories.add(m);
114         }
115         m.addItem(new PageMenuItem(p));
116
117     }
118
119     @Override
120     protected void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
121         addXSSHeaders(resp);
122         // if (req.getHeader("Origin") != null) {
123         // resp.getWriter().println("No cross domain access allowed.");
124         // return;
125         // }
126         HttpSession hs = req.getSession();
127         if (req.getPathInfo() != null && req.getPathInfo().equals("/logout")) {
128             if (hs != null) {
129                 hs.setAttribute(LOGGEDIN, null);
130                 hs.invalidate();
131             }
132             resp.sendRedirect("/");
133             return;
134         }
135
136         final Page p = getPage(req.getPathInfo());
137         if (p != null) {
138
139             User currentPageUser = LoginPage.getUser(req);
140             if ( !p.isPermitted(currentPageUser) && hs.getAttribute("loggedin") == null) {
141                 String request = req.getPathInfo();
142                 request = request.split("\\?")[0];
143                 hs.setAttribute(LoginPage.LOGIN_RETURNPATH, request);
144                 resp.sendRedirect("/login");
145                 return;
146             }
147             if (p.beforeTemplate(req, resp)) {
148                 return;
149             }
150             HashMap<String, Object> vars = new HashMap<String, Object>();
151
152             resp.setContentType("text/html; charset=utf-8");
153             Outputable content = new Outputable() {
154
155                 @Override
156                 public void output(PrintWriter out, Language l, Map<String, Object> vars) {
157                     try {
158                         if (req.getMethod().equals("POST")) {
159                             if (req.getQueryString() != null) {
160                                 return;
161                             }
162                             p.doPost(req, resp);
163                         } else {
164                             p.doGet(req, resp);
165                         }
166                     } catch (CSRFException err) {
167                         try {
168                             resp.sendError(500, "CSRF invalid");
169                         } catch (IOException e) {
170                             e.printStackTrace();
171                         }
172                     } catch (IOException e) {
173                         e.printStackTrace();
174                     }
175
176                 }
177             };
178             vars.put(Menu.USER_VALUE, currentPageUser);
179             vars.put("menu", rootMenu);
180             vars.put("title", p.getTitle());
181             vars.put("static", ServerConstants.getStaticHostNamePort());
182             vars.put("year", Calendar.getInstance().get(Calendar.YEAR));
183             vars.put("content", content);
184             baseTemplate.output(resp.getWriter(), Page.getLanguage(req), vars);
185         } else {
186             resp.sendError(404, "Page not found.");
187         }
188
189     }
190
191     private Page getPage(String pathInfo) {
192         if (pathInfo.endsWith("/") && !pathInfo.equals("/")) {
193             pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
194         }
195         Page page = pages.get(pathInfo);
196         if (page != null) {
197             return page;
198         }
199         page = pages.get(pathInfo + "/*");
200         if (page != null) {
201             return page;
202         }
203         int idx = pathInfo.lastIndexOf('/');
204         pathInfo = pathInfo.substring(0, idx);
205
206         page = pages.get(pathInfo + "/*");
207         if (page != null) {
208             return page;
209         }
210         return null;
211
212     }
213
214     public static void addXSSHeaders(HttpServletResponse hsr) {
215         hsr.addHeader("Access-Control-Allow-Origin", "https://" + ServerConstants.getWwwHostNamePort() + " https://" + ServerConstants.getSecureHostNamePort());
216         hsr.addHeader("Access-Control-Max-Age", "60");
217
218         hsr.addHeader("Content-Security-Policy", getDefaultCSP());
219         hsr.addHeader("Strict-Transport-Security", "max-age=31536000");
220
221     }
222
223     private static String defaultCSP = null;
224
225     private static String getDefaultCSP() {
226         if (defaultCSP == null) {
227             StringBuffer csp = new StringBuffer();
228             csp.append("default-src 'none';");
229             csp.append("font-src https://" + ServerConstants.getStaticHostNamePort());
230             csp.append(";img-src https://" + ServerConstants.getStaticHostNamePort());
231             csp.append(";media-src 'none'; object-src 'none';");
232             csp.append("script-src https://" + ServerConstants.getStaticHostNamePort());
233             csp.append(";style-src https://" + ServerConstants.getStaticHostNamePort());
234             csp.append(";form-action https://" + ServerConstants.getSecureHostNamePort() + " https://" + ServerConstants.getWwwHostNamePort());
235             csp.append("report-url https://api.cacert.org/security/csp/report");
236             defaultCSP = csp.toString();
237         }
238         return defaultCSP;
239     }
240
241     public static String getPathByPage(Page p) {
242         return instance.reveresePages.get(p).replaceFirst("/?\\*$", "");
243     }
244
245 }