You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

371 lines
14 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
2 years ago
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "kernel.h"
  2. #define LOG( X ) m_pLog->Log( "KERNEL", this, X )
  3. #define LOG_ERROR( X ) m_pLog->Log( "KERNEL", this, _LOG_ERROR, X )
  4. SP_KERNEL *SP_KERNEL::_instance = NULL;
  5. SP_KERNEL *SP_KERNEL::getInstance( bool ColdStart ){
  6. if( _instance == NULL ) {
  7. _instance = new SP_KERNEL();
  8. };
  9. return _instance;
  10. };
  11. SP_KERNEL::SP_KERNEL(): basicThread(){
  12. m_pLog = basicLogCollection::getInstance();
  13. m_pSettings = basicSettingsProvider::getInstance()->getSubNode( NULL, (CSTR)"KERNEL" );
  14. m_iServerSocket = INVALID_SOCKET;
  15. m_iExitCause = 0;
  16. };
  17. SP_KERNEL::~SP_KERNEL(){
  18. if( m_iServerSocket != INVALID_SOCKET ) {
  19. shutdown( m_iServerSocket, 2 );
  20. close( m_iServerSocket );
  21. if( fileExist ( m_pUnixSocketName ) ) unlink( m_pUnixSocketName );
  22. };
  23. };
  24. void SP_KERNEL::wd_shutdown( void ){
  25. m_bThreadStatus = TH_ENDED;
  26. m_iExitCause = 33;
  27. };
  28. //Use Killall prior to kill all instances of mojo
  29. // https://stackoverflow.com/questions/8166415/how-to-get-the-pid-of-a-process-in-linux-in-c
  30. #include <sys/param.h>
  31. #include <sys/user.h>
  32. //#include <sys/sysctl.h>
  33. #include <sys/socket.h>
  34. #include <sys/un.h>
  35. #include <stdio.h>
  36. #include <stdlib.h>
  37. //https://www.educative.io/answers/unix-socket-programming-in-c
  38. /************************************************************************
  39. *
  40. * Returns the pid of the process name which is given as the function
  41. * argument.
  42. * In case no process found with the given name -1 will be returned.
  43. *
  44. ************************************************************************* /
  45. pid_t getProcessId(const char * csProcessName){
  46. struct kinfo_proc * sProcesses = NULL;
  47. struct kinfo_proc * sNewProcesses = NULL;
  48. pid_t iCurrentPid;
  49. int aiNames[4];
  50. size_t iNamesLength;
  51. int i, iRetCode, iNumProcs;
  52. size_t iSize = 0;
  53. aiNames[0] = CTL_KERN;
  54. aiNames[1] = KERN_PROC;
  55. aiNames[2] = KERN_PROC_ALL;
  56. aiNames[3] = 0;
  57. iNamesLength = 3;
  58. iRetCode = sysctl( aiNames, iNamesLength, NULL, &iSize, NULL, 0 );
  59. /*
  60. * Allocate memory and populate info in the processes structure
  61. * /
  62. do {
  63. iSize += iSize / 10;
  64. sNewProcesses = (struct kinfo_proc *) realloc( sProcesses, iSize );
  65. if( sNewProcesses == 0 ){
  66. if( sProcesses ) free(sProcesses);
  67. errx(1, "could not reallocate memory");
  68. };
  69. sProcesses = sNewProcesses;
  70. iRetCode = sysctl(aiNames, iNamesLength, sProcesses, &iSize, NULL, 0);
  71. } while ( iRetCode == -1 && errno == ENOMEM );
  72. iNumProcs = iSize / sizeof(struct kinfo_proc);
  73. /*
  74. * Search for the given process name and return its pid.
  75. * /
  76. for (i = 0; i < iNumProcs; i++) {
  77. iCurrentPid = sProcesses[i].kp_proc.p_pid;
  78. if( strncmp(csProcessName, sProcesses[i].kp_proc.p_comm, MAXCOMLEN) == 0 ) {
  79. free(sProcesses);
  80. return iCurrentPid;
  81. }
  82. }
  83. /*
  84. * Clean up and return -1 because the given proc name was not found
  85. * /
  86. free(sProcesses);
  87. return (-1);
  88. } /* end of getProcessId() * /
  89. int main(int argc, char **argv)
  90. {
  91. int pid = 0;
  92. pid = getProcessId( argv[1] );
  93. if( pid < 0 ){
  94. printf("process [%s] not found in the system\n", argv[1]);
  95. } else {
  96. printf("pid of [%s] is %d\n", argv[1], pid);
  97. }
  98. }
  99. */
  100. bool SP_KERNEL::create(void){
  101. char tBuffer[PATH_MAX];
  102. if( m_pSettings != NULL ) {
  103. config_setting_t * pSetting;
  104. int tVal;
  105. const char * tBuf;
  106. LOG("Getting Settings ...");
  107. if( !config_setting_lookup_string( m_pSettings, "SOCKET_PATH", &tBuf ) ){
  108. LOG("Socket Path not defined - generating dummy!");
  109. sprintf( m_pUnixSocketName, "/srv/etc/watchdog" );
  110. pSetting = config_setting_add( m_pSettings, "SOCKET_PATH", CONFIG_TYPE_STRING );
  111. config_setting_set_string( pSetting, m_pUnixSocketName );
  112. basicSettingsProvider::getInstance()->compromise();
  113. } else {
  114. sprintf( m_pUnixSocketName, tBuf );
  115. sprintf( tBuffer, "Socket Path From Settings: %s", tBuf );
  116. LOG( tBuffer );
  117. };
  118. /*
  119. if( !config_setting_lookup_string( m_pSettings, "TARGET_APP_FILE", &tBuf ) ){
  120. LOG("Target Application not defined - generating dummy!");
  121. sprintf( m_pTargetAppFile, "TARGET_APP_NAME" );
  122. pSetting = config_setting_add( m_pSettings, "TARGET_APP_FILE", CONFIG_TYPE_STRING );
  123. config_setting_set_string( pSetting, m_pTargetAppFile );
  124. basicSettingsProvider::getInstance()->compromise();
  125. basicSettingsProvider::getInstance()->validate();
  126. LOG_ERROR("Exiting!");
  127. return false;
  128. } else {
  129. sprintf( m_pTargetAppFile, "%s/%s", m_pTargetEnvPath, tBuf );
  130. sprintf( tBuffer, "Target Application Read From Settings: %s", tBuf );
  131. LOG( tBuffer );
  132. if( !fileExist ( m_pTargetAppFile ) ) {
  133. LOG_ERROR("Target Application File Not Exists!");
  134. LOG_ERROR("Exiting!");
  135. return false;
  136. };
  137. };
  138. if( !config_setting_lookup_string( m_pSettings, "TARGET_PID_FILE", &tBuf ) ){
  139. LOG("Target PID File not defined - generating dummy!");
  140. sprintf( m_pTargetPIDFile, "TARGET_FILE_PATH" );
  141. pSetting = config_setting_add( m_pSettings, "TARGET_PID_FILE", CONFIG_TYPE_STRING );
  142. config_setting_set_string( pSetting, m_pTargetPIDFile );
  143. basicSettingsProvider::getInstance()->compromise();
  144. basicSettingsProvider::getInstance()->validate();
  145. LOG_ERROR("Exiting!");
  146. return false;
  147. } else {
  148. sprintf( m_pTargetPIDFile, tBuf );
  149. sprintf( tBuffer, "Target PID File Read From Settings: %s", tBuf );
  150. LOG( tBuffer );
  151. if( !fileExist ( m_pTargetPIDFile ) ) {
  152. LOG_ERROR("Target PID File Not Exists!");
  153. LOG_ERROR("Starting Target Application!");
  154. if( !startTargetApplication() ){
  155. LOG_ERROR("Can not start application!");
  156. return false;
  157. };
  158. };
  159. };
  160. */
  161. basicSettingsProvider::getInstance()->validate();
  162. } else {
  163. LOG_ERROR("Failed Read Config Settings!");
  164. return false;
  165. };
  166. // Remove Dead Process Socket
  167. if ( fileExist( m_pUnixSocketName ) ) {
  168. unlink( m_pUnixSocketName );
  169. };
  170. m_iServerSocket = socket(AF_UNIX, SOCK_STREAM, 0);
  171. struct sockaddr_un server_addr;
  172. server_addr.sun_family = AF_UNIX;
  173. strcpy( server_addr.sun_path, m_pUnixSocketName );
  174. int slen = sizeof( server_addr );
  175. int x = fcntl( m_iServerSocket ,F_GETFL, 0);
  176. fcntl( m_iServerSocket, F_SETFL, x | O_NONBLOCK);
  177. bind( m_iServerSocket, (struct sockaddr *) &server_addr, slen );
  178. if ( m_iServerSocket == INVALID_SOCKET ){
  179. LOG_ERROR("Could not bind to the UX socket!");
  180. return false;
  181. };
  182. listen( m_iServerSocket, 5 );
  183. return init();
  184. };
  185. void SP_KERNEL::WaitFinish( bool force ){
  186. waitThreadEnd( force );
  187. };
  188. void *SP_KERNEL::sw_proc( void *ptr ){
  189. char tB[64];
  190. uint64_t cMS;
  191. uint64_t tMS;
  192. WATCHDOG_PROC_REC * mR = (WATCHDOG_PROC_REC *) ptr;
  193. pid_t CPID = 0;
  194. if ( mR ) {
  195. cMS = getMilliseconds();
  196. tMS = cMS + SW_DEFAULT_TIMEOUT;
  197. while( 1 ){
  198. cMS = getMilliseconds();
  199. int retVal = readLine( mR->client_socket, tB, 64 );
  200. if ( retVal < 0 ) {
  201. if( errno!=EAGAIN && errno!=EINTR ) {
  202. mR->master->m_pLog->Log( "K_T", mR->master, "Peer Closes Connection!");
  203. shutdown( mR->client_socket, 2 );
  204. close( mR->client_socket );
  205. mR->client_socket = -1;
  206. break; //-----> exit thread
  207. };
  208. } else {
  209. if ( retVal ) {
  210. //char jB[128];
  211. //sprintf( jB, "Server: I recieved [%d] %s from client!", retVal, tB );
  212. //mR->master->m_pLog->Log( "K_T", mR->master, jB );
  213. if( CPID ){
  214. int64_t nMS = atoll(tB);
  215. //Stop WD and exit
  216. if ( nMS < 0 ) {
  217. shutdown( mR->client_socket, 2 );
  218. close( mR->client_socket );
  219. mR->client_socket = -1;
  220. break;
  221. };
  222. //sprintf( jB, "Will Wait next [%d] milliseconds", nMS );
  223. //mR->master->m_pLog->Log( "K_T", mR->master, jB );
  224. tMS = cMS + nMS;
  225. } else {
  226. CPID = ( pid_t ) atoll(tB);
  227. };
  228. };
  229. };
  230. if ( cMS > tMS ) {
  231. // WD TO EXIT!
  232. mR->master->m_pLog->Log( "K_T", mR->master, "WD update STALLED!" );
  233. if ( CPID ) {
  234. // Try Kill Client Process;
  235. char jB[128];
  236. sprintf( jB, "Try Killing Process[%lld] By Signal 9!", CPID );
  237. mR->master->m_pLog->Log( "K_T", mR->master, jB );
  238. kill( CPID, 9 );
  239. } else {
  240. mR->master->wd_shutdown();
  241. };
  242. break; //-----> exit thread
  243. };
  244. SLEEP( SW_TIMEOUT_PERCISION );
  245. };
  246. };
  247. mR->finished = true;
  248. pthread_exit( NULL );
  249. return NULL;
  250. /*
  251. read(client_socket, &ch, 1);
  252. printf("\nServer: I recieved %c from client!\n", ch);
  253. ch++;
  254. write(client_socket, &ch, 1);
  255. close(client_socket);
  256. */
  257. };
  258. void SP_KERNEL::m_fThreadProc( void ){
  259. struct sockaddr_un client_addr;
  260. unsigned int clen = sizeof( client_addr );
  261. int ClientSocket;
  262. m_bThreadStatus = TH_WORKING;
  263. while( m_bThreadStatus < TH_ENDED ) {
  264. ClientSocket = accept( m_iServerSocket, (struct sockaddr *) &client_addr, &clen );
  265. if ( ClientSocket < 0 ) {
  266. switch( errno ){
  267. case EAGAIN:{
  268. // Checkup client disconnection
  269. if( m_vWPV.size()) {
  270. for( WATCHDOG_PROCS_VECTOR::iterator index = m_vWPV.begin(); index < m_vWPV.end(); index++ ) {
  271. if( (*index)->finished ){
  272. LOG("Detach WD Procedure");
  273. pthread_join((*index)->handler, NULL);
  274. LOG("WD Procedure Detached");
  275. // Remove Client Handler
  276. LOG("Remove WD Procedure");
  277. m_vWPV.erase( index );
  278. };
  279. };
  280. };
  281. SLEEP(10);
  282. continue;
  283. };
  284. //case EWOULDBLOCK: me->Log(" The socket is marked non-blocking and no connections are present to be accepted."); break;
  285. case EBADF: LOG_ERROR( "The descriptor is invalid." ); break;
  286. case ECONNABORTED: LOG_ERROR( "A connection has been aborted."); break;
  287. case EINTR: LOG_ERROR( "The system call was interrupted by a signal that was caught before a valid connection arrived."); break;
  288. case EINVAL: LOG_ERROR( "Socket is not listening for connections, or addrlen is invalid (e.g., is negative)."); break;
  289. case EMFILE: LOG_ERROR( "The per-process limit of open file descriptors has been reached."); break;
  290. case ENFILE: LOG_ERROR( "The system limit on the total number of open files has been reached."); break;
  291. case ENOTSOCK: LOG_ERROR( "The descriptor references a file, not a socket."); break;
  292. case EOPNOTSUPP: LOG_ERROR( "The referenced socket is not of type SOCK_STREAM."); break;
  293. case EFAULT: LOG_ERROR( "The addr argument is not in a writable part of the user address space."); break;
  294. case ENOBUFS:
  295. case ENOMEM: LOG_ERROR( "Not enough free memory. This often means that the memory allocation is limited by the socket buffer limits, not by the system memory."); break;
  296. case EPROTO: LOG_ERROR( "Protocol error."); break;
  297. case EPERM: LOG_ERROR( "Firewall rules forbid connection."); break;
  298. case ENOSR:
  299. #ifdef __linux__
  300. case ESOCKTNOSUPPORT:
  301. #endif
  302. case EPROTONOSUPPORT:
  303. case ETIMEDOUT: LOG_ERROR( " Unusual error in Kernel (Timeout, No Socket Support in Kernel, Unsupported Protocol)"); break;
  304. //case ERESTARTSYS: me->Log(" Unusual error by Kernel"); break;
  305. default: LOG_ERROR( " Unhandled error in Kernel"); break;
  306. };
  307. m_bThreadStatus = TH_ENDED;
  308. } else {
  309. WATCHDOG_PROC_REC *tPRC = (WATCHDOG_PROC_REC *) malloc(sizeof(WATCHDOG_PROC_REC));
  310. if ( tPRC ) {
  311. int x = fcntl( ClientSocket, F_GETFL, 0 );
  312. fcntl( ClientSocket, F_SETFL, x | O_NONBLOCK );
  313. tPRC->client_socket = ClientSocket;
  314. tPRC->master = this;
  315. int RetVal = pthread_create( &tPRC->handler, NULL, sw_proc, ( void * ) tPRC );
  316. if( RetVal == -1 ) {
  317. LOG_ERROR("No Client Thread Created!");
  318. shutdown( ClientSocket, 2 );
  319. close( ClientSocket );
  320. } else {
  321. LOG("New Handler Created");
  322. m_vWPV.push_back( tPRC );
  323. };
  324. } else {
  325. LOG_ERROR("No Client Handler Created!");
  326. shutdown( ClientSocket, 2 );
  327. close( ClientSocket );
  328. };
  329. };
  330. };
  331. };
  332. #undef LOG_ERROR
  333. #undef LOG