Exemple #1
0
    int fastPy::go(int argc, char **argv) {
        int c;
        
        app_name = argv[0];
        
        while ((c = getopt (argc, argv, "dhvc:s:")) != -1) {
            switch (c) {
                case 'd':
                    detach = true;
                    break;                    
                case 'v':
                    if (verbose) debug = true;
                    verbose = true;
                    break;
                case 'c':
                    config_f = optarg;
                    break;
                case 's':
                    sock_f = optarg;
                    break;                    
                case 'h':
                default:
                    usage();
                    return 255;
            }        
        }

        if (config_f == NULL || sock_f == NULL) {
            ts_cout("Config and socket is required");
            usage();
            return 254;
        }
        
        if (readConf(config_f) < 0) {
            return 253;
        }

        if (changeID() < 0) {
            logError("master", LOG_ERROR, "Unable start with user: %s and group: %s", conf.user.c_str(), conf.group.c_str());
            return 252;
        }
                
        if (chdir(wsgi.base_dir.c_str()) < 0) {
            logError("master", LOG_ERROR, "Unable to change working directory to <%s>, check ownership", wsgi.base_dir.c_str());
            return 251;
        }
        
        fcgi = new fastcgi;
        
        // opening socket
        if (fcgi->openSock(sock_f) < 0) {
            logError("master", LOG_ERROR, "Unable to open socket");
            return 250;
        }
                
        if (detach) {
            int d_rc = detachProc();
            if (d_rc > 0) {
                // write pid file here
                return 0;
            } else if (d_rc < 0) {
                return 249;
            }
        } 
        
        for (int i=0; i < conf.workers_cnt; i++) {
            startChild();
        }
        
        if (masterLoop() < 0) {
            return 248;
        }
        
        return 0;
    }
Exemple #2
0
void MainWindow::enginioError(EnginioReply *error)
{
  logError(error->errorString());
}
Exemple #3
0
Pgn* getMatchingPgn(int pgnId, uint8_t *dataStart, int length)
{
  Pgn *pgn = searchForPgn(pgnId);
  int prn;
  int i;

  if (!pgn)
  {
    pgn = searchForUnknownPgn(pgnId);
  }

  prn = pgn->pgn;

  if (pgn == pgnListEnd() - 1 || pgn[1].pgn != prn)
  {
    // Don't bother complex search if there is only one PGN with this PRN.
    return pgn;
  }

  for (; pgn->pgn == prn; pgn++) // we never get here for the last pgn, so no need to check for end of list
  {
    int startBit = 0;
    uint8_t *data = dataStart;

    bool matchedFixedField = true;
    bool hasFixedField = false;

    /* There is a next index that we can use as well. We do so if the 'fixed' fields don't match */

    if (!pgn->fieldCount)
    {
      logError("Internal error: %p PGN %d offset %u '%s' has no fields\n", pgn, prn, (unsigned) (pgn - pgnList), pgn->description);
      for (i = 0; pgn->fieldList[i].name; i++)
      {
        logInfo("Field %d: %s\n", i, pgn->fieldList[i].name);
      }
      // exit(2);
      pgn->fieldCount = i;
    }

    // Iterate over fields
    for (i = 0, startBit = 0, data = dataStart; i < pgn->fieldCount; i++)
    {
      const Field *field = &pgn->fieldList[i];
      int bits = field->size;

      if (field->units && field->units[0] == '=')
      {
        int64_t value, desiredValue;
        int64_t maxValue;

        hasFixedField = true;
        extractNumber(field, data, startBit, field->size, &value, &maxValue);
        desiredValue = strtol(field->units + 1, 0, 10);
        if (value != desiredValue)
        {
          matchedFixedField = false;
          break;
        }
      }
      startBit += bits;
      data += startBit / 8;
      startBit %= 8;
    }
    if (!hasFixedField)
    {
      logDebug("Cant determine prn choice, return prn=%d variation '%s'\n", prn, pgn->description);
      return pgn;
    }
    if (matchedFixedField)
    {
      return pgn;
    }
  }
  return 0;
}
char *getExeAbsoluteFilename(const char *exeFilename, char *szAbsFilename, \
		const int maxSize)
{
	const char *filename;
	const char *p;
	int nFileLen;
	int nPathLen;
	char cwd[256];
	char szPath[1024];
	
	nFileLen = strlen(exeFilename);
	if (nFileLen >= sizeof(szPath))
	{
		logError("file: "__FILE__", line: %d, " \
			"filename length: %d is too long, exceeds %d!", \
			__LINE__, nFileLen, (int)sizeof(szPath));
		return NULL;
	}
	
	p = strrchr(exeFilename, '/');
	if (p == NULL)
	{
		int i;
		char *search_paths[] = {"/bin", "/usr/bin", "/usr/local/bin"};

		*szPath = '\0';
		filename = exeFilename;
		for (i=0; i<3; i++)
		{
			snprintf(cwd, sizeof(cwd), "%s/%s", \
				search_paths[i], filename);
			if (fileExists(cwd))
			{
				strcpy(szPath, search_paths[i]);
				break;
			}
		}

		if (*szPath == '\0')
		{
			if (!fileExists(filename))
			{
				logError("file: "__FILE__", line: %d, " \
					"can't find exe file %s!", __LINE__, \
					filename);
				return NULL;
			}
		}
		else
		{
			snprintf(szAbsFilename, maxSize, "%s/%s", \
				szPath, filename);
			return szAbsFilename;
		}
	}
	else
	{
		filename = p + 1;
		nPathLen = p - exeFilename;
		memcpy(szPath, exeFilename, nPathLen);
		szPath[nPathLen] = '\0';
	}
	
	if (*szPath == '/')
	{
		snprintf(szAbsFilename, maxSize, "%s/%s", szPath, filename);
	}
	else
	{
		if (getcwd(cwd, sizeof(cwd)) == NULL)
		{
			logError("file: "__FILE__", line: %d, " \
				"call getcwd fail, errno: %d, error info: %s", \
				__LINE__, errno, STRERROR(errno));
			return NULL;
		}
		
		nPathLen = strlen(cwd);
		if (cwd[nPathLen - 1] == '/')
		{
			cwd[nPathLen - 1] = '\0';
		}
		
		if (*szPath != '\0')
		{
			snprintf(szAbsFilename, maxSize, "%s/%s/%s", \
				cwd, szPath, filename);
		}
		else
		{
			snprintf(szAbsFilename, maxSize, "%s/%s", \
				cwd, filename);
		}
	}
	
	return szAbsFilename;
}
int getFileContent(const char *filename, char **buff, int64_t *file_size)
{
	int fd;
	
	fd = open(filename, O_RDONLY);
	if (fd < 0)
	{
		*buff = NULL;
		*file_size = 0;
		logError("file: "__FILE__", line: %d, " \
			"open file %s fail, " \
			"errno: %d, error info: %s", __LINE__, \
			filename, errno, STRERROR(errno));
		return errno != 0 ? errno : ENOENT;
	}

	if ((*file_size=lseek(fd, 0, SEEK_END)) < 0)
	{
		*buff = NULL;
		*file_size = 0;
		close(fd);
		logError("file: "__FILE__", line: %d, " \
			"lseek file %s fail, " \
			"errno: %d, error info: %s", __LINE__, \
			filename, errno, STRERROR(errno));
		return errno != 0 ? errno : EIO;
	}

	*buff = (char *)malloc(*file_size + 1);
	if (*buff == NULL)
	{
		*file_size = 0;
		close(fd);

		logError("file: "__FILE__", line: %d, " \
			"malloc %d bytes fail", __LINE__, \
			(int)(*file_size + 1));
		return errno != 0 ? errno : ENOMEM;
	}

	if (lseek(fd, 0, SEEK_SET) < 0)
	{
		*buff = NULL;
		*file_size = 0;
		close(fd);
		logError("file: "__FILE__", line: %d, " \
			"lseek file %s fail, " \
			"errno: %d, error info: %s", __LINE__, \
			filename, errno, STRERROR(errno));
		return errno != 0 ? errno : EIO;
	}
	if (read(fd, *buff, *file_size) != *file_size)
	{
		free(*buff);
		*buff = NULL;
		*file_size = 0;
		close(fd);
		logError("file: "__FILE__", line: %d, " \
			"read from file %s fail, " \
			"errno: %d, error info: %s", __LINE__, \
			filename, errno, STRERROR(errno));
		return errno != 0 ? errno : EIO;
	}

	(*buff)[*file_size] = '\0';
	close(fd);

	return 0;
}
int ioevent_loop(struct nio_thread_data *pThreadData,
	IOEventCallback recv_notify_callback, TaskCleanUpCallback
	clean_up_callback, volatile bool *continue_flag)
{
	int result;
	IOEventEntry ev_notify;
	FastTimerEntry head;
	struct fast_task_info *pTask;
	time_t last_check_time;
	int count;

	memset(&ev_notify, 0, sizeof(ev_notify));
	ev_notify.fd = pThreadData->pipe_fds[0];
	ev_notify.callback = recv_notify_callback;
	if (ioevent_attach(&pThreadData->ev_puller,
		pThreadData->pipe_fds[0], IOEVENT_READ,
		&ev_notify) != 0)
	{
		result = errno != 0 ? errno : ENOMEM;
		logCrit("file: "__FILE__", line: %d, " \
			"ioevent_attach fail, " \
			"errno: %d, error info: %s", \
			__LINE__, result, STRERROR(result));
		return result;
	}

    pThreadData->deleted_list = NULL;
	last_check_time = g_current_time;
	while (*continue_flag)
	{
		pThreadData->ev_puller.iterator.count = ioevent_poll(&pThreadData->ev_puller);
		if (pThreadData->ev_puller.iterator.count > 0)
		{
			deal_ioevents(&pThreadData->ev_puller);
		}
		else if (pThreadData->ev_puller.iterator.count < 0)
		{
			result = errno != 0 ? errno : EINVAL;
			if (result != EINTR)
			{
				logError("file: "__FILE__", line: %d, " \
					"ioevent_poll fail, " \
					"errno: %d, error info: %s", \
					__LINE__, result, STRERROR(result));
				return result;
			}
		}

		if (pThreadData->deleted_list != NULL)
		{
			count = 0;
			while (pThreadData->deleted_list != NULL)
			{
				pTask = pThreadData->deleted_list;
				pThreadData->deleted_list = pTask->next;

				clean_up_callback(pTask);
				count++;
			}
			logDebug("cleanup task count: %d", count);
		}

		if (g_current_time - last_check_time > 0)
		{
			last_check_time = g_current_time;
			count = fast_timer_timeouts_get(
				&pThreadData->timer, g_current_time, &head);
			if (count > 0)
			{
				deal_timeouts(&head);
			}
		}

        if (pThreadData->thread_loop_callback != NULL) {
            pThreadData->thread_loop_callback(pThreadData);
        }
	}

	return 0;
}
Exemple #7
0
int tracker_load_from_conf_file(const char *filename, \
		char *bind_addr, const int addr_size)
{
	char *pBasePath;
	char *pBindAddr;
	char *pRunByGroup;
	char *pRunByUser;
	char *pThreadStackSize;
	char *pSlotMinSize;
	char *pSlotMaxSize;
	char *pSpaceThreshold;
	char *pTrunkFileSize;
	char *pRotateErrorLogSize;
    char *pMinBuffSize;
    char *pMaxBuffSize;
#ifdef WITH_HTTPD
	char *pHttpCheckUri;
	char *pHttpCheckType;
#endif
	IniContext iniContext;
	int result;
	int64_t thread_stack_size;
	int64_t trunk_file_size;
	int64_t slot_min_size;
	int64_t slot_max_size;
	int64_t rotate_error_log_size;
    int64_t min_buff_size;
    int64_t max_buff_size;
    char sz_min_buff_size[32];
    char sz_max_buff_size[32];
	char reserved_space_str[32];

	memset(&g_groups, 0, sizeof(FDFSGroups));
	memset(&iniContext, 0, sizeof(IniContext));
	if ((result=iniLoadFromFile(filename, &iniContext)) != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"load conf file \"%s\" fail, ret code: %d", \
			__LINE__, filename, result);
		return result;
	}

	//iniPrintItems(&iniContext);

	do
	{
		if (iniGetBoolValue(NULL, "disabled", &iniContext, false))
		{
			logError("file: "__FILE__", line: %d, " \
				"conf file \"%s\" disabled=true, exit", \
				__LINE__, filename);
			result = ECANCELED;
			break;
		}

		pBasePath = iniGetStrValue(NULL, "base_path", &iniContext);
		if (pBasePath == NULL)
		{
			logError("file: "__FILE__", line: %d, " \
				"conf file \"%s\" must have item " \
				"\"base_path\"!", __LINE__, filename);
			result = ENOENT;
			break;
		}

		snprintf(g_fdfs_base_path, sizeof(g_fdfs_base_path), "%s", pBasePath);
		chopPath(g_fdfs_base_path);
		if (!fileExists(g_fdfs_base_path))
		{
			logError("file: "__FILE__", line: %d, " \
				"\"%s\" can't be accessed, error info: %s", \
				__LINE__, g_fdfs_base_path, STRERROR(errno));
			result = errno != 0 ? errno : ENOENT;
			break;
		}
		if (!isDir(g_fdfs_base_path))
		{
			logError("file: "__FILE__", line: %d, " \
				"\"%s\" is not a directory!", \
				__LINE__, g_fdfs_base_path);
			result = ENOTDIR;
			break;
		}

		load_log_level(&iniContext);
		if ((result=log_set_prefix(g_fdfs_base_path, \
				TRACKER_ERROR_LOG_FILENAME)) != 0)
		{
			break;
		}

		g_fdfs_connect_timeout = iniGetIntValue(NULL, "connect_timeout", \
				&iniContext, DEFAULT_CONNECT_TIMEOUT);
		if (g_fdfs_connect_timeout <= 0)
		{
			g_fdfs_connect_timeout = DEFAULT_CONNECT_TIMEOUT;
		}

		g_fdfs_network_timeout = iniGetIntValue(NULL, "network_timeout", \
				&iniContext, DEFAULT_NETWORK_TIMEOUT);
		if (g_fdfs_network_timeout <= 0)
		{
			g_fdfs_network_timeout = DEFAULT_NETWORK_TIMEOUT;
		}

		g_server_port = iniGetIntValue(NULL, "port", &iniContext, \
				FDFS_TRACKER_SERVER_DEF_PORT);
		if (g_server_port <= 0)
		{
			g_server_port = FDFS_TRACKER_SERVER_DEF_PORT;
		}

		pBindAddr = iniGetStrValue(NULL, "bind_addr", &iniContext);
		if (pBindAddr == NULL)
		{
			bind_addr[0] = '\0';
		}
		else
		{
			snprintf(bind_addr, addr_size, "%s", pBindAddr);
		}

		if ((result=tracker_load_store_lookup(filename, \
			&iniContext)) != 0)
		{
			break;
		}

		g_groups.store_server = (byte)iniGetIntValue(NULL, \
				"store_server",  &iniContext, \
				FDFS_STORE_SERVER_ROUND_ROBIN);
		if (!(g_groups.store_server == FDFS_STORE_SERVER_FIRST_BY_IP ||\
			g_groups.store_server == FDFS_STORE_SERVER_FIRST_BY_PRI||
			g_groups.store_server == FDFS_STORE_SERVER_ROUND_ROBIN))
		{
			logWarning("file: "__FILE__", line: %d, " \
				"store_server 's value %d is invalid, " \
				"set to %d (round robin)!", \
				__LINE__, g_groups.store_server, \
				FDFS_STORE_SERVER_ROUND_ROBIN);

			g_groups.store_server = FDFS_STORE_SERVER_ROUND_ROBIN;
		}

		g_groups.download_server = (byte)iniGetIntValue(NULL, \
			"download_server", &iniContext, \
			FDFS_DOWNLOAD_SERVER_ROUND_ROBIN);
		if (!(g_groups.download_server==FDFS_DOWNLOAD_SERVER_ROUND_ROBIN
			|| g_groups.download_server == 
				FDFS_DOWNLOAD_SERVER_SOURCE_FIRST))
		{
			logWarning("file: "__FILE__", line: %d, " \
				"download_server 's value %d is invalid, " \
				"set to %d (round robin)!", \
				__LINE__, g_groups.download_server, \
				FDFS_DOWNLOAD_SERVER_ROUND_ROBIN);

			g_groups.download_server = \
				FDFS_DOWNLOAD_SERVER_ROUND_ROBIN;
		}

		g_groups.store_path = (byte)iniGetIntValue(NULL, "store_path", \
			&iniContext, FDFS_STORE_PATH_ROUND_ROBIN);
		if (!(g_groups.store_path == FDFS_STORE_PATH_ROUND_ROBIN || \
			g_groups.store_path == FDFS_STORE_PATH_LOAD_BALANCE))
		{
			logWarning("file: "__FILE__", line: %d, " \
				"store_path 's value %d is invalid, " \
				"set to %d (round robin)!", \
				__LINE__, g_groups.store_path , \
				FDFS_STORE_PATH_ROUND_ROBIN);
			g_groups.store_path = FDFS_STORE_PATH_ROUND_ROBIN;
		}

		if ((result=fdfs_parse_storage_reserved_space(&iniContext, \
				&g_storage_reserved_space)) != 0)
		{
			break;
		}

		g_max_connections = iniGetIntValue(NULL, "max_connections", \
				&iniContext, DEFAULT_MAX_CONNECTONS);
		if (g_max_connections <= 0)
		{
			g_max_connections = DEFAULT_MAX_CONNECTONS;
		}
	
		g_accept_threads = iniGetIntValue(NULL, "accept_threads", \
				&iniContext, 1);
		if (g_accept_threads <= 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"accept_threads\" is invalid, " \
				"value: %d <= 0!", __LINE__, g_accept_threads);
			result = EINVAL;
                        break;
		}

		g_work_threads = iniGetIntValue(NULL, "work_threads", \
				&iniContext, DEFAULT_WORK_THREADS);
		if (g_work_threads <= 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"work_threads\" is invalid, " \
				"value: %d <= 0!", __LINE__, g_work_threads);
			result = EINVAL;
                        break;
		}

		if ((result=set_rlimit(RLIMIT_NOFILE, g_max_connections)) != 0)
		{
			break;
		}
	
		pRunByGroup = iniGetStrValue(NULL, "run_by_group", &iniContext);
		pRunByUser = iniGetStrValue(NULL, "run_by_user", &iniContext);
		if (pRunByGroup == NULL)
		{
			*g_run_by_group = '\0';
		}
		else
		{
			snprintf(g_run_by_group, sizeof(g_run_by_group), \
				"%s", pRunByGroup);
		}
		if (*g_run_by_group == '\0')
		{
			g_run_by_gid = getegid();
		}
		else
		{
			struct group *pGroup;

     			pGroup = getgrnam(g_run_by_group);
			if (pGroup == NULL)
			{
				result = errno != 0 ? errno : ENOENT;
				logError("file: "__FILE__", line: %d, " \
					"getgrnam fail, errno: %d, " \
					"error info: %s", __LINE__, \
					result, STRERROR(result));
				return result;
			}

			g_run_by_gid = pGroup->gr_gid;
		}


		if (pRunByUser == NULL)
		{
			*g_run_by_user = '******';
		}
		else
		{
			snprintf(g_run_by_user, sizeof(g_run_by_user), \
				"%s", pRunByUser);
		}
		if (*g_run_by_user == '\0')
		{
			g_run_by_uid = geteuid();
		}
		else
		{
			struct passwd *pUser;

     			pUser = getpwnam(g_run_by_user);
			if (pUser == NULL)
			{
				result = errno != 0 ? errno : ENOENT;
				logError("file: "__FILE__", line: %d, " \
					"getpwnam fail, errno: %d, " \
					"error info: %s", __LINE__, \
					result, STRERROR(result));
				return result;
			}

			g_run_by_uid = pUser->pw_uid;
		}

		if ((result=load_allow_hosts(&iniContext, \
                	 &g_allow_ip_addrs, &g_allow_ip_count)) != 0)
		{
			return result;
		}

		g_sync_log_buff_interval = iniGetIntValue(NULL, \
				"sync_log_buff_interval", &iniContext, \
				SYNC_LOG_BUFF_DEF_INTERVAL);
		if (g_sync_log_buff_interval <= 0)
		{
			g_sync_log_buff_interval = SYNC_LOG_BUFF_DEF_INTERVAL;
		}

		g_check_active_interval = iniGetIntValue(NULL, \
				"check_active_interval", &iniContext, \
				CHECK_ACTIVE_DEF_INTERVAL);
		if (g_check_active_interval <= 0)
		{
			g_check_active_interval = CHECK_ACTIVE_DEF_INTERVAL;
		}

		pThreadStackSize = iniGetStrValue(NULL, \
			"thread_stack_size", &iniContext);
		if (pThreadStackSize == NULL)
		{
			thread_stack_size = 64 * 1024;
		}
		else if ((result=parse_bytes(pThreadStackSize, 1, \
				&thread_stack_size)) != 0)
		{
			return result;
		}
		g_thread_stack_size = (int)thread_stack_size;

		g_storage_ip_changed_auto_adjust = iniGetBoolValue(NULL, \
				"storage_ip_changed_auto_adjust", \
				&iniContext, true);

		g_storage_sync_file_max_delay = iniGetIntValue(NULL, \
				"storage_sync_file_max_delay", &iniContext, \
				DEFAULT_STORAGE_SYNC_FILE_MAX_DELAY);
		if (g_storage_sync_file_max_delay <= 0)
		{
			g_storage_sync_file_max_delay = \
					DEFAULT_STORAGE_SYNC_FILE_MAX_DELAY;
		}

		g_storage_sync_file_max_time = iniGetIntValue(NULL, \
				"storage_sync_file_max_time", &iniContext, \
				DEFAULT_STORAGE_SYNC_FILE_MAX_TIME);
		if (g_storage_sync_file_max_time <= 0)
		{
			g_storage_sync_file_max_time = \
				DEFAULT_STORAGE_SYNC_FILE_MAX_TIME;
		}

		g_if_use_trunk_file = iniGetBoolValue(NULL, \
			"use_trunk_file", &iniContext, false);

		pSlotMinSize = iniGetStrValue(NULL, \
			"slot_min_size", &iniContext);
		if (pSlotMinSize == NULL)
		{
			slot_min_size = 256;
		}
		else if ((result=parse_bytes(pSlotMinSize, 1, \
				&slot_min_size)) != 0)
		{
			return result;
		}
		g_slot_min_size = (int)slot_min_size;
		if (g_slot_min_size <= 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"slot_min_size\" %d is invalid, " \
				"which <= 0", __LINE__, g_slot_min_size);
			result = EINVAL;
			break;
		}
		if (g_slot_min_size > 64 * 1024)
		{
			logWarning("file: "__FILE__", line: %d, " \
				"item \"slot_min_size\" %d is too large, " \
				"change to 64KB", __LINE__, g_slot_min_size);
			g_slot_min_size = 64 * 1024;
		}

		pTrunkFileSize = iniGetStrValue(NULL, \
			"trunk_file_size", &iniContext);
		if (pTrunkFileSize == NULL)
		{
			trunk_file_size = 64 * 1024 * 1024;
		}
		else if ((result=parse_bytes(pTrunkFileSize, 1, \
				&trunk_file_size)) != 0)
		{
			return result;
		}
		g_trunk_file_size = (int)trunk_file_size;
		if (g_trunk_file_size < 4 * 1024 * 1024)
		{
			logWarning("file: "__FILE__", line: %d, " \
				"item \"trunk_file_size\" %d is too small, " \
				"change to 4MB", __LINE__, g_trunk_file_size);
			g_trunk_file_size = 4 * 1024 * 1024;
		}

		pSlotMaxSize = iniGetStrValue(NULL, \
			"slot_max_size", &iniContext);
		if (pSlotMaxSize == NULL)
		{
			slot_max_size = g_trunk_file_size / 2;
		}
		else if ((result=parse_bytes(pSlotMaxSize, 1, \
				&slot_max_size)) != 0)
		{
			return result;
		}
		g_slot_max_size = (int)slot_max_size;
		if (g_slot_max_size <= g_slot_min_size)
		{
			logError("file: "__FILE__", line: %d, " \
				"item \"slot_max_size\" %d is invalid, " \
				"which <= slot_min_size: %d", \
				__LINE__, g_slot_max_size, g_slot_min_size);
			result = EINVAL;
			break;
		}
		if (g_slot_max_size > g_trunk_file_size / 2)
		{
			logWarning("file: "__FILE__", line: %d, " \
				"item \"slot_max_size\": %d is too large, " \
				"change to %d", __LINE__, g_slot_max_size, \
				g_trunk_file_size / 2);
			g_slot_max_size = g_trunk_file_size / 2;
		}

		g_trunk_create_file_advance = iniGetBoolValue(NULL, \
			"trunk_create_file_advance", &iniContext, false);
		if ((result=get_time_item_from_conf(&iniContext, \
                	"trunk_create_file_time_base", \
			&g_trunk_create_file_time_base, 2, 0)) != 0)
		{
			return result;
		}

		g_trunk_create_file_interval = iniGetIntValue(NULL, \
				"trunk_create_file_interval", &iniContext, \
				86400);
		pSpaceThreshold = iniGetStrValue(NULL, \
			"trunk_create_file_space_threshold", &iniContext);
		if (pSpaceThreshold == NULL)
		{
			g_trunk_create_file_space_threshold = 0;
		}
		else if ((result=parse_bytes(pSpaceThreshold, 1, \
				&g_trunk_create_file_space_threshold)) != 0)
		{
			return result;
		}
		g_trunk_compress_binlog_min_interval = iniGetIntValue(NULL, \
				"trunk_compress_binlog_min_interval", \
				&iniContext, 0);

		g_trunk_init_check_occupying = iniGetBoolValue(NULL, \
			"trunk_init_check_occupying", &iniContext, false);

		g_trunk_init_reload_from_binlog = iniGetBoolValue(NULL, \
			"trunk_init_reload_from_binlog", &iniContext, false);

		if ((result=tracker_load_storage_id_info( \
				filename, &iniContext)) != 0)
		{
			return result;
		}

		g_rotate_error_log = iniGetBoolValue(NULL, "rotate_error_log",\
					&iniContext, false);
		if ((result=get_time_item_from_conf(&iniContext, \
			"error_log_rotate_time", &g_error_log_rotate_time, \
			0, 0)) != 0)
		{
			break;
		}

		pRotateErrorLogSize = iniGetStrValue(NULL, \
			"rotate_error_log_size", &iniContext);
		if (pRotateErrorLogSize == NULL)
		{
			rotate_error_log_size = 0;
		}
		else if ((result=parse_bytes(pRotateErrorLogSize, 1, \
				&rotate_error_log_size)) != 0)
		{
			break;
		}
		if (rotate_error_log_size > 0 && \
			rotate_error_log_size < FDFS_ONE_MB)
		{
			logWarning("file: "__FILE__", line: %d, " \
				"item \"rotate_error_log_size\": " \
				"%"PRId64" is too small, " \
				"change to 1 MB", __LINE__, \
				rotate_error_log_size);
			rotate_error_log_size = FDFS_ONE_MB;
		}
		fdfs_set_log_rotate_size(&g_log_context, rotate_error_log_size);

		g_log_file_keep_days = iniGetIntValue(NULL, \
				"log_file_keep_days", &iniContext, 0);

		g_store_slave_file_use_link = iniGetBoolValue(NULL, \
			"store_slave_file_use_link", &iniContext, false);

		if ((result=fdfs_connection_pool_init(filename, &iniContext)) != 0)
		{
			break;
		}


        pMinBuffSize = iniGetStrValue(NULL,
                "min_buff_size", &iniContext);
        if (pMinBuffSize == NULL) {
            min_buff_size = TRACKER_MAX_PACKAGE_SIZE;
        }
        else if ((result=parse_bytes(pMinBuffSize, 1,
                        &min_buff_size)) != 0)
        {
            return result;
        }
        g_min_buff_size = (int)min_buff_size;

        pMaxBuffSize = iniGetStrValue(NULL,
                "max_buff_size", &iniContext);
        if (pMaxBuffSize == NULL) {
            max_buff_size = 16 * TRACKER_MAX_PACKAGE_SIZE;
        }
        else if ((result=parse_bytes(pMaxBuffSize, 1,
                        &max_buff_size)) != 0)
        {
            return result;
        }
        g_max_buff_size = (int)max_buff_size;

        if (g_min_buff_size < TRACKER_MAX_PACKAGE_SIZE) {
            g_min_buff_size = TRACKER_MAX_PACKAGE_SIZE;
        }
        if (g_max_buff_size < g_min_buff_size) {
            g_max_buff_size = g_min_buff_size;
        }

#ifdef WITH_HTTPD
		if ((result=fdfs_http_params_load(&iniContext, \
				filename, &g_http_params)) != 0)
		{
			return result;
		}

		g_http_check_interval = iniGetIntValue(NULL, \
			"http.check_alive_interval", &iniContext, 30);

		pHttpCheckType = iniGetStrValue(NULL, \
			"http.check_alive_type", &iniContext);
		if (pHttpCheckType != NULL && \
			strcasecmp(pHttpCheckType, "http") == 0)
		{
			g_http_check_type = FDFS_HTTP_CHECK_ALIVE_TYPE_HTTP;
		}
		else
		{
			g_http_check_type = FDFS_HTTP_CHECK_ALIVE_TYPE_TCP;
		}

		pHttpCheckUri = iniGetStrValue(NULL, \
			"http.check_alive_uri", &iniContext);
		if (pHttpCheckUri == NULL)
		{
			*g_http_check_uri = '/';
			*(g_http_check_uri+1) = '\0';
		}
		else if (*pHttpCheckUri == '/')
		{
			snprintf(g_http_check_uri, sizeof(g_http_check_uri), \
				"%s", pHttpCheckUri);
		}
		else
		{
			snprintf(g_http_check_uri, sizeof(g_http_check_uri), \
				"/%s", pHttpCheckUri);
		}


#endif

        if (g_if_use_trunk_file && g_groups.store_server == FDFS_STORE_SERVER_ROUND_ROBIN)
        {
            logInfo("file: "__FILE__", line: %d, "
                    "set store_server to %d because use_trunk_file is true",
                    __LINE__, FDFS_STORE_SERVER_FIRST_BY_IP);
            g_groups.store_server = FDFS_STORE_SERVER_FIRST_BY_IP;
        }

        int_to_comma_str(g_min_buff_size, sz_min_buff_size);
        int_to_comma_str(g_max_buff_size, sz_max_buff_size);

		logInfo("FastDFS v%d.%02d, base_path=%s, " \
			"run_by_group=%s, run_by_user=%s, " \
			"connect_timeout=%ds, "    \
			"network_timeout=%ds, "    \
			"port=%d, bind_addr=%s, " \
			"max_connections=%d, "    \
			"accept_threads=%d, "    \
			"work_threads=%d, "    \
            "min_buff_size=%s, " \
            "max_buff_size=%s, " \
			"store_lookup=%d, store_group=%s, " \
			"store_server=%d, store_path=%d, " \
			"reserved_storage_space=%s, " \
			"download_server=%d, " \
			"allow_ip_count=%d, sync_log_buff_interval=%ds, " \
			"check_active_interval=%ds, " \
			"thread_stack_size=%d KB, " \
			"storage_ip_changed_auto_adjust=%d, "  \
			"storage_sync_file_max_delay=%ds, " \
			"storage_sync_file_max_time=%ds, "  \
			"use_trunk_file=%d, " \
			"slot_min_size=%d, " \
			"slot_max_size=%d MB, " \
			"trunk_file_size=%d MB, " \
			"trunk_create_file_advance=%d, " \
			"trunk_create_file_time_base=%02d:%02d, " \
			"trunk_create_file_interval=%d, " \
			"trunk_create_file_space_threshold=%d GB, " \
			"trunk_init_check_occupying=%d, " \
			"trunk_init_reload_from_binlog=%d, " \
			"trunk_compress_binlog_min_interval=%d, " \
			"use_storage_id=%d, " \
			"id_type_in_filename=%s, " \
			"storage_id_count=%d, " \
			"rotate_error_log=%d, " \
			"error_log_rotate_time=%02d:%02d, " \
			"rotate_error_log_size=%"PRId64", " \
			"log_file_keep_days=%d, " \
			"store_slave_file_use_link=%d, " \
			"use_connection_pool=%d, " \
			"g_connection_pool_max_idle_time=%ds", \
			g_fdfs_version.major, g_fdfs_version.minor,  \
			g_fdfs_base_path, g_run_by_group, g_run_by_user, \
			g_fdfs_connect_timeout, \
			g_fdfs_network_timeout, g_server_port, bind_addr, \
			g_max_connections, g_accept_threads, g_work_threads, \
            sz_min_buff_size, sz_max_buff_size, \
			g_groups.store_lookup, g_groups.store_group, \
			g_groups.store_server, g_groups.store_path, \
			fdfs_storage_reserved_space_to_string( \
			    &g_storage_reserved_space, reserved_space_str), \
			g_groups.download_server, \
			g_allow_ip_count, g_sync_log_buff_interval, \
			g_check_active_interval, g_thread_stack_size / 1024, \
			g_storage_ip_changed_auto_adjust, \
			g_storage_sync_file_max_delay, \
			g_storage_sync_file_max_time, \
			g_if_use_trunk_file, g_slot_min_size, \
			g_slot_max_size / FDFS_ONE_MB, \
			g_trunk_file_size / FDFS_ONE_MB, \
			g_trunk_create_file_advance, \
			g_trunk_create_file_time_base.hour, \
			g_trunk_create_file_time_base.minute, \
			g_trunk_create_file_interval, \
			(int)(g_trunk_create_file_space_threshold / \
			(FDFS_ONE_MB * 1024)), g_trunk_init_check_occupying, \
			g_trunk_init_reload_from_binlog, \
			g_trunk_compress_binlog_min_interval, \
			g_use_storage_id, g_id_type_in_filename == \
			FDFS_ID_TYPE_SERVER_ID ? "id" : "ip", g_storage_id_count, \
			g_rotate_error_log, g_error_log_rotate_time.hour, \
			g_error_log_rotate_time.minute, \
			g_log_context.rotate_size, g_log_file_keep_days,
			g_store_slave_file_use_link, \
			g_use_connection_pool, g_connection_pool_max_idle_time);

#ifdef WITH_HTTPD
		if (!g_http_params.disabled)
		{
			logInfo("HTTP supported: " \
				"server_port=%d, " \
				"default_content_type=%s, " \
				"anti_steal_token=%d, " \
				"token_ttl=%ds, " \
				"anti_steal_secret_key length=%d, "  \
				"token_check_fail content_type=%s, " \
				"token_check_fail buff length=%d, "  \
				"check_active_interval=%d, " \
				"check_active_type=%s, " \
				"check_active_uri=%s",  \
				g_http_params.server_port, \
				g_http_params.default_content_type, \
				g_http_params.anti_steal_token, \
				g_http_params.token_ttl, \
				g_http_params.anti_steal_secret_key.length, \
				g_http_params.token_check_fail_content_type, \
				g_http_params.token_check_fail_buff.length, \
				g_http_check_interval, g_http_check_type == \
				FDFS_HTTP_CHECK_ALIVE_TYPE_TCP ? "tcp":"http",\
				g_http_check_uri);
		}
#endif

	} while (0);

	iniFreeContext(&iniContext);

	load_local_host_ip_addrs();

	return result;
}
Exemple #8
0
static int trunk_delete_space(const FDFSTrunkFullInfo *pTrunkInfo, \
		const bool bWriteBinLog)
{
	int result;
	FDFSTrunkSlot target_slot;
	char buff[256];
	FDFSTrunkSlot *pSlot;
	FDFSTrunkNode *pPrevious;
	FDFSTrunkNode *pCurrent;

	target_slot.size = pTrunkInfo->file.size;
	target_slot.head = NULL;

	pthread_mutex_lock(&trunk_mem_lock);
	pSlot = (FDFSTrunkSlot *)avl_tree_find(&tree_info_by_size, &target_slot);
	if (pSlot == NULL)
	{
		pthread_mutex_unlock(&trunk_mem_lock);
		logError("file: "__FILE__", line: %d, " \
			"can't find trunk entry: %s", __LINE__, \
			trunk_info_dump(pTrunkInfo, buff, sizeof(buff)));
		return ENOENT;
	}

	pPrevious = NULL;
	pCurrent = pSlot->head;
	while (pCurrent != NULL && memcmp(&(pCurrent->trunk), pTrunkInfo, \
		sizeof(FDFSTrunkFullInfo)) != 0)
	{
		pPrevious = pCurrent;
		pCurrent = pCurrent->next;
	}

	if (pCurrent == NULL)
	{
		pthread_mutex_unlock(&trunk_mem_lock);
		logError("file: "__FILE__", line: %d, " \
			"can't find trunk entry: %s", __LINE__, \
			trunk_info_dump(pTrunkInfo, buff, sizeof(buff)));
		return ENOENT;
	}

	if (pPrevious == NULL)
	{
		pSlot->head = pCurrent->next;
		if (pSlot->head == NULL)
		{
			trunk_delete_size_tree_entry(pSlot);
		}
	}
	else
	{
		pPrevious->next = pCurrent->next;
	}

	trunk_free_block_delete(&(pCurrent->trunk));
	pthread_mutex_unlock(&trunk_mem_lock);

	if (bWriteBinLog)
	{
		result = trunk_mem_binlog_write(g_current_time, \
				TRUNK_OP_TYPE_DEL_SPACE, &(pCurrent->trunk));
	}
	else
	{
		pthread_mutex_lock(&trunk_file_lock);
		g_trunk_total_free_space -= pCurrent->trunk.file.size;
		pthread_mutex_unlock(&trunk_file_lock);
		result = 0;
	}

	fast_mblock_free(&free_blocks_man, pCurrent->pMblockNode);
	return result;
}
Exemple #9
0
int storage_trunk_init()
{
	int result;

	if (!g_if_trunker_self)
	{
		logError("file: "__FILE__", line: %d, " \
			"I am not trunk server!", __LINE__);
		return 0;
	}

	if (trunk_init_flag != STORAGE_TRUNK_INIT_FLAG_NONE)
	{
		logWarning("file: "__FILE__", line: %d, " \
			"trunk already inited!", __LINE__);
		return 0;
	}

	logDebug("file: "__FILE__", line: %d, " \
		"storage trunk init ...", __LINE__);

	g_trunk_server.sock = -1;
	g_trunk_server.port = g_server_port;

	if ((result=init_pthread_lock(&trunk_file_lock)) != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"init_pthread_lock fail, " \
			"errno: %d, error info: %s", \
			__LINE__, result, STRERROR(result));
		return result;
	}

	if ((result=init_pthread_lock(&trunk_mem_lock)) != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"init_pthread_lock fail, " \
			"errno: %d, error info: %s", \
			__LINE__, result, STRERROR(result));
		return result;
	}

	if ((result=fast_mblock_init(&free_blocks_man, \
			sizeof(FDFSTrunkNode), 0)) != 0)
	{
		return result;
	}

	if ((result=fast_mblock_init(&tree_nodes_man, \
			sizeof(FDFSTrunkSlot), 0)) != 0)
	{
		return result;
	}

	if ((result=avl_tree_init(&tree_info_by_size, NULL, \
			storage_trunk_node_compare_size)) != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"avl_tree_init fail, " \
			"errno: %d, error info: %s", \
			__LINE__, result, STRERROR(result));
		return result;
	}

	if ((result=trunk_free_block_checker_init()) != 0)
	{
		return result;
	}

	if ((result=storage_trunk_load()) != 0)
	{
		return result;
	}

	logInfo("file: "__FILE__", line: %d, " \
		"tree by space size node count: %d, tree by trunk file id " \
		"node count: %d, free block count: %d, " \
		"trunk_total_free_space: "INT64_PRINTF_FORMAT, __LINE__, \
		avl_tree_count(&tree_info_by_size), \
		trunk_free_block_tree_node_count(), \
		trunk_free_block_total_count(), \
		g_trunk_total_free_space);

	/*
	{
	char filename[MAX_PATH_SIZE];
	sprintf(filename, "%s/logs/tttt.dat", g_fdfs_base_path);
	trunk_free_block_tree_print(filename);
	}
	*/

	trunk_init_flag = STORAGE_TRUNK_INIT_FLAG_DONE;
	return 0;
}
void loadMiscSettings() {
	// reset to defaults
	ELEMENTS.clear();
	EQUIP_FLAGS.clear();
	HERO_CLASSES.clear();
	FRAME_W = 0;
	FRAME_H = 0;
	IGNORE_TEXTURE_FILTER = false;
	ICON_SIZE = 0;
	AUTOPICKUP_CURRENCY = false;
	MAX_ABSORB = 90;
	MAX_RESIST = 90;
	MAX_BLOCK = 100;
	MAX_AVOIDANCE = 99;
	MIN_ABSORB = 0;
	MIN_RESIST = 0;
	MIN_BLOCK = 0;
	MIN_AVOIDANCE = 0;
	CURRENCY = "Gold";
	VENDOR_RATIO = 0.25;
	DEATH_PENALTY = true;
	DEATH_PENALTY_PERMADEATH = false;
	DEATH_PENALTY_CURRENCY = 50;
	DEATH_PENALTY_XP = 0;
	DEATH_PENALTY_XP_CURRENT = 0;
	DEATH_PENALTY_ITEM = false;
	MENUS_PAUSE = false;
	SAVE_HPMP = false;
	ENABLE_PLAYGAME = false;
	CORPSE_TIMEOUT = 60*MAX_FRAMES_PER_SEC;
	SELL_WITHOUT_VENDOR = true;
	AIM_ASSIST = 0;
	SAVE_PREFIX = "";
	WINDOW_TITLE = "Flare";
	SOUND_FALLOFF = 15;
	PARTY_EXP_PERCENTAGE = 100;
	ENABLE_ALLY_COLLISION_AI = true;
	ENABLE_ALLY_COLLISION = true;
	CURRENCY_ID = 1;
	INTERACT_RANGE = 3;
	SAVE_ONLOAD = true;
	SAVE_ONEXIT = true;
	TOOLTIP_OFFSET = 0;
	TOOLTIP_WIDTH = 1;
	TOOLTIP_MARGIN = 0;
	TOOLTIP_MARGIN_NPC = 0;

	FileParser infile;
	// @CLASS Settings: Misc|Description of engine/misc.txt
	if (infile.open("engine/misc.txt")) {
		while (infile.next()) {
			// @ATTR save_hpmp|boolean|When saving the game, keep the hero's current HP and MP.
			if (infile.key == "save_hpmp")
				SAVE_HPMP = toBool(infile.val);
			// @ATTR corpse_timeout|duration|Duration that a corpse can exist on the map in 'ms' or 's'.
			else if (infile.key == "corpse_timeout")
				CORPSE_TIMEOUT = parse_duration(infile.val);
			// @ATTR sell_without_vendor|boolean|Allows selling items when not at a vendor via CTRL-Click.
			else if (infile.key == "sell_without_vendor")
				SELL_WITHOUT_VENDOR = toBool(infile.val);
			// @ATTR aim_assist|integer|The pixel offset for powers that use aim_assist.
			else if (infile.key == "aim_assist")
				AIM_ASSIST = toInt(infile.val);
			// @ATTR window_title|string|Sets the text in the window's titlebar.
			else if (infile.key == "window_title")
				WINDOW_TITLE = infile.val;
			// @ATTR save_prefix|string|A string that's prepended to save filenames to prevent conflicts between mods.
			else if (infile.key == "save_prefix")
				SAVE_PREFIX = infile.val;
			// @ATTR sound_falloff|integer|The maximum radius in tiles that any single sound is audible.
			else if (infile.key == "sound_falloff")
				SOUND_FALLOFF = toInt(infile.val);
			// @ATTR party_exp_percentage|integer|The percentage of XP given to allies.
			else if (infile.key == "party_exp_percentage")
				PARTY_EXP_PERCENTAGE = toInt(infile.val);
			// @ATTR enable_ally_collision|boolean|Allows allies to block the player's path.
			else if (infile.key == "enable_ally_collision")
				ENABLE_ALLY_COLLISION = toBool(infile.val);
			// @ATTR enable_ally_collision_ai|boolean|Allows allies to block the path of other AI creatures.
			else if (infile.key == "enable_ally_collision_ai")
				ENABLE_ALLY_COLLISION_AI = toBool(infile.val);
			else if (infile.key == "currency_id") {
				// @ATTR currency_id|integer|An item id that will be used as currency.
				CURRENCY_ID = toInt(infile.val);
				if (CURRENCY_ID < 1) {
					CURRENCY_ID = 1;
					logError("Settings: Currency ID below the minimum allowed value. Resetting it to %d", CURRENCY_ID);
				}
			}
			// @ATTR interact_range|float|Distance where the player can interact with objects and NPCs.
			else if (infile.key == "interact_range")
				INTERACT_RANGE = toFloat(infile.val);
			// @ATTR menus_pause|boolean|Opening any menu will pause the game.
			else if (infile.key == "menus_pause")
				MENUS_PAUSE = toBool(infile.val);
			// @ATTR save_onload|boolean|Save the game upon changing maps.
			else if (infile.key == "save_onload")
				SAVE_ONLOAD = toBool(infile.val);
			// @ATTR save_onexit|boolean|Save the game upon quitting to the title screen or desktop.
			else if (infile.key == "save_onexit")
				SAVE_ONEXIT = toBool(infile.val);

			else infile.error("Settings: '%s' is not a valid key.", infile.key.c_str());
		}
		infile.close();
	}

	if (SAVE_PREFIX == "") {
		logError("Settings: save_prefix not found in engine/misc.txt, setting to 'default'. This may cause save file conflicts between games that have no save_prefix.");
		SAVE_PREFIX = "default";
	}

	// @CLASS Settings: Resolution|Description of engine/resolutions.txt
	if (infile.open("engine/resolutions.txt")) {
		while (infile.next()) {
			// @ATTR menu_frame_width|integer|Width of frame for New Game, Configuration, etc. menus.
			if (infile.key == "menu_frame_width")
				FRAME_W = toInt(infile.val);
			// @ATTR menu_frame_height|integer|Height of frame for New Game, Configuration, etc. menus.
			else if (infile.key == "menu_frame_height")
				FRAME_H = toInt(infile.val);
			// @ATTR icon_size|integer|Size of icons.
			else if (infile.key == "icon_size")
				ICON_SIZE = toInt(infile.val);
			// @ATTR required_width|integer|Minimum window/screen resolution width.
			else if (infile.key == "required_width") {
				MIN_SCREEN_W = toInt(infile.val);
			}
			// @ATTR required_height|integer|Minimum window/screen resolution height.
			else if (infile.key == "required_height") {
				MIN_SCREEN_H = toInt(infile.val);
			}
			// @ATTR virtual_height|integer|The height (in pixels) of the game's actual rendering area. The width will be resized to match the window's aspect ration, and everything will be scaled up to fill the window.
			else if (infile.key == "virtual_height") {
				VIEW_H = toInt(infile.val);
				VIEW_H_HALF = VIEW_H / 2;
			}
			// @ATTR ignore_texture_filter|boolean|If true, this ignores the "Texture Filtering" video setting and uses only nearest-neighbor scaling. This is good for games that use pixel art assets.
			else if (infile.key == "ignore_texture_filter") {
				IGNORE_TEXTURE_FILTER = toBool(infile.val);
			}
			else infile.error("Settings: '%s' is not a valid key.", infile.key.c_str());
		}
		infile.close();
	}

	// prevent the window from being too small
	if (SCREEN_W < MIN_SCREEN_W) SCREEN_W = MIN_SCREEN_W;
	if (SCREEN_H < MIN_SCREEN_H) SCREEN_H = MIN_SCREEN_H;

	// set the default virtual height if it's not defined
	if (VIEW_H == 0) {
		logError("Settings: virtual_height is undefined. Setting it to %d.", MIN_SCREEN_H);
		VIEW_H = MIN_SCREEN_H;
		VIEW_H_HALF = VIEW_H / 2;
	}

	// @CLASS Settings: Gameplay|Description of engine/gameplay.txt
	if (infile.open("engine/gameplay.txt")) {
		while (infile.next()) {
			if (infile.key == "enable_playgame") {
				// @ATTR enable_playgame|boolean|Enables the "Play Game" button on the main menu.
				ENABLE_PLAYGAME = toBool(infile.val);
			}
			else infile.error("Settings: '%s' is not a valid key.", infile.key.c_str());
		}
		infile.close();
	}

	// @CLASS Settings: Combat|Description of engine/combat.txt
	if (infile.open("engine/combat.txt")) {
		while (infile.next()) {
			// @ATTR max_absorb_percent|integer|Maximum percentage of damage that can be absorbed.
			if (infile.key == "max_absorb_percent") MAX_ABSORB = toInt(infile.val);
			// @ATTR max_resist_percent|integer|Maximum percentage of elemental damage that can be resisted.
			else if (infile.key == "max_resist_percent") MAX_RESIST = toInt(infile.val);
			// @ATTR max_block_percent|integer|Maximum percentage of damage that can be blocked.
			else if (infile.key == "max_block_percent") MAX_BLOCK = toInt(infile.val);
			// @ATTR max_avoidance_percent|integer|Maximum percentage chance that hazards can be avoided.
			else if (infile.key == "max_avoidance_percent") MAX_AVOIDANCE = toInt(infile.val);
			// @ATTR min_absorb_percent|integer|Minimum percentage of damage that can be absorbed.
			else if (infile.key == "min_absorb_percent") MIN_ABSORB = toInt(infile.val);
			// @ATTR min_resist_percent|integer|Minimum percentage of elemental damage that can be resisted.
			else if (infile.key == "min_resist_percent") MIN_RESIST = toInt(infile.val);
			// @ATTR min_block_percent|integer|Minimum percentage of damage that can be blocked.
			else if (infile.key == "min_block_percent") MIN_BLOCK = toInt(infile.val);
			// @ATTR min_avoidance_percent|integer|Minimum percentage chance that hazards can be avoided.
			else if (infile.key == "min_avoidance_percent") MIN_AVOIDANCE = toInt(infile.val);

			else infile.error("Settings: '%s' is not a valid key.", infile.key.c_str());
		}
		infile.close();
	}

	// @CLASS Settings: Elements|Description of engine/elements.txt
	if (infile.open("engine/elements.txt")) {
		Element e;
		while (infile.next()) {
			// @ATTR name|string|An identifier for this element.
			if (infile.key == "name") e.name = infile.val;
			// @ATTR description|string|The displayed name of this element.
			else if (infile.key == "description") e.description = infile.val;

			else infile.error("Settings: '%s' is not a valid key.", infile.key.c_str());

			if (e.name != "" && e.description != "") {
				ELEMENTS.push_back(e);
				e.name = e.description = "";
			}
		}
		infile.close();
	}

	// @CLASS Settings: Equip flags|Description of engine/equip_flags.txt
	if (infile.open("engine/equip_flags.txt")) {
		std::string type,description;
		type = description = "";

		while (infile.next()) {
			// @ATTR name|string|An identifier for this equip flag.
			if (infile.key == "name") type = infile.val;
			// @ATTR description|string|The displayed name of this equip flag.
			else if (infile.key == "description") description = infile.val;

			else infile.error("Settings: '%s' is not a valid key.", infile.key.c_str());

			if (type != "" && description != "") {
				EQUIP_FLAGS[type] = description;
				type = description = "";
			}
		}
		infile.close();
	}

	// @CLASS Settings: Classes|Description of engine/classes.txt
	if (infile.open("engine/classes.txt")) {
		while (infile.next()) {
			if (infile.new_section) {
				if (infile.section == "class") {
					HERO_CLASSES.push_back(HeroClass());
				}
			}

			if (infile.section != "class")
				continue;

			if (!HERO_CLASSES.empty()) {
				// @ATTR name|string|The displayed name of this class.
				if (infile.key == "name") HERO_CLASSES.back().name = infile.val;
				// @ATTR description|string|A description of this class.
				else if (infile.key == "description") HERO_CLASSES.back().description = infile.val;
				// @ATTR currency|integer|The amount of currency this class will start with.
				else if (infile.key == "currency") HERO_CLASSES.back().currency = toInt(infile.val);
				// @ATTR equipment|item (integer), ...|A list of items that are equipped when starting with this class.
				else if (infile.key == "equipment") HERO_CLASSES.back().equipment = infile.val;
				// @ATTR physical|integer|Class starts with this physical stat.
				else if (infile.key == "physical") HERO_CLASSES.back().physical = toInt(infile.val);
				// @ATTR mental|integer|Class starts with this mental stat.
				else if (infile.key == "mental") HERO_CLASSES.back().mental = toInt(infile.val);
				// @ATTR offense|integer|Class starts with this offense stat.
				else if (infile.key == "offense") HERO_CLASSES.back().offense = toInt(infile.val);
				// @ATTR defense|integer|Class starts with this defense stat.
				else if (infile.key == "defense") HERO_CLASSES.back().defense = toInt(infile.val);

				else if (infile.key == "actionbar") {
					// @ATTR actionbar|power (integer), ...|A list of powers to place in the action bar for the class.
					for (int i=0; i<12; i++) {
						HERO_CLASSES.back().hotkeys[i] = toInt(infile.nextValue());
					}
				}
				else if (infile.key == "powers") {
					// @ATTR powers|power (integer), ...|A list of powers that are unlocked when starting this class.
					std::string power;
					while ( (power = infile.nextValue()) != "") {
						HERO_CLASSES.back().powers.push_back(toInt(power));
					}
				}
				else if (infile.key == "campaign") {
					// @ATTR campaign|status (string), ...|A list of campaign statuses that are set when starting this class.
					std::string status;
					while ( (status = infile.nextValue()) != "") {
						HERO_CLASSES.back().statuses.push_back(status);
					}
				}
				// @ATTR power_tree|string|Power tree that will be loaded by MenuPowers
				else if (infile.key == "power_tree") HERO_CLASSES.back().power_tree = infile.val;

				else infile.error("Settings: '%s' is not a valid key.", infile.key.c_str());
			}
		}
		infile.close();
	}
	// Make a default hero class if none were found
	if (HERO_CLASSES.empty()) {
		HeroClass c;
		c.name = "Adventurer";
		HERO_CLASSES.push_back(c);
	}

	// @CLASS Settings: Death penalty|Description of engine/death_penalty.txt
	if (infile.open("engine/death_penalty.txt")) {
		while (infile.next()) {
			// @ATTR enable|boolean|Enable the death penalty.
			if (infile.key == "enable") DEATH_PENALTY = toBool(infile.val);
			// @ATTR permadeath|boolean|Force permadeath for all new saves.
			else if (infile.key == "permadeath") DEATH_PENALTY_PERMADEATH = toBool(infile.val);
			// @ATTR currency|integer|Remove this percentage of currency.
			else if (infile.key == "currency") DEATH_PENALTY_CURRENCY = toInt(infile.val);
			// @ATTR xp_total|integer|Remove this percentage of total XP.
			else if (infile.key == "xp_total") DEATH_PENALTY_XP = toInt(infile.val);
			// @ATTR xp_current_level|integer|Remove this percentage of the XP gained since the last level.
			else if (infile.key == "xp_current_level") DEATH_PENALTY_XP_CURRENT = toInt(infile.val);
			// @ATTR random_item|integer|Removes a random item from the player's inventory.
			else if (infile.key == "random_item") DEATH_PENALTY_ITEM = toBool(infile.val);

			else infile.error("Settings: '%s' is not a valid key.", infile.key.c_str());
		}
		infile.close();
	}

	// @CLASS Settings: Tooltips|Description of engine/tooltips.txt
	if (infile.open("engine/tooltips.txt")) {
		while (infile.next()) {
			// @ATTR tooltip_offset|integer|Offset in pixels from the origin point (usually mouse cursor).
			if (infile.key == "tooltip_offset")
				TOOLTIP_OFFSET = toInt(infile.val);
			// @ATTR tooltip_width|integer|Maximum width of tooltip in pixels.
			else if (infile.key == "tooltip_width")
				TOOLTIP_WIDTH = toInt(infile.val);
			// @ATTR tooltip_margin|integer|Padding between the text and the tooltip borders.
			else if (infile.key == "tooltip_margin")
				TOOLTIP_MARGIN = toInt(infile.val);
			// @ATTR npc_tooltip_margin|integer|Vertical offset for NPC labels.
			else if (infile.key == "npc_tooltip_margin")
				TOOLTIP_MARGIN_NPC = toInt(infile.val);
		}
		infile.close();
	}
}
Exemple #11
0
static int trunk_add_free_block(FDFSTrunkNode *pNode, const bool bWriteBinLog)
{
	int result;
	struct fast_mblock_node *pMblockNode;
	FDFSTrunkSlot target_slot;
	FDFSTrunkSlot *chain;

	pthread_mutex_lock(&trunk_mem_lock);

	if ((result=trunk_free_block_check_duplicate(&(pNode->trunk))) != 0)
	{
		pthread_mutex_unlock(&trunk_mem_lock);
		return result;
	}

	target_slot.size = pNode->trunk.file.size;
	target_slot.head = NULL;
	chain = (FDFSTrunkSlot *)avl_tree_find(&tree_info_by_size, &target_slot);
	if (chain == NULL)
	{
		pMblockNode = fast_mblock_alloc(&tree_nodes_man);
		if (pMblockNode == NULL)
		{
			result = errno != 0 ? errno : EIO;
			logError("file: "__FILE__", line: %d, " \
				"malloc %d bytes fail, " \
				"errno: %d, error info: %s", \
				__LINE__, (int)sizeof(FDFSTrunkSlot), \
				result, STRERROR(result));
			pthread_mutex_unlock(&trunk_mem_lock);
			return result;
		}

		chain = (FDFSTrunkSlot *)pMblockNode->data;
		chain->pMblockNode = pMblockNode;
		chain->size = pNode->trunk.file.size;
		pNode->next = NULL;
		chain->head = pNode;

		if (avl_tree_insert(&tree_info_by_size, chain) != 1)
		{
			result = errno != 0 ? errno : ENOMEM;
			logError("file: "__FILE__", line: %d, " \
				"avl_tree_insert fail, " \
				"errno: %d, error info: %s", \
				__LINE__, result, STRERROR(result));
			pthread_mutex_unlock(&trunk_mem_lock);
			return result;
		}
	}
	else
	{
		pNode->next = chain->head;
		chain->head = pNode;
	}

	if (bWriteBinLog)
	{
		result = trunk_mem_binlog_write(g_current_time, \
				TRUNK_OP_TYPE_ADD_SPACE, &(pNode->trunk));
	}
	else
	{
		pthread_mutex_lock(&trunk_file_lock);
		g_trunk_total_free_space += pNode->trunk.file.size;
		pthread_mutex_unlock(&trunk_file_lock);
		result = 0;
	}

	if (result == 0)
	{
		result = trunk_free_block_insert(&(pNode->trunk));
	}
	else
	{
		trunk_free_block_insert(&(pNode->trunk));
	}

	pthread_mutex_unlock(&trunk_mem_lock);

	return result;
}
void loadTilesetSettings() {
	// reset defaults
	UNITS_PER_PIXEL_X = 2;
	UNITS_PER_PIXEL_Y = 4;
	TILE_W = 64;
	TILE_H = 32;
	TILE_W_HALF = TILE_W/2;
	TILE_H_HALF = TILE_H/2;
	TILESET_ISOMETRIC = 0;
	TILESET_ORTHOGONAL = 1;
	TILESET_ORIENTATION = TILESET_ISOMETRIC;

	FileParser infile;
	// load tileset settings from engine config
	// @CLASS Settings: Tileset config|Description of engine/tileset_config.txt
	if (infile.open("engine/tileset_config.txt", true, "Unable to open engine/tileset_config.txt! Defaulting to 64x32 isometric tiles.")) {
		while (infile.next()) {
			if (infile.key == "tile_size") {
				// @ATTR tile_size|w (integet), h (integer)|The width and height of a tile.
				TILE_W = toInt(infile.nextValue());
				TILE_H = toInt(infile.nextValue());
				TILE_W_HALF = TILE_W /2;
				TILE_H_HALF = TILE_H /2;
			}
			else if (infile.key == "orientation") {
				// @ATTR orientation|[isometric, orthogonal]|The perspective of tiles; isometric or orthogonal.
				if (infile.val == "isometric")
					TILESET_ORIENTATION = TILESET_ISOMETRIC;
				else if (infile.val == "orthogonal")
					TILESET_ORIENTATION = TILESET_ORTHOGONAL;
			}
			else {
				infile.error("Settings: '%s' is not a valid key.", infile.key.c_str());
			}
		}
		infile.close();
	}

	// Init automatically calculated parameters
	if (TILESET_ORIENTATION == TILESET_ISOMETRIC) {
		if (TILE_W > 0 && TILE_H > 0) {
			UNITS_PER_PIXEL_X = 2.0f / TILE_W;
			UNITS_PER_PIXEL_Y = 2.0f / TILE_H;
		}
		else {
			logError("Settings: Tile dimensions must be greater than 0. Resetting to the default size of 64x32.");
			TILE_W = 64;
			TILE_H = 32;
		}
	}
	else { // TILESET_ORTHOGONAL
		if (TILE_W > 0 && TILE_H > 0) {
			UNITS_PER_PIXEL_X = 1.0f / TILE_W;
			UNITS_PER_PIXEL_Y = 1.0f / TILE_H;
		}
		else {
			logError("Settings: Tile dimensions must be greater than 0. Resetting to the default size of 64x32.");
			TILE_W = 64;
			TILE_H = 32;
		}
	}
	if (UNITS_PER_PIXEL_X == 0 || UNITS_PER_PIXEL_Y == 0) {
		logError("Settings: One of UNITS_PER_PIXEL values is zero! %dx%d", (int)UNITS_PER_PIXEL_X, (int)UNITS_PER_PIXEL_Y);
		SDL_Quit();
		exit(1);
	}
}
Exemple #13
0
int fdfs_gen_slave_filename(const char *master_filename, \
                            const char *prefix_name, const char *ext_name, \
                            char *filename, int *filename_len)
{
    char true_ext_name[FDFS_FILE_EXT_NAME_MAX_LEN + 2];
    char *pDot;
    int master_file_len;

    master_file_len = strlen(master_filename);
    if (master_file_len < 28 + FDFS_FILE_EXT_NAME_MAX_LEN)
    {
        logError("file: "__FILE__", line: %d, " \
                 "master filename \"%s\" is invalid", \
                 __LINE__, master_filename);
        return EINVAL;
    }

    pDot = strchr(master_filename + (master_file_len - \
                                     (FDFS_FILE_EXT_NAME_MAX_LEN + 1)), '.');
    if (ext_name != NULL)
    {
        if (*ext_name == '\0')
        {
            *true_ext_name = '\0';
        }
        else if (*ext_name == '.')
        {
            snprintf(true_ext_name, sizeof(true_ext_name), \
                     "%s", ext_name);
        }
        else
        {
            snprintf(true_ext_name, sizeof(true_ext_name), \
                     ".%s", ext_name);
        }
    }
    else
    {
        if (pDot == NULL)
        {
            *true_ext_name = '\0';
        }
        else
        {
            strcpy(true_ext_name, pDot);
        }
    }

    if (*true_ext_name == '\0' && strcmp(prefix_name, "-m") == 0)
    {
        logError("file: "__FILE__", line: %d, " \
                 "prefix_name \"%s\" is invalid", \
                 __LINE__, prefix_name);
        return EINVAL;
    }

    /* when prefix_name is empty, the extension name of master file and
       slave file can not be same
    */
    if ((*prefix_name == '\0') && ((pDot == NULL && *true_ext_name == '\0')
                                   || (pDot != NULL && strcmp(pDot, true_ext_name) == 0)))
    {
        logError("file: "__FILE__", line: %d, " \
                 "empty prefix_name is not allowed", __LINE__);
        return EINVAL;
    }

    if (pDot == NULL)
    {
        *filename_len = sprintf(filename, "%s%s%s", master_filename, \
                                prefix_name, true_ext_name);
    }
    else
    {
        *filename_len = pDot - master_filename;
        memcpy(filename, master_filename, *filename_len);
        *filename_len += sprintf(filename + *filename_len, "%s%s", \
                                 prefix_name, true_ext_name);
    }

    return 0;
}
Exemple #14
0
int main(int argc, char **argv)
{
	TSS_HTPM hTpm;
	TSS_HNVSTORE nvObject;
	TSS_FLAG fNvAttrs;
	TSS_HPOLICY hTpmPolicy, hDataPolicy;
	int iRc = -1;
	BYTE well_known_secret[] = TSS_WELL_KNOWN_SECRET;
	int opswd_len = -1;
	int dpswd_len = -1;
	struct option hOpts[] = {
		{"index"           , required_argument, NULL, 'i'},
		{"size"            , required_argument, NULL, 's'},
		{"permissions"     , required_argument, NULL, 'p'},
		{"pwdo"            , optional_argument, NULL, 'o'},
		{"pwda"            , optional_argument, NULL, 'a'},
		{"use-unicode"     ,       no_argument, NULL, 'u'},
		{"data-well-known" ,       no_argument, NULL, 'z'},
		{"owner-well-known",       no_argument, NULL, 'y'},
		{NULL              ,       no_argument, NULL, 0},
	};

	initIntlSys();

	if (genericOptHandler
		    (argc, argv, "i:s:p:o:a:yzu", hOpts,
		     sizeof(hOpts) / sizeof(struct option), parse, help) != 0)
		goto out;

	if (end) {
		iRc = 0;
		goto out;
	}

	if (!nvindex_set) {
		logError(_("You must provide an index for the NVRAM area.\n"));
		goto out;
	}

	if (nvperm == 0 &&
	    (UINT32)nvindex != TPM_NV_INDEX_LOCK &&
	    (UINT32)nvindex != TPM_NV_INDEX0) {
		logError(_("You must provide permission bits for the NVRAM area.\n"));
		goto out;
	}

	logDebug("permissions = 0x%08x\n", nvperm);

	if (contextCreate(&hContext) != TSS_SUCCESS)
		goto out;

	if (contextConnect(hContext) != TSS_SUCCESS)
		goto out_close;

	if (contextGetTpm(hContext, &hTpm) != TSS_SUCCESS)
		goto out_close;

	fNvAttrs = 0;

	if (contextCreateObject(hContext,
				TSS_OBJECT_TYPE_NV,
				fNvAttrs,
				&nvObject) != TSS_SUCCESS)
		goto out_close;

	if (askOwnerPass) {
		ownerpass = _GETPASSWD(_("Enter owner password: "******"Failed to get owner password\n"));
			goto out_close;
		}
	}

	if (ownerpass || ownerWellKnown) {
		if (policyGet(hTpm, &hTpmPolicy) != TSS_SUCCESS)
			goto out_close;
		if (ownerpass) {
			if (opswd_len < 0)
				opswd_len = strlen(ownerpass);
			if (policySetSecret(hTpmPolicy, opswd_len,
					    (BYTE *)ownerpass) != TSS_SUCCESS)
				goto out_close;
		} else {
			if (policySetSecret(hTpmPolicy, TCPA_SHA1_160_HASH_LEN,
					    (BYTE *)well_known_secret) != TSS_SUCCESS)
				goto out_close;
		}
	}

	if (askDataPass) {
		datapass = _GETPASSWD(_("Enter NVRAM data password: "******"Failed to get NVRAM data password\n"));
			goto out_close;
		}
	}

	if (datapass || dataWellKnown) {
		if (contextCreateObject
		    (hContext, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE,
		     &hDataPolicy) != TSS_SUCCESS)
			goto out_close;

		if (datapass) {
			if (dpswd_len < 0)
				dpswd_len = strlen(datapass);
			if (policySetSecret(hDataPolicy, dpswd_len,
				    (BYTE *)datapass) != TSS_SUCCESS)
				goto out_close;
		} else {
			if (policySetSecret(hDataPolicy, TCPA_SHA1_160_HASH_LEN,
				    (BYTE *)well_known_secret) != TSS_SUCCESS)
				goto out_close;
		}

		if (Tspi_Policy_AssignToObject(hDataPolicy, nvObject) !=
		    TSS_SUCCESS)
			goto out_close;
	}

	if (Tspi_SetAttribUint32(nvObject,
				 TSS_TSPATTRIB_NV_INDEX,
				 0,
				 nvindex) != TSS_SUCCESS)
		goto out_close_obj;

	if (Tspi_SetAttribUint32(nvObject,
				 TSS_TSPATTRIB_NV_PERMISSIONS,
				 0,
				 nvperm) != TSS_SUCCESS)
		goto out_close_obj;

	if (Tspi_SetAttribUint32(nvObject,
				 TSS_TSPATTRIB_NV_DATASIZE,
				 0,
				 nvsize) != TSS_SUCCESS)
		goto out_close_obj;

	if (NVDefineSpace(nvObject, (TSS_HPCRS)0, (TSS_HPCRS)0) !=
	    TSS_SUCCESS)
		goto out_close;

	logMsg(_("Successfully created NVRAM area at index 0x%x (%u).\n"),
	       nvindex, nvindex);

	iRc = 0;

	goto out_close;

      out_close_obj:
	contextCloseObject(hContext, nvObject);

      out_close:
	contextClose(hContext);

      out:
	return iRc;
}
Exemple #15
0
program_state 
timedWaitChild(
  pid_t child, 
  problem p
) {
  program_state state = STATE_CORRECT;
  
  // use this for debugging
  char childstr[64];
  (void) sprintf(childstr, "%ld", (long) child);

  // syscall remembering mechanism
  long syscall; // value from ORIG_RAX or ORIG_EAX
  long cur_call = -1; // default non-existent
  char insyscall = 0; // if entering or exiting syscall
  
  //TODO: change mechanics if we no longer use bash -c
  int execcount = 0; // number of execs, one for bash, one for process
  
  // resource usage
  struct rusage ru, initru;
  // process registries
  // struct user_regs_struct regs;
  
  // values for waitpid
  int waitstatus;
  int waitresult;
  // execute once for initial resource offsetting
  waitresult = wait4(child, &waitstatus, 0, &ru);
  if (-1 == waitresult) 
  {
    criticalFail("Error on waitpid");
    //logError("Wait failed", child);
    //return STATE_INTERNAL_ERROR;
  }
  memcpy(&initru, &ru, sizeof(ru));

  // loop while not done
  char done = 0;
  do 
  {
    // do something with rusage, after eliminating initial
    // ru.ru_stime -= initru.ru_stime;
    // ru.ru_utime -= initru.ru_utime;
    
    //TODO: remove useless messages...they are just for debug now
    if (WIFSTOPPED(waitstatus)) 
    {
      switch(WSTOPSIG(waitstatus)) 
      {
      case SIGALRM: // real timer
        logError("Real time expired in process", childstr);
        ptrace(PTRACE_KILL, child, NULL, NULL);
        state = STATE_TIME_LIMIT_EXCEEDED;
        done = 1;
        break;
      case SIGXCPU: // CPU resource limit exceeded
      case SIGPROF: // profile timer expired
      case SIGVTALRM: // virtual timer expired
        logError("Virtual time expired in process", childstr);
        ptrace(PTRACE_KILL, child, NULL, NULL);
        state = STATE_TIME_LIMIT_EXCEEDED;
        done = 1;
        break;
      case SIGUSR1: // memory limit exceeded ... doesn't really work :p
        logError("Memory limit exceeded in process", childstr);
        ptrace(PTRACE_KILL, child, NULL, NULL);
        state = STATE_MEMORY_LIMIT_EXCEEDED;
        done = 1;
        break;
        /*
      case SIGSEGV:
        printf("Current syscall %ld\nExpected syscall %d\nCurrent errno %d\nExpected errno %d\n", cur_call, SYS_mmap, errno, ENOMEM);
        ptrace(PTRACE_KILL, child, NULL, NULL);
        state = STATE_MEMORY_LIMIT_EXCEEDED;
        done = 1;
        break;
        */
      case SIGXFSZ: // output file size exceeded
        logError("Output size exceeded in process", childstr);
        ptrace(PTRACE_KILL, child, NULL, NULL);
        state = STATE_OUTPUT_LIMIT_EXCEEDED;
        done = 1;
        break;
      case SIGTRAP: // ptrace trap
        // ptrace(PTRACE_GETREGS, child, NULL, &regs);
#ifdef __x86_64__
        syscall = ptrace(PTRACE_PEEKUSER, child, 8 * ORIG_RAX, NULL);
#else
        syscall = ptrace(PTRACE_PEEKUSER, child, 4 * ORIG_EAX, NULL);
#endif
        if (-1 == syscall) 
        {
          //criticalFail("Error on ptrace");
          logError("Error ptrace", childstr);
          state = STATE_INTERNAL_ERROR;
          done = 1;
          break;
        }

        char syscallstr[64];
        (void) sprintf(syscallstr, "%ld", syscall);
        if (SYS_execve == syscall) 
        {
          if (execcount++ < 2) 
          {
            break;
            // run /bin/bash
            // then run the actual program
          } 
          else 
          {
            logError("Illegal operation", syscallstr);
            ptrace(PTRACE_KILL, child, NULL, NULL);
            state = STATE_ILLEGAL_SYSCALL;
            done = 1;
            break;
          }
        }

        // not execv
        if (0 == insyscall) 
        {
          insyscall = 1;
          cur_call = syscall;
          printf("SYSCALL > %ld\n", syscall);
        } 
        else if (cur_call == syscall) 
        {
          insyscall = 0;
          printf("SYSCALL < %ld\n", syscall);
        }
        break;
      case SIGCHLD:
        // child ended, rerun the loop to get exit status info
        //printf("Current syscall %ld\nExpected syscall %d\nCurrent errno %d\nExpected errno %d\n", cur_call, SYS_mmap, errno, ENOMEM);
        printf("Child finished\n");
        break;
      default :
        printf("Unusual signal ...%d\n", WSTOPSIG(waitstatus));
        break;
      }
    } 
    else if (WIFSIGNALED(waitstatus)) 
    {
      printf("Child stopped via signal %d\n", WTERMSIG(waitstatus));
      break;
    } 
    else if (WIFEXITED(waitstatus)) 
    {
      printf("Child exited with status %d\n", WEXITSTATUS(waitstatus));
      break;
    }
    
    if (!done) 
    {
      // trace next call
      ptrace(PTRACE_SYSCALL, child, NULL, NULL);
      waitresult = wait4(child, &waitstatus, 0, &ru);
      if (-1 == waitresult) 
      {
        logError("Error waitpid", childstr);
        state = STATE_INTERNAL_ERROR;
        done = 1;
      }
    }
  }
  while (!done);

  return state;
}
Exemple #16
0
int trunk_check_and_init_file_ex(const char *filename, const int64_t file_size)
{
	struct stat file_stat;
	int fd;
	int result;
	
	result = trunk_wait_file_ready(filename, file_size, false);
	if (result == 0)
	{
		return 0;
	}
	if (result == ENOENT)
	{
		return trunk_init_file_ex(filename, file_size);
	}
	if (result != ETIMEDOUT)
	{
		return result;
	}

	if (stat(filename, &file_stat) != 0)
	{
		result = errno != 0 ? errno : ENOENT;
		logError("file: "__FILE__", line: %d, " \
			"stat file %s fail, " \
			"errno: %d, error info: %s", \
			__LINE__, filename, \
			result, STRERROR(result));
		return result;
	}

	logWarning("file: "__FILE__", line: %d, " \
		"file: %s, file size: "INT64_PRINTF_FORMAT \
		" < "INT64_PRINTF_FORMAT", should be resize", \
		__LINE__, filename, (int64_t)file_stat.st_size, file_size);

	fd = open(filename, O_WRONLY, 0644);
	if (fd < 0)
	{
		result = errno != 0 ? errno : EIO;
		logError("file: "__FILE__", line: %d, " \
			"open file %s fail, " \
			"errno: %d, error info: %s", \
			__LINE__, filename, \
			result, STRERROR(result));
		return result;
	}

	if (ftruncate(fd, file_size) == 0)
	{
		result = 0;
	}
	else
	{
		result = errno != 0 ? errno : EIO;
		logError("file: "__FILE__", line: %d, " \
			"ftruncate file %s fail, " \
			"errno: %d, error info: %s", \
			__LINE__, filename, \
			result, STRERROR(result));
	}

	close(fd);
	return result;
}
Exemple #17
0
PQLCollation *
getCollations(PGconn *c, int *n)
{
	char			*query = NULL;
	int				nquery = PGQQRYLEN;
	PQLCollation	*d;
	PGresult		*res;
	int				i;
	int				r;

	logNoise("collation: server version: %d", PQserverVersion(c));

	/* bail out if we do not support it */
	if (PQserverVersion(c) < 90100)
	{
		logWarning("ignoring collations because server does not support it");
		return NULL;
	}

	do
	{
		query = (char *) malloc(nquery * sizeof(char));

		r = snprintf(query, nquery,
					 "SELECT c.oid, n.nspname, collname, pg_encoding_to_char(collencoding) AS collencoding, collcollate, collctype, pg_get_userbyid(collowner) AS collowner, obj_description(c.oid, 'pg_collation') AS description FROM pg_collation c INNER JOIN pg_namespace n ON (c.collnamespace = n.oid) WHERE c.oid >= %u AND NOT EXISTS(SELECT 1 FROM pg_depend d WHERE c.oid = d.objid AND d.deptype = 'e') ORDER BY n.nspname, collname",
					 PGQ_FIRST_USER_OID);

		if (r < nquery)
			break;

		logNoise("query size: required (%u) ; initial (%u)", r, nquery);
		nquery = r + 1;	/* make enough room for query */
		free(query);
	}
	while (true);

	res = PQexec(c, query);

	free(query);

	if (PQresultStatus(res) != PGRES_TUPLES_OK)
	{
		logError("query failed: %s", PQresultErrorMessage(res));
		PQclear(res);
		PQfinish(c);
		/* XXX leak another connection? */
		exit(EXIT_FAILURE);
	}

	*n = PQntuples(res);
	if (*n > 0)
		d = (PQLCollation *) malloc(*n * sizeof(PQLCollation));
	else
		d = NULL;

	logDebug("number of collations in server: %d", *n);

	for (i = 0; i < *n; i++)
	{
		d[i].obj.oid = strtoul(PQgetvalue(res, i, PQfnumber(res, "oid")), NULL, 10);
		d[i].obj.schemaname = strdup(PQgetvalue(res, i, PQfnumber(res, "nspname")));
		d[i].obj.objectname = strdup(PQgetvalue(res, i, PQfnumber(res, "collname")));
		d[i].encoding = strdup(PQgetvalue(res, i, PQfnumber(res, "collencoding")));
		d[i].collate = strdup(PQgetvalue(res, i, PQfnumber(res, "collcollate")));
		d[i].ctype = strdup(PQgetvalue(res, i, PQfnumber(res, "collctype")));

		if (PQgetisnull(res, i, PQfnumber(res, "description")))
			d[i].comment = NULL;
		else
			d[i].comment = strdup(PQgetvalue(res, i, PQfnumber(res, "description")));

		d[i].owner = strdup(PQgetvalue(res, i, PQfnumber(res, "collowner")));

		logDebug("collation \"%s\".\"%s\"", d[i].obj.schemaname, d[i].obj.objectname);
	}

	PQclear(res);

	return d;
}
Exemple #18
0
int trunk_create_trunk_file_advance(void *args)
{
	int64_t total_mb_sum;
	int64_t free_mb_sum;
	int64_t alloc_space;
	FDFSTrunkNode *pTrunkNode;
	int result;
	int i;
	int file_count;

	if (!g_trunk_create_file_advance)
	{
		logError("file: "__FILE__", line: %d, " \
			"do not need create trunk file advancely!", __LINE__);
		return EINVAL;
	}

	if (!g_if_trunker_self)
	{
		logError("file: "__FILE__", line: %d, " \
			"I am not trunk server!", __LINE__);
		return ENOENT;
	}

	alloc_space = g_trunk_create_file_space_threshold - \
			g_trunk_total_free_space;
	if (alloc_space <= 0)
	{
		logDebug("file: "__FILE__", line: %d, " \
			"do not need create trunk file!", __LINE__);
		return 0;
	}

	total_mb_sum = 0;
	free_mb_sum = 0;
	for (i=0; i<g_fdfs_store_paths.count; i++)
	{
		total_mb_sum += g_path_space_list[i].total_mb;
		free_mb_sum += g_path_space_list[i].free_mb;
	}

	if (!storage_check_reserved_space_path(total_mb_sum, free_mb_sum \
		- (alloc_space / FDFS_ONE_MB), g_storage_reserved_space.rs.mb))
	{
		logError("file: "__FILE__", line: %d, " \
			"free space is not enough!", __LINE__);
		return ENOSPC;
	}

	result = 0;
	file_count = alloc_space / g_trunk_file_size;
	for (i=0; i<file_count; i++)
	{
		pTrunkNode = trunk_create_trunk_file(&result);
		if (pTrunkNode != NULL)
		{
			result = trunk_add_free_block(pTrunkNode, false);
			if (result != 0)
			{
				break;
			}
		}
	}

	if (result == 0)
	{
		logDebug("file: "__FILE__", line: %d, " \
			"create trunk file count: %d", __LINE__, file_count);
	}
 
	return result;
}
void PlatformSetPaths() {

    // attempting to follow this spec:
    // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html

    // set config path (settings, keybindings)
    // $XDG_CONFIG_HOME/flare/
    if (getenv("XDG_CONFIG_HOME") != NULL) {
        PATH_CONF = (std::string)getenv("XDG_CONFIG_HOME") + "/flare/";
    }
    // $HOME/.config/flare/
    else if (getenv("HOME") != NULL) {
        PATH_CONF = (std::string)getenv("HOME") + "/.config/";
        createDir(PATH_CONF);
        PATH_CONF += "flare/";
    }
    // ./config/
    else {
        PATH_CONF = "./config/";
    }

    createDir(PATH_CONF);

    // set user path (save games)
    // $XDG_DATA_HOME/flare/
    if (getenv("XDG_DATA_HOME") != NULL) {
        PATH_USER = (std::string)getenv("XDG_DATA_HOME") + "/flare/";
    }
    // $HOME/.local/share/flare/
    else if (getenv("HOME") != NULL) {
        PATH_USER = (std::string)getenv("HOME") + "/.local/";
        createDir(PATH_USER);
        PATH_USER += "share/";
        createDir(PATH_USER);
        PATH_USER += "flare/";
    }
    // ./saves/
    else {
        PATH_USER = "******";
    }

    createDir(PATH_USER);
    createDir(PATH_USER + "mods/");
    createDir(PATH_USER + "saves/");

    // data folder
    // while PATH_CONF and PATH_USER are created if not found,
    // PATH_DATA must already have the game data for the game to work.
    // in most releases the data will be in the same folder as the executable
    // - Windows apps are released as a simple folder
    // - OSX apps are released in a .app folder
    // Official linux distros might put the executable and data files
    // in a more standard location.

    // these flags are set to true when a valid directory is found
    bool path_data = false;

    // if the user specified a data path, try to use it
    if (dirExists(CUSTOM_PATH_DATA)) {
        if (!path_data) PATH_DATA = CUSTOM_PATH_DATA;
        path_data = true;
    }
    else if (!CUSTOM_PATH_DATA.empty()) {
        logError("Settings: Could not find specified game data directory.");
        CUSTOM_PATH_DATA = "";
    }

    // Check for the local data before trying installed ones.
    if (dirExists("./mods")) {
        if (!path_data) PATH_DATA = "./";
        path_data = true;
    }

    // check $XDG_DATA_DIRS options
    // a list of directories in preferred order separated by :
    if (getenv("XDG_DATA_DIRS") != NULL) {
        std::string pathlist = (std::string)getenv("XDG_DATA_DIRS");
        std::string pathtest;
        pathtest = popFirstString(pathlist,':');
        while (pathtest != "") {
            if (!path_data) {
                PATH_DATA = pathtest + "/flare/";
                if (dirExists(PATH_DATA)) path_data = true;
            }
            if (path_data) break;
            pathtest = popFirstString(pathlist,':');
        }
    }

#if defined DATA_INSTALL_DIR
    if (!path_data) PATH_DATA = DATA_INSTALL_DIR "/";
    if (!path_data && dirExists(PATH_DATA)) path_data = true;
#endif

    // check /usr/local/share/flare/ and /usr/share/flare/ next
    if (!path_data) PATH_DATA = "/usr/local/share/flare/";
    if (!path_data && dirExists(PATH_DATA)) path_data = true;

    if (!path_data) PATH_DATA = "/usr/share/flare/";
    if (!path_data && dirExists(PATH_DATA)) path_data = true;

    // check "games" variants of these
    if (!path_data) PATH_DATA = "/usr/local/share/games/flare/";
    if (!path_data && dirExists(PATH_DATA)) path_data = true;

    if (!path_data) PATH_DATA = "/usr/share/games/flare/";
    if (!path_data && dirExists(PATH_DATA)) path_data = true;

    // finally assume the local folder
    if (!path_data)	PATH_DATA = "./";
}
Exemple #20
0
static int storage_trunk_save()
{
	int64_t trunk_binlog_size;
	char true_trunk_filename[MAX_PATH_SIZE];
	struct walk_callback_args callback_args;
	int len;
	int result;

	trunk_binlog_size = storage_trunk_get_binlog_size();
	if (trunk_binlog_size < 0)
	{
		return errno != 0 ? errno : EPERM;
	}

	memset(&callback_args, 0, sizeof(callback_args));
	callback_args.pCurrent = callback_args.buff;

	sprintf(callback_args.temp_trunk_filename, "%s/data/.%s.tmp", \
		g_fdfs_base_path, STORAGE_TRUNK_DATA_FILENAME);
	callback_args.fd = open(callback_args.temp_trunk_filename, \
				O_WRONLY | O_CREAT | O_TRUNC, 0644);
	if (callback_args.fd < 0)
	{
		result = errno != 0 ? errno : EIO;
		logError("file: "__FILE__", line: %d, " \
			"open file %s fail, " \
			"errno: %d, error info: %s", \
			__LINE__, callback_args.temp_trunk_filename, \
			result, STRERROR(result));
		return result;
	}

	len = sprintf(callback_args.pCurrent, INT64_PRINTF_FORMAT"\n", \
			trunk_binlog_size);
	callback_args.pCurrent += len;

	pthread_mutex_lock(&trunk_mem_lock);
	result = avl_tree_walk(&tree_info_by_size, tree_walk_callback, &callback_args);

	len = callback_args.pCurrent - callback_args.buff;
	if (len > 0 && result == 0)
	{
		if (write(callback_args.fd, callback_args.buff, len) != len)
		{
			result = errno != 0 ? errno : EIO;
			logError("file: "__FILE__", line: %d, "\
				"write to file %s fail, " \
				"errno: %d, error info: %s", \
				__LINE__, callback_args.temp_trunk_filename, \
				result, STRERROR(result));
		}
	}

	if (result == 0 && fsync(callback_args.fd) != 0)
	{
		result = errno != 0 ? errno : EIO;
		logError("file: "__FILE__", line: %d, "\
			"fsync file %s fail, " \
			"errno: %d, error info: %s", \
			__LINE__, callback_args.temp_trunk_filename, \
			result, STRERROR(result));
	}

	close(callback_args.fd);
	pthread_mutex_unlock(&trunk_mem_lock);

	if (result != 0)
	{
		return result;
	}

	sprintf(true_trunk_filename, "%s/data/%s", \
		g_fdfs_base_path, STORAGE_TRUNK_DATA_FILENAME);
	if (rename(callback_args.temp_trunk_filename, true_trunk_filename) != 0)
	{
		result = errno != 0 ? errno : EIO;
		logError("file: "__FILE__", line: %d, "\
			"rename file %s to %s fail, " \
			"errno: %d, error info: %s", __LINE__, \
			callback_args.temp_trunk_filename, true_trunk_filename, \
			result, STRERROR(result));
	}

	return result;
}
int load_allow_hosts(IniContext *pIniContext, \
		in_addr_t **allow_ip_addrs, int *allow_ip_count)
{
	int count;
	IniItem *pItem;
	IniItem *pItemStart;
	IniItem *pItemEnd;
	char *pItemValue;
	char *pStart;
	char *pEnd;
	char *p;
	char *pTail;
	int alloc_count;
	int nHeadLen;
	int i;
	in_addr_t addr;
	char hostname[256];

	if ((pItemStart=iniGetValuesEx(NULL, "allow_hosts", \
		pIniContext, &count)) == NULL)
	{
		*allow_ip_count = -1; /* -1 means match any ip address */
		*allow_ip_addrs = NULL;
		return 0;
	}

	pItemEnd = pItemStart + count;
	for (pItem=pItemStart; pItem<pItemEnd; pItem++)
	{
		if (strcmp(pItem->value, "*") == 0)
		{
			*allow_ip_count = -1; /* -1 means match any ip address*/
			*allow_ip_addrs = NULL;
			return 0;
		}
	}

	alloc_count = count;
	*allow_ip_count = 0;
	*allow_ip_addrs = (in_addr_t *)malloc(sizeof(in_addr_t) * alloc_count);
	if (*allow_ip_addrs == NULL)
	{
		logError("file: "__FILE__", line: %d, " \
			"malloc %d bytes fail, errno: %d, error info: %s.", \
			__LINE__, (int)sizeof(in_addr_t) * alloc_count, \
			errno, STRERROR(errno));
		return errno != 0 ? errno : ENOMEM;
	}

	for (pItem=pItemStart; pItem<pItemEnd; pItem++)
	{
		if (*(pItem->value) == '\0')
		{
			continue;
		}

		pStart = strchr(pItem->value, '[');
		if (pStart == NULL)
		{
			addr = getIpaddrByName(pItem->value, NULL, 0);
			if (addr == INADDR_NONE)
			{
				logWarning("file: "__FILE__", line: %d, " \
					"invalid host name: %s", \
					__LINE__, pItem->value);
			}
			else
			{
				if (alloc_count < (*allow_ip_count) + 1)
				{
					alloc_count = (*allow_ip_count) + \
							(pItemEnd - pItem);
					*allow_ip_addrs = (in_addr_t *)realloc(
						*allow_ip_addrs, 
						sizeof(in_addr_t)*alloc_count);
					if (*allow_ip_addrs == NULL)
					{
					logError("file: "__FILE__", line: %d, "\
						"malloc %d bytes fail, " \
						"errno: %d, error info: %s", \
						__LINE__, (int)sizeof(in_addr_t)
							* alloc_count, \
						errno, STRERROR(errno));

					return errno != 0 ? errno : ENOMEM;
					}
				}

				(*allow_ip_addrs)[*allow_ip_count] = addr;
				(*allow_ip_count)++;
			}

			continue;
		}

		
		pEnd = strchr(pStart, ']');
		if (pEnd == NULL)
		{
			logWarning("file: "__FILE__", line: %d, " \
				"invalid host name: %s, expect \"]\"", \
				__LINE__, pItem->value);
			continue;
		}

		pItemValue = strdup(pItem->value);
		if (pItemValue == NULL)
		{
			logWarning("file: "__FILE__", line: %d, " \
				"strdup fail, " \
				"errno: %d, error info: %s.", \
				__LINE__, errno, STRERROR(errno));
			continue;
		}

		nHeadLen = pStart - pItem->value;
		pStart = pItemValue + nHeadLen;
		pEnd = pItemValue + (pEnd - pItem->value);
		pTail = pEnd + 1;

		memcpy(hostname, pItem->value, nHeadLen);
		p = pStart + 1;  //skip [

		while (p <= pEnd)
		{
			char *pNumStart1;
			char *pNumStart2;
			int nStart;
			int nEnd;
			int nNumLen1;
			int nNumLen2;
			char end_ch1;
			char end_ch2;
			char szFormat[16];

			while (*p == ' ' || *p == '\t') //trim prior spaces
			{
				p++;
			}

			pNumStart1 = p;
			while (*p >='0' && *p <= '9')
			{
				p++;
			}

			nNumLen1 = p - pNumStart1;
			while (*p == ' ' || *p == '\t') //trim tail spaces
			{
				p++;
			}

			if (!(*p == ',' || *p == '-' || *p == ']'))
			{
				logWarning("file: "__FILE__", line: %d, " \
					"invalid char \"%c\" in host name: %s",\
					__LINE__, *p, pItem->value);
				break;
			}

			end_ch1 = *p;
			*(pNumStart1 + nNumLen1) = '\0';

			if (nNumLen1 == 0)
			{
				logWarning("file: "__FILE__", line: %d, " \
					"invalid host name: %s, " \
					"empty entry before \"%c\"", \
					__LINE__, pItem->value, end_ch1);
				break;
			}

			nStart = atoi(pNumStart1);
			if (end_ch1 == '-')
			{
				p++;   //skip -

				/* trim prior spaces */
				while (*p == ' ' || *p == '\t')
				{
					p++;
				}

				pNumStart2 = p;
				while (*p >='0' && *p <= '9')
				{
					p++;
				}

				nNumLen2 = p - pNumStart2;
				/* trim tail spaces */
				while (*p == ' ' || *p == '\t')
				{
					p++;
				}

				if (!(*p == ',' || *p == ']'))
				{
				logWarning("file: "__FILE__", line: %d, " \
					"invalid char \"%c\" in host name: %s",\
					__LINE__, *p, pItem->value);
				break;
				}

				end_ch2 = *p;
				*(pNumStart2 + nNumLen2) = '\0';

				if (nNumLen2 == 0)
				{
				logWarning("file: "__FILE__", line: %d, " \
					"invalid host name: %s, " \
					"empty entry before \"%c\"", \
					__LINE__, pItem->value, end_ch2);
				break;
				}

				nEnd = atoi(pNumStart2);
			}
			else
			{
				nEnd = nStart;
			}

			if (alloc_count < *allow_ip_count+(nEnd - nStart + 1))
			{
				alloc_count = *allow_ip_count + (nEnd - nStart)
						 + (pItemEnd - pItem);
				*allow_ip_addrs = (in_addr_t *)realloc(
					*allow_ip_addrs, 
					sizeof(in_addr_t)*alloc_count);
				if (*allow_ip_addrs == NULL)
				{
					logError("file: "__FILE__", line: %d, "\
						"malloc %d bytes fail, " \
						"errno: %d, error info: %s.", \
						__LINE__, \
						(int)sizeof(in_addr_t) * \
						alloc_count,\
						errno, STRERROR(errno));

					free(pItemValue);
					return errno != 0 ? errno : ENOMEM;
				}
			}

			sprintf(szFormat, "%%0%dd%%s",  nNumLen1);
			for (i=nStart; i<=nEnd; i++)
			{
				sprintf(hostname + nHeadLen, szFormat, \
					i, pTail);

				addr = getIpaddrByName(hostname, NULL, 0);
				if (addr == INADDR_NONE)
				{
				logWarning("file: "__FILE__", line: %d, " \
					"invalid host name: %s", \
					__LINE__, hostname);
				}
				else
				{
					(*allow_ip_addrs)[*allow_ip_count]=addr;
					(*allow_ip_count)++;
				}

			}

			p++;
		}

		free(pItemValue);
	}

	if (*allow_ip_count == 0)
	{
		logWarning("file: "__FILE__", line: %d, " \
			"allow ip count: 0", __LINE__);
	}

	if (*allow_ip_count > 0)
	{
		qsort(*allow_ip_addrs,  *allow_ip_count, sizeof(in_addr_t), \
			cmp_by_ip_addr_t);
	}

	/*
	printf("*allow_ip_count=%d\n", *allow_ip_count);
	for (i=0; i<*allow_ip_count; i++)
	{
		struct in_addr address;
		address.s_addr = (*allow_ip_addrs)[i];
		printf("%s\n", inet_ntoa(address));
	}
	*/

	return 0;
}
Exemple #22
0
static int storage_trunk_restore(const int64_t restore_offset)
{
	int64_t trunk_binlog_size;
	int64_t line_count;
	TrunkBinLogReader reader;
	TrunkBinLogRecord record;
	char trunk_mark_filename[MAX_PATH_SIZE];
	char buff[256];
	int record_length;
	int result;
	AVLTreeInfo tree_info_by_offset;
	struct fast_mblock_node *pMblockNode;
	FDFSTrunkNode *pTrunkNode;
	FDFSTrunkNode trunkNode;
	bool trunk_init_reload_from_binlog;

	trunk_binlog_size = storage_trunk_get_binlog_size();
	if (trunk_binlog_size < 0)
	{
		return errno != 0 ? errno : EPERM;
	}

	if (restore_offset == trunk_binlog_size)
	{
		return 0;
	}

	if (restore_offset > trunk_binlog_size)
	{
		logWarning("file: "__FILE__", line: %d, " \
			"restore_offset: "INT64_PRINTF_FORMAT \
			" > trunk_binlog_size: "INT64_PRINTF_FORMAT, \
			__LINE__, restore_offset, trunk_binlog_size);
		return storage_trunk_save();
	}

	logDebug("file: "__FILE__", line: %d, " \
		"trunk metadata recovering, start offset: " \
		INT64_PRINTF_FORMAT", need recovery binlog bytes: " \
		INT64_PRINTF_FORMAT, __LINE__, \
		restore_offset, trunk_binlog_size - restore_offset);

	trunk_init_reload_from_binlog = (restore_offset == 0);
	if (trunk_init_reload_from_binlog)
	{
		memset(&trunkNode, 0, sizeof(trunkNode));
		if ((result=avl_tree_init(&tree_info_by_offset, \
			storage_trunk_free_node, \
			storage_trunk_node_compare_offset)) != 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"avl_tree_init fail, " \
				"errno: %d, error info: %s", \
				__LINE__, result, STRERROR(result));
			return result;
		}
	}

	memset(&record, 0, sizeof(record));
	memset(&reader, 0, sizeof(reader));
	reader.binlog_offset = restore_offset;
	if ((result=trunk_reader_init(NULL, &reader)) != 0)
	{
		return result;
	}

	line_count = 0;
	while (1)
	{
		record_length = 0;
		result = trunk_binlog_read(&reader, &record, &record_length);
		if (result != 0)
		{
			if (result == ENOENT)
			{
				if (record_length > 0)  //skip incorrect record
				{
					line_count++;
					reader.binlog_offset += record_length;
					continue;
				}

				result = (reader.binlog_offset >= \
					trunk_binlog_size) ? 0 : EINVAL;
				if (result != 0)
				{
				logError("file: "__FILE__", line: %d, " \
					"binlog offset: "INT64_PRINTF_FORMAT \
					" < binlog size: "INT64_PRINTF_FORMAT \
					", please check the end of trunk " \
					"binlog", __LINE__, \
					reader.binlog_offset, trunk_binlog_size);
				}
			}
		
			break;
		}

		line_count++;
		if (record.op_type == TRUNK_OP_TYPE_ADD_SPACE)
		{
			record.trunk.status = FDFS_TRUNK_STATUS_FREE;

			if (trunk_init_reload_from_binlog)
			{
				pMblockNode = fast_mblock_alloc(&free_blocks_man);
				if (pMblockNode == NULL)
				{
					result = errno != 0 ? errno : EIO;
					logError("file: "__FILE__", line: %d, "\
						"malloc %d bytes fail, " \
						"errno: %d, error info: %s", \
						__LINE__, \
						(int)sizeof(FDFSTrunkNode), \
						result, STRERROR(result));
					return result;
				}

				pTrunkNode = (FDFSTrunkNode *)pMblockNode->data;
				memcpy(&pTrunkNode->trunk, &(record.trunk), \
					sizeof(FDFSTrunkFullInfo));

				pTrunkNode->pMblockNode = pMblockNode;
				pTrunkNode->next = NULL;
				result = avl_tree_insert(&tree_info_by_offset,\
							pTrunkNode);
				if (result < 0) //error
				{
					result *= -1;
					logError("file: "__FILE__", line: %d, "\
						"avl_tree_insert fail, " \
						"errno: %d, error info: %s", \
						__LINE__, result, \
						STRERROR(result));
					return result;
				}
				else if (result == 0)
				{
					trunk_info_dump(&(record.trunk), \
							buff, sizeof(buff));
					logWarning("file: "__FILE__", line: %d"\
						", trunk data line: " \
						INT64_PRINTF_FORMAT", trunk "\
						"space already exist, "\
						"trunk info: %s", \
						__LINE__, line_count, buff);
				}
			}
			else if ((result=trunk_add_space_by_trunk( \
						&record.trunk)) != 0)
			{
				break;
			}
		}
		else if (record.op_type == TRUNK_OP_TYPE_DEL_SPACE)
		{
			record.trunk.status = FDFS_TRUNK_STATUS_FREE;
			if (trunk_init_reload_from_binlog)
			{
				memcpy(&trunkNode.trunk, &record.trunk, \
					sizeof(FDFSTrunkFullInfo));
				if (avl_tree_delete(&tree_info_by_offset,\
							&trunkNode) != 1)
				{
				trunk_info_dump(&(record.trunk), \
						buff, sizeof(buff));
				logWarning("file: "__FILE__", line: %d"\
					", binlog offset: "INT64_PRINTF_FORMAT \
					", trunk data line: "INT64_PRINTF_FORMAT \
					" trunk node not exist, " \
					"trunk info: %s", __LINE__, \
					reader.binlog_offset, \
					line_count, buff);
				}
			}
			else if ((result=trunk_delete_space( \
						&record.trunk, false)) != 0)
			{
				if (result == ENOENT)
				{
				logDebug("file: "__FILE__", line: %d, "\
					"binlog offset: "INT64_PRINTF_FORMAT \
					", trunk data line: "INT64_PRINTF_FORMAT,\
					__LINE__, reader.binlog_offset, \
					line_count);

					result = 0;
				}
				else
				{
					break;
				}
			}
		}

		reader.binlog_offset += record_length;
	}

	trunk_reader_destroy(&reader);
	trunk_mark_filename_by_reader(&reader, trunk_mark_filename);
	if (unlink(trunk_mark_filename) != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"unlink file %s fail, " \
			"errno: %d, error info: %s", __LINE__, \
			trunk_mark_filename, errno, STRERROR(errno));
	}

	if (result != 0)
	{
		if (trunk_init_reload_from_binlog)
		{
			avl_tree_destroy(&tree_info_by_offset);
		}

		logError("file: "__FILE__", line: %d, " \
			"trunk load fail, errno: %d, error info: %s", \
			__LINE__, result, STRERROR(result));
		return result;
	}

	if (trunk_init_reload_from_binlog)
	{
		logInfo("file: "__FILE__", line: %d, " \
			"free tree node count: %d", \
			__LINE__, avl_tree_count(&tree_info_by_offset));

		result = avl_tree_walk(&tree_info_by_offset, \
				storage_trunk_add_free_blocks_callback, NULL);

		tree_info_by_offset.free_data_func = NULL;
		avl_tree_destroy(&tree_info_by_offset);
	}

	if (result == 0)
	{
		logDebug("file: "__FILE__", line: %d, " \
			"trunk metadata recovery done. start offset: " \
			INT64_PRINTF_FORMAT", recovery file size: " \
			INT64_PRINTF_FORMAT, __LINE__, \
			restore_offset, trunk_binlog_size - restore_offset);
		return storage_trunk_save();
	}

	return result;
}
int getUserProcIds(const char *progName, const bool bAllOwners, \
		int pids[], const int arrSize)
{
	char path[128]="/proc";
	char fullpath[128];
	struct stat statbuf;
	struct dirent *dirp;
	DIR  *dp;
	int  myuid=getuid();
	int  fd;
	char filepath[128];
	char buf[256];
	char *ptr;
	int  nbytes;
	char procname[64];
	int  cnt=0;
	char *pTargetProg;
	
	if ((dp = opendir(path)) == NULL)
	{
		return -1;
	}
	
	pTargetProg = (char *)malloc(strlen(progName) + 1);
	if (pTargetProg == NULL)
	{
		logError("file: "__FILE__", line: %d, " \
			"malloc %d bytes fail", __LINE__, \
			(int)strlen(progName) + 1);
		return -1;
	}

	ptr = strrchr(progName, '/');
	if (ptr == NULL)
	{
		strcpy(pTargetProg, progName);
	}
	else
	{
		strcpy(pTargetProg, ptr + 1);
	}
	
	while( (dirp = readdir(dp)) != NULL )
	{
		if (strcmp(dirp->d_name, ".")==0 || strcmp(dirp->d_name, "..")==0 )
		{
			continue;
		}
		
		sprintf(fullpath, "%s/%s", path, dirp->d_name);
		memset(&statbuf, 0, sizeof(statbuf));
		if (lstat(fullpath, &statbuf)<0)
		{
			continue;
		}
		
		if ((bAllOwners || (statbuf.st_uid == myuid)) && S_ISDIR(statbuf.st_mode))
		{
			sprintf(filepath, "%s/cmdline", fullpath);
			if ((fd = open(filepath, O_RDONLY))<0)
			{
				continue;
			}
			
			memset(buf, 0, 256);
			if ((nbytes = read(fd, buf, 255)) < 0){
				close(fd);
				continue;
			}
			close(fd);
			
			if (*buf == '\0')
			{
				continue;
			}
			
			ptr = strrchr(buf, '/');
			if (ptr == NULL)
			{
				snprintf(procname, 64, "%s", buf);
			}
			else
			{
				snprintf(procname, 64, "%s", ptr + 1);
			}
			
			if (strcmp(procname, pTargetProg) == 0)
			{				
				if (pids != NULL)
				{
					if (cnt >= arrSize)
					{
						break;
					}
					pids[cnt] = atoi(dirp->d_name);
				}
				
				cnt++;
			}
		}
	}
	free(pTargetProg);
	
	closedir(dp);
	return cnt;
}
Exemple #24
0
static int storage_trunk_load()
{
#define TRUNK_DATA_FIELD_COUNT  6
#define TRUNK_LINE_MAX_LENGHT  64

	int64_t restore_offset;
	char trunk_data_filename[MAX_PATH_SIZE];
	char buff[4 * 1024 + 1];
	int line_count;
	char *pLineStart;
	char *pLineEnd;
	char *cols[TRUNK_DATA_FIELD_COUNT];
	FDFSTrunkFullInfo trunkInfo;
	int result;
	int fd;
	int bytes;
	int len;

	snprintf(trunk_data_filename, sizeof(trunk_data_filename), \
		"%s/data/%s", g_fdfs_base_path, STORAGE_TRUNK_DATA_FILENAME);
	if (g_trunk_init_reload_from_binlog)
	{
		if (unlink(trunk_data_filename) != 0)
		{
			result = errno != 0 ? errno : ENOENT;
			if (result != ENOENT)
			{
				logError("file: "__FILE__", line: %d, " \
					"unlink file %s fail, " \
					"errno: %d, error info: %s", __LINE__, \
					trunk_data_filename, result, \
					STRERROR(result));
				return result;
			}
		}

		restore_offset = 0;
		return storage_trunk_restore(restore_offset);
	}

	fd = open(trunk_data_filename, O_RDONLY);
	if (fd < 0)
	{
		result = errno != 0 ? errno : EIO;
		if (result == ENOENT)
		{
			restore_offset = 0;
			return storage_trunk_restore(restore_offset);
		}

		logError("file: "__FILE__", line: %d, " \
			"open file %s fail, " \
			"errno: %d, error info: %s", \
			__LINE__, trunk_data_filename, \
			result, STRERROR(result));
		return result;
	}

	if ((bytes=read(fd, buff, sizeof(buff) - 1)) < 0)
	{
		result = errno != 0 ? errno : EIO;
		logError("file: "__FILE__", line: %d, " \
			"read from file %s fail, " \
			"errno: %d, error info: %s", \
			__LINE__, trunk_data_filename, \
			result, STRERROR(result));
		close(fd);
		return result;
	}

	*(buff + bytes) = '\0';
	pLineEnd = strchr(buff, '\n');
	if (pLineEnd == NULL)
	{
		logError("file: "__FILE__", line: %d, " \
			"read offset from file %s fail", \
			__LINE__, trunk_data_filename);
		close(fd);
		return EINVAL;
	}

	*pLineEnd = '\0';
	restore_offset = strtoll(buff, NULL, 10);
	pLineStart = pLineEnd + 1;  //skip \n
	line_count = 0;
	while (1)
	{
		pLineEnd = strchr(pLineStart, '\n');
		if (pLineEnd == NULL)
		{
			if (bytes < sizeof(buff) - 1) //EOF
			{
				break;
			}

			len = strlen(pLineStart);
			if (len > TRUNK_LINE_MAX_LENGHT)
			{
				logError("file: "__FILE__", line: %d, " \
					"file %s, line length: %d too long", \
					__LINE__, trunk_data_filename, len);
				close(fd);
				return EINVAL;
			}

			memcpy(buff, pLineStart, len);
			if ((bytes=read(fd, buff + len, sizeof(buff) \
					- len - 1)) < 0)
			{
				result = errno != 0 ? errno : EIO;
				logError("file: "__FILE__", line: %d, " \
					"read from file %s fail, " \
					"errno: %d, error info: %s", \
					__LINE__, trunk_data_filename, \
					result, STRERROR(result));
				close(fd);
				return result;
			}

			if (bytes == 0)
			{
				result = ENOENT;
				logError("file: "__FILE__", line: %d, " \
					"file: %s, end of file, expect " \
					"end line", __LINE__, \
					trunk_data_filename);
				close(fd);
				return result;
			}

			bytes += len;
			*(buff + bytes) = '\0';
			pLineStart = buff;
			continue;
		}

		++line_count;
		*pLineEnd = '\0';
		if (splitEx(pLineStart, ' ', cols, TRUNK_DATA_FIELD_COUNT) \
			!= TRUNK_DATA_FIELD_COUNT)
		{
			logError("file: "__FILE__", line: %d, " \
				"file %s, line: %d is invalid", \
				__LINE__, trunk_data_filename, line_count);
			close(fd);
			return EINVAL;
		}

		trunkInfo.path.store_path_index = atoi(cols[0]);
		trunkInfo.path.sub_path_high = atoi(cols[1]);
		trunkInfo.path.sub_path_low = atoi(cols[2]);
		trunkInfo.file.id = atoi(cols[3]);
		trunkInfo.file.offset = atoi(cols[4]);
		trunkInfo.file.size = atoi(cols[5]);
		if ((result=storage_trunk_do_add_space(&trunkInfo)) != 0)
		{
			close(fd);
			return result;
		}

		pLineStart = pLineEnd + 1;  //next line
	}

	close(fd);

	if (*pLineStart != '\0')
	{
		logError("file: "__FILE__", line: %d, " \
			"file %s does not end correctly", \
			__LINE__, trunk_data_filename);
		return EINVAL;
	}

	logDebug("file: "__FILE__", line: %d, " \
		"file %s, line count: %d", \
		__LINE__, trunk_data_filename, line_count);

	return storage_trunk_restore(restore_offset);
}
Exemple #25
0
void 
unloadSharedObject (void *object) {
  clearError();
  if (dlclose(object)) logError();
}
Exemple #26
0
GLenum convertToGL(const PixelFormat& format, bool sRGB)
{
  switch (format.type())
  {
    case PixelFormat::UINT8:
    {
      switch (format.semantic())
      {
        case PixelFormat::L:
        {
          if (sRGB)
            return GL_SLUMINANCE8;
          else
            return GL_LUMINANCE8;
        }

        case PixelFormat::LA:
        {
          if (sRGB)
            return GL_SLUMINANCE8_ALPHA8;
          else
            return GL_LUMINANCE8_ALPHA8;
        }

        case PixelFormat::RGB:
        {
          if (sRGB)
            return GL_SRGB8;
          else
            return GL_RGB8;
        }

        case PixelFormat::RGBA:
        {
          if (sRGB)
            return GL_SRGB8_ALPHA8;
          else
            return GL_RGBA8;
        }

        default:
          break;
      }

      break;
    }

    case PixelFormat::UINT16:
    {
      if (format.semantic() == PixelFormat::DEPTH)
        return GL_DEPTH_COMPONENT16;

      break;
    }

    case PixelFormat::UINT24:
    {
      if (format.semantic() == PixelFormat::DEPTH)
        return GL_DEPTH_COMPONENT24;

      break;
    }

    case PixelFormat::UINT32:
    {
      if (format.semantic() == PixelFormat::DEPTH)
        return GL_DEPTH_COMPONENT32;

      break;
    }

    case PixelFormat::FLOAT16:
    {
      switch (format.semantic())
      {
        case PixelFormat::L:
        {
          if (!GLEW_ARB_texture_float)
          {
            logError("Half-precision floating point textures not supported; "
                     "cannot convert pixel format");
            return 0;
          }

          return GL_LUMINANCE16F_ARB;
        }

        case PixelFormat::LA:
        {
          if (!GLEW_ARB_texture_float)
          {
            logError("Half-precision floating point textures not supported; "
                     "cannot convert pixel format");
            return 0;
          }

          return GL_LUMINANCE_ALPHA16F_ARB;
        }

        case PixelFormat::RGB:
          return GL_RGB16F;
        case PixelFormat::RGBA:
          return GL_RGBA16F;
        default:
          break;
      }

      break;
    }

    case PixelFormat::FLOAT32:
    {
      switch (format.semantic())
      {
        case PixelFormat::L:
        {
          if (!GLEW_ARB_texture_float)
          {
            logError("Floating point textures not supported; cannot convert pixel format");
            return 0;
          }

          return GL_LUMINANCE32F_ARB;
        }

        case PixelFormat::LA:
        {
          if (!GLEW_ARB_texture_float)
          {
            logError("Floating point textures not supported; cannot convert pixel format");
            return 0;
          }

          return GL_LUMINANCE_ALPHA32F_ARB;
        }

        case PixelFormat::RGB:
          return GL_RGB32F;
        case PixelFormat::RGBA:
          return GL_RGBA32F;
        default:
          break;
      }

      break;
    }

    default:
      break;
  }

  logError("No OpenGL equivalent for pixel format %s",
           format.asString().c_str());
  return 0;
}
Exemple #27
0
int parseRawFormatFast(char * msg, RawMessage * m, bool showJson)
{
  unsigned int prio, pgn, dst, src, len, r, i;
  char * p;

  p = findFirstOccurrence(msg, ',');
  if(!p)
  {
    return 1;
  }

  memcpy(m->timestamp, msg, p - msg);
  m->timestamp[p - msg] = 0;

  /* Moronic Windows does not support %hh<type> so we use intermediate variables */
  r = sscanf( p
    , ",%u,%u,%u,%u,%u "
    , &prio
    , &pgn
    , &src
    , &dst
    , &len
  );
  if (r < 5)
  {
    logError("Error reading message, scanned %u from %s", r, msg);
    if (!showJson) fprintf(stdout, "%s", msg);
    return 2;
  }
  for (i = 0; *p && i < 5;)
  {
    if (*++p == ',')
    {
      i++;
    }
  }
  if (!p)
  {
    logError("Error reading message, scanned %zu bytes from %s", p - msg, msg);
    if (!showJson) fprintf(stdout, "%s", msg);
    return 2;
  }
  p++;
  for (i = 0; i < len; i++)
  {
    if (scanHex(&p, &m->data[i]))
    {
      logError("Error reading message, scanned %zu bytes from %s/%s, index %u", p - msg, msg, p, i);
      if (!showJson) fprintf(stdout, "%s", msg);
      return 2;
    }
    if (i < len)
    {
      if (*p != ',' && !isspace(*p))
      {
        logError("Error reading message, scanned %zu bytes from %s", p - msg, msg);
        if (!showJson) fprintf(stdout, "%s", msg);
        return 2;
      }
      p++;
    }
  }

  return setParsedValues(m, prio, pgn, dst, src, len);
}
Exemple #28
0
void EthernetServer::begin(IPAddress address)
{
	struct addrinfo hints, *servinfo, *p;
	int yes=1;
	int rv;
	char ipstr[INET_ADDRSTRLEN];
	char portstr[6];

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE;

	sprintf(portstr, "%d", port);
	if ((rv = getaddrinfo(address.toString().c_str(), portstr, &hints, &servinfo)) != 0) {
		logError("getaddrinfo: %s\n", gai_strerror(rv));
		return;
	}

	// loop through all the results and bind to the first we can
	for (p = servinfo; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
			logError("socket: %s\n", strerror(errno));
			continue;
		}

		if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
			logError("setsockopt: %s\n", strerror(errno));
			freeaddrinfo(servinfo);
			return;
		}

		if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			logError("bind: %s\n", strerror(errno));
			continue;
		}

		break;
	}

	if (p == NULL)  {
		logError("Failed to bind!\n");
		freeaddrinfo(servinfo);
		return;
	}

	if (listen(sockfd, ETHERNETSERVER_BACKLOG) == -1) {
		logError("listen: %s\n", strerror(errno));
		freeaddrinfo(servinfo);
		return;
	}

	freeaddrinfo(servinfo);

	fcntl(sockfd, F_SETFL, O_NONBLOCK);

	struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
	void *addr = &(ipv4->sin_addr);
	inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
	logDebug("Listening for connections on %s:%s\n", ipstr, portstr);
}
Exemple #29
0
boost::shared_ptr<ModelInterface>  parseURDF(const std::string &xml_string)
{
  boost::shared_ptr<ModelInterface> model(new ModelInterface);
  model->clear();

  TiXmlDocument xml_doc;
  xml_doc.Parse(xml_string.c_str());

  TiXmlElement *robot_xml = xml_doc.FirstChildElement("robot");
  if (!robot_xml)
  {
    logError("Could not find the 'robot' element in the xml file");
    model.reset();
    return model;
  }

  // Get robot name
  const char *name = robot_xml->Attribute("name");
  if (!name)
  {
    logError("No name given for the robot.");
    model.reset();
    return model;
  }
  model->name_ = std::string(name);

  // Get all Material elements
  for (TiXmlElement* material_xml = robot_xml->FirstChildElement("material"); material_xml; material_xml = material_xml->NextSiblingElement("material"))
  {
    boost::shared_ptr<Material> material;
    material.reset(new Material);

    try {
      parseMaterial(*material, material_xml, false); // material needs to be fully defined here
      if (model->getMaterial(material->name))
      {
        logError("material '%s' is not unique.", material->name.c_str());
        material.reset();
        model.reset();
        return model;
      }
      else
      {
        model->materials_.insert(make_pair(material->name,material));
        logDebug("successfully added a new material '%s'", material->name.c_str());
      }
    }
    catch (ParseError &e) {
      logError("material xml is not initialized correctly");
      material.reset();
      model.reset();
      return model;
    }
  }

  // Get all Link elements
  for (TiXmlElement* link_xml = robot_xml->FirstChildElement("link"); link_xml; link_xml = link_xml->NextSiblingElement("link"))
  {
    boost::shared_ptr<Link> link;
    link.reset(new Link);

    try {
      parseLink(*link, link_xml);
      if (model->getLink(link->name))
      {
        logError("link '%s' is not unique.", link->name.c_str());
        model.reset();
        return model;
      }
      else
      {
        // set link visual material
        logDebug("setting link '%s' material", link->name.c_str());
        if (link->visual)
        {
          if (!link->visual->material_name.empty())
          {
            if (model->getMaterial(link->visual->material_name))
            {
              logDebug("setting link '%s' material to '%s'", link->name.c_str(),link->visual->material_name.c_str());
              link->visual->material = model->getMaterial( link->visual->material_name.c_str() );
            }
            else
            {
              if (link->visual->material)
              {
                logDebug("link '%s' material '%s' defined in Visual.", link->name.c_str(),link->visual->material_name.c_str());
                model->materials_.insert(make_pair(link->visual->material->name,link->visual->material));
              }
              else
              {
                logError("link '%s' material '%s' undefined.", link->name.c_str(),link->visual->material_name.c_str());
                model.reset();
                return model;
              }
            }
          }
        }

        model->links_.insert(make_pair(link->name,link));
        logDebug("successfully added a new link '%s'", link->name.c_str());
      }
    }
    catch (ParseError &e) {
      logError("link xml is not initialized correctly");
      model.reset();
      return model;
    }
  }
  if (model->links_.empty()){
    logError("No link elements found in urdf file");
    model.reset();
    return model;
  }

  // Get all Joint elements
  for (TiXmlElement* joint_xml = robot_xml->FirstChildElement("joint"); joint_xml; joint_xml = joint_xml->NextSiblingElement("joint"))
  {
    boost::shared_ptr<Joint> joint;
    joint.reset(new Joint);

    if (parseJoint(*joint, joint_xml))
    {
      if (model->getJoint(joint->name))
      {
        logError("joint '%s' is not unique.", joint->name.c_str());
        model.reset();
        return model;
      }
      else
      {
        model->joints_.insert(make_pair(joint->name,joint));
        logDebug("successfully added a new joint '%s'", joint->name.c_str());
      }
    }
    else
    {
      logError("joint xml is not initialized correctly");
      model.reset();
      return model;
    }
  }


  // every link has children links and joints, but no parents, so we create a
  // local convenience data structure for keeping child->parent relations
  std::map<std::string, std::string> parent_link_tree;
  parent_link_tree.clear();

  // building tree: name mapping
  try 
  {
    model->initTree(parent_link_tree);
  }
  catch(ParseError &e)
  {
    logError("Failed to build tree: %s", e.what());
    model.reset();
    return model;
  }

  // find the root link
  try
  {
    model->initRoot(parent_link_tree);
  }
  catch(ParseError &e)
  {
    logError("Failed to find root link: %s", e.what());
    model.reset();
    return model;
  }
  
  return model;
}
Exemple #30
0
    int fastPy::masterLoop() {
        std::map<int,child_t>::iterator c_it;

        // registering signal handler
        signal(SIGHUP, sig_handler);
        signal(SIGINT, sig_handler);
        signal(SIGTERM, sig_handler);
        signal(SIGUSR1, sig_handler);
        signal(SIGUSR2, sig_handler);

        bool working = true, terminating = true;

        logError("master", LOG_DEBUG, "schedulling workers");
        // main schedule loop
        while (working) {
            // iterating throw the map
            for (c_it = childrens.begin(); c_it != childrens.end(); c_it++) {
                pid_t c_pid = (*c_it).first;
                child_t *c = &(*c_it).second;
                int c_ec, w_ec;

                // we against zombie on linux ;-)
                w_ec = waitpid(c_pid, &c_ec, WNOHANG);

                if (w_ec == c_pid) {
                    if (WIFEXITED(c_ec) != 0) {
                        c->dead = true;
                        logError("master", LOG_WARN, "child %d exited normaly with code: %d", c_pid, WEXITSTATUS(c_ec));
                    } else if (WIFSIGNALED(c_ec) != 0) {
                        c->dead = true;
                        logError("master", LOG_WARN, "child %d died as an hero with signal: %d", c_pid, WTERMSIG(c_ec));
                    }
                } else if (w_ec < 0) {
                    logError("master", LOG_WARN, "waitpid error for child %d failed, error code: %d", c_pid, errno);
                }
                
                if (c->dead) {
                    c->cipc.freeSHM(true);
                    childrens.erase(c_it);
                    logError("master", LOG_WARN, "starting new child");
                    startChild();
                    break;
                }
                
                if (c->cipc.shm->timestamp != 0 && (c->cipc.shm->timestamp + 10) < time(NULL)) {
                    logError("master", LOG_WARN, "child ts is timed out, terminating child");
                    c->cipc.shm->m_code = M_TERM;
                    c->cipc.freeSHM(true);
                    childrens.erase(c_it);
                    startChild();
                    break;
                }
                                
                switch (c->cipc.shm->w_code) {
                    case W_TERM:
                        c->dead = true;
                        break;
                    case W_FAIL:
                        working = false;
                        break;
                    default:
                        break;
                }
            }
            
            // checking our own state
            if (msig != 0) {
                switch (msig) {
                    case SIGHUP:
                        logError("master", LOG_WARN, "restarting workers pool");
                        for (c_it = childrens.begin(); c_it != childrens.end(); c_it++) {
                            child_t *c = &(*c_it).second;
                            c->cipc.shm->m_code = M_TERM;
                        }
                        
                        msig = 0;
                        
                        break;
                    case SIGTERM:
                    case SIGINT:
                        working = false;
                        break;
                    default:
                        break;
                }
            }

            usleep(200000);
        }
        
        logError("master", LOG_WARN, "going to shutdown");

        for (c_it = childrens.begin(); c_it != childrens.end(); c_it++) {
            child_t *c = &(*c_it).second;
            
            c->cipc.shm->m_code = M_TERM;
        }
        
        // main terminate loop
        while (terminating) {            
            for (c_it = childrens.begin(); c_it != childrens.end(); c_it++) {
                child_t *c = &(*c_it).second;
                                
                if (c->dead) {
                    c->cipc.freeSHM(true);
                    childrens.erase(c_it);
                    break;
                }
                
                if (c->cipc.shm->timestamp != 0 && (c->cipc.shm->timestamp + 10) < time(NULL)) {
                    logError("master", LOG_DEBUG, "looks like child is already dead");
                    c->cipc.freeSHM(true);
                    childrens.erase(c_it);
                    break;
                }

                if (c->cipc.shm->w_code == W_TERM || c->cipc.shm->w_code == W_FAIL) {
                    c->dead = true;
                }
            }
            
            if (childrens.size() == 0) {
                break;
            }

            usleep(10000);
        }
        
        logError("master", LOG_WARN, "childs are dead, terminating master");
        
        return 0;
    }