1 | package com.bowman.cardserv;
|
---|
2 |
|
---|
3 | import com.bowman.cardserv.cws.*;
|
---|
4 | import com.bowman.cardserv.interfaces.*;
|
---|
5 | import com.bowman.cardserv.rmi.*;
|
---|
6 | import com.bowman.cardserv.session.*;
|
---|
7 | import com.bowman.cardserv.util.*;
|
---|
8 | import com.bowman.cardserv.web.WebBackend;
|
---|
9 | import com.bowman.cardserv.crypto.DESUtil;
|
---|
10 |
|
---|
11 | import java.io.*;
|
---|
12 | import java.net.*;
|
---|
13 | import java.rmi.RMISecurityManager;
|
---|
14 | import java.rmi.registry.*;
|
---|
15 | import java.rmi.server.RMISocketFactory;
|
---|
16 | import java.util.*;
|
---|
17 |
|
---|
18 | /**
|
---|
19 | * Created by IntelliJ IDEA.
|
---|
20 | * User: bowman
|
---|
21 | * Date: Oct 8, 2005
|
---|
22 | * Time: 3:29:23 PM
|
---|
23 | */
|
---|
24 | public class CardServProxy implements CamdMessageListener, XmlConfigurable, Runnable {
|
---|
25 |
|
---|
26 | public static final String APP_VERSION = "0.9.0";
|
---|
27 | public static String APP_BUILD = "";
|
---|
28 | static ProxyLogger logger;
|
---|
29 | private static Registry registry;
|
---|
30 |
|
---|
31 | static {
|
---|
32 | System.setProperty("java.security.policy", "etc/policy.all");
|
---|
33 | try {
|
---|
34 | RMISocketFactory.setSocketFactory(new IpCheckSocketFactory());
|
---|
35 | } catch(IOException e) {
|
---|
36 | e.printStackTrace();
|
---|
37 | }
|
---|
38 | try {
|
---|
39 | Properties props = new Properties();
|
---|
40 | props.load(CardServProxy.class.getResourceAsStream("build.properties"));
|
---|
41 | String svnRev = props.getProperty("svn.revision");
|
---|
42 | if(svnRev != null && svnRev.indexOf('$') == -1) APP_BUILD = "r" + svnRev;
|
---|
43 | } catch(Exception e) {}
|
---|
44 | }
|
---|
45 |
|
---|
46 | private ProxyConfig config;
|
---|
47 | private CwsConnectorManager connManager;
|
---|
48 | private UserManager userManager;
|
---|
49 | private CacheHandler cacheHandler;
|
---|
50 | private RemoteHandler remoteHandler;
|
---|
51 | private WebBackend webBackend;
|
---|
52 | private SessionManager sessionManager;
|
---|
53 | private String remoteName;
|
---|
54 |
|
---|
55 | private long startTimeStamp;
|
---|
56 | private boolean alive;
|
---|
57 |
|
---|
58 | private int ecmCount, ecmForwards, ecmCacheHits, ecmFailures, ecmDenied, ecmFiltered;
|
---|
59 | private int emmCount;
|
---|
60 | private TimedAverageList ecmRate = new TimedAverageList(10);
|
---|
61 |
|
---|
62 | private List broadcastQueue = new ArrayList();
|
---|
63 |
|
---|
64 | public CardServProxy(File cfgFile) throws FileNotFoundException, ConfigException {
|
---|
65 | config = ProxyConfig.getInstance();
|
---|
66 | config.readConfig(this, cfgFile);
|
---|
67 |
|
---|
68 | new Thread(this, "CwsProbeThread").start();
|
---|
69 | }
|
---|
70 |
|
---|
71 | public void configUpdated(ProxyXmlConfig xml) throws ConfigException {
|
---|
72 |
|
---|
73 | ProxyLogger.initFormatter(config.isDebug(), config.isHideIPs());
|
---|
74 |
|
---|
75 | if(logger != null) {
|
---|
76 | logger.close(); // force new filehandles on updated config
|
---|
77 | } else { // first load
|
---|
78 | ProxyLogger.initConsole(config.getLogLevel());
|
---|
79 | }
|
---|
80 |
|
---|
81 | try {
|
---|
82 | logger = ProxyLogger.getFileLogger(ProxyLogger.LOG_BASE, new File(config.getLogFile()), config.getLogLevel(),
|
---|
83 | config.getLogRotateCount(), config.getLogRotateLimit(), false);
|
---|
84 |
|
---|
85 | } catch(IOException e) {
|
---|
86 | throw new ConfigException(xml.getFullName(), "log-file", "Unable to initialize logger FileHandler: " + e, e);
|
---|
87 | }
|
---|
88 |
|
---|
89 | logger.setSilent(config.isSilent());
|
---|
90 |
|
---|
91 | ProxyXmlConfig rmi;
|
---|
92 | try {
|
---|
93 | rmi = xml.getSubConfig("rmi");
|
---|
94 | } catch (ConfigException e) {
|
---|
95 | rmi = null;
|
---|
96 | }
|
---|
97 | updateRmi(rmi);
|
---|
98 | config.setRemoteHandler(remoteHandler);
|
---|
99 |
|
---|
100 | logger.fine("Configuration updated");
|
---|
101 | }
|
---|
102 |
|
---|
103 | private void updateRmi(ProxyXmlConfig rmiConfig) throws ConfigException {
|
---|
104 | if(rmiConfig != null && "true".equalsIgnoreCase(rmiConfig.getStringValue("enabled", "true"))) {
|
---|
105 |
|
---|
106 | System.setSecurityManager(new RMISecurityManager());
|
---|
107 |
|
---|
108 | try {
|
---|
109 | IpCheckServerSocket.clearIpMasks();
|
---|
110 | String[] allowedIps = rmiConfig.getStringValue("allowed-ip-masks").split(" ");
|
---|
111 | for(int i = 0; i < allowedIps.length; i++) IpCheckServerSocket.addIpMask(allowedIps[i]);
|
---|
112 | } catch (ConfigException e) {
|
---|
113 | }
|
---|
114 |
|
---|
115 | InetAddress bindAddr = null; String bindIp = null;
|
---|
116 | try {
|
---|
117 | bindIp = rmiConfig.getStringValue("bind-ip");
|
---|
118 | bindAddr = InetAddress.getByName(bindIp);
|
---|
119 | } catch (ConfigException e) {
|
---|
120 | } catch (UnknownHostException e) {
|
---|
121 | throw new ConfigException(rmiConfig.getFullName(), "bind-ip", "Invalid rmi bind-ip: " + bindIp);
|
---|
122 | }
|
---|
123 | IpCheckServerSocket.setBindAddress(bindAddr);
|
---|
124 |
|
---|
125 | try {
|
---|
126 | if(registry == null) registry = LocateRegistry.createRegistry(rmiConfig.getPortValue("registry-port", 4099));
|
---|
127 | if(remoteHandler == null) remoteHandler = new RemoteHandler(rmiConfig.getPortValue("local-port", 4098), this);
|
---|
128 | remoteHandler.setName(rmiConfig.getStringValue("display-name"));
|
---|
129 | remoteName = rmiConfig.getStringValue("local-name", "cardservproxy");
|
---|
130 | registry.rebind(remoteName, remoteHandler);
|
---|
131 | } catch(IOException e) {
|
---|
132 | throw new ConfigException(rmiConfig.getFullName(), "Unable to initialize rmi: " + e, e);
|
---|
133 | }
|
---|
134 |
|
---|
135 | ProxyXmlConfig webConfig = rmiConfig.getSubConfig("status-web");
|
---|
136 | if(webConfig != null) {
|
---|
137 | if("true".equalsIgnoreCase(webConfig.getStringValue("enabled", "true"))) {
|
---|
138 | if(webBackend == null) webBackend = new WebBackend(remoteHandler);
|
---|
139 | webBackend.configUpdated(webConfig);
|
---|
140 | } else {
|
---|
141 | if(webBackend != null) webBackend.stop();
|
---|
142 | }
|
---|
143 | }
|
---|
144 |
|
---|
145 | } else { // disable rmi
|
---|
146 | try {
|
---|
147 | if(registry != null && remoteName != null) registry.unbind(remoteName);
|
---|
148 | } catch(Exception e) {
|
---|
149 | logger.throwing(e);
|
---|
150 | }
|
---|
151 | if(remoteHandler != null) remoteHandler.destroy();
|
---|
152 | remoteHandler = null;
|
---|
153 | }
|
---|
154 |
|
---|
155 | startPlugins();
|
---|
156 | }
|
---|
157 |
|
---|
158 | private void startPlugins() {
|
---|
159 | ProxyPlugin plugin;
|
---|
160 | for(Iterator iter = config.getProxyPlugins().values().iterator(); iter.hasNext(); ) {
|
---|
161 | plugin = (ProxyPlugin)iter.next();
|
---|
162 | try {
|
---|
163 | logger.info("Starting plugin: " + plugin.getName() + " - " + plugin.getDescription());
|
---|
164 | plugin.start(this);
|
---|
165 | } catch (Throwable t) {
|
---|
166 | logger.severe("Exception starting plugin '" + plugin.getClass().getName() + "': " + t, t);
|
---|
167 | }
|
---|
168 | }
|
---|
169 | }
|
---|
170 |
|
---|
171 | public boolean isAlive() {
|
---|
172 | return alive;
|
---|
173 | }
|
---|
174 |
|
---|
175 | public void setAlive(boolean alive) {
|
---|
176 | this.alive = alive;
|
---|
177 | }
|
---|
178 |
|
---|
179 | public void init() throws IOException, InterruptedException {
|
---|
180 |
|
---|
181 | startTimeStamp = System.currentTimeMillis();
|
---|
182 |
|
---|
183 | logger.info("-= CardServProxy " + APP_VERSION + APP_BUILD + " initialized =-");
|
---|
184 | logger.fine("CA-Profiles: ");
|
---|
185 | CaProfile cp;
|
---|
186 | for(Iterator iter = config.getProfiles().values().iterator(); iter.hasNext(); ) {
|
---|
187 | cp = (CaProfile)iter.next();
|
---|
188 | long wait = config.getCacheHandler().getMaxCacheWait(config.getConnManager().getMaxCwWait(cp));
|
---|
189 | logger.fine(" - " + cp + ((cp != CaProfile.MULTIPLE)?" (cache wait: " + wait + ")":""));
|
---|
190 | }
|
---|
191 | logger.fine("Connectors: ");
|
---|
192 | for(Iterator iter = config.getConnManager().getConnectors().values().iterator(); iter.hasNext(); )
|
---|
193 | logger.fine(" - " + iter.next());
|
---|
194 | logger.fine("User-Manager: " + config.getUserManager().getClass().getName());
|
---|
195 | logger.fine("Cache-Handler: " + config.getCacheHandler().getClass().getName());
|
---|
196 | logger.fine("Plugins: " + config.getProxyPlugins());
|
---|
197 | logger.fine("Services: " + config.getServiceCount() + " parsed");
|
---|
198 |
|
---|
199 | CaProfile[] profiles = openPorts();
|
---|
200 |
|
---|
201 | if(remoteHandler != null) remoteHandler.start();
|
---|
202 |
|
---|
203 | cacheHandler = config.getCacheHandler();
|
---|
204 | cacheHandler.start();
|
---|
205 |
|
---|
206 | connManager = config.getConnManager();
|
---|
207 | connManager.start();
|
---|
208 |
|
---|
209 | userManager = config.getUserManager();
|
---|
210 | userManager.start();
|
---|
211 |
|
---|
212 | sessionManager = SessionManager.getInstance();
|
---|
213 |
|
---|
214 | if(webBackend != null) webBackend.start();
|
---|
215 |
|
---|
216 | logger.info("Waiting for connection manager to finish one cycle...");
|
---|
217 | while(!connManager.isReady()) Thread.sleep(500);
|
---|
218 | logger.info("Ready. Receiving connections...");
|
---|
219 |
|
---|
220 | startListening(profiles);
|
---|
221 |
|
---|
222 | }
|
---|
223 |
|
---|
224 | private CaProfile[] openPorts() throws IOException {
|
---|
225 | Set set = config.getRealProfiles();
|
---|
226 | CaProfile[] profiles = (CaProfile[])set.toArray(new CaProfile[set.size()]);
|
---|
227 | List portList = new ArrayList();
|
---|
228 |
|
---|
229 | for(int i = 0; i < profiles.length; i++) {
|
---|
230 | ListenPort lp = null;
|
---|
231 | try {
|
---|
232 | if(profiles[i].getServiceConflicts() > 0)
|
---|
233 | logger.warning("Service conflict(s) for Ca[" + profiles[i].getName() +"]: " + profiles[i].getServiceConflicts());
|
---|
234 |
|
---|
235 | for(Iterator iter = profiles[i].getListenPorts().iterator(); iter.hasNext(); ) {
|
---|
236 | lp = (ListenPort)iter.next();
|
---|
237 | lp.createServerSocket();
|
---|
238 | portList.add(lp.toString());
|
---|
239 | }
|
---|
240 |
|
---|
241 | } catch(IOException e) {
|
---|
242 | logger.severe("Failed to open listen port [" + lp + "] for '" + profiles[i].getName() +
|
---|
243 | "' (" + e.getMessage() + ")", e);
|
---|
244 | throw e;
|
---|
245 | }
|
---|
246 | }
|
---|
247 | Collections.sort(portList);
|
---|
248 | logger.info("Listening on: " + portList);
|
---|
249 | return profiles;
|
---|
250 | }
|
---|
251 |
|
---|
252 | private void startListening(CaProfile[] profiles) {
|
---|
253 | setAlive(true);
|
---|
254 | for(int i = 0; i < profiles.length; i++) {
|
---|
255 | profiles[i].startListening(this);
|
---|
256 | }
|
---|
257 | config.setDefaultMsgListener(this); // register as listener for any ports added later
|
---|
258 | }
|
---|
259 |
|
---|
260 |
|
---|
261 | public static void main(String[] args) {
|
---|
262 |
|
---|
263 | if("true".equalsIgnoreCase(System.getProperty("com.bowman.cardserv.allowanyjvm"))) {
|
---|
264 | // any jvm allowed
|
---|
265 | } else {
|
---|
266 | boolean start = true;
|
---|
267 | String vendorUrl = System.getProperty("java.vendor.url");
|
---|
268 | String vmName = System.getProperty("java.vm.name");
|
---|
269 | if(vendorUrl != null)
|
---|
270 | if(!vendorUrl.startsWith("http://java.sun.com")) start = false;
|
---|
271 | if(vendorUrl.startsWith("http://java.oracle.com/")) start = true; // Support Oracle Sun Java Ver 1.7
|
---|
272 | if(vmName != null)
|
---|
273 | if(vmName.startsWith("OpenJDK")) start = false;
|
---|
274 | if(!start) {
|
---|
275 | System.err.println("Startup failed: Unsupported java vm '" + System.getProperty("java.vm.name") +
|
---|
276 | "', only the original sun vm has been tested with csp.");
|
---|
277 | System.exit(5);
|
---|
278 | }
|
---|
279 | }
|
---|
280 |
|
---|
281 | File cfgFile = null;
|
---|
282 | if(args.length > 0) cfgFile = new File(args[0]);
|
---|
283 | try {
|
---|
284 | new CardServProxy(cfgFile).init();
|
---|
285 | } catch(FileNotFoundException e) {
|
---|
286 | System.err.println("Configuration file not found: " + e.getMessage());
|
---|
287 | System.exit(1);
|
---|
288 | } catch(ConfigException e) {
|
---|
289 | System.err.println("Configuration error:");
|
---|
290 | if(e.getLabel() != null) {
|
---|
291 | if(e.getLabel().indexOf(' ') == -1) System.err.println("- Element: <" + e.getLabel() + ">");
|
---|
292 | else {
|
---|
293 | System.err.println("- Element: <" + e.getLabel());
|
---|
294 | if(e.getSubLabel() != null) System.err.println("- Attribute: " + e.getSubLabel());
|
---|
295 | }
|
---|
296 | }
|
---|
297 | System.err.println("- Message: " + e.getMessage());
|
---|
298 | System.exit(2);
|
---|
299 | } catch(IOException e) {
|
---|
300 | System.err.println("Failed to open listen port: " + e.getMessage());
|
---|
301 | System.exit(3);
|
---|
302 | } catch(InterruptedException e) {
|
---|
303 | System.err.println("Startup aborted: " + e);
|
---|
304 | System.exit(4);
|
---|
305 | }
|
---|
306 | }
|
---|
307 |
|
---|
308 | private CamdNetMessage applyFilters(ProxySession session, CamdNetMessage msg) {
|
---|
309 | for(Iterator iter = new ArrayList(config.getProxyPlugins().values()).iterator(); iter.hasNext(); ) {
|
---|
310 | try {
|
---|
311 | msg = ((ProxyPlugin)iter.next()).doFilter(session, msg);
|
---|
312 | if(msg == null) break;
|
---|
313 | } catch (Throwable t) {
|
---|
314 | logger.severe("Exception in plugin filtering: " + t, t);
|
---|
315 | }
|
---|
316 | }
|
---|
317 |
|
---|
318 | if(msg != null && msg.getFilteredBy() != null) {
|
---|
319 | if(config.isLogEcm() || userManager.isDebug(session.getUser())) {
|
---|
320 | logger.info("ECM " + msg.hashCodeStr() + " (0x" + Integer.toHexString(msg.getDataLength()) + " " +
|
---|
321 | DESUtil.intToHexString(msg.getNetworkId(), 4) + " " + DESUtil.intToHexString(msg.getCaId(), 4) + ") " +
|
---|
322 | (msg.getProviderIdent()<0?"":"[" + DESUtil.intToByteString(msg.getProviderIdent(), 3) + "]") + " - " +
|
---|
323 | session + "[" + config.getServiceName(msg) + "] -> " + msg.getFilteredBy());
|
---|
324 | }
|
---|
325 | }
|
---|
326 |
|
---|
327 | return msg;
|
---|
328 | }
|
---|
329 |
|
---|
330 | private Set applySelectors(ProxySession session, CamdNetMessage msg, Set connectors) {
|
---|
331 | ProxyPlugin plugin;
|
---|
332 | for(Iterator iter = new ArrayList(config.getProxyPlugins().values()).iterator(); iter.hasNext(); ) {
|
---|
333 | try {
|
---|
334 | plugin = (ProxyPlugin)iter.next();
|
---|
335 | if(plugin instanceof CwsSelector) connectors = ((CwsSelector)plugin).doSelection(session, msg, connectors);
|
---|
336 | if(connectors == null || connectors.isEmpty()) break;
|
---|
337 | } catch (Throwable t) {
|
---|
338 | logger.severe("Exception in plugin connector selection: " + t, t);
|
---|
339 | }
|
---|
340 | }
|
---|
341 | return connectors;
|
---|
342 | }
|
---|
343 |
|
---|
344 | public void messageReceived(ProxySession session, CamdNetMessage msg) {
|
---|
345 |
|
---|
346 | msg = applyFilters(session, msg);
|
---|
347 | if(msg == null || msg.isFiltered()) {
|
---|
348 | if(msg.isEcm()) {
|
---|
349 | ecmFiltered++;
|
---|
350 | ecmCount++;
|
---|
351 | }
|
---|
352 | return;
|
---|
353 | }
|
---|
354 | CaProfile profile = session.getProfile();
|
---|
355 |
|
---|
356 | if(msg.isEcm() || msg.isEmm()) {
|
---|
357 | if(profile == CaProfile.MULTIPLE) { // deny ambigious ecms from multi-context sessions
|
---|
358 | profile = config.getProfileById(msg.getNetworkId(), msg.getCaId());
|
---|
359 | if(profile == null) {
|
---|
360 | if(msg.getNetworkId() == -1) logger.warning("Denying multi-context message without network id from: " + session);
|
---|
361 | else logger.warning("Denying csp message with unknown network-id from '" + session + "': " +
|
---|
362 | DESUtil.intToHexString(msg.getNetworkId(), 4));
|
---|
363 | denyMessage(session, msg);
|
---|
364 | return;
|
---|
365 | } else {
|
---|
366 | if(msg.getNetworkId() == -1) msg.setNetworkId(profile.getNetworkId());
|
---|
367 | }
|
---|
368 | } else { // allow plugins to move messages to other profiles regardless of origin
|
---|
369 | if(msg.getNetworkId() != profile.getNetworkId()) {
|
---|
370 | profile = config.getProfileById(msg.getNetworkId(), msg.getCaId());
|
---|
371 | if(profile == null) profile = session.getProfile();
|
---|
372 | }
|
---|
373 | }
|
---|
374 | msg.setProfileName(profile.getName()); // just a lookup shortcut for all remaining processing
|
---|
375 | }
|
---|
376 |
|
---|
377 | switch(msg.getCommandTag()) {
|
---|
378 |
|
---|
379 | case EXT_GET_VERSION:
|
---|
380 | case MSG_CLIENT_2_SERVER_LOGIN:
|
---|
381 | case MSG_CARD_DATA_REQ:
|
---|
382 | case MSG_KEEPALIVE:
|
---|
383 | // handled by NewcamdSession
|
---|
384 | break;
|
---|
385 |
|
---|
386 | case 0x80: // ECM
|
---|
387 | case 0x81: // ECM
|
---|
388 | ecmCount++;
|
---|
389 | ecmRate.addRecord(1);
|
---|
390 |
|
---|
391 | Set allowed = session.getAllowedConnectors();
|
---|
392 | if(allowed == null || allowed.isEmpty()) {
|
---|
393 | allowed = new HashSet(connManager.getReadyConnectors(profile.getName()).keySet());
|
---|
394 | // add multi connectors not registered with the profile
|
---|
395 | allowed.addAll(connManager.getMultiConnectors(profile.getNetworkId(), profile.getCaId()).keySet());
|
---|
396 | }
|
---|
397 |
|
---|
398 | Set modified = applySelectors(session, msg, allowed); // give plugins a chance to modify the allowed list
|
---|
399 | logger.finer("Allowed connectors '" + modified + "' for: " + msg.hashCodeStr());
|
---|
400 | modified = filterConnectors(msg, modified); // remove connectors that claim they cant decode this message
|
---|
401 |
|
---|
402 | if(modified.isEmpty() && !(profile.isCacheOnly() || config.isCatchAll())) {
|
---|
403 | logger.fine("Denying message with no connector candidates from '" + session + "': " + msg.hashCodeStr());
|
---|
404 | denyMessage(session, msg);
|
---|
405 | return;
|
---|
406 | }
|
---|
407 |
|
---|
408 | ServiceMapping id = new ServiceMapping(msg);
|
---|
409 |
|
---|
410 | ConnectorSelection connectors;
|
---|
411 |
|
---|
412 | if(!profile.isCacheOnly()) {
|
---|
413 | // request optimal connector to handle this ecm (+ any connectors with unknown status for this sid, for broadcast)
|
---|
414 | connectors = connManager.getConnectorsForService(profile.getName(), id, modified);
|
---|
415 |
|
---|
416 | // do a faster fail if there is reason to believe this is a decoy? i.e skip cache check
|
---|
417 | if(msg.getCustomId() != 0 && connectors.isEmpty()) {
|
---|
418 | msg.setFilteredBy("No available connectors for cid: " + DESUtil.intToHexString(msg.getCustomId(), 4));
|
---|
419 | session.setFlag(msg, 'B');
|
---|
420 | session.sendEcmReply(msg, msg.getEmptyReply());
|
---|
421 | ecmFiltered++;
|
---|
422 | return;
|
---|
423 | }
|
---|
424 |
|
---|
425 | } else connectors = ConnectorSelection.EMPTY;
|
---|
426 |
|
---|
427 | // this calculation is for the experimental sync-period used by the clustered-cache
|
---|
428 | int successFactor = -1; // numerical value indicating how fast this proxy can get a cw result for this ecm
|
---|
429 | CwsConnector cws = connectors.getPrimary();
|
---|
430 | if(cws != null) {
|
---|
431 | Boolean status = connManager.canDecode(cws, id);
|
---|
432 | successFactor = cws.getEstimatedQueueTime();
|
---|
433 | if(successFactor < 5 && successFactor != -1) {
|
---|
434 | successFactor = -1;
|
---|
435 | } else {
|
---|
436 | if(cws.getTimeoutCount() > 0) successFactor = successFactor * 3; // connector might be dead, reduce chance
|
---|
437 | if(status == null || id.serviceId == 0) successFactor = successFactor * 3; // status is unknown, reduce chance
|
---|
438 | else if(status == Boolean.FALSE) successFactor = -1; // can't decode at all, no chance of success
|
---|
439 | }
|
---|
440 | }
|
---|
441 |
|
---|
442 | CamdNetMessage cached = checkCache(successFactor, msg, session, false);
|
---|
443 | if(!session.isConnected()) return;
|
---|
444 | if(cached != null) {
|
---|
445 |
|
---|
446 | // cache hit, we're done
|
---|
447 | // well except for probing...
|
---|
448 | probeConnectors(connectors.getUnknown(), session, msg);
|
---|
449 | session.sendEcmReply(msg, cached);
|
---|
450 |
|
---|
451 | } else {
|
---|
452 |
|
---|
453 | if(msg.isTimeOut() && cws != null) { // see if there is time left for a forward
|
---|
454 | int qt = cws.getEstimatedQueueTime();
|
---|
455 | if(msg.getCacheTime() + qt > connManager.getMaxCwWait(profile)) {
|
---|
456 | // no point in continuing
|
---|
457 | logger.warning("Cache timeout at " + msg.getCacheTime() + " ms left no time for forwarding to '" +
|
---|
458 | cws.getName() + "' (" + qt + " ms queue), discarding request and returning empty for: " + session +
|
---|
459 | " - max-cw-wait is " + connManager.getMaxCwWait(profile) + " ms");
|
---|
460 | session.setFlag(msg, 'T');
|
---|
461 | session.sendEcmReply(msg, msg.getEmptyReply());
|
---|
462 | return;
|
---|
463 | }
|
---|
464 | }
|
---|
465 |
|
---|
466 | try {
|
---|
467 | forwardEcmRequest(profile, session, msg, connectors);
|
---|
468 | } catch (IllegalStateException e) { // this ecm was already pending on the chosen connector
|
---|
469 | if(!session.isConnected()) return;
|
---|
470 |
|
---|
471 | logger.fine("Duplicate request in connector queue '" + e.getMessage() +"' for:" + msg + " (" + session
|
---|
472 | + ") - sleeping 200 and rechecking once...");
|
---|
473 |
|
---|
474 | try {
|
---|
475 | Thread.sleep(200);
|
---|
476 | cached = checkCache(successFactor, msg, session, false);
|
---|
477 | if(cached == null) {
|
---|
478 | cached = msg.getEmptyReply();
|
---|
479 | session.setFlag(msg, 'H');
|
---|
480 | }
|
---|
481 | session.sendEcmReply(msg, cached);
|
---|
482 | } catch(InterruptedException e1) {
|
---|
483 | return;
|
---|
484 | }
|
---|
485 |
|
---|
486 | }
|
---|
487 | }
|
---|
488 |
|
---|
489 | break;
|
---|
490 |
|
---|
491 | default:
|
---|
492 | if(msg.isEmm()) { // 0x82 - 0x8F - only newcamd sessions send these atm
|
---|
493 | emmCount++;
|
---|
494 | int seqNr = msg.getSequenceNr();
|
---|
495 | if(!profile.isCacheOnly() && msg.getProfileName() != null) forwardEmmRequest(session, msg);
|
---|
496 | CamdNetMessage emmReplyMsg = msg.getEmmReply();
|
---|
497 | ((NewcamdSession)session).sendMessageNative(emmReplyMsg, seqNr, true); // acknowledge the emm by giving the client the correct signature?
|
---|
498 | ((NewcamdSession)session).fireCamdMessage(emmReplyMsg, true);
|
---|
499 | } else {
|
---|
500 | // unknown command?
|
---|
501 | logger.warning("Unknown message received and ignored: " + msg + " (" + session + ")");
|
---|
502 | }
|
---|
503 | }
|
---|
504 |
|
---|
505 | }
|
---|
506 |
|
---|
507 | private Set filterConnectors(CamdNetMessage msg, Set modified) {
|
---|
508 |
|
---|
509 | /*
|
---|
510 | System.out.println(msg.hashCodeStr() + " [" + DESUtil.intToHexString(msg.getServiceId(), 4) + " " +
|
---|
511 | DESUtil.intToHexString(msg.getCaId(), 4) + " " + DESUtil.intToByteString(msg.getProviderIdent(), 3) +
|
---|
512 | "] connectors before: " + modified);
|
---|
513 | */
|
---|
514 |
|
---|
515 | // remove connectors that blacklist this message, or that lack the proper provider ident
|
---|
516 | int count = modified.size();
|
---|
517 | Set set = new HashSet();
|
---|
518 | String cwsName; CwsConnector cws;
|
---|
519 | for(Iterator iter = new ArrayList(modified).iterator(); iter.hasNext(); ) {
|
---|
520 | cwsName = (String)iter.next();
|
---|
521 | cws = connManager.getCwsConnectorByName(cwsName);
|
---|
522 | if(cws.isBlackListed(msg)) {
|
---|
523 | if(count > 1) { // dont blacklist if there is only one candidate
|
---|
524 | modified.remove(cwsName);
|
---|
525 | set.add(cwsName);
|
---|
526 | }
|
---|
527 | } else if(!cws.canDecode(msg)) {
|
---|
528 | modified.remove(cwsName);
|
---|
529 | set.add(cwsName);
|
---|
530 | }
|
---|
531 | }
|
---|
532 | if(!set.isEmpty()) logger.fine("Blacklisting/filtering removed allowed connector(s) " + set +
|
---|
533 | " for: " + msg.hashCodeStr() + " [" + DESUtil.intToHexString(msg.getServiceId(), 4) + " " +
|
---|
534 | DESUtil.intToHexString(msg.getCaId(), 4) + " - " + DESUtil.intToByteString(msg.getProviderIdent(), 3) + "]");
|
---|
535 |
|
---|
536 | /*
|
---|
537 | System.out.println(msg.hashCodeStr() + " [" + DESUtil.intToHexString(msg.getServiceId(), 4) + " " +
|
---|
538 | DESUtil.intToHexString(msg.getCaId(), 4) + " " + DESUtil.intToByteString(msg.getProviderIdent(), 3) +
|
---|
539 | "] connectors after: " + modified);
|
---|
540 |
|
---|
541 | */
|
---|
542 |
|
---|
543 | return modified;
|
---|
544 | }
|
---|
545 |
|
---|
546 | private CamdNetMessage checkCache(int successFactor, CamdNetMessage msg, ProxySession session, boolean peek) {
|
---|
547 | CamdNetMessage cached;
|
---|
548 | CaProfile profile = config.getProfile(msg.getProfileName());
|
---|
549 | if(!peek) {
|
---|
550 | if(msg.getServiceId() == 0 && connManager.getDelayNoSid() > 0) try {
|
---|
551 | Thread.sleep(connManager.getDelayNoSid());
|
---|
552 | } catch(InterruptedException e) {
|
---|
553 | session.setFlag(msg, 'U');
|
---|
554 | logger.warning(session + " thread interrupted while in no-sid-delay, session closed?");
|
---|
555 | return null;
|
---|
556 | }
|
---|
557 | cached = cacheHandler.processRequest(successFactor, msg, session.getProfile().isCacheOnly() || config.isCatchAll(), connManager.getMaxCwWait(profile));
|
---|
558 | } else {
|
---|
559 | cached = cacheHandler.peekReply(msg);
|
---|
560 | if(cached != null) session.setFlag(msg, 'W');
|
---|
561 | }
|
---|
562 | if(cached != null) {
|
---|
563 | ecmCacheHits++;
|
---|
564 | if(msg.getLinkedService() != null) session.setFlag(msg, 'L');
|
---|
565 | session.setFlag(msg, cached.getOriginAddress()==null?'C':'R');
|
---|
566 | if(config.isLogEcm() || userManager.isDebug(session.getUser())) {
|
---|
567 | String origin = (cached.getOriginAddress() == null)?"":" - (remote origin)";
|
---|
568 | logger.info("ECM cache hit for - " + session + ": " + msg.hashCodeStr() + " [" +
|
---|
569 | config.getServiceName(msg) + "]" + origin);
|
---|
570 | }
|
---|
571 | sessionManager.updateUserStatus(session, msg, userManager.isDebug(session.getUser()));
|
---|
572 | } else {
|
---|
573 | if(msg.isTimeOut()) {
|
---|
574 | if(msg.getCacheTime() >= cacheHandler.getMaxCacheWait(connManager.getMaxCwWait(profile))) session.setFlag(msg, 'O');
|
---|
575 | else session.setFlag(msg, 'Q');
|
---|
576 | }
|
---|
577 | }
|
---|
578 | return cached;
|
---|
579 | }
|
---|
580 |
|
---|
581 | private void forwardEcmRequest(CaProfile profile, ProxySession session, CamdNetMessage msg, ConnectorSelection connectors) {
|
---|
582 |
|
---|
583 | CwsConnector cws = connectors.getPrimary();
|
---|
584 |
|
---|
585 | // any additional connectors returned for channel auto-discovery?
|
---|
586 | probeConnectors(connectors.getUnknown(), session, msg);
|
---|
587 |
|
---|
588 | // any connectors selected for broadcast?
|
---|
589 | if(connectors.getSecondary() != null) {
|
---|
590 | session.setFlag(msg, '2');
|
---|
591 | broadcastMessage(msg, connectors.getSecondary(), false);
|
---|
592 | }
|
---|
593 |
|
---|
594 | if(cws != null) {
|
---|
595 | if(config.isLogEcm() || userManager.isDebug(session.getUser()))
|
---|
596 | logger.info("ECM " + msg.hashCodeStr() + " (0x" + Integer.toHexString(msg.getDataLength()) + " " +
|
---|
597 | DESUtil.intToHexString(msg.getNetworkId(), 4) + " " + DESUtil.intToHexString(msg.getCaId(), 4) + ") " +
|
---|
598 | (msg.getProviderIdent()<0?"":"[" + DESUtil.intToByteString(msg.getProviderIdent(), 3) + "]") + " - " +
|
---|
599 | session + "[" + config.getServiceName(msg) + "] -> " + cws.getLabel());
|
---|
600 |
|
---|
601 | if(!cws.sendEcmRequest(msg, session)) {
|
---|
602 | ecmFailures++;
|
---|
603 |
|
---|
604 | if(session.getTransactionTime() >= connManager.getMaxCwWait(profile)) { // is there time left for a retry?
|
---|
605 | session.setFlag(msg, 'S');
|
---|
606 | session.sendEcmReply(msg, msg.getEmptyReply());
|
---|
607 | logger.warning(session + " transaction timeout in send queue, returned empty...");
|
---|
608 | } else {
|
---|
609 | if(!session.isConnected()) return;
|
---|
610 | logger.warning(session + " lost card? Trying another in 100 ms...");
|
---|
611 | session.setFlag(msg, 'Y');
|
---|
612 | try {
|
---|
613 | Thread.sleep(100);
|
---|
614 | forwardEcmRequest(profile, session, msg, connManager.getConnectorsForService(profile.getName(),
|
---|
615 | new ServiceMapping(msg), session.getAllowedConnectors())); // try again recursively while there are still connectors and time
|
---|
616 | } catch (InterruptedException e) {
|
---|
617 | logger.throwing(e);
|
---|
618 | }
|
---|
619 | }
|
---|
620 | } else {
|
---|
621 | ecmForwards++;
|
---|
622 | session.setFlag(msg, 'F');
|
---|
623 | sessionManager.updateUserStatus(session, msg, userManager.isDebug(session.getUser()));
|
---|
624 | }
|
---|
625 |
|
---|
626 | } else { // no connectors available to decode this ecm, no forward possible
|
---|
627 |
|
---|
628 | if(!profile.isCacheOnly() && connManager.getCannotDecodeWait() > 0) { // wait and re-check cache before failing
|
---|
629 | try {
|
---|
630 | Thread.sleep(connManager.getCannotDecodeWait() * 1000);
|
---|
631 | } catch(InterruptedException e) {
|
---|
632 | logger.throwing(e);
|
---|
633 | }
|
---|
634 | CamdNetMessage cached = checkCache(-1, msg, session, true);
|
---|
635 | if(cached != null) {
|
---|
636 | session.sendEcmReply(msg, cached);
|
---|
637 | logger.fine("Session " + session + " received cache-reply after cannot-decode-wait for: [ " +
|
---|
638 | config.getServiceName(profile.getName(), msg.getServiceId()) + "]");
|
---|
639 | return;
|
---|
640 | }
|
---|
641 |
|
---|
642 | }
|
---|
643 |
|
---|
644 | logger.fine("Session " + session + " has no available card for [" + config.getServiceName(msg) + "], sending empty...");
|
---|
645 |
|
---|
646 | cacheHandler.processReply(msg, null); // notify cache to release any other sessions waiting on this ECM
|
---|
647 | denyMessage(session, msg);
|
---|
648 | }
|
---|
649 | }
|
---|
650 |
|
---|
651 | private void denyMessage(ProxySession session, CamdNetMessage msg) {
|
---|
652 | session.setFlag(msg, 'N');
|
---|
653 | ecmDenied++;
|
---|
654 | sessionManager.updateUserStatus(session, msg, userManager.isDebug(session.getUser()));
|
---|
655 | session.sendEcmReply(msg, msg.getEmptyReply());
|
---|
656 | }
|
---|
657 |
|
---|
658 | private void forwardEmmRequest(ProxySession session, CamdNetMessage msg) {
|
---|
659 | CwsConnector cws = connManager.getConnectorForAU(msg.getProfileName(), session.getUser());
|
---|
660 | if(cws != null) {
|
---|
661 | cws.sendMessage(msg); // just send the emm, ignore any reply
|
---|
662 | if(config.isLogEmm() || userManager.isDebug(session.getUser()))
|
---|
663 | logger.info("EMM " + msg.hashCodeStr() + " (0x" + Integer.toHexString(msg.getDataLength()) + ", 0x"
|
---|
664 | + Integer.toHexString(msg.getUpperBits()) + ") from " + session + " -> " + cws.getName());
|
---|
665 | } else if(config.isLogEmm() || userManager.isDebug(session.getUser()))
|
---|
666 | logger.info("EMM " + msg.hashCodeStr() + " (0x" + Integer.toHexString(msg.getDataLength()) + ", 0x"
|
---|
667 | + Integer.toHexString(msg.getUpperBits()) + ") from " + session);
|
---|
668 | }
|
---|
669 |
|
---|
670 | private void probeConnectors(List candidates, ProxySession session, CamdNetMessage msg) {
|
---|
671 | if(candidates != null) {
|
---|
672 | if(!userManager.isMapExcluded(session.getUser())) {
|
---|
673 | session.setFlag(msg, 'P');
|
---|
674 | msg.setOriginAddress(session.toString()); // hack to track the origin user of the probe later
|
---|
675 | broadcastMessage(msg, candidates, true);
|
---|
676 | }
|
---|
677 | }
|
---|
678 | }
|
---|
679 |
|
---|
680 | private void broadcastMessage(CamdNetMessage msg, List connectors, boolean probe) {
|
---|
681 | broadcastQueue.add(new BroadcastEntry(msg, connectors, probe));
|
---|
682 | if(!broadcastQueue.isEmpty()) {
|
---|
683 | synchronized(this) {
|
---|
684 | notifyAll();
|
---|
685 | }
|
---|
686 | }
|
---|
687 | }
|
---|
688 |
|
---|
689 | public void messageSent(ProxySession session, CamdNetMessage msg) {
|
---|
690 | if(msg.isEcm())
|
---|
691 | if(config.isLogEcm() || userManager.isDebug(session.getUser())) {
|
---|
692 | if(!msg.isFiltered()) logger.info("CW " + msg.hashCodeStr() + " (0x" + Integer.toHexString(msg.getDataLength()) + ") - [" +
|
---|
693 | session.getLastTransactionTime() + ":" + session.getLastTransactionFlags() + "] -> " + session);
|
---|
694 | }
|
---|
695 |
|
---|
696 | applyFilters(session, msg);
|
---|
697 | }
|
---|
698 |
|
---|
699 | public int getEcmCount() {
|
---|
700 | return ecmCount;
|
---|
701 | }
|
---|
702 |
|
---|
703 | public int getEcmForwards() {
|
---|
704 | return ecmForwards;
|
---|
705 | }
|
---|
706 |
|
---|
707 | public int getEcmCacheHits() {
|
---|
708 | return ecmCacheHits;
|
---|
709 | }
|
---|
710 |
|
---|
711 | public int getEcmFailures() {
|
---|
712 | return ecmFailures;
|
---|
713 | }
|
---|
714 |
|
---|
715 | public int getEcmDenied() {
|
---|
716 | return ecmDenied;
|
---|
717 | }
|
---|
718 |
|
---|
719 | public int getEcmFiltered() {
|
---|
720 | return ecmFiltered;
|
---|
721 | }
|
---|
722 |
|
---|
723 | public int getEcmRate() {
|
---|
724 | double rate = ((double)ecmRate.getTotal(true) / 10.0);
|
---|
725 | return (int)Math.round(rate);
|
---|
726 | }
|
---|
727 |
|
---|
728 | public int getEmmCount() {
|
---|
729 | return emmCount;
|
---|
730 | }
|
---|
731 |
|
---|
732 | public long getStartTime() {
|
---|
733 | return startTimeStamp;
|
---|
734 | }
|
---|
735 |
|
---|
736 | public RemoteHandler getRemoteHandler() {
|
---|
737 | return remoteHandler;
|
---|
738 | }
|
---|
739 |
|
---|
740 | public CacheHandler getCacheHandler() {
|
---|
741 | return cacheHandler;
|
---|
742 | }
|
---|
743 |
|
---|
744 | public UserManager getUserManager() {
|
---|
745 | return userManager;
|
---|
746 | }
|
---|
747 |
|
---|
748 | public CwsConnectorManager getConnManager() {
|
---|
749 | return connManager;
|
---|
750 | }
|
---|
751 |
|
---|
752 | public WebBackend getWebBackend() {
|
---|
753 | return webBackend;
|
---|
754 | }
|
---|
755 |
|
---|
756 | public SessionManager getSessionManager() {
|
---|
757 | return sessionManager;
|
---|
758 | }
|
---|
759 |
|
---|
760 | public int getProbeQueue() {
|
---|
761 | return broadcastQueue.size();
|
---|
762 | }
|
---|
763 |
|
---|
764 | public void run() {
|
---|
765 | while(true) {
|
---|
766 | synchronized(this) {
|
---|
767 | try {
|
---|
768 | wait();
|
---|
769 | } catch (InterruptedException e) {
|
---|
770 | break;
|
---|
771 | }
|
---|
772 | }
|
---|
773 | try {
|
---|
774 |
|
---|
775 | CwsConnector conn; ServiceMapping id; BroadcastEntry entry;
|
---|
776 | for(Iterator iter = new ArrayList(broadcastQueue).iterator(); iter.hasNext(); ) {
|
---|
777 | entry = (BroadcastEntry)iter.next();
|
---|
778 | if(entry == null) continue;
|
---|
779 | broadcastQueue.remove(entry);
|
---|
780 | id = new ServiceMapping(entry.msg);
|
---|
781 |
|
---|
782 | for(Iterator i = entry.connectors.iterator(); i.hasNext();) {
|
---|
783 | conn = (CwsConnector)i.next();
|
---|
784 | if(conn.isReady()) {
|
---|
785 |
|
---|
786 | if(entry.probe) { // perform probing
|
---|
787 | if(connManager.canDecode(conn, id) == null) { // is status still unknown?
|
---|
788 | if(conn.getEstimatedQueueTime() < (connManager.getMaxCwWait(null) / 2)) { // only probe if there is capacity
|
---|
789 | if(!conn.isPending(entry.msg) && conn.canDecode(entry.msg)) try {
|
---|
790 | if(conn.sendEcmRequest(new CamdNetMessage(entry.msg), null))
|
---|
791 | if(entry.msg.getServiceId() != 0) logger.info("Probing " + conn.getLabel() + " for service [" +
|
---|
792 | config.getServiceName(entry.msg) + "] ...");
|
---|
793 |
|
---|
794 | } catch (IllegalStateException e) {
|
---|
795 | logger.fine("Skipping probe for " + entry.msg.hashCodeStr() + ", request already in connector queue: " + conn.getName());
|
---|
796 | }
|
---|
797 | }
|
---|
798 | }
|
---|
799 | } else { // perform broadcast
|
---|
800 |
|
---|
801 | if(conn.getEstimatedQueueTime() < (connManager.getMaxCwWait(null) / 2)) { // only broadcast if there is capacity - todo change criteria?
|
---|
802 | if(!conn.isPending(entry.msg) && conn.canDecode(entry.msg)) try {
|
---|
803 | if(conn.sendEcmRequest(new CamdNetMessage(entry.msg), null)) {
|
---|
804 | if(!connManager.isServiceUnknown(entry.msg.getProfileName(), entry.msg.getServiceId()))
|
---|
805 | logger.fine("Redundant forward to " + conn.getLabel() + " for service [" + config.getServiceName(entry.msg) + "] ...");
|
---|
806 | else logger.fine("Broadcasting " + entry.msg.hashCodeStr() + " with unknown service to " + conn.getLabel() + "...");
|
---|
807 | }
|
---|
808 |
|
---|
809 | } catch (IllegalStateException e) {
|
---|
810 | logger.fine("Skipping broadcast for " + entry.msg.hashCodeStr() + ", request already in connector queue: " + conn.getName());
|
---|
811 | }
|
---|
812 | }
|
---|
813 |
|
---|
814 | }
|
---|
815 | }
|
---|
816 | }
|
---|
817 |
|
---|
818 | }
|
---|
819 |
|
---|
820 | if(!alive) break;
|
---|
821 |
|
---|
822 | } catch (Exception e) {
|
---|
823 | logger.severe("Uncaught exception in broadcast loop: " + e, e);
|
---|
824 | }
|
---|
825 | }
|
---|
826 | }
|
---|
827 |
|
---|
828 | static class BroadcastEntry {
|
---|
829 |
|
---|
830 | CamdNetMessage msg;
|
---|
831 | List connectors;
|
---|
832 | boolean probe;
|
---|
833 |
|
---|
834 | BroadcastEntry(CamdNetMessage msg, List connectors, boolean probe) {
|
---|
835 | this.msg = msg;
|
---|
836 | this.connectors = connectors;
|
---|
837 | this.probe = probe;
|
---|
838 | }
|
---|
839 | }
|
---|
840 |
|
---|
841 | }
|
---|