swad-core/swad_session.c

505 lines
20 KiB
C
Raw Normal View History

2014-12-01 23:55:08 +01:00
// swad_session.c: sessions
/*
SWAD (Shared Workspace At a Distance),
is a web platform developed at the University of Granada (Spain),
and used to support university teaching.
This file is part of SWAD core.
2017-01-13 01:51:23 +01:00
Copyright (C) 1999-2017 Antonio Ca<EFBFBD>as Vargas
2014-12-01 23:55:08 +01:00
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*****************************************************************************/
/************************************ Headers ********************************/
/*****************************************************************************/
#include <linux/stddef.h> // For NULL
#include <mysql/mysql.h> // To access MySQL databases
#include <stdio.h> // For sprintf
2017-03-14 10:04:35 +01:00
#include <stdlib.h> // For malloc and free
2014-12-01 23:55:08 +01:00
#include <string.h> // For string functions
#include "swad_connected.h"
#include "swad_database.h"
#include "swad_global.h"
#include "swad_parameter.h"
2016-01-12 20:58:19 +01:00
#include "swad_social.h"
2014-12-01 23:55:08 +01:00
/*****************************************************************************/
/**************************** Internal constants *****************************/
/*****************************************************************************/
/*****************************************************************************/
/************** External global variables from others modules ****************/
/*****************************************************************************/
extern struct Globals Gbl;
/*****************************************************************************/
/***************************** Internal prototypes ***************************/
/*****************************************************************************/
2016-01-12 20:58:19 +01:00
static void Ses_RemoveSessionFromDB (void);
2017-05-09 20:56:02 +02:00
static bool Ses_CheckIfHiddenParIsAlreadyInDB (Act_Action_t NextAction,
const char *ParamName);
2014-12-01 23:55:08 +01:00
/*****************************************************************************/
/************************** Get number of open sessions **********************/
/*****************************************************************************/
void Ses_GetNumSessions (void)
{
char Query[128];
/***** Get the number of open sessions from database *****/
sprintf (Query,"SELECT COUNT(*) FROM sessions");
Gbl.Session.NumSessions = (unsigned) DB_QueryCOUNT (Query,"can not get the number of open sessions");
Gbl.Usrs.Connected.TimeToRefreshInMs = (unsigned long) (Gbl.Session.NumSessions/Cfg_TIMES_PER_SECOND_REFRESH_CONNECTED) * 1000UL;
if (Gbl.Usrs.Connected.TimeToRefreshInMs < Con_MIN_TIME_TO_REFRESH_CONNECTED_IN_MS)
Gbl.Usrs.Connected.TimeToRefreshInMs = Con_MIN_TIME_TO_REFRESH_CONNECTED_IN_MS;
else if (Gbl.Usrs.Connected.TimeToRefreshInMs > Con_MAX_TIME_TO_REFRESH_CONNECTED_IN_MS)
Gbl.Usrs.Connected.TimeToRefreshInMs = Con_MAX_TIME_TO_REFRESH_CONNECTED_IN_MS;
}
/*****************************************************************************/
/*************************** Create a new session ****************************/
/*****************************************************************************/
void Ses_CreateSession (void)
{
/***** Create a unique name for the session *****/
2017-01-17 03:10:43 +01:00
Str_Copy (Gbl.Session.Id,Gbl.UniqueNameEncrypted,
2017-03-13 14:22:36 +01:00
Ses_BYTES_SESSION_ID);
2014-12-01 23:55:08 +01:00
/***** Check that session is not open *****/
if (Ses_CheckIfSessionExists (Gbl.Session.Id))
Lay_ShowErrorAndExit ("Can not create session.");
/***** Add session to database *****/
Ses_InsertSessionInDB ();
/***** Update time and course in connected list *****/
Con_UpdateMeInConnectedList ();
/***** Update number of open sessions in order to show them properly *****/
Ses_GetNumSessions ();
}
/*****************************************************************************/
/*********** Check if the session already exists in the database *************/
/*****************************************************************************/
// Return true if session exists
// Return false if session does not exist or error
bool Ses_CheckIfSessionExists (const char *IdSes)
{
2017-03-13 14:22:36 +01:00
char Query[128 + Ses_BYTES_SESSION_ID];
2014-12-01 23:55:08 +01:00
/***** Get if session already exists in database *****/
sprintf (Query,"SELECT COUNT(*) FROM sessions WHERE SessionId='%s'",
IdSes);
return (DB_QueryCOUNT (Query,"can not check if a session already existed") != 0);
}
/*****************************************************************************/
/************************** Close current session ****************************/
/*****************************************************************************/
void Ses_CloseSession (void)
{
if (Gbl.Usrs.Me.Logged)
{
/***** Remove session from database *****/
Ses_RemoveSessionFromDB ();
Gbl.Session.IsOpen = false;
// Gbl.Session.HasBeenDisconnected = true;
Gbl.Session.Id[0] = '\0';
/***** If there are no more sessions for current user ==> remove user from connected list *****/
Con_RemoveOldConnected ();
Ses_RemoveHiddenParFromExpiredSessions ();
/***** Now, user is not logged in *****/
2017-06-04 14:22:04 +02:00
Gbl.Usrs.Me.Roles.LoggedRoleBeforeCloseSession = Gbl.Usrs.Me.Roles.LoggedRole;
2014-12-01 23:55:08 +01:00
Gbl.Usrs.Me.Logged = false;
2015-01-20 20:03:38 +01:00
Gbl.Usrs.Me.IBelongToCurrentIns = false;
Gbl.Usrs.Me.IBelongToCurrentCtr = false;
Gbl.Usrs.Me.IBelongToCurrentDeg = false;
2014-12-01 23:55:08 +01:00
Gbl.Usrs.Me.IBelongToCurrentCrs = false;
2017-06-04 14:22:04 +02:00
Gbl.Usrs.Me.Roles.LoggedRole = Rol_UNK; // Don't uncomment this line. Don't change the role to unknown. Keep user's role in order to log the access
2016-10-28 10:03:37 +02:00
Gbl.Usrs.Me.MyCrss.Filled = false;
Gbl.Usrs.Me.MyCrss.Num = 0;
2014-12-01 23:55:08 +01:00
/***** Update number of open sessions in order to show them properly *****/
Ses_GetNumSessions ();
}
}
/*****************************************************************************/
/******************** Insert new session in the database *********************/
/*****************************************************************************/
void Ses_InsertSessionInDB (void)
{
2017-03-13 14:22:36 +01:00
char Query[1024 +
Ses_BYTES_SESSION_ID +
Pwd_BYTES_ENCRYPTED_PASSWORD];
2014-12-01 23:55:08 +01:00
/***** Insert session in the database *****/
2017-01-29 12:42:19 +01:00
if (Gbl.Search.WhatToSearch == Sch_SEARCH_UNKNOWN)
Gbl.Search.WhatToSearch = Sch_WHAT_TO_SEARCH_DEFAULT;
2017-03-13 13:17:53 +01:00
sprintf (Query,"INSERT INTO sessions"
" (SessionId,UsrCod,Password,Role,"
2016-05-03 14:54:12 +02:00
"CtyCod,InsCod,CtrCod,DegCod,CrsCod,LastTime,LastRefresh,WhatToSearch)"
2017-03-13 13:17:53 +01:00
" VALUES"
2017-03-24 01:09:27 +01:00
" ('%s',%ld,'%s',%u,"
"%ld,%ld,%ld,%ld,%ld,NOW(),NOW(),%u)",
2014-12-01 23:55:08 +01:00
Gbl.Session.Id,
Gbl.Usrs.Me.UsrDat.UsrCod,
Gbl.Usrs.Me.UsrDat.Password,
2017-06-04 14:22:04 +02:00
(unsigned) Gbl.Usrs.Me.Roles.LoggedRole,
2014-12-01 23:55:08 +01:00
Gbl.CurrentCty.Cty.CtyCod,
Gbl.CurrentIns.Ins.InsCod,
Gbl.CurrentCtr.Ctr.CtrCod,
Gbl.CurrentDeg.Deg.DegCod,
Gbl.CurrentCrs.Crs.CrsCod,
Gbl.Search.WhatToSearch);
DB_QueryINSERT (Query,"can not create session");
}
/*****************************************************************************/
/***************** Modify data of session in the database ********************/
/*****************************************************************************/
void Ses_UpdateSessionDataInDB (void)
{
2017-03-13 14:22:36 +01:00
char Query[1024 +
Pwd_BYTES_ENCRYPTED_PASSWORD +
Ses_BYTES_SESSION_ID];
2014-12-01 23:55:08 +01:00
/***** Update session in database *****/
2017-03-24 01:09:27 +01:00
sprintf (Query,"UPDATE sessions SET UsrCod=%ld,Password='%s',Role=%u,"
"CtyCod=%ld,InsCod=%ld,CtrCod=%ld,DegCod=%ld,CrsCod=%ld,"
2014-12-01 23:55:08 +01:00
"LastTime=NOW(),LastRefresh=NOW()"
" WHERE SessionId='%s'",
Gbl.Usrs.Me.UsrDat.UsrCod,
Gbl.Usrs.Me.UsrDat.Password,
2017-06-04 14:22:04 +02:00
(unsigned) Gbl.Usrs.Me.Roles.LoggedRole,
2014-12-01 23:55:08 +01:00
Gbl.CurrentCty.Cty.CtyCod,
Gbl.CurrentIns.Ins.InsCod,
Gbl.CurrentCtr.Ctr.CtrCod,
Gbl.CurrentDeg.Deg.DegCod,
Gbl.CurrentCrs.Crs.CrsCod,
Gbl.Session.Id);
DB_QueryUPDATE (Query,"can not update session");
}
/*****************************************************************************/
/******************** Modify session last refresh in database ****************/
/*****************************************************************************/
void Ses_UpdateSessionLastRefreshInDB (void)
{
2017-03-13 14:22:36 +01:00
char Query[128 + Ses_BYTES_SESSION_ID];
2014-12-01 23:55:08 +01:00
/***** Update session in database *****/
2017-03-13 14:22:36 +01:00
sprintf (Query,"UPDATE sessions SET LastRefresh=NOW() WHERE SessionId='%s'",
2014-12-01 23:55:08 +01:00
Gbl.Session.Id);
DB_QueryUPDATE (Query,"can not update session");
}
/*****************************************************************************/
/********************** Remove session from the database *********************/
/*****************************************************************************/
2016-01-12 20:58:19 +01:00
static void Ses_RemoveSessionFromDB (void)
2014-12-01 23:55:08 +01:00
{
2017-03-13 14:22:36 +01:00
char Query[128 + Ses_BYTES_SESSION_ID];
2014-12-01 23:55:08 +01:00
/***** Remove current session *****/
sprintf (Query,"DELETE FROM sessions WHERE SessionId='%s'",
Gbl.Session.Id);
DB_QueryDELETE (Query,"can not remove a session");
2016-01-12 20:58:19 +01:00
/***** Clear old unused social timelines in database *****/
// This is necessary to prevent the table growing and growing
Soc_ClearOldTimelinesDB ();
2014-12-01 23:55:08 +01:00
}
/*****************************************************************************/
/*************************** Remove expired sessions *************************/
/*****************************************************************************/
void Ses_RemoveExpiredSessions (void)
{
char Query[1024];
/***** Remove expired sessions *****/
2015-11-11 09:53:36 +01:00
/* A session expire
when last click (LastTime) is too old,
or (when there was at least one refresh (navigator supports AJAX)
and last refresh is too old (browser probably was closed)) */
2014-12-01 23:55:08 +01:00
sprintf (Query,"DELETE LOW_PRIORITY FROM sessions WHERE"
2015-11-11 09:53:36 +01:00
" LastTime<FROM_UNIXTIME(UNIX_TIMESTAMP()-'%lu')"
" OR "
"(LastRefresh>LastTime+INTERVAL 1 SECOND"
" AND"
" LastRefresh<FROM_UNIXTIME(UNIX_TIMESTAMP()-'%lu'))",
2014-12-01 23:55:08 +01:00
Cfg_TIME_TO_CLOSE_SESSION_FROM_LAST_CLICK,
Cfg_TIME_TO_CLOSE_SESSION_FROM_LAST_REFRESH);
DB_QueryDELETE (Query,"can not remove expired sessions");
}
/*****************************************************************************/
/******* Get the data (user code and password) of an initiated session *******/
/*****************************************************************************/
bool Ses_GetSessionData (void)
{
2017-03-13 14:22:36 +01:00
char Query[256 + Ses_BYTES_SESSION_ID];
2014-12-01 23:55:08 +01:00
MYSQL_RES *mysql_res;
MYSQL_ROW row;
unsigned UnsignedNum;
bool Result = false;
/***** Query data of session from database *****/
sprintf (Query,"SELECT UsrCod,Password,Role,"
"CtyCod,InsCod,CtrCod,DegCod,CrsCod,"
2017-03-12 21:15:32 +01:00
"WhatToSearch,SearchStr"
2014-12-01 23:55:08 +01:00
" FROM sessions WHERE SessionId='%s'",
Gbl.Session.Id);
/***** Check if the session existed in the database *****/
if (DB_QuerySELECT (Query,&mysql_res,"can not get data of session"))
{
row = mysql_fetch_row (mysql_res);
/***** Get user code (row[0]) *****/
Gbl.Session.UsrCod = Str_ConvertStrCodToLongCod (row[0]);
/***** Get password (row[1]) *****/
2017-01-15 22:58:26 +01:00
Str_Copy (Gbl.Usrs.Me.LoginEncryptedPassword,row[1],
2017-03-13 14:22:36 +01:00
Pwd_BYTES_ENCRYPTED_PASSWORD);
2014-12-01 23:55:08 +01:00
/***** Get logged user type (row[2]) *****/
2017-06-04 14:22:04 +02:00
if (sscanf (row[2],"%u",&Gbl.Usrs.Me.Roles.RoleFromSession) != 1)
Gbl.Usrs.Me.Roles.RoleFromSession = Rol_UNK;
2014-12-01 23:55:08 +01:00
/***** Get country code (row[3]) *****/
Gbl.CurrentCty.Cty.CtyCod = Str_ConvertStrCodToLongCod (row[3]);
/***** Get institution code (row[4]) *****/
Gbl.CurrentIns.Ins.InsCod = Str_ConvertStrCodToLongCod (row[4]);
/***** Get centre code (row[5]) *****/
Gbl.CurrentCtr.Ctr.CtrCod = Str_ConvertStrCodToLongCod (row[5]);
/***** Get degree code (row[6]) *****/
Gbl.CurrentDeg.Deg.DegCod = Str_ConvertStrCodToLongCod (row[6]);
/***** Get course code (row[7]) *****/
Gbl.CurrentCrs.Crs.CrsCod = Str_ConvertStrCodToLongCod (row[7]);
/***** Get last search *****/
2016-01-17 15:10:54 +01:00
if (Gbl.Action.Act != ActLogOut) // When closing session, last search will not be needed
2014-12-01 23:55:08 +01:00
{
/* Get what to search (row[8]) */
2017-01-29 12:42:19 +01:00
Gbl.Search.WhatToSearch = Sch_SEARCH_UNKNOWN;
2014-12-01 23:55:08 +01:00
if (sscanf (row[8],"%u",&UnsignedNum) == 1)
if (UnsignedNum < Sch_NUM_WHAT_TO_SEARCH)
Gbl.Search.WhatToSearch = (Sch_WhatToSearch_t) UnsignedNum;
2017-01-29 12:42:19 +01:00
if (Gbl.Search.WhatToSearch == Sch_SEARCH_UNKNOWN)
Gbl.Search.WhatToSearch = Sch_WHAT_TO_SEARCH_DEFAULT;
2014-12-01 23:55:08 +01:00
/* Get search string (row[9]) */
2017-01-17 03:10:43 +01:00
Str_Copy (Gbl.Search.Str,row[9],
2017-03-07 11:03:05 +01:00
Sch_MAX_BYTES_STRING_TO_FIND);
2014-12-01 23:55:08 +01:00
}
Result = true;
}
/***** Free structure that stores the query result *****/
DB_FreeMySQLResult (&mysql_res);
return Result;
}
/*****************************************************************************/
/******************* Insert hidden parameter in the database *****************/
/*****************************************************************************/
2017-05-09 20:56:02 +02:00
void Ses_InsertHiddenParInDB (Act_Action_t NextAction,
const char *ParamName,const char *ParamValue)
2014-12-01 23:55:08 +01:00
{
2017-05-09 20:56:02 +02:00
extern struct Act_Actions Act_Actions[Act_NUM_ACTIONS];
2017-03-12 16:39:16 +01:00
char *Query;
2017-03-15 11:10:16 +01:00
size_t LengthParamName;
size_t LengthParamValue;
2017-03-12 16:39:16 +01:00
size_t MaxLength;
2014-12-01 23:55:08 +01:00
/***** Before of inserting the first hidden parameter passed to the next action,
delete all the parameters coming from the previous action *****/
2017-02-05 22:23:41 +01:00
Ses_RemoveHiddenParFromThisSession ();
2014-12-01 23:55:08 +01:00
/***** For a unique session-action-parameter, don't insert a parameter more than one time *****/
2017-03-15 11:10:16 +01:00
if (ParamName)
if ((LengthParamName = strlen (ParamName)))
2017-05-09 20:56:02 +02:00
if (!Ses_CheckIfHiddenParIsAlreadyInDB (NextAction,ParamName))
2017-03-15 11:10:16 +01:00
{
/***** Allocate space for query *****/
if (ParamValue)
LengthParamValue = strlen (ParamValue);
else
LengthParamValue = 0;
MaxLength = 256 +
Ses_BYTES_SESSION_ID +
LengthParamName +
LengthParamValue;
if ((Query = (char *) malloc (MaxLength + 1)) == NULL)
Lay_ShowErrorAndExit ("Not enough memory for query.");
/***** Insert parameter in the database *****/
sprintf (Query,"INSERT INTO hidden_params"
" (SessionId,Action,ParamName,ParamValue)"
" VALUES"
2017-05-09 20:56:02 +02:00
" ('%s',%ld,'%s','%s')",
Gbl.Session.Id,
Act_Actions[NextAction].ActCod,
2017-03-15 11:10:16 +01:00
ParamName,
LengthParamValue ? ParamValue :
"");
DB_QueryINSERT (Query,"can not create hidden parameter");
Gbl.HiddenParamsInsertedIntoDB = true;
/***** Free query *****/
free ((void *) Query);
}
2014-12-01 23:55:08 +01:00
}
/*****************************************************************************/
/************ Remove hidden parameters of a session from database ************/
/*****************************************************************************/
void Ses_RemoveHiddenParFromThisSession (void)
{
2017-03-13 14:22:36 +01:00
char Query[128 + Ses_BYTES_SESSION_ID];
2014-12-01 23:55:08 +01:00
2017-02-05 22:23:41 +01:00
if (Gbl.Session.IsOpen && // There is an open session
!Gbl.HiddenParamsInsertedIntoDB) // No params just inserted
2014-12-01 23:55:08 +01:00
{
/***** Remove hidden parameters of this session *****/
sprintf (Query,"DELETE FROM hidden_params WHERE SessionId='%s'",
Gbl.Session.Id);
DB_QueryDELETE (Query,"can not remove hidden parameters of current session");
}
}
/*****************************************************************************/
/********* Remove expired hidden parameters (from expired sessions) **********/
/*****************************************************************************/
void Ses_RemoveHiddenParFromExpiredSessions (void)
{
2017-03-13 14:22:36 +01:00
char Query[256];
2014-12-01 23:55:08 +01:00
/***** Remove hidden parameters from expired sessions *****/
sprintf (Query,"DELETE FROM hidden_params"
" WHERE SessionId NOT IN (SELECT SessionId FROM sessions)");
DB_QueryDELETE (Query,"can not remove hidden parameters of expired sessions");
}
/*****************************************************************************/
/*************** Check if a hidden parameter existed in database *************/
/*****************************************************************************/
// Return true if the parameter already existed in database
2017-05-09 20:56:02 +02:00
static bool Ses_CheckIfHiddenParIsAlreadyInDB (Act_Action_t NextAction,
const char *ParamName)
2014-12-01 23:55:08 +01:00
{
2017-05-09 20:56:02 +02:00
extern struct Act_Actions Act_Actions[Act_NUM_ACTIONS];
char Query[512 + Ses_BYTES_SESSION_ID];
2014-12-01 23:55:08 +01:00
/***** Get a hidden parameter from database *****/
sprintf (Query,"SELECT COUNT(*) FROM hidden_params"
2017-05-09 20:56:02 +02:00
" WHERE SessionId='%s' AND Action=%ld AND ParamName='%s'",
Gbl.Session.Id,Act_Actions[NextAction].ActCod,ParamName);
2014-12-01 23:55:08 +01:00
return (DB_QueryCOUNT (Query,"can not check if a hidden parameter is already in database") != 0);
}
/*****************************************************************************/
/***************** Get hidden parameter from the database ********************/
/*****************************************************************************/
// Return true if the parameter is too big
2017-05-09 20:56:02 +02:00
unsigned Ses_GetHiddenParFromDB (Act_Action_t NextAction,
const char *ParamName,char *ParamValue,
size_t MaxBytes)
2014-12-01 23:55:08 +01:00
{
2017-05-09 20:56:02 +02:00
extern struct Act_Actions Act_Actions[Act_NUM_ACTIONS];
char Query[512 + Ses_BYTES_SESSION_ID];
2014-12-01 23:55:08 +01:00
MYSQL_RES *mysql_res;
MYSQL_ROW row;
unsigned long NumRows;
bool ParameterIsTooBig = false;
unsigned NumTimes = 0;
const char *Ptr;
ParamValue[0] = '\0';
if (Gbl.Session.IsOpen) // If the session is open, get parameter from DB
{
/***** Get a hidden parameter from database *****/
sprintf (Query,"SELECT ParamValue FROM hidden_params"
2017-05-09 20:56:02 +02:00
" WHERE SessionId='%s' AND Action=%ld AND ParamName='%s'",
Gbl.Session.Id,Act_Actions[NextAction].ActCod,ParamName);
2014-12-01 23:55:08 +01:00
NumRows = DB_QuerySELECT (Query,&mysql_res,"can not get a hidden parameter");
/***** Check if the parameter is found in database *****/
if (NumRows)
{
/***** Get the value del parameter *****/
row = mysql_fetch_row (mysql_res);
2017-01-17 03:10:43 +01:00
2014-12-01 23:55:08 +01:00
ParameterIsTooBig = (strlen (row[0]) > MaxBytes);
2017-01-17 03:10:43 +01:00
if (!ParameterIsTooBig)
Str_Copy (ParamValue,row[0],
MaxBytes);
2014-12-01 23:55:08 +01:00
}
/***** Free structure that stores the query result *****/
DB_FreeMySQLResult (&mysql_res);
}
if (ParameterIsTooBig)
{
2017-05-10 10:25:01 +02:00
sprintf (Gbl.Alert.Txt,"Hidden parameter <strong>%s</strong> too large,"
2014-12-01 23:55:08 +01:00
" it exceed the maximum allowed size (%lu bytes).",
ParamName,(unsigned long) MaxBytes);
2017-05-10 10:25:01 +02:00
Lay_ShowErrorAndExit (Gbl.Alert.Txt);
2014-12-01 23:55:08 +01:00
}
/***** Count number of values of the parameter *****/
Ptr = ParamValue;
while (*Ptr)
if (Par_GetNextStrUntilSeparParamMult (&Ptr,NULL,MaxBytes)) // Characters found?
NumTimes++;
return NumTimes;
}