View Javadoc
1   /*
2    * Copyright 2012-2019 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.es.config.exentity;
17  
18  import java.util.ArrayList;
19  import java.util.Arrays;
20  import java.util.Collections;
21  import java.util.HashMap;
22  import java.util.List;
23  import java.util.Map;
24  import java.util.Properties;
25  import java.util.regex.Pattern;
26  import java.util.stream.Collectors;
27  
28  import org.apache.http.auth.AuthScheme;
29  import org.apache.http.auth.AuthScope;
30  import org.apache.http.auth.Credentials;
31  import org.apache.http.auth.NTCredentials;
32  import org.apache.http.auth.UsernamePasswordCredentials;
33  import org.apache.http.impl.auth.BasicScheme;
34  import org.apache.http.impl.auth.DigestScheme;
35  import org.apache.http.impl.auth.NTLMScheme;
36  import org.codelibs.core.lang.StringUtil;
37  import org.codelibs.fess.Constants;
38  import org.codelibs.fess.crawler.client.CrawlerClientFactory;
39  import org.codelibs.fess.crawler.client.ftp.FtpAuthentication;
40  import org.codelibs.fess.crawler.client.ftp.FtpClient;
41  import org.codelibs.fess.crawler.client.http.Authentication;
42  import org.codelibs.fess.crawler.client.http.HcHttpClient;
43  import org.codelibs.fess.crawler.client.http.form.FormScheme;
44  import org.codelibs.fess.crawler.client.http.impl.AuthenticationImpl;
45  import org.codelibs.fess.crawler.client.http.ntlm.JcifsEngine;
46  import org.codelibs.fess.crawler.client.smb.SmbAuthentication;
47  import org.codelibs.fess.crawler.client.smb.SmbClient;
48  import org.codelibs.fess.crawler.exception.CrawlerSystemException;
49  import org.codelibs.fess.es.config.bsentity.BsDataConfig;
50  import org.codelibs.fess.util.ParameterUtil;
51  import org.slf4j.Logger;
52  import org.slf4j.LoggerFactory;
53  
54  /**
55   * @author FreeGen
56   */
57  public class DataConfig extends BsDataConfig implements CrawlingConfig {
58  
59      private static final long serialVersionUID = 1L;
60  
61      private static final Logger logger = LoggerFactory.getLogger(DataConfig.class);
62  
63      private static final String CRAWLER_WEB_PREFIX = "crawler.web.";
64  
65      private static final String CRAWLER_WEB_HEADER_PREFIX = CRAWLER_WEB_PREFIX + "header.";
66  
67      private static final String CRAWLER_WEB_AUTH = CRAWLER_WEB_PREFIX + "auth";
68  
69      private static final String CRAWLER_USERAGENT = "crawler.useragent";
70  
71      private static final String CRAWLER_PARAM_PREFIX = "crawler.param.";
72  
73      private static final Object CRAWLER_FILE_AUTH = "crawler.file.auth";
74  
75      protected Pattern[] includedDocPathPatterns;
76  
77      protected Pattern[] excludedDocPathPatterns;
78  
79      private Map<String, String> handlerParameterMap;
80  
81      private Map<String, String> handlerScriptMap;
82  
83      public DataConfig() {
84          super();
85          setBoost(1.0f);
86      }
87  
88      @Override
89      public String getDocumentBoost() {
90          return getBoost().toString();
91      }
92  
93      public String getBoostValue() {
94          if (boost != null) {
95              return boost.toString();
96          }
97          return null;
98      }
99  
100     public void setBoostValue(final String value) {
101         if (value != null) {
102             try {
103                 boost = Float.parseFloat(value);
104             } catch (final Exception e) {}
105         }
106     }
107 
108     @Override
109     public String getIndexingTarget(final String input) {
110         // always return true
111         return Constants.TRUE;
112     }
113 
114     @Override
115     public String getConfigId() {
116         return ConfigType.DATA.getConfigId(getId());
117     }
118 
119     public Map<String, String> getHandlerParameterMap() {
120         if (handlerParameterMap == null) {
121             handlerParameterMap = ParameterUtil.parse(getHandlerParameter());
122         }
123         return handlerParameterMap;
124     }
125 
126     public Map<String, String> getHandlerScriptMap() {
127         if (handlerScriptMap == null) {
128             handlerScriptMap = ParameterUtil.parse(getHandlerScript());
129         }
130         return handlerScriptMap;
131     }
132 
133     @Override
134     public Map<String, Object> initializeClientFactory(final CrawlerClientFactory crawlerClientFactory) {
135         final Map<String, String> paramMap = getHandlerParameterMap();
136 
137         final Map<String, Object> factoryParamMap = new HashMap<>();
138         crawlerClientFactory.setInitParameterMap(factoryParamMap);
139 
140         // parameters
141         for (final Map.Entry<String, String> entry : paramMap.entrySet()) {
142             final String key = entry.getKey();
143             if (key.startsWith(CRAWLER_PARAM_PREFIX)) {
144                 factoryParamMap.put(key.substring(CRAWLER_PARAM_PREFIX.length()), entry.getValue());
145             }
146         }
147 
148         // user agent
149         final String userAgent = paramMap.get(CRAWLER_USERAGENT);
150         if (StringUtil.isNotBlank(userAgent)) {
151             factoryParamMap.put(HcHttpClient.USER_AGENT_PROPERTY, userAgent);
152         }
153 
154         // web auth
155         final String webAuthStr = paramMap.get(CRAWLER_WEB_AUTH);
156         if (StringUtil.isNotBlank(webAuthStr)) {
157             final String[] webAuthNames = webAuthStr.split(",");
158             final List<Authentication> basicAuthList = new ArrayList<>();
159             for (final String webAuthName : webAuthNames) {
160                 final String scheme = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".scheme");
161 
162                 final AuthScheme authScheme = getAuthScheme(paramMap, webAuthName, scheme);
163                 final AuthScope authScope = getAuthScope(webAuthName, scheme, paramMap);
164                 final Credentials credentials = getCredentials(webAuthName, scheme, paramMap);
165                 basicAuthList.add(new AuthenticationImpl(authScope, credentials, authScheme));
166             }
167             factoryParamMap.put(HcHttpClient.BASIC_AUTHENTICATIONS_PROPERTY,
168                     basicAuthList.toArray(new Authentication[basicAuthList.size()]));
169         }
170 
171         // request header
172         final List<org.codelibs.fess.crawler.client.http.RequestHeader> rhList = new ArrayList<>();
173         int count = 1;
174         String headerName = paramMap.get(CRAWLER_WEB_HEADER_PREFIX + count + ".name");
175         while (StringUtil.isNotBlank(headerName)) {
176             final String headerValue = paramMap.get(CRAWLER_WEB_HEADER_PREFIX + count + ".value");
177             rhList.add(new org.codelibs.fess.crawler.client.http.RequestHeader(headerName, headerValue));
178             count++;
179             headerName = paramMap.get(CRAWLER_WEB_HEADER_PREFIX + count + ".name");
180         }
181         if (!rhList.isEmpty()) {
182             factoryParamMap.put(HcHttpClient.REQUERT_HEADERS_PROPERTY,
183                     rhList.toArray(new org.codelibs.fess.crawler.client.http.RequestHeader[rhList.size()]));
184         }
185 
186         // proxy credentials
187         final String proxyHost = paramMap.get(CRAWLER_WEB_PREFIX + "proxyHost");
188         final String proxyPort = paramMap.get(CRAWLER_WEB_PREFIX + "proxyPort");
189         if (StringUtil.isNotBlank(proxyHost) && StringUtil.isNotBlank(proxyPort)) {
190             factoryParamMap.put(HcHttpClient.PROXY_HOST_PROPERTY, proxyHost);
191             factoryParamMap.put(HcHttpClient.PROXY_PORT_PROPERTY, proxyPort);
192             final String proxyUsername = paramMap.get(CRAWLER_WEB_PREFIX + "proxyUsername");
193             final String proxyPassword = paramMap.get(CRAWLER_WEB_PREFIX + "proxyPassword");
194             if (proxyUsername != null && proxyPassword != null) {
195                 factoryParamMap.put(HcHttpClient.PROXY_CREDENTIALS_PROPERTY, new UsernamePasswordCredentials(proxyUsername, proxyPassword));
196             }
197         } else {
198             initializeDefaultHttpProxy(factoryParamMap);
199         }
200 
201         // file auth
202         final String fileAuthStr = paramMap.get(CRAWLER_FILE_AUTH);
203         if (StringUtil.isNotBlank(fileAuthStr)) {
204             final String[] fileAuthNames = fileAuthStr.split(",");
205             final List<SmbAuthentication> smbAuthList = new ArrayList<>();
206             final List<org.codelibs.fess.crawler.client.smb1.SmbAuthentication> smb1AuthList = new ArrayList<>();
207             final List<FtpAuthentication> ftpAuthList = new ArrayList<>();
208             for (final String fileAuthName : fileAuthNames) {
209                 final String scheme = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".scheme");
210                 if (Constants.SAMBA.equals(scheme)) {
211                     final String domain = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".domain");
212                     final String hostname = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".host");
213                     final String port = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".port");
214                     final String username = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".username");
215                     final String password = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".password");
216 
217                     if (StringUtil.isEmpty(username)) {
218                         logger.warn("username is empty. fileAuth:" + fileAuthName);
219                         continue;
220                     }
221 
222                     final SmbAuthentication smbAuth = new SmbAuthentication();
223                     smbAuth.setDomain(domain == null ? StringUtil.EMPTY : domain);
224                     smbAuth.setServer(hostname);
225                     if (StringUtil.isNotBlank(port)) {
226                         try {
227                             smbAuth.setPort(Integer.parseInt(port));
228                         } catch (final NumberFormatException e) {
229                             logger.warn("Failed to parse " + port, e);
230                         }
231                     }
232                     smbAuth.setUsername(username);
233                     smbAuth.setPassword(password == null ? StringUtil.EMPTY : password);
234                     smbAuthList.add(smbAuth);
235 
236                     final org.codelibs.fess.crawler.client.smb1.SmbAuthentication smb1Auth =
237                             new org.codelibs.fess.crawler.client.smb1.SmbAuthentication();
238                     smb1Auth.setDomain(domain == null ? StringUtil.EMPTY : domain);
239                     smb1Auth.setServer(hostname);
240                     if (StringUtil.isNotBlank(port)) {
241                         try {
242                             smb1Auth.setPort(Integer.parseInt(port));
243                         } catch (final NumberFormatException e) {
244                             logger.warn("Failed to parse " + port, e);
245                         }
246                     }
247                     smb1Auth.setUsername(username);
248                     smb1Auth.setPassword(password == null ? StringUtil.EMPTY : password);
249                     smb1AuthList.add(smb1Auth);
250                 } else if (Constants.FTP.equals(scheme)) {
251                     final String hostname = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".host");
252                     final String port = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".port");
253                     final String username = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".username");
254                     final String password = paramMap.get(CRAWLER_FILE_AUTH + "." + fileAuthName + ".password");
255 
256                     if (StringUtil.isEmpty(username)) {
257                         logger.warn("username is empty. fileAuth:" + fileAuthName);
258                         continue;
259                     }
260 
261                     final FtpAuthentication ftpAuth = new FtpAuthentication();
262                     ftpAuth.setServer(hostname);
263                     if (StringUtil.isNotBlank(port)) {
264                         try {
265                             ftpAuth.setPort(Integer.parseInt(port));
266                         } catch (final NumberFormatException e) {
267                             logger.warn("Failed to parse " + port, e);
268                         }
269                     }
270                     ftpAuth.setUsername(username);
271                     ftpAuth.setPassword(password == null ? StringUtil.EMPTY : password);
272                     ftpAuthList.add(ftpAuth);
273                 }
274             }
275             if (!smbAuthList.isEmpty()) {
276                 factoryParamMap.put(SmbClient.SMB_AUTHENTICATIONS_PROPERTY, smbAuthList.toArray(new SmbAuthentication[smbAuthList.size()]));
277             }
278             if (!smb1AuthList.isEmpty()) {
279                 factoryParamMap.put(org.codelibs.fess.crawler.client.smb1.SmbClient.SMB_AUTHENTICATIONS_PROPERTY,
280                         smb1AuthList.toArray(new org.codelibs.fess.crawler.client.smb1.SmbAuthentication[smb1AuthList.size()]));
281             }
282             if (!ftpAuthList.isEmpty()) {
283                 factoryParamMap.put(FtpClient.FTP_AUTHENTICATIONS_PROPERTY, ftpAuthList.toArray(new FtpAuthentication[ftpAuthList.size()]));
284             }
285         }
286 
287         return factoryParamMap;
288     }
289 
290     private AuthScheme getAuthScheme(final Map<String, String> paramMap, final String webAuthName, final String scheme) {
291         AuthScheme authScheme = null;
292         if (Constants.BASIC.equals(scheme)) {
293             authScheme = new BasicScheme();
294         } else if (Constants.DIGEST.equals(scheme)) {
295             authScheme = new DigestScheme();
296         } else if (Constants.NTLM.equals(scheme)) {
297             final Properties props = new Properties();
298             paramMap.entrySet().stream().filter(e -> e.getKey().startsWith("jcifs.")).forEach(e -> {
299                 props.setProperty(e.getKey(), e.getValue());
300             });
301             authScheme = new NTLMScheme(new JcifsEngine(props));
302         } else if (Constants.FORM.equals(scheme)) {
303             final String prefix = CRAWLER_WEB_AUTH + "." + webAuthName + ".";
304             final Map<String, String> parameterMap =
305                     paramMap.entrySet().stream().filter(e -> e.getKey().startsWith(prefix))
306                             .collect(Collectors.toMap(e -> e.getKey().substring(prefix.length()), e -> e.getValue()));
307             authScheme = new FormScheme(parameterMap);
308         }
309         return authScheme;
310     }
311 
312     private Credentials getCredentials(final String webAuthName, final String scheme, final Map<String, String> paramMap) {
313         final String username = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".username");
314         if (StringUtil.isEmpty(username)) {
315             throw new CrawlerSystemException("username is empty. webAuth:" + webAuthName);
316         }
317         final String password = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".password");
318         Credentials credentials;
319         if (Constants.NTLM.equals(scheme)) {
320             final String workstation = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".workstation");
321             final String domain = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".domain");
322             credentials =
323                     new NTCredentials(username, password == null ? StringUtil.EMPTY : password, workstation == null ? StringUtil.EMPTY
324                             : workstation, domain == null ? StringUtil.EMPTY : domain);
325         } else {
326             credentials = new UsernamePasswordCredentials(username, password == null ? StringUtil.EMPTY : password);
327         }
328         return credentials;
329     }
330 
331     private AuthScope getAuthScope(final String webAuthName, final String scheme, final Map<String, String> paramMap) {
332         final String hostname = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".host");
333         final String port = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".port");
334         final String realm = paramMap.get(CRAWLER_WEB_AUTH + "." + webAuthName + ".realm");
335         AuthScope authScope;
336         if (StringUtil.isBlank(hostname)) {
337             authScope = AuthScope.ANY;
338         } else {
339             int p = AuthScope.ANY_PORT;
340             if (StringUtil.isNotBlank(port)) {
341                 try {
342                     p = Integer.parseInt(port);
343                 } catch (final NumberFormatException e) {
344                     logger.warn("Failed to parse " + port, e);
345                 }
346             }
347 
348             String r = realm;
349             if (StringUtil.isBlank(realm)) {
350                 r = AuthScope.ANY_REALM;
351             }
352 
353             String s = scheme;
354             if (StringUtil.isBlank(scheme) || Constants.NTLM.equals(scheme)) {
355                 s = AuthScope.ANY_SCHEME;
356             }
357             authScope = new AuthScope(hostname, p, r, s);
358         }
359         return authScope;
360     }
361 
362     @Override
363     public Map<String, String> getConfigParameterMap(final ConfigName name) {
364         return Collections.emptyMap();
365     }
366 
367     @Override
368     public String getId() {
369         return asDocMeta().id();
370     }
371 
372     public void setId(final String id) {
373         asDocMeta().id(id);
374     }
375 
376     public Long getVersionNo() {
377         return asDocMeta().version();
378     }
379 
380     public void setVersionNo(final Long version) {
381         asDocMeta().version(version);
382     }
383 
384     @Override
385     public Integer getTimeToLive() {
386         final String value = getHandlerParameterMap().get("timeToLive");
387         if (StringUtil.isBlank(value)) {
388             return null;
389         }
390         try {
391             return Integer.parseInt(value);
392         } catch (final NumberFormatException e) {
393             if (logger.isDebugEnabled()) {
394                 logger.debug("Invalid format: " + value, e);
395             }
396         }
397         return null;
398     }
399 
400     @Override
401     public String toString() {
402         return "DataConfig [available=" + available + ", boost=" + boost + ", createdBy=" + createdBy + ", createdTime=" + createdTime
403                 + ", handlerName=" + handlerName + ", handlerParameter=" + handlerParameter + ", handlerScript=" + handlerScript
404                 + ", name=" + name + ", permissions=" + Arrays.toString(permissions) + ", sortOrder=" + sortOrder + ", updatedBy="
405                 + updatedBy + ", updatedTime=" + updatedTime + "]";
406     }
407 
408 }