1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.catalina.session;
import java.beans.PropertyChangeSupport;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serial;
import java.io.Serializable;
import java.io.WriteAbortedException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionActivationListener;
import jakarta.servlet.http.HttpSessionAttributeListener;
import jakarta.servlet.http.HttpSessionBindingEvent;
import jakarta.servlet.http.HttpSessionBindingListener;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionIdListener;
import jakarta.servlet.http.HttpSessionListener;
import org.apache.catalina.Context;
import org.apache.catalina.Manager;
import org.apache.catalina.Session;
import org.apache.catalina.SessionEvent;
import org.apache.catalina.SessionListener;
import org.apache.catalina.TomcatPrincipal;
import org.apache.catalina.authenticator.SavedRequest;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.res.StringManager;
/**
* Standard implementation of the <b>Session</b> interface. This object is serializable, so that it can be stored in
* persistent storage or transferred to a different JVM for distributable session support.
* <p>
* <b>IMPLEMENTATION NOTE</b>: If you add fields to this class, you must make sure that you carry them over in the
* read/writeObject methods so that this class is properly serialized.
*
* @author Craig R. McClanahan
* @author Sean Legassick
* @author <a href="mailto:jon@latchkey.com">Jon S. Stevens</a>
*/
public class StandardSession implements HttpSession, Session, Serializable {
@Serial
private static final long serialVersionUID = 1L;
// ----------------------------------------------------------- Constructors
/**
* Construct a new Session associated with the specified Manager.
*
* @param manager The manager with which this Session is associated
*/
public StandardSession(Manager manager) {
super();
this.manager = manager;
if (manager != null) {
// Manager could be null in test environments
activityCheck = manager.getSessionActivityCheck();
lastAccessAtStart = manager.getSessionLastAccessAtStart();
}
// Initialize access count
if (activityCheck) {
accessCount = new AtomicInteger();
}
}
// ----------------------------------------------------- Instance Variables
/**
* Type array.
*/
protected static final String[] EMPTY_ARRAY = new String[0];
/**
* The collection of user data attributes associated with this Session.
*/
protected ConcurrentMap<String,Object> attributes = new ConcurrentHashMap<>();
/**
* The authentication type used to authenticate our cached Principal, if any. NOTE: This value is not included in
* the serialized version of this object.
*/
protected transient String authType = null;
/**
* The time this session was created, in milliseconds since midnight, January 1, 1970 GMT.
*/
protected long creationTime = 0L;
/**
* We are currently processing a session expiration, so bypass certain IllegalStateException tests. NOTE: This value
* is not included in the serialized version of this object.
*/
protected transient volatile boolean expiring = false;
/**
* The facade associated with this session. NOTE: This value is not included in the serialized version of this
* object.
*/
protected transient StandardSessionFacade facade = null;
/**
* The session identifier of this Session.
*/
protected String id = null;
/**
* The last accessed time for this Session.
*/
protected volatile long lastAccessedTime = creationTime;
/**
* The session event listeners for this Session.
*/
protected transient ArrayList<SessionListener> listeners = new ArrayList<>();
/**
* The Manager with which this Session is associated.
*/
protected transient Manager manager;
/**
* The maximum time interval, in seconds, between client requests before the servlet container may invalidate this
* session. A negative time indicates that the session should never time out.
*/
protected volatile int maxInactiveInterval = -1;
/**
* Flag indicating whether this session is new or not.
*/
protected volatile boolean isNew = false;
/**
* Flag indicating whether this session is valid or not.
*/
protected volatile boolean isValid = false;
/**
* Internal notes associated with this session by Catalina components and event listeners. <b>IMPLEMENTATION
* NOTE:</b> This object is <em>not</em> saved and restored across session serializations!
*/
protected transient Map<String,Object> notes = new ConcurrentHashMap<>();
/**
* The authenticated Principal associated with this session, if any. <b>IMPLEMENTATION NOTE:</b> This object is
* <i>not</i> saved and restored across session serializations!
*/
protected transient Principal principal = null;
/**
* The string manager for this package.
*/
protected static final StringManager sm = StringManager.getManager(StandardSession.class);
/**
* The property change support for this component. NOTE: This value is not included in the serialized version of
* this object.
*/
protected final transient PropertyChangeSupport support = new PropertyChangeSupport(this);
/**
* The current accessed time for this session.
*/
protected volatile long thisAccessedTime = creationTime;
/**
* The access count for this session.
*/
protected transient AtomicInteger accessCount = null;
/**
* The activity check for this session.
*/
protected transient boolean activityCheck;
/**
* The behavior of the last access check.
*/
protected transient boolean lastAccessAtStart;
// ----------------------------------------------------- Session Properties
@Override
public String getAuthType() {
return this.authType;
}
@Override
public void setAuthType(String authType) {
String oldAuthType = this.authType;
this.authType = authType;
support.firePropertyChange("authType", oldAuthType, this.authType);
}
@Override
public void setCreationTime(long time) {
this.creationTime = time;
this.lastAccessedTime = time;
this.thisAccessedTime = time;
}
@Override
public String getId() {
return this.id;
}
@Override
public String getIdInternal() {
return this.id;
}
@Override
public void setId(String id) {
setId(id, true);
}
@Override
public void setId(String id, boolean notify) {
if ((this.id != null) && (manager != null)) {
manager.remove(this);
}
this.id = id;
if (manager != null) {
manager.add(this);
}
if (notify) {
tellNew();
}
}
/**
* Inform the listeners about the new session.
*/
public void tellNew() {
// Notify interested session event listeners
fireSessionEvent(SESSION_CREATED_EVENT, null);
// Notify interested application event listeners
Context context = manager.getContext();
Object[] listeners = context.getApplicationLifecycleListeners();
if (listeners != null && listeners.length > 0) {
HttpSessionEvent event = new HttpSessionEvent(getSession());
for (Object o : listeners) {
if (!(o instanceof HttpSessionListener listener)) {
continue;
}
try {
context.fireContainerEvent("beforeSessionCreated", listener);
listener.sessionCreated(event);
context.fireContainerEvent("afterSessionCreated", listener);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
try {
context.fireContainerEvent("afterSessionCreated", listener);
} catch (Exception e) {
// Ignore
}
manager.getContext().getLogger().error(sm.getString("standardSession.sessionEvent"), t);
}
}
}
}
@Override
public void tellChangedSessionId(String newId, String oldId, boolean notifySessionListeners,
boolean notifyContainerListeners) {
Context context = manager.getContext();
// notify ContainerListeners
if (notifyContainerListeners) {
context.fireContainerEvent(Context.CHANGE_SESSION_ID_EVENT, new String[] { oldId, newId });
}
// notify HttpSessionIdListener
if (notifySessionListeners) {
Object[] listeners = context.getApplicationEventListeners();
if (listeners != null && listeners.length > 0) {
HttpSessionEvent event = new HttpSessionEvent(getSession());
for (Object listener : listeners) {
if (!(listener instanceof HttpSessionIdListener idListener)) {
continue;
}
try {
idListener.sessionIdChanged(event, oldId);
} catch (Throwable t) {
manager.getContext().getLogger().error(sm.getString("standardSession.sessionEvent"), t);
}
}
}
}
}
@Override
public long getThisAccessedTime() {
if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("standardSession.getThisAccessedTime.ise"));
}
return this.thisAccessedTime;
}
@Override
public long getThisAccessedTimeInternal() {
return this.thisAccessedTime;
}
@Override
public long getLastAccessedTime() {
if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("standardSession.getLastAccessedTime.ise"));
}
return this.lastAccessedTime;
}
@Override
public long getLastAccessedTimeInternal() {
return this.lastAccessedTime;
}
@Override
public long getIdleTime() {
if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("standardSession.getIdleTime.ise"));
}
return getIdleTimeInternal();
}
@Override
public long getIdleTimeInternal() {
long timeNow = System.currentTimeMillis();
long timeIdle;
if (lastAccessAtStart) {
timeIdle = timeNow - lastAccessedTime;
} else {
timeIdle = timeNow - thisAccessedTime;
}
return timeIdle;
}
@Override
public Manager getManager() {
return this.manager;
}
@Override
public void setManager(Manager manager) {
this.manager = manager;
}
@Override
public int getMaxInactiveInterval() {
return this.maxInactiveInterval;
}
@Override
public void setMaxInactiveInterval(int interval) {
this.maxInactiveInterval = interval;
}
@Override
public void setNew(boolean isNew) {
this.isNew = isNew;
}
@Override
public Principal getPrincipal() {
return this.principal;
}
@Override
public void setPrincipal(Principal principal) {
Principal oldPrincipal = this.principal;
this.principal = principal;
support.firePropertyChange("principal", oldPrincipal, this.principal);
}
@Override
public HttpSession getSession() {
if (facade == null) {
facade = new StandardSessionFacade(this);
}
return facade;
}
@Override
public boolean isValid() {
if (!this.isValid) {
return false;
}
if (this.expiring) {
return true;
}
if (activityCheck && accessCount.get() > 0) {
return true;
}
if (maxInactiveInterval > 0) {
int timeIdle = (int) (getIdleTimeInternal() / 1000L);
if (timeIdle >= maxInactiveInterval) {
expire(true);
}
}
return this.isValid;
}
@Override
public void setValid(boolean isValid) {
this.isValid = isValid;
}
@Override
public Accessor getAccessor() {
if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("standardSession.getAccessor.ise"));
}
return new StandardSessionAccessor(getManager(), getId());
}
// ------------------------------------------------- Session Public Methods
@Override
public void access() {
this.thisAccessedTime = System.currentTimeMillis();
if (activityCheck) {
accessCount.incrementAndGet();
}
}
@Override
public void endAccess() {
isNew = false;
/*
* The servlet spec mandates to ignore request handling time in lastAccessedTime.
*/
if (lastAccessAtStart) {
this.lastAccessedTime = this.thisAccessedTime;
this.thisAccessedTime = System.currentTimeMillis();
} else {
this.thisAccessedTime = System.currentTimeMillis();
this.lastAccessedTime = this.thisAccessedTime;
}
if (activityCheck) {
accessCount.decrementAndGet();
}
}
@Override
public void addSessionListener(SessionListener listener) {
listeners.add(listener);
}
@Override
public void expire() {
expire(true);
}
/**
* Perform the internal processing required to invalidate this session, without triggering an exception if the
* session has already expired.
*
* @param notify Should we notify listeners about the demise of this session?
*/
public void expire(boolean notify) {
// Check to see if session has already been invalidated.
// Do not check expiring at this point as expire should not return until
// isValid is false
if (!isValid) {
return;
}
synchronized (this) {
// Check again, now we are inside the sync so this code only runs once
// Double check locking - isValid needs to be volatile
// The check of expiring is to ensure that an infinite loop is not
// entered as per bug 56339
if (expiring || !isValid) {
return;
}
if (manager == null) {
return;
}
// Mark this session as "being expired"
expiring = true;
// Notify interested application event listeners
// Call listeners in reverse order
Context context = manager.getContext();
// The call to expire() may not have been triggered by the webapp.
// Make sure the webapp's class loader is set when calling the
// listeners
if (notify) {
ClassLoader oldContextClassLoader = null;
try {
oldContextClassLoader = context.bind(null);
Object[] listeners = context.getApplicationLifecycleListeners();
if (listeners != null && listeners.length > 0) {
HttpSessionEvent event = new HttpSessionEvent(getSession());
for (int i = 0; i < listeners.length; i++) {
int j = (listeners.length - 1) - i;
if (!(listeners[j] instanceof HttpSessionListener listener)) {
continue;
}
try {
context.fireContainerEvent("beforeSessionDestroyed", listener);
listener.sessionDestroyed(event);
context.fireContainerEvent("afterSessionDestroyed", listener);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
try {
context.fireContainerEvent("afterSessionDestroyed", listener);
} catch (Exception e) {
// Ignore
}
manager.getContext().getLogger().error(sm.getString("standardSession.sessionEvent"), t);
}
}
}
} finally {
context.unbind(oldContextClassLoader);
}
}
if (activityCheck) {
accessCount.set(0);
}
// Remove this session from our manager's active sessions
manager.remove(this, true);
// Notify interested session event listeners
if (notify) {
fireSessionEvent(SESSION_DESTROYED_EVENT, null);
}
// Call the logout method
if (principal instanceof TomcatPrincipal gp) {
try {
gp.logout();
} catch (Exception e) {
manager.getContext().getLogger().error(sm.getString("standardSession.logoutfail"), e);
}
}
// We have completed expire of this session
setValid(false);
expiring = false;
// Unbind any objects associated with this session
String[] keys = keys();
ClassLoader oldContextClassLoader = null;
try {
oldContextClassLoader = context.bind(null);
for (String key : keys) {
removeAttributeInternal(key, notify);
}
} finally {
context.unbind(oldContextClassLoader);
}
}
}
/**
* Perform the internal processing required to passivate this session.
*/
public void passivate() {
// Notify interested session event listeners
fireSessionEvent(SESSION_PASSIVATED_EVENT, null);
// Notify ActivationListeners
HttpSessionEvent event = null;
String[] keys = keys();
for (String key : keys) {
Object attribute = attributes.get(key);
if (attribute instanceof HttpSessionActivationListener) {
if (event == null) {
event = new HttpSessionEvent(getSession());
}
try {
((HttpSessionActivationListener) attribute).sessionWillPassivate(event);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
manager.getContext().getLogger().error(sm.getString("standardSession.attributeEvent"), t);
}
}
}
}
/**
* Perform internal processing required to activate this session.
*/
public void activate() {
// Initialize access count
if (activityCheck) {
accessCount = new AtomicInteger();
}
// Notify interested session event listeners
fireSessionEvent(SESSION_ACTIVATED_EVENT, null);
// Notify ActivationListeners
HttpSessionEvent event = null;
String[] keys = keys();
for (String key : keys) {
Object attribute = attributes.get(key);
if (attribute instanceof HttpSessionActivationListener) {
if (event == null) {
event = new HttpSessionEvent(getSession());
}
try {
((HttpSessionActivationListener) attribute).sessionDidActivate(event);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
manager.getContext().getLogger().error(sm.getString("standardSession.attributeEvent"), t);
}
}
}
}
@Override
public Object getNote(String name) {
return notes.get(name);
}
@Override
public Iterator<String> getNoteNames() {
return notes.keySet().iterator();
}
@Override
public void recycle() {
// Reset the instance variables associated with this Session
attributes.clear();
setAuthType(null);
creationTime = 0L;
expiring = false;
id = null;
lastAccessedTime = 0L;
maxInactiveInterval = -1;
notes.clear();
setPrincipal(null);
isNew = false;
isValid = false;
manager = null;
}
@Override
public void removeNote(String name) {
notes.remove(name);
}
@Override
public void removeSessionListener(SessionListener listener) {
listeners.remove(listener);
}
@Override
public void setNote(String name, Object value) {
notes.put(name, value);
}
@Override
public String toString() {
return "StandardSession[" + id + "]";
}
// ------------------------------------------------ Session Package Methods
/**
* Read a serialized version of the contents of this session object from the specified object input stream, without
* requiring that the StandardSession itself have been serialized.
*
* @param stream The object input stream to read from
*
* @exception ClassNotFoundException if an unknown class is specified
* @exception IOException if an input/output error occurs
*/
public void readObjectData(ObjectInputStream stream) throws ClassNotFoundException, IOException {
doReadObject(stream);
}
/**
* Write a serialized version of the contents of this session object to the specified object output stream, without
* requiring that the StandardSession itself have been serialized.
*
* @param stream The object output stream to write to
*
* @exception IOException if an input/output error occurs
*/
public void writeObjectData(ObjectOutputStream stream) throws IOException {
doWriteObject(stream);
}
// ------------------------------------------------- HttpSession Properties
@Override
public long getCreationTime() {
if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("standardSession.getCreationTime.ise"));
}
return this.creationTime;
}
@Override
public long getCreationTimeInternal() {
return this.creationTime;
}
@Override
public ServletContext getServletContext() {
if (manager == null) {
return null;
}
Context context = manager.getContext();
return context.getServletContext();
}
// ----------------------------------------------HttpSession Public Methods
@Override
public Object getAttribute(String name) {
if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("standardSession.getAttribute.ise"));
}
if (name == null) {
return null;
}
return attributes.get(name);
}
@Override
public Enumeration<String> getAttributeNames() {
if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("standardSession.getAttributeNames.ise"));
}
Set<String> names = new HashSet<>(attributes.keySet());
return Collections.enumeration(names);
}
@Override
public void invalidate() {
if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("standardSession.invalidate.ise"));
}
// Cause this session to expire
expire();
}
@Override
public boolean isNew() {
if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("standardSession.isNew.ise"));
}
return this.isNew;
}
@Override
public void removeAttribute(String name) {
removeAttribute(name, true);
}
/**
* Remove the object bound with the specified name from this session. If the session does not have an object bound
* with this name, this method does nothing.
* <p>
* After this method executes, and if the object implements <code>HttpSessionBindingListener</code>, the container
* calls <code>valueUnbound()</code> on the object.
*
* @param name Name of the object to remove from this session.
* @param notify Should we notify interested listeners that this attribute is being removed?
*
* @exception IllegalStateException if this method is called on an invalidated session
*/
public void removeAttribute(String name, boolean notify) {
// Validate our current state
if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("standardSession.removeAttribute.ise"));
}
removeAttributeInternal(name, notify);
}
@Override
public void setAttribute(String name, Object value) {
setAttribute(name, value, true);
}
/**
* Bind an object to this session, using the specified name. If an object of the same name is already bound to this
* session, the object is replaced.
* <p>
* After this method executes, and if the object implements <code>HttpSessionBindingListener</code>, the container
* calls <code>valueBound()</code> on the object.
*
* @param name Name to which the object is bound, cannot be null
* @param value Object to be bound, cannot be null
* @param notify whether to notify session listeners
*
* @exception IllegalArgumentException if an attempt is made to add a non-serializable object in an environment
* marked distributable.
* @exception IllegalStateException if this method is called on an invalidated session
*/
public void setAttribute(String name, Object value, boolean notify) {
// Name cannot be null
if (name == null) {
throw new IllegalArgumentException(sm.getString("standardSession.setAttribute.namenull"));
}
// Null value is the same as removeAttribute()
if (value == null) {
removeAttribute(name);
return;
}
// Validate our current state
if (!isValidInternal()) {
throw new IllegalStateException(sm.getString("standardSession.setAttribute.ise", getIdInternal()));
}
Context context = manager.getContext();
if (context.getDistributable() && !isAttributeDistributable(name, value) && !exclude(name, value)) {
throw new IllegalArgumentException(sm.getString("standardSession.setAttribute.iae", name));
}
// Construct an event with the new value
HttpSessionBindingEvent event = null;
// Call the valueBound() method if necessary
if (notify && value instanceof HttpSessionBindingListener) {
// Don't call any notification if replacing with the same value
// unless configured to do so
Object oldValue = attributes.get(name);
if (value != oldValue || manager.getNotifyBindingListenerOnUnchangedValue()) {
event = new HttpSessionBindingEvent(getSession(), name, value);
try {
((HttpSessionBindingListener) value).valueBound(event);
} catch (Throwable t) {
manager.getContext().getLogger().error(sm.getString("standardSession.bindingEvent"), t);
}
}
}
// Replace or add this attribute
Object unbound = attributes.put(name, value);
// Call the valueUnbound() method if necessary
if (notify && unbound instanceof HttpSessionBindingListener) {
// Don't call any notification if replacing with the same value
// unless configured to do so
if (unbound != value || manager.getNotifyBindingListenerOnUnchangedValue()) {
try {
((HttpSessionBindingListener) unbound)
.valueUnbound(new HttpSessionBindingEvent(getSession(), name));
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
manager.getContext().getLogger().error(sm.getString("standardSession.bindingEvent"), t);
}
}
}
if (!notify) {
return;
}
// Notify interested application event listeners
Object[] listeners = context.getApplicationEventListeners();
if (listeners == null) {
return;
}
for (Object o : listeners) {
if (!(o instanceof HttpSessionAttributeListener listener)) {
continue;
}
try {
if (unbound != null) {
if (unbound != value || manager.getNotifyAttributeListenerOnUnchangedValue()) {
context.fireContainerEvent("beforeSessionAttributeReplaced", listener);
if (event == null) {
event = new HttpSessionBindingEvent(getSession(), name, unbound);
}
listener.attributeReplaced(event);
context.fireContainerEvent("afterSessionAttributeReplaced", listener);
}
} else {
context.fireContainerEvent("beforeSessionAttributeAdded", listener);
if (event == null) {
event = new HttpSessionBindingEvent(getSession(), name, value);
}
listener.attributeAdded(event);
context.fireContainerEvent("afterSessionAttributeAdded", listener);
}
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
try {
if (unbound != null) {
if (unbound != value || manager.getNotifyAttributeListenerOnUnchangedValue()) {
context.fireContainerEvent("afterSessionAttributeReplaced", listener);
}
} else {
context.fireContainerEvent("afterSessionAttributeAdded", listener);
}
} catch (Exception e) {
// Ignore
}
manager.getContext().getLogger().error(sm.getString("standardSession.attributeEvent"), t);
}
}
}
// ------------------------------------------ HttpSession Protected Methods
/**
* @return the <code>isValid</code> flag for this session without any expiration check.
*/
protected boolean isValidInternal() {
return this.isValid;
}
/**
* {@inheritDoc}
* <p>
* This implementation simply checks the value for serializability. Subclasses might use other distribution
* technology not based on serialization and can override this check.
*/
@Override
public boolean isAttributeDistributable(String name, Object value) {
return value instanceof Serializable;
}
/**
* Read a serialized version of this session object from the specified object input stream.
* <p>
* <b>IMPLEMENTATION NOTE</b>: The reference to the owning Manager is not restored by this method, and must be set
* explicitly.
*
* @param stream The input stream to read from
*
* @exception ClassNotFoundException if an unknown class is specified
* @exception IOException if an input/output error occurs
*/
protected void doReadObject(ObjectInputStream stream) throws ClassNotFoundException, IOException {
// Deserialize the scalar instance variables (except Manager)
authType = null; // Transient (may be set later)
creationTime = ((Long) stream.readObject()).longValue();
lastAccessedTime = ((Long) stream.readObject()).longValue();
maxInactiveInterval = ((Integer) stream.readObject()).intValue();
isNew = ((Boolean) stream.readObject()).booleanValue();
isValid = ((Boolean) stream.readObject()).booleanValue();
thisAccessedTime = ((Long) stream.readObject()).longValue();
principal = null; // Transient (may be set later)
// setId((String) stream.readObject());
id = (String) stream.readObject();
if (manager.getContext().getLogger().isTraceEnabled()) {
manager.getContext().getLogger().trace("readObject() loading session " + id);
}
if (notes == null) {
notes = new ConcurrentHashMap<>();
}
/*
* The next object read could either be the number of attributes (Integer) or if authentication information is
* persisted then: - authType (String) - always present - Principal object - always present - expected session
* ID - present if BZ 66120 is fixed - saved request - present if BZ 66120 is fixed
*
* Note: Some, all or none of the above objects may be null
*/
Object nextObject = stream.readObject();
if (!(nextObject instanceof Integer)) {
// Not an Integer so the next two objects will be authType and
// Principal
setAuthType((String) nextObject);
try {
setPrincipal((Principal) stream.readObject());
} catch (ClassNotFoundException | ObjectStreamException e) {
String msg = sm.getString("standardSession.principalNotDeserializable", id);
if (manager.getContext().getLogger().isDebugEnabled()) {
manager.getContext().getLogger().debug(msg, e);
} else {
manager.getContext().getLogger().warn(msg);
}
throw e;
}
nextObject = stream.readObject();
if (!(nextObject instanceof Integer)) {
// Not an Integer so the next two objects will be
// 'expected session ID' and 'saved request'
if (nextObject != null) {
notes.put(org.apache.catalina.authenticator.Constants.SESSION_ID_NOTE, nextObject);
}
nextObject = stream.readObject();
if (nextObject != null) {
notes.put(org.apache.catalina.authenticator.Constants.FORM_REQUEST_NOTE, nextObject);
}
// Next object will be the number of attributes
nextObject = stream.readObject();
}
}
// Deserialize the attribute count and attribute values
if (attributes == null) {
attributes = new ConcurrentHashMap<>();
}
int n = ((Integer) nextObject).intValue();
boolean isValidSave = isValid;
isValid = true;
for (int i = 0; i < n; i++) {
String name = (String) stream.readObject();
final Object value;
try {
value = stream.readObject();
} catch (WriteAbortedException wae) {
if (wae.getCause() instanceof NotSerializableException) {
String msg = sm.getString("standardSession.notDeserializable", name, id);
if (manager.getContext().getLogger().isDebugEnabled()) {
manager.getContext().getLogger().debug(msg, wae);
} else {
manager.getContext().getLogger().warn(msg);
}
// Skip non serializable attributes
continue;
}
throw wae;
}
if (manager.getContext().getLogger().isTraceEnabled()) {
manager.getContext().getLogger().trace(" loading attribute '" + name + "' with value '" + value + "'");
}
// Handle the case where the filter configuration was changed while
// the web application was stopped.
if (exclude(name, value)) {
continue;
}
// ConcurrentHashMap does not allow null keys or values
if (null != value) {
attributes.put(name, value);
}
}
isValid = isValidSave;
if (listeners == null) {
listeners = new ArrayList<>();
}
}
/**
* Write a serialized version of this session object to the specified object output stream.
* <p>
* <b>IMPLEMENTATION NOTE</b>: The owning Manager will not be stored in the serialized representation of this
* Session. After calling <code>readObject()</code>, you must set the associated Manager explicitly.
* <p>
* <b>IMPLEMENTATION NOTE</b>: Any attribute that is not Serializable will be unbound from the session, with
* appropriate actions if it implements HttpSessionBindingListener. If you do not want any such attributes, be sure
* the <code>distributable</code> property of the associated Manager is set to <code>true</code>.
*
* @param stream The output stream to write to
*
* @exception IOException if an input/output error occurs
*/
protected void doWriteObject(ObjectOutputStream stream) throws IOException {
// Write the scalar instance variables (except Manager)
stream.writeObject(Long.valueOf(creationTime));
stream.writeObject(Long.valueOf(lastAccessedTime));
stream.writeObject(Integer.valueOf(maxInactiveInterval));
stream.writeObject(Boolean.valueOf(isNew));
stream.writeObject(Boolean.valueOf(isValid));
stream.writeObject(Long.valueOf(thisAccessedTime));
stream.writeObject(id);
if (manager.getContext().getLogger().isTraceEnabled()) {
manager.getContext().getLogger().trace("writeObject() storing session " + id);
}
// Gather authentication information (if configured)
String sessionAuthType = null;
Principal sessionPrincipal = null;
String expectedSessionId = null;
SavedRequest savedRequest = null;
if (getPersistAuthentication()) {
sessionAuthType = getAuthType();
sessionPrincipal = getPrincipal();
if (sessionPrincipal != null && !(sessionPrincipal instanceof Serializable)) {
sessionPrincipal = null;
manager.getContext().getLogger().warn(sm.getString("standardSession.principalNotSerializable", id));
}
expectedSessionId = (String) notes.get(org.apache.catalina.authenticator.Constants.SESSION_ID_NOTE);
savedRequest = (SavedRequest) notes.get(org.apache.catalina.authenticator.Constants.FORM_REQUEST_NOTE);
}
// Write authentication information (may be null values)
stream.writeObject(sessionAuthType);
try {
stream.writeObject(sessionPrincipal);
} catch (NotSerializableException e) {
manager.getContext().getLogger().warn(sm.getString("standardSession.principalNotSerializable", id), e);
}
stream.writeObject(expectedSessionId);
stream.writeObject(savedRequest);
// Accumulate the names of serializable and non-serializable attributes
String[] keys = keys();
List<String> saveNames = new ArrayList<>();
List<Object> saveValues = new ArrayList<>();
for (String key : keys) {
Object value = attributes.get(key);
if (value == null) {
// Continue
} else if (isAttributeDistributable(key, value) && !exclude(key, value)) {
saveNames.add(key);
saveValues.add(value);
} else {
removeAttributeInternal(key, true);
}
}
// Serialize the attribute count and the Serializable attributes
int n = saveNames.size();
stream.writeObject(Integer.valueOf(n));
for (int i = 0; i < n; i++) {
stream.writeObject(saveNames.get(i));
try {
stream.writeObject(saveValues.get(i));
if (manager.getContext().getLogger().isTraceEnabled()) {
manager.getContext().getLogger().trace(
" storing attribute '" + saveNames.get(i) + "' with value '" + saveValues.get(i) + "'");
}
} catch (NotSerializableException e) {
manager.getContext().getLogger()
.warn(sm.getString("standardSession.notSerializable", saveNames.get(i), id), e);
}
}
}
/**
* Return whether authentication information shall be persisted or not.
*
* @return {@code true}, if authentication information shall be persisted; {@code false} otherwise
*/
private boolean getPersistAuthentication() {
if (manager instanceof ManagerBase) {
return ((ManagerBase) manager).getPersistAuthentication();
}
return false;
}
/**
* Should the given session attribute be excluded? This implementation checks:
* <ul>
* <li>{@link Constants#excludedAttributeNames}</li>
* <li>{@link Manager#willAttributeDistribute(String, Object)}</li>
* </ul>
* Note: This method deliberately does not check {@link #isAttributeDistributable(String, Object)} which is kept
* separate to support the checks required in {@link #setAttribute(String, Object, boolean)}
*
* @param name The attribute name
* @param value The attribute value
*
* @return {@code true} if the attribute should be excluded from distribution, otherwise {@code false}
*/
protected boolean exclude(String name, Object value) {
if (Constants.excludedAttributeNames.contains(name)) {
return true;
}
// Manager is required for remaining check
Manager manager = getManager();
if (manager == null) {
// Manager may be null during replication of new sessions in a
// cluster. Avoid the NPE.
return false;
}
// Last check so use a short-cut
return !manager.willAttributeDistribute(name, value);
}
// ------------------------------------------------------ Protected Methods
/**
* Notify all session event listeners that a particular event has occurred for this Session. The default
* implementation performs this notification synchronously using the calling thread.
*
* @param type Event type
* @param data Event data
*/
public void fireSessionEvent(String type, Object data) {
if (listeners.isEmpty()) {
return;
}
SessionEvent event = new SessionEvent(this, type, data);
SessionListener[] list = new SessionListener[0];
synchronized (listeners) {
list = listeners.toArray(list);
}
for (SessionListener sessionListener : list) {
sessionListener.sessionEvent(event);
}
}
/**
* @return the names of all currently defined session attributes as an array of Strings. If there are no defined
* attributes, a zero-length array is returned.
*/
protected String[] keys() {
return attributes.keySet().toArray(EMPTY_ARRAY);
}
/**
* Remove the object bound with the specified name from this session. If the session does not have an object bound
* with this name, this method does nothing.
* <p>
* After this method executes, and if the object implements <code>HttpSessionBindingListener</code>, the container
* calls <code>valueUnbound()</code> on the object.
*
* @param name Name of the object to remove from this session.
* @param notify Should we notify interested listeners that this attribute is being removed?
*/
protected void removeAttributeInternal(String name, boolean notify) {
// Avoid NPE
if (name == null) {
return;
}
// Remove this attribute from our collection
Object value = attributes.remove(name);
// Do we need to do valueUnbound() and attributeRemoved() notification?
if (!notify || (value == null)) {
return;
}
// Call the valueUnbound() method if necessary
HttpSessionBindingEvent event = null;
if (value instanceof HttpSessionBindingListener) {
event = new HttpSessionBindingEvent(getSession(), name, value);
((HttpSessionBindingListener) value).valueUnbound(event);
}
// Notify interested application event listeners
Context context = manager.getContext();
Object[] listeners = context.getApplicationEventListeners();
if (listeners == null) {
return;
}
for (Object o : listeners) {
if (!(o instanceof HttpSessionAttributeListener listener)) {
continue;
}
try {
context.fireContainerEvent("beforeSessionAttributeRemoved", listener);
if (event == null) {
event = new HttpSessionBindingEvent(getSession(), name, value);
}
listener.attributeRemoved(event);
context.fireContainerEvent("afterSessionAttributeRemoved", listener);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
try {
context.fireContainerEvent("afterSessionAttributeRemoved", listener);
} catch (Exception e) {
// Ignore
}
manager.getContext().getLogger().error(sm.getString("standardSession.attributeEvent"), t);
}
}
}
}
|