This article shares locks and concurrency issues during the use of PHP sessions. Related phenomena include request blocking and session data Lost, session data cannot be read.
I can’t log in
One day, I was going to log in to one of our backend systems to solve a bug. Even though I entered the account and password verification codes accurately, I couldn't log in. After many experiments, I found that there were two main error messages:
Our System
Our system is developed based on phalcon 2.0.8. As you can see, we have added fields to prevent CSRF attacks in the form fields. Captcha is also enabled.
<input type="hidden" name="{{ security.getTokenKey() }}" value="{{ security.getToken() }}"/> <img src="/login/getCaptcha" id="img-captcha"/>
I first checked these two components and found that they both store data in the session:
# phalcon/security.zep # Security::getToken() let session = <SessionInterface> dependencyInjector->getShared("session"); session->set(this->_tokenValueSessionID, token); $this->session->set('admin_get_captcha_action', $captcha);
Then I checked the implementation of our session and found that the data is stored in redis.
Looking and looking
What is the problem that prevents me from logging in? Since there is a problem with data verification, let’s start with the data. I logged in to the redis machine in our test environment, executed redis-cli monitor, and then went through the login process and found the output as follows (meaning):
We can see:
1. There are two requests here, one is to load the form, and the other is to generate the verification code.
2. There is a "concurrency" situation. These two requests should request the verification code after the form is loaded and rendered. That is, the session sequence should be get->set->get->set. Why does it seem to be concurrent? Requested.
3. The latter SETEX has no csrf content, which means it overwrites the previous data
The whole world is not good, but I understand a little bit what the problem is. What's the problem? It's a long story, starting with PHP's session data access.
Access to php session data
The session data is encoded into a string and stored in the storage [file, db, redis, memcache, etc.]. When we use the session, when do we get the data from the storage? When is the data written to memory?
The answer to this question may be different from what some friends think. In a request, PHP will only read the memory once, during session_start, and then it will only write to the memory once, at the end of the request, or by calling During session_write_close, the data is flushed back to the memory and the session is closed.
Then the question is:
1. If there are two read and write session requests in a session at the same time, there is no guarantee of getting 1-writing 1-getting 2-writing 2, and there is no cas version management mechanism, these concurrent requests will interact with each other. If the other party's write cannot be read, the last write will overwrite the session written by the previous request.
2. If the request is serial, such as the form and verification code on the login page, it is possible that the previous request has already output the content, but the session has not yet been written, and the subsequent request has been initiated.
Locked or Unlocked
Solving the concurrency of such resources is generally handled through locks or version management. But I don't see a good way to do version management. Let’s talk about locks.
In fact, locks are not very suitable and have disadvantages.
PHP sessions are stored in files by default. When the session is opened, an exclusive lock will be added to the file. In this way, other requests cannot obtain the lock and can only wait until the previous lock is released.
This ensures the order of read-write, read-write.
Other storage, such as mysql, can use select for update to perform row locks. Redis can be implemented through an auto-increment key, returning 1 to acquire the lock, etc.
This implementation is ideal for data flow. However, for the current situation where ajax is widely used on pages, all requests will be queued for processing, which will greatly increase the time consumption of page display, and even cause request timeout and other unavailability. Fault.
There is no solution
It is not recommended to use session too much. The problems caused by its read-once-write-once mechanism will cause pitfalls.
Call session_write_close
before template rendering or output request
# 立刻回写session,避免session覆盖 $eventManager = $this->view->getEventsManager(); if (!$eventManager) { $eventManager = new Manager(); $this->view->setEventsManager($eventManager); } $eventManager->attach("view:afterRender",function(){ session_write_close(); }); return $this->view;
if($login) { # 立刻回写session,避免session读取不到 $eventManager = $this->dispatcher->getEventsManager(); if (!$eventManager) { $eventManager = new Manager(); $this->dispatcher->setEventsManager($eventManager); } $eventManager->attach('dispatch:afterDispatchLoop',function(){ session_write_close(); }); return $this->response->setHeader('Location', '/'); }
The above is about the locking and concurrency of php session. I hope it will be helpful to everyone's learning.