Пример #1
0
int trunk_binlog_truncate()
{
	int result;

	if (trunk_binlog_write_cache_len > 0)
	{
		if ((result=trunk_binlog_fsync(true)) != 0)
		{
			return result;
		}
	}

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

	return 0;
}
Пример #2
0
int
main (int argc,
      char **argv)
{
  const char *basename;
  const char *dirname;

  basename = getenv ("GNUNET_PREFIX");
  if (NULL == basename)
  {
    fprintf (stderr,
	     _("Environment variable GNUNET_PREFIX not set\n"));
    fprintf (stderr,
	     _("Testcases will not work!\n"));
    return 1;
  }
  dirname = DIR_SEPARATOR_STR ".." DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR "gnunet" DIR_SEPARATOR_STR "config.d";
  {
    char tmp[strlen (basename) + strlen (dirname) + 1];
    sprintf (tmp, "%s%s", basename, dirname);
    if (0 != access (tmp, R_OK))
    {
      fprintf (stderr,
	       _("Failed to access `%s': %s\n"),
	       tmp,
	       STRERROR (errno));
      fprintf (stderr,
	       _("Check that you did run `make install' and that GNUNET_PREFIX='%s' is the correct prefix.\n"),
	       basename);
      fprintf (stderr,
	       _("Testcases will not work!\n"));
      return 2;
    }
  }
  return 0;
}
Пример #3
0
int trunk_rename_mark_file(const char *old_ip_addr, const int old_port, \
		const char *new_ip_addr, const int new_port)
{
	char old_filename[MAX_PATH_SIZE];
	char new_filename[MAX_PATH_SIZE];

	trunk_get_mark_filename_by_id_and_port(old_ip_addr, old_port, \
			old_filename, sizeof(old_filename));
	if (!fileExists(old_filename))
	{
		return ENOENT;
	}

	trunk_get_mark_filename_by_id_and_port(new_ip_addr, new_port, \
			new_filename, sizeof(new_filename));
	if (fileExists(new_filename))
	{
		logWarning("file: "__FILE__", line: %d, " \
			"mark file %s already exists, " \
			"ignore rename file %s to %s", \
			__LINE__, new_filename, old_filename, new_filename);
		return EEXIST;
	}

	if (rename(old_filename, new_filename) != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"rename file %s to %s fail" \
			", errno: %d, error info: %s", \
			__LINE__, old_filename, new_filename, \
			errno, STRERROR(errno));
		return errno != 0 ? errno : EACCES;
	}

	return 0;
}
Пример #4
0
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;
}
Пример #5
0
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;
}
int free_queue_init_ex(const int max_connections, const int init_connections,
        const int alloc_task_once, const int min_buff_size,
        const int max_buff_size, const int arg_size)
{
#define MAX_DATA_SIZE  (256 * 1024 * 1024)
	int64_t total_size;
	struct mpool_node *mpool;
	int alloc_size;
    int alloc_once;
	int result;
	int loop_count;
	int aligned_min_size;
	int aligned_max_size;
	int aligned_arg_size;
	rlim_t max_data_size;

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

	aligned_min_size = MEM_ALIGN(min_buff_size);
	aligned_max_size = MEM_ALIGN(max_buff_size);
	aligned_arg_size = MEM_ALIGN(arg_size);
	g_free_queue.block_size = ALIGNED_TASK_INFO_SIZE + aligned_arg_size;
	alloc_size = g_free_queue.block_size * init_connections;
	if (aligned_max_size > aligned_min_size)
	{
		total_size = alloc_size;
		g_free_queue.malloc_whole_block = false;
		max_data_size = 0;
	}
	else
	{
		struct rlimit rlimit_data;

		if (getrlimit(RLIMIT_DATA, &rlimit_data) < 0)
		{
			logError("file: "__FILE__", line: %d, " \
				"call getrlimit fail, " \
				"errno: %d, error info: %s", \
				__LINE__, errno, STRERROR(errno));
			return errno != 0 ? errno : EPERM;
		}
		if (rlimit_data.rlim_cur == RLIM_INFINITY)
		{
			max_data_size = MAX_DATA_SIZE;
		}
		else
		{
			max_data_size = rlimit_data.rlim_cur;
			if (max_data_size > MAX_DATA_SIZE)
			{
				max_data_size = MAX_DATA_SIZE;
			}
		}

		if (max_data_size >= (int64_t)(g_free_queue.block_size + aligned_min_size) *
			(int64_t)init_connections)
		{
			total_size = alloc_size + (int64_t)aligned_min_size *
					init_connections;
			g_free_queue.malloc_whole_block = true;
			g_free_queue.block_size += aligned_min_size;
		}
		else
		{
			total_size = alloc_size;
			g_free_queue.malloc_whole_block = false;
			max_data_size = 0;
		}
	}

	g_free_queue.max_connections = max_connections;
	g_free_queue.alloc_connections = init_connections;
    if (alloc_task_once <= 0)
    {
        g_free_queue.alloc_task_once = 256;
		alloc_once = MAX_DATA_SIZE / g_free_queue.block_size;
        if (g_free_queue.alloc_task_once > alloc_once)
        {
            g_free_queue.alloc_task_once = alloc_once;
        }
    }
    else
    {
        g_free_queue.alloc_task_once = alloc_task_once;
    }
	g_free_queue.min_buff_size = aligned_min_size;
	g_free_queue.max_buff_size = aligned_max_size;
	g_free_queue.arg_size = aligned_arg_size;

	logDebug("file: "__FILE__", line: %d, "
		"max_connections: %d, init_connections: %d, alloc_task_once: %d, "
        "min_buff_size: %d, max_buff_size: %d, block_size: %d, "
        "arg_size: %d, max_data_size: %d, total_size: %"PRId64,
        __LINE__, max_connections, init_connections,
        g_free_queue.alloc_task_once, aligned_min_size, aligned_max_size,
        g_free_queue.block_size, aligned_arg_size, (int)max_data_size, total_size);

	if ((!g_free_queue.malloc_whole_block) || (total_size <= max_data_size))
	{
		loop_count = 1;
		mpool = malloc_mpool(total_size);
		if (mpool == NULL)
		{
			return errno != 0 ? errno : ENOMEM;
		}
		g_mpool.head = mpool;
		g_mpool.tail = mpool;
	}
	else
	{
		int remain_count;
		int alloc_count;
		int current_alloc_size;

		loop_count = 0;
		remain_count = init_connections;
		alloc_once = max_data_size / g_free_queue.block_size;
		while (remain_count > 0)
		{
			alloc_count = (remain_count > alloc_once) ?
					alloc_once : remain_count;
			current_alloc_size = g_free_queue.block_size * alloc_count;
			mpool = malloc_mpool(current_alloc_size);
			if (mpool == NULL)
			{
				free_queue_destroy();
				return errno != 0 ? errno : ENOMEM;
			}

			if (g_mpool.tail == NULL)
			{
				g_mpool.head = mpool;
			}
			else
			{
				g_mpool.tail->next = mpool;
				g_mpool.tail->last_block->next = mpool->blocks;  //link previous mpool to current
			}
            g_mpool.tail = mpool;

			remain_count -= alloc_count;
			loop_count++;
		}

		logDebug("file: "__FILE__", line: %d, " \
			"alloc_once: %d", __LINE__, alloc_once);
	}

	logDebug("file: "__FILE__", line: %d, " \
		"malloc task info as whole: %d, malloc loop count: %d", \
		__LINE__, g_free_queue.malloc_whole_block, loop_count);

	if (g_mpool.head != NULL)
	{
		g_free_queue.head = g_mpool.head->blocks;
		g_free_queue.tail = g_mpool.tail->last_block;
	}

	return 0;
}
Пример #7
0
static void doLogEx(LogContext *pContext, struct timeval *tv, \
		const char *caption, const char *text, const int text_len, \
		const bool bNeedSync, const bool bNeedLock)
{
	struct tm tm;
	int time_fragment;
	int buff_len;
	int result;

	if ((pContext->time_precision == LOG_TIME_PRECISION_SECOND)
            || (pContext->time_precision == LOG_TIME_PRECISION_NONE))
	{
		time_fragment = 0;
	}
	else
	{
		if (pContext->time_precision == LOG_TIME_PRECISION_MSECOND)
		{
			time_fragment = tv->tv_usec / 1000;
		}
		else
		{
			time_fragment = tv->tv_usec;
		}
	}

	if (bNeedLock && (result=pthread_mutex_lock(&pContext->log_thread_lock)) != 0)
	{
		fprintf(stderr, "file: "__FILE__", line: %d, " \
			"call pthread_mutex_lock fail, " \
			"errno: %d, error info: %s", \
			__LINE__, result, STRERROR(result));
	}

	if (text_len + 64 > LOG_BUFF_SIZE)
	{
		fprintf(stderr, "file: "__FILE__", line: %d, " \
			"log buff size: %d < log text length: %d ", \
			__LINE__, LOG_BUFF_SIZE, text_len + 64);
        if (bNeedLock)
        {
		    pthread_mutex_unlock(&(pContext->log_thread_lock));
        }
		return;
	}

	if ((pContext->pcurrent_buff - pContext->log_buff) + text_len + 64 \
			> LOG_BUFF_SIZE)
	{
		log_fsync(pContext, false);
	}

    if (pContext->time_precision != LOG_TIME_PRECISION_NONE)
    {
        localtime_r(&tv->tv_sec, &tm);
        if (pContext->time_precision == LOG_TIME_PRECISION_SECOND)
        {
            buff_len = sprintf(pContext->pcurrent_buff, \
                    "[%04d-%02d-%02d %02d:%02d:%02d] ", \
                    tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, \
                    tm.tm_hour, tm.tm_min, tm.tm_sec);
        }
        else
        {
            buff_len = sprintf(pContext->pcurrent_buff, \
                    "[%04d-%02d-%02d %02d:%02d:%02d.%03d] ", \
                    tm.tm_year+1900, tm.tm_mon+1, tm.tm_mday, \
                    tm.tm_hour, tm.tm_min, tm.tm_sec, time_fragment);
        }
        pContext->pcurrent_buff += buff_len;
    }

	if (caption != NULL)
	{
		buff_len = sprintf(pContext->pcurrent_buff, "%s - ", caption);
		pContext->pcurrent_buff += buff_len;
	}
	memcpy(pContext->pcurrent_buff, text, text_len);
	pContext->pcurrent_buff += text_len;
	*pContext->pcurrent_buff++ = '\n';

	if (!pContext->log_to_cache || bNeedSync)
	{
		log_fsync(pContext, false);
	}

	if (bNeedLock && (result=pthread_mutex_unlock(&(pContext->log_thread_lock))) != 0)
	{
		fprintf(stderr, "file: "__FILE__", line: %d, " \
			"call pthread_mutex_unlock fail, " \
			"errno: %d, error info: %s", \
			__LINE__, result, STRERROR(result));
	}
}
Пример #8
0
int log_rotate(LogContext *pContext)
{
	struct tm tm;
	time_t current_time;
    int len;
    int result;
	char old_filename[MAX_PATH_SIZE + 32];
    bool exist;

	if (*(pContext->log_filename) == '\0')
	{
		return ENOENT;
	}

	close(pContext->log_fd);

	current_time = get_current_time();
	localtime_r(&current_time, &tm);
    if (tm.tm_hour == 0 && tm.tm_min <= 1)
    {
        if (strstr(pContext->rotate_time_format, "%H") == NULL
                && strstr(pContext->rotate_time_format, "%M") == NULL
                && strstr(pContext->rotate_time_format, "%S") == NULL)
        {
            current_time -= 120;
            localtime_r(&current_time, &tm);
        }
    }

    memset(old_filename, 0, sizeof(old_filename));
	len = sprintf(old_filename, "%s.", pContext->log_filename);
    strftime(old_filename + len, sizeof(old_filename) - len,
            pContext->rotate_time_format, &tm);
    if (access(old_filename, F_OK) == 0)
    {
		fprintf(stderr, "file: "__FILE__", line: %d, " \
			"file: %s already exist, rotate file fail\n",
			__LINE__, old_filename);
        exist = true;
    }
    else if (rename(pContext->log_filename, old_filename) != 0)
	{
		fprintf(stderr, "file: "__FILE__", line: %d, " \
			"rename %s to %s fail, errno: %d, error info: %s\n", \
			__LINE__, pContext->log_filename, old_filename, \
			errno, STRERROR(errno));
        exist = false;
	}
    else
    {
        exist = true;
    }

	result = log_open(pContext);

    if (exist && NEED_COMPRESS_LOG(pContext->compress_log_flags))
    {
        log_gzip(pContext);
    }

    return result;
}
Пример #9
0
uint4 gtmcrypt_entry()
{
	void_ptr_t		handle, fptr;
	char_ptr_t		err_str, env_ptr, libname_ptr, libpath_ptr;
	char			*gtmcryptlib_fname[] = {
					GTMCRYPT_INIT_FNAME,
					GTMCRYPT_CLOSE_FNAME,
					GTMCRYPT_HASH_GEN_FNAME,
					GTMCRYPT_ENCRYPT_FNAME,
					GTMCRYPT_DECRYPT_FNAME,
					GTMCRYPT_GETKEY_BY_NAME,
					GTMCRYPT_GETKEY_BY_HASH,
					GTMCRYPT_STRERROR
				};
	void			**gtmcryptlib_fptr[] = {
					(void **)&gtmcrypt_init_fnptr,
					(void **)&gtmcrypt_close_fnptr,
					(void **)&gtmcrypt_hash_gen_fnptr,
					(void **)&gtmcrypt_encrypt_fnptr,
					(void **)&gtmcrypt_decrypt_fnptr,
					(void **)&gtmcrypt_getkey_by_name_fnptr,
					(void **)&gtmcrypt_getkey_by_hash_fnptr,
					(void **)&gtmcrypt_strerror_fnptr
				};
	int			findx, num_dlsyms, plugin_dir_len, save_errno;
	char			libpath[GTM_PATH_MAX], buf[MAX_GTMCRYPT_PLUGIN_STR_LEN], plugin_dir_path[GTM_PATH_MAX];
	char			resolved_libpath[GTM_PATH_MAX], resolved_gtmdist[GTM_PATH_MAX];
	mstr			trans, env_var = {0, SIZEOF(GTM_CRYPT_PLUGIN) - 1, GTM_CRYPT_PLUGIN};

	if (NULL == (env_ptr = getenv(GTM_DIST)))
		rts_error(VARLSTCNT(1) ERR_GTMDISTUNDEF);
	if (NULL == realpath(env_ptr, &resolved_gtmdist[0]))
	{
		save_errno = errno;
		SNPRINTF(dl_err, MAX_ERRSTR_LEN, "Failed to find symbolic link for %s. %s", env_ptr, STRERROR(save_errno));
		return ERR_CRYPTDLNOOPEN;
	}
	SNPRINTF(plugin_dir_path, GTM_PATH_MAX, "%s/%s", resolved_gtmdist, PLUGIN_DIR_NAME);
	plugin_dir_len = STRLEN(plugin_dir_path);
	if ((SS_NORMAL != TRANS_LOG_NAME(&env_var, &trans, buf, SIZEOF(buf), do_sendmsg_on_log2long)) || (0 >= trans.len))
	{	/* Either $gtm_crypt_plugin is not defined in the environment variable OR it is set to null-string. Fall-back to
		 * using libgtmcrypt.so
		 */
		libname_ptr = GTMCRYPT_LIBNAME;
	} else
		libname_ptr = &buf[0];		/* value of $gtm_crypt_plugin */
	SNPRINTF(libpath, GTM_PATH_MAX, "%s/%s", plugin_dir_path, libname_ptr);
	if (NULL == realpath(&libpath[0], &resolved_libpath[0]))
	{
		save_errno = errno;
		SNPRINTF(dl_err, MAX_ERRSTR_LEN, "Failed to find symbolic link for %s. %s", libpath, STRERROR(save_errno));
		return ERR_CRYPTDLNOOPEN;
	}
	/* Symbolic link found. dlopen resolved_libpath */
	if (0 != memcmp(&resolved_libpath[0], plugin_dir_path, plugin_dir_len))
	{	/* resolved_path doesn't contain $gtm_dist/plugin as the prefix */
		SNPRINTF(dl_err, MAX_ERRSTR_LEN, "Symbolic link for %s must be relative to %s", libpath, plugin_dir_path);
		return ERR_CRYPTDLNOOPEN;
	}
	handle = dlopen(&resolved_libpath[0], GTMCRYPT_LIBFLAGS);
	if (NULL == handle)
	{
		COPY_DLLERR_MSG(err_str, dl_err);
		return ERR_CRYPTDLNOOPEN;
	}
	num_dlsyms = ARRAYSIZE(gtmcryptlib_fptr); /* number of functions to be dlsym'ed */
	for(findx = 0; findx < num_dlsyms; ++findx)
	{
		fptr = (void *)dlsym(handle, gtmcryptlib_fname[findx]);
		if (NULL == fptr)
		{
			COPY_DLLERR_MSG(err_str, dl_err);
			return ERR_CRYPTDLNOOPEN;
		}
		*gtmcryptlib_fptr[findx] = fptr;
	}
	return 0;
}
Пример #10
0
void mupip_restore(void)
{
	static readonly char	label[] =   GDS_LABEL;
	char			db_name[MAX_FN_LEN + 1], *inbuf, *p;
	inc_list_struct 	*ptr;
	inc_header		*inhead;
	sgmnt_data		*old_data;
	short			iosb[4];
	unsigned short		n_len;
	int4			status, vbn, rsize, temp, save_errno;
	uint4			rest_blks, totblks;
	trans_num		curr_tn;
	uint4			ii;
	block_id		blk_num;
	bool			extend;
	uint4			cli_status;
	BFILE			*in;
	int			i, db_fd;
 	uint4			old_blk_size, old_tot_blks, bplmap;
	short			old_start_vbn;
	off_t			new_eof;
	char			buff[DISK_BLOCK_SIZE];
 	char			msg_buffer[1024], *newmap, *newmap_bptr;
	mstr			msg_string;
	char			addr[SA_MAXLEN+1];
	unsigned char		tcp[5];
	backup_type		type;
	unsigned short		port;
	int4			timeout, cut, match;
	char			debug_info[256];
	void			(*common_read)();
	char			*errptr;
	pid_t			waitpid_res;

	error_def(ERR_MUPRESTERR);
	error_def(ERR_MUPCLIERR);
	error_def(ERR_IOEOF);

	extend = TRUE;
	if (CLI_NEGATED == (cli_status = cli_present("EXTEND")))
		extend = FALSE;
	mu_outofband_setup();
	mu_gv_cur_reg_init();
	n_len = sizeof(db_name);
	if (cli_get_str("DATABASE", db_name, &n_len) == FALSE)
		mupip_exit(ERR_MUPCLIERR);
	strcpy((char *)gv_cur_region->dyn.addr->fname, db_name);
	gv_cur_region->dyn.addr->fname_len = n_len;
	if (!mu_rndwn_file(gv_cur_region, TRUE))
	{
		util_out_print("Error securing stand alone access to output file !AD. Aborting restore.", TRUE, n_len, db_name);
		mupip_exit(ERR_MUPRESTERR);
	}
	OPENFILE(db_name, O_RDWR, db_fd);
	if (-1 == db_fd)
	{
		save_errno = errno;
		util_out_print("Error accessing output file !AD. Aborting restore.", TRUE, n_len, db_name);
		errptr = (char *)STRERROR(save_errno);
		util_out_print("open : !AZ", TRUE, errptr);
		mupip_exit(save_errno);
	}
	murgetlst();
	inbuf = (char*)malloc(INC_BACKUP_CHUNK_SIZE);
	old_data = (sgmnt_data*)malloc(sizeof(sgmnt_data));
	LSEEKREAD(db_fd, 0, old_data, sizeof(sgmnt_data), save_errno);
	if (0 != save_errno)
	{
		util_out_print("Error accessing output file !AD. Aborting restore.", TRUE, n_len, db_name);
		if (-1 != save_errno)
		{
			errptr = (char *)STRERROR(save_errno);
			util_out_print("read : !AZ", TRUE, errptr);
			db_ipcs_reset(gv_cur_region, TRUE);
			mu_gv_cur_reg_free();
			mupip_exit(save_errno);
		} else
		{
			db_ipcs_reset(gv_cur_region, TRUE);
			mu_gv_cur_reg_free();
			mupip_exit(ERR_IOEOF);
		}
	}
	if (memcmp(&old_data->label[0], &label[0], GDS_LABEL_SZ))
	{
		util_out_print("Output file !AD has an unrecognizable format", TRUE, n_len, db_name);
		free(old_data);
		free(inbuf);
		db_ipcs_reset(gv_cur_region, TRUE);
		mu_gv_cur_reg_free();
		mupip_exit(ERR_MUPRESTERR);
	}

	curr_tn = old_data->trans_hist.curr_tn;
	old_blk_size = old_data->blk_size;
	old_tot_blks = old_data->trans_hist.total_blks;
	old_start_vbn = old_data->start_vbn;
 	bplmap = old_data->bplmap;
	free(old_data);

	msg_string.addr = msg_buffer;
	msg_string.len = sizeof(msg_buffer);

	inhead = (inc_header *)malloc(sizeof(inc_header) + 8);
	inhead = (inc_header *)((((int4)inhead) + 7) & -8);
	rest_blks = 0;

	for (ptr = in_files.next;  ptr;  ptr = ptr->next)
	{	/* --- determine source type --- */
		type = backup_to_file;
		if (0 == ptr->input_file.len)
			continue;
		else if ('|' == *(ptr->input_file.addr + ptr->input_file.len - 1))
		{
			type = backup_to_exec;
			ptr->input_file.len--;
			*(ptr->input_file.addr + ptr->input_file.len) = '\0';
		} else if (ptr->input_file.len > 5)
		{
			lower_to_upper(tcp, (uchar_ptr_t)ptr->input_file.addr, 5);
			if (0 == memcmp(tcp, "TCP:/", 5))
			{
				type = backup_to_tcp;
				cut = 5;
				while ('/' == *(ptr->input_file.addr + cut))
					cut++;
				ptr->input_file.len -= cut;
				p = ptr->input_file.addr;
				while (p < ptr->input_file.addr + ptr->input_file.len)
				{
					*p = *(p + cut);
					p++;
				}
				*p = '\0';
			}
		}
		/* --- open the input stream --- */
		restore_read_errno = 0;
		switch(type)
		{
			case backup_to_file:
				common_read = iob_read;
				if ((in = iob_open_rd(ptr->input_file.addr, DISK_BLOCK_SIZE, BLOCKING_FACTOR)) == NULL)
				{
					save_errno = errno;
					util_out_print("Error accessing input file !AD. Aborting restore.", TRUE,
						ptr->input_file.len, ptr->input_file.addr);
					errptr = (char *)STRERROR(save_errno);
					util_out_print("open : !AZ", TRUE, errptr);
					db_ipcs_reset(gv_cur_region, TRUE);
					mu_gv_cur_reg_free();
					mupip_exit(save_errno);
				}
				ESTABLISH(iob_io_error);
				break;
			case backup_to_exec:
				pipe_child = 0;
				common_read = exec_read;
				in = (BFILE *)malloc(sizeof(BFILE));
				if (0 > (in->fd = gtm_pipe(ptr->input_file.addr, input_from_comm)))
				{
					util_out_print("Error creating input pipe from !AD.",
						TRUE, ptr->input_file.len, ptr->input_file.addr);
					db_ipcs_reset(gv_cur_region, TRUE);
					mu_gv_cur_reg_free();
					mupip_exit(ERR_MUPRESTERR);
				}
#ifdef DEBUG_ONLINE
				PRINTF("file descriptor for the openned pipe is %d.\n", in->fd);
				PRINTF("the command passed to gtm_pipe is %s.\n", ptr->input_file.addr);
#endif
				break;
			case backup_to_tcp:
				common_read = tcp_read;
				/* parse the input */
				switch (match = SSCANF(ptr->input_file.addr, "%[^:]:%hu", addr, &port))
				{
					case 1 :
						port = DEFAULT_BKRS_PORT;
					case 2 :
						break;
					default :
						util_out_print("Error : A hostname has to be specified.", TRUE);
						db_ipcs_reset(gv_cur_region, TRUE);
						mu_gv_cur_reg_free();
						mupip_exit(ERR_MUPRESTERR);
				}
				if ((0 == cli_get_int("NETTIMEOUT", &timeout)) || (0 > timeout))
					timeout = DEFAULT_BKRS_TIMEOUT;
				in = (BFILE *)malloc(sizeof(BFILE));
				iotcp_fillroutine();
				if (0 > (in->fd = tcp_open(addr, port, timeout, TRUE)))
				{
					util_out_print("Error establishing TCP connection to !AD.",
						TRUE, ptr->input_file.len, ptr->input_file.addr);
					db_ipcs_reset(gv_cur_region, TRUE);
					mu_gv_cur_reg_free();
					mupip_exit(ERR_MUPRESTERR);
				}
				break;
			default:
				util_out_print("Aborting restore!/", TRUE);
				util_out_print("Unrecognized input format !AD", TRUE, ptr->input_file.len, ptr->input_file.addr);
				db_ipcs_reset(gv_cur_region, TRUE);
				mu_gv_cur_reg_free();
				mupip_exit(ERR_MUPRESTERR);
		}
		COMMON_READ(in, inhead, sizeof(inc_header));
		if (memcmp(&inhead->label[0], INC_HEADER_LABEL, INC_HDR_LABEL_SZ))
		{
			util_out_print("Input file !AD has an unrecognizable format", TRUE, ptr->input_file.len,
				ptr->input_file.addr);
			free(inbuf);
			db_ipcs_reset(gv_cur_region, TRUE);
			mu_gv_cur_reg_free();
			mupip_exit(ERR_MUPRESTERR);
		}
		if (curr_tn != inhead->start_tn)
		{
			util_out_print("Transaction in input file !AD does not align with database TN.!/DB: !XL!_Input file: !XL",
				TRUE, ptr->input_file.len, ptr->input_file.addr, curr_tn, inhead->start_tn);
			free(inbuf);
			db_ipcs_reset(gv_cur_region, TRUE);
			mu_gv_cur_reg_free();
			mupip_exit(ERR_MUPRESTERR);
		}
		if (old_blk_size != inhead->blk_size)
		{
			util_out_print("Incompatable block size.  Output file !AD has block size !XL,", TRUE, n_len, db_name);
			util_out_print("while input file !AD is from a database with block size !XL,", TRUE, ptr->input_file.len,
				ptr->input_file.addr, inhead->blk_size);
			free(inbuf);
			db_ipcs_reset(gv_cur_region, TRUE);
			mu_gv_cur_reg_free();
			mupip_exit(ERR_MUPRESTERR);
		}
		if (old_tot_blks != inhead->db_total_blks)
		{
			if (old_tot_blks > inhead->db_total_blks || !extend)
			{
				totblks = old_tot_blks - DIVIDE_ROUND_UP(old_tot_blks, DISK_BLOCK_SIZE);
				util_out_print("Incompatable database sizes.  Output file !AD has!/  !UL (!XL hex) total blocks,",
						TRUE, n_len, db_name, totblks, totblks);
				totblks = inhead->db_total_blks - DIVIDE_ROUND_UP(inhead->db_total_blks, DISK_BLOCK_SIZE);
				util_out_print("while input file !AD is from a database with!/  !UL (!XL hex) total blocks",
						TRUE, ptr->input_file.len, ptr->input_file.addr, totblks, totblks);
				free(inbuf);
				db_ipcs_reset(gv_cur_region, TRUE);
				mu_gv_cur_reg_free();
				mupip_exit(ERR_MUPRESTERR);
			} else
			{	/* this part of the code is similar to gdsfilext except that you don't need to do
				 * most of the work that gdsfilext does. However, for situations where the database
				 * extended since the last backup (the beginning of this incremental backup), and
				 * there are new bitmaps that are never touched later on by GT.M, these bitmaps
				 * will have tn == 0, which prevents the backup process to pick up these blocks,
				 * so, we need to initialize these bitmaps here
				 */
				new_eof = ((off_t)(old_start_vbn - 1) * DISK_BLOCK_SIZE)
						+ ((off_t)inhead->db_total_blks * old_blk_size);
				memset(buff, 0, DISK_BLOCK_SIZE);
				LSEEKWRITE(db_fd, new_eof, buff, DISK_BLOCK_SIZE, status);
				if (0 != status)
				{
					util_out_print("Aborting restore!/", TRUE);
					util_out_print("lseek or write error : Unable to extend output file !AD!/",
												TRUE, n_len, db_name);
					util_out_print("  from !UL (!XL hex) total blocks to !UL (!XL hex) total blocks.!/",
						TRUE, old_tot_blks, old_tot_blks, inhead->db_total_blks, inhead->db_total_blks);
					util_out_print("  Current input file is !AD with !UL (!XL hex) total blocks!/",
						TRUE, ptr->input_file.len, ptr->input_file.addr,
						inhead->db_total_blks, inhead->db_total_blks);
					gtm_putmsg(VARLSTCNT(1) status);
					free(inbuf);
					db_ipcs_reset(gv_cur_region, TRUE);
					mu_gv_cur_reg_free();
					mupip_exit(ERR_MUPRESTERR);
				}
				/* --- initialize all new bitmaps, just in case they are not touched later --- */
        			if (DIVIDE_ROUND_DOWN(inhead->db_total_blks, bplmap) > DIVIDE_ROUND_DOWN(old_tot_blks, bplmap))
        			{	/* -- similar logic exist in bml_newmap.c, which need to pick up any new updates here -- */
					newmap = (char *)malloc(old_blk_size);
					((blk_hdr *)newmap)->bsiz = BM_SIZE(bplmap);
					((blk_hdr *)newmap)->levl = LCL_MAP_LEVL;
					((blk_hdr *)newmap)->tn = curr_tn;
					newmap_bptr = newmap + sizeof(blk_hdr);
					*newmap_bptr++ = THREE_BLKS_FREE;
					memset(newmap_bptr, FOUR_BLKS_FREE, BM_SIZE(bplmap) - sizeof(blk_hdr) - 1);
			                for (ii = ROUND_UP(old_tot_blks, bplmap); ii <= inhead->db_total_blks; ii += bplmap)
                			{
						new_eof = (off_t)(old_start_vbn - 1) * DISK_BLOCK_SIZE + (off_t)ii * old_blk_size;
						LSEEKWRITE(db_fd, new_eof, newmap, old_blk_size, status);
						if (0 != status)
                        			{
							util_out_print("Aborting restore!/", TRUE);
							util_out_print("Bitmap 0x!XL initialization error!", TRUE, ii);
							gtm_putmsg(VARLSTCNT(1) status);
							free(inbuf);
							free(newmap);
							db_ipcs_reset(gv_cur_region, TRUE);
							mu_gv_cur_reg_free();
							mupip_exit(ERR_MUPRESTERR);
						}
					}
					free(newmap);
				}
				old_tot_blks = inhead->db_total_blks;
			}
		}
		COMMON_READ(in, &rsize, sizeof(int4));
		for ( ; ;)
		{	/* rsize is the size of the record, including the size, but, since the size has already been
			   read in, this will read in the current record and the size for the next record */
		        /* ensure we have a reasonable record size, at least */
		        if (rsize - sizeof(int4) - sizeof(block_id) > old_blk_size)
			{
				util_out_print("Invalid information in restore file !AD. Aborting restore.",
					TRUE, ptr->input_file.len,
					ptr->input_file.addr);
				iob_close(in);
				db_ipcs_reset(gv_cur_region, TRUE);
				mu_gv_cur_reg_free();
				mupip_exit(ERR_MUPRESTERR);
			}
		    	COMMON_READ(in, inbuf, rsize);
			if (!memcmp(inbuf, &end_msg[0], sizeof end_msg - 1))
				break;
			rest_blks++;
			blk_num = *(block_id*)inbuf;
			vbn = old_start_vbn - 1 + (old_blk_size / DISK_BLOCK_SIZE * blk_num);
			LSEEKWRITE(db_fd,
				   (off_t)vbn * DISK_BLOCK_SIZE,
				   inbuf + sizeof(block_id),
				   rsize - sizeof(block_id) - sizeof(int4),
				   save_errno);
			if (0 != save_errno)
			{
				util_out_print("Error accessing output file !AD. Aborting restore.",
					TRUE, n_len, db_name);
				errptr = (char *)STRERROR(save_errno);
				util_out_print("write : !AZ", TRUE, errptr);
				db_ipcs_reset(gv_cur_region, TRUE);
				mu_gv_cur_reg_free();
				mupip_exit(save_errno);
			}
			GET_LONG(temp, (inbuf + rsize - sizeof(int4)));
			rsize = temp;
		}
		GET_LONG(temp, (inbuf + rsize - sizeof(int4)));
		rsize = temp;
		vbn = 0;
		for (i = 0;  ;  i++)	/* Restore file header */
		{
		    	COMMON_READ(in, inbuf, rsize);
			if (!memcmp(inbuf, &hdr_msg[0], sizeof hdr_msg - 1))
				break;
			LSEEKWRITE(db_fd,
				   vbn,
				   inbuf,
				   rsize - sizeof(int4),
				   save_errno);
			if (0 != save_errno)
			{
				util_out_print("Error accessing output file !AD. Aborting restore.",
					TRUE, n_len, db_name);
				errptr = (char *)STRERROR(save_errno);
				util_out_print("write : !AZ", TRUE, errptr);
				db_ipcs_reset(gv_cur_region, TRUE);
				mu_gv_cur_reg_free();
				mupip_exit(save_errno);
			}
			vbn += rsize - sizeof(int4);
			GET_LONG(temp, (inbuf + rsize - sizeof(int4)));
			rsize = temp;
		}
		curr_tn = inhead->end_tn;
		switch (type)
		{
			case backup_to_file:
				REVERT;
				iob_close(in);
				break;
			case backup_to_exec:
				close(in->fd);
				if ((pipe_child > 0) && (FALSE != is_proc_alive(pipe_child, 0)))
					WAITPID(pipe_child, (int *)&status, 0, waitpid_res);
				break;
			case backup_to_tcp:
				break;
		}
	}
	util_out_print("!/RESTORE COMPLETED", TRUE);
	util_out_print("!UL blocks restored", TRUE, rest_blks);
	free(inbuf);
	db_ipcs_reset(gv_cur_region, FALSE);
	mu_gv_cur_reg_free();
 	mupip_exit(SS_NORMAL);
}
Пример #11
0
int fdfs_dump_tracker_global_vars_to_file(const char *filename)
{
	char buff[16 * 1024];
	char szCurrentTime[32];
	int len;
	int result;
	int fd;
	FDFSGroupInfo **ppGroup;
	FDFSGroupInfo **ppGroupEnd;

	fd = open(filename, O_WRONLY | O_CREAT | O_APPEND, 0644);
	if (fd < 0)
	{
		logError("file: "__FILE__", line: %d, "
			"open file %s fail, errno: %d, error info: %s",
			__LINE__, filename, errno, STRERROR(errno));
		return errno;
	}

	do
	{
		result = 0;
		formatDatetime(g_current_time, "%Y-%m-%d %H:%M:%S", 
				szCurrentTime, sizeof(szCurrentTime));

		len = sprintf(buff, "\n====time: %s  DUMP START====\n", 
				szCurrentTime);
		WRITE_TO_FILE(fd, buff, len)

		len = fdfs_dump_global_vars(buff, sizeof(buff));
		WRITE_TO_FILE(fd, buff, len)

		len = fdfs_dump_tracker_servers(buff, sizeof(buff));
		WRITE_TO_FILE(fd, buff, len)

		len = fdfs_dump_groups_info(buff, sizeof(buff));
		WRITE_TO_FILE(fd, buff, len)

		len = sprintf(buff, "\ngroup name list:\n");
		WRITE_TO_FILE(fd, buff, len)
		len = 0;
		ppGroupEnd = g_groups.groups + g_groups.count;
		for (ppGroup=g_groups.groups; ppGroup<ppGroupEnd; ppGroup++)
		{
			len += sprintf(buff+len, "\t%s\n", (*ppGroup)->group_name);
		}
		len += sprintf(buff+len, "\n");
		WRITE_TO_FILE(fd, buff, len)

		ppGroupEnd = g_groups.sorted_groups + g_groups.count;
		for (ppGroup=g_groups.sorted_groups; ppGroup<ppGroupEnd; ppGroup++)
		{
			len = sprintf(buff, "\nGroup %d.\n", 
				(int)(ppGroup - g_groups.sorted_groups) + 1);
			WRITE_TO_FILE(fd, buff, len)

			len = fdfs_dump_group_stat(*ppGroup, buff, sizeof(buff));
			WRITE_TO_FILE(fd, buff, len)
		}

		len = sprintf(buff, "\n====time: %s  DUMP END====\n\n", 
				szCurrentTime);
		WRITE_TO_FILE(fd, buff, len)
	} while(0);

	close(fd);

	return result;
}
Пример #12
0
static int fdfs_ping_leader(ConnectionInfo *pTrackerServer)
{
	TrackerHeader header;
	int result;
	int success_count;
	int64_t in_bytes;
	char in_buff[(FDFS_GROUP_NAME_MAX_LEN + FDFS_STORAGE_ID_MAX_SIZE) * \
			FDFS_MAX_GROUPS];
	char *pInBuff;
	char *p;
	char *pEnd;
	FDFSGroupInfo *pGroup;
	char group_name[FDFS_GROUP_NAME_MAX_LEN + 1];
	char trunk_server_id[FDFS_STORAGE_ID_MAX_SIZE];

	memset(&header, 0, sizeof(header));
	header.cmd = TRACKER_PROTO_CMD_TRACKER_PING_LEADER;
	result = tcpsenddata_nb(pTrackerServer->sock, &header, \
			sizeof(header), g_fdfs_network_timeout);
	if(result != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"tracker server ip: %s, send data fail, " \
			"errno: %d, error info: %s", \
			__LINE__, pTrackerServer->ip_addr, \
			result, STRERROR(result));
		return result;
	}

	pInBuff = in_buff;
	if ((result=fdfs_recv_response(pTrackerServer, &pInBuff, \
			sizeof(in_buff), &in_bytes)) != 0)
	{
		return result;
	}

	if (in_bytes == 0)
	{
		return 0;
	}
	else if (in_bytes % (FDFS_GROUP_NAME_MAX_LEN + \
			FDFS_STORAGE_ID_MAX_SIZE) != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"tracker server ip: %s, invalid body length: " \
			"%"PRId64, __LINE__, \
			pTrackerServer->ip_addr, in_bytes);
		return EINVAL;
	}

	success_count = 0;
	memset(group_name, 0, sizeof(group_name));
	memset(trunk_server_id, 0, sizeof(trunk_server_id));

	pEnd = in_buff + in_bytes;
	for (p=in_buff; p<pEnd; p += FDFS_GROUP_NAME_MAX_LEN + \
					FDFS_STORAGE_ID_MAX_SIZE)
	{
		memcpy(group_name, p, FDFS_GROUP_NAME_MAX_LEN);
		memcpy(trunk_server_id, p + FDFS_GROUP_NAME_MAX_LEN, \
			FDFS_STORAGE_ID_MAX_SIZE - 1);

		pGroup = tracker_mem_get_group(group_name);
		if (pGroup == NULL)
		{
			logWarning("file: "__FILE__", line: %d, " \
				"tracker server ip: %s, group: %s not exists", \
				__LINE__, pTrackerServer->ip_addr, group_name);
			continue;
		}

		if (*trunk_server_id == '\0')
		{
			*(pGroup->last_trunk_server_id) = '\0';
			pGroup->pTrunkServer = NULL;
			success_count++;
			continue;
		}

		pGroup->pTrunkServer = tracker_mem_get_storage(pGroup, \
							trunk_server_id);
		if (pGroup->pTrunkServer == NULL)
		{
			logWarning("file: "__FILE__", line: %d, " \
				"tracker server ip: %s, group: %s, " \
				"trunk server: %s not exists", \
				__LINE__, pTrackerServer->ip_addr, \
				group_name, trunk_server_id);
		}
		snprintf(pGroup->last_trunk_server_id, sizeof( \
			pGroup->last_trunk_server_id), "%s", trunk_server_id);
		success_count++;
	}

	if (success_count > 0)
	{
		tracker_save_groups();
	}

	return 0;
}
Пример #13
0
static int do_notify_leader_changed(ConnectionInfo *pTrackerServer, \
		ConnectionInfo *pLeader, const char cmd, bool *bConnectFail)
{
	char out_buff[sizeof(TrackerHeader) + FDFS_PROTO_IP_PORT_SIZE];
	char in_buff[1];
	ConnectionInfo *conn;
	TrackerHeader *pHeader;
	char *pInBuff;
	int64_t in_bytes;
	int result;

	pTrackerServer->sock = -1;
	if ((conn=tracker_connect_server(pTrackerServer, &result)) == NULL)
	{
		*bConnectFail = true;
		return result;
	}
	*bConnectFail = false;

	do
	{
	memset(out_buff, 0, sizeof(out_buff));
	pHeader = (TrackerHeader *)out_buff;
	pHeader->cmd = cmd;
	sprintf(out_buff + sizeof(TrackerHeader), "%s:%d", \
			pLeader->ip_addr, pLeader->port);
	long2buff(FDFS_PROTO_IP_PORT_SIZE, pHeader->pkg_len);
	if ((result=tcpsenddata_nb(conn->sock, out_buff, \
			sizeof(out_buff), g_fdfs_network_timeout)) != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"send data to tracker server %s:%d fail, " \
			"errno: %d, error info: %s", __LINE__, \
			pTrackerServer->ip_addr, \
			pTrackerServer->port, \
			result, STRERROR(result));

		result = (result == ENOENT ? EACCES : result);
		break;
	}

	pInBuff = in_buff;
	result = fdfs_recv_response(conn, &pInBuff, \
				0, &in_bytes);
	if (result != 0)
	{
		break;
	}

	if (in_bytes != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"tracker server %s:%d response data " \
			"length: %"PRId64" is invalid, " \
			"expect length: %d.", __LINE__, \
			pTrackerServer->ip_addr, pTrackerServer->port, \
			in_bytes, 0);
		result = EINVAL;
		break;
	}
	} while (0);

	if (pTrackerServer->port == g_server_port && \
		is_local_host_ip(pTrackerServer->ip_addr))
	{
		tracker_disconnect_server_ex(conn, true);
	}
	else
	{
		tracker_disconnect_server_ex(conn, result != 0);
	}

	return result;
}
Пример #14
0
void	iosocket_use(io_desc *iod, mval *pp)
{
    unsigned char	ch, len;
    int		handled_len, handlea_len, handles_len;
    int4		length, width, new_len;
    d_socket_struct *dsocketptr;
    socket_struct	*socketptr, newsocket;
    char		handlea[MAX_HANDLE_LEN], handles[MAX_HANDLE_LEN], handled[MAX_HANDLE_LEN];
    char            addr[SA_MAXLITLEN], *errptr, sockaddr[SA_MAXLITLEN],
                    temp_addr[SA_MAXLITLEN], ioerror;
    unsigned char	delimiter_buffer[MAX_N_DELIMITER * (MAX_DELIM_LEN + 1)];
    unsigned char	zff_buffer[MAX_ZFF_LEN];
    boolean_t	attach_specified = FALSE,
                detach_specified = FALSE,
                connect_specified = FALSE,
                ioerror_specified = FALSE,
                listen_specified = FALSE,
                socket_specified = FALSE,
                delay_specified = FALSE,
                nodelay_specified = FALSE,
                bfsize_specified = FALSE,
                ibfsize_specified = FALSE,
                moreread_specified = FALSE,
                create_new_socket;
    int4 		index, n_specified, zff_len, delimiter_len, moreread_timeout;
    int		fil_type, nodelay, p_offset = 0;
    uint4		bfsize = DEFAULT_SOCKET_BUFFER_SIZE, ibfsize;
    char		*tab;
    int		save_errno;
    size_t		d_socket_struct_len;
    mstr		lcl_zff;

    assert(iod->state == dev_open);
    assert(iod->type == gtmsocket);
    dsocketptr = (d_socket_struct *)(iod->dev_sp);
    /* ---------------------------------- parse the command line ------------------------------------ */
    n_specified = 0;
    zff_len = -1; /* indicates neither ZFF nor ZNOFF specified */
    delimiter_len = -1; /* indicates neither DELIM nor NODELIM specified */

    /* A read or wait was interrupted for this device. Allow only parmless use in $zinterrupt code for
       and interrupted device.
    */
    if (iop_eol != *(pp->str.addr + p_offset))
    {   /* Parameters were specified */
        if (dsocketptr->mupintr)
        {   /* And if we are in $zinterrupt code this is not allowed */
            if (dollar_zininterrupt)
                rts_error(VARLSTCNT(1) ERR_ZINTRECURSEIO);
            /* We are not in $zinterrupt code and this device was not resumed properly
               so clear its restartability.
            */
            io_find_mvstent(iod, TRUE);
            dsocketptr->mupintr = FALSE;
        }
    } else if (dsocketptr->mupintr && !dollar_zininterrupt)
    {   /* The interrupted read was not properly resumed so clear it now */
        dsocketptr->mupintr = FALSE;
        dsocketptr->sock_save_state.who_saved = sockwhich_invalid;
        io_find_mvstent(iod, TRUE);
    }

    while (iop_eol != (ch = *(pp->str.addr + p_offset++)))
    {
        assert((params)ch < (params)n_iops);
        switch (ch)
        {
        case iop_exception:
            iod->error_handler.len = *(pp->str.addr + p_offset);
            iod->error_handler.addr = (char *)(pp->str.addr + p_offset + 1);
            s2pool(&iod->error_handler);
            break;
        case iop_filter:
            len = *(pp->str.addr + p_offset);
            tab = pp->str.addr + p_offset + 1;
            if ((fil_type = namelook(filter_index, filter_names, tab, len)) < 0)
            {
                rts_error(VARLSTCNT(1) ERR_TTINVFILTER);
                return;
            }
            switch (fil_type)
            {
            case 0:
                iod->write_filter |= CHAR_FILTER;
                break;
            case 1:
                iod->write_filter |= ESC1;
                break;
            case 2:
                iod->write_filter &= ~CHAR_FILTER;
                break;
            case 3:
                iod->write_filter &= ~ESC1;
                break;
            }
            break;
        case iop_nofilter:
            iod->write_filter = 0;
            break;
        case iop_attach:
            n_specified++;
            attach_specified = TRUE;
            handlea_len = (int)(*(pp->str.addr + p_offset));
            memcpy(handlea, (char *)(pp->str.addr + p_offset + 1), handlea_len);
            break;
        case iop_detach:
            n_specified++;
            detach_specified = TRUE;
            handled_len = (int)(*(pp->str.addr + p_offset));
            memcpy(handled, (char *)(pp->str.addr + p_offset + 1), handled_len);
            break;
        case iop_connect:
            n_specified++;
            connect_specified = TRUE;
            len = *(pp->str.addr + p_offset);
            if (len < SA_MAXLITLEN)
            {
                memcpy(sockaddr, (char *)(pp->str.addr + p_offset + 1), len);
                sockaddr[len] = '\0';
            } else
                rts_error(VARLSTCNT(6) ERR_ADDRTOOLONG,
                          4, len, pp->str.addr + p_offset + 1, len, SA_MAXLITLEN);
            break;
        case iop_delimiter:
            n_specified++;
            delimiter_len = (int4)(unsigned char)*(pp->str.addr + p_offset);
            if (((MAX_DELIM_LEN + 1) * MAX_N_DELIMITER) >= delimiter_len)
                memcpy(delimiter_buffer, (pp->str.addr + p_offset + 1), delimiter_len);
            else
                rts_error(VARLSTCNT(1) ERR_DELIMSIZNA);
            break;
        case	iop_nodelimiter:
            delimiter_len = 0;
            break;
        case	iop_zdelay:
            delay_specified = TRUE;
            break;
        case	iop_znodelay:
            nodelay_specified = TRUE;
            break;
        case	iop_zbfsize:
            bfsize_specified = TRUE;
            GET_ULONG(bfsize, pp->str.addr + p_offset);
            if ((0 == bfsize) || (MAX_SOCKET_BUFFER_SIZE < bfsize))
                rts_error(VARLSTCNT(3) ERR_ILLESOCKBFSIZE, 1, bfsize);
            break;
        case	iop_zibfsize:
            ibfsize_specified = TRUE;
            GET_ULONG(ibfsize, pp->str.addr + p_offset);
            if ((0 == ibfsize) || (MAX_INTERNAL_SOCBUF_SIZE < ibfsize))
                rts_error(VARLSTCNT(3) ERR_ILLESOCKBFSIZE, 1, ibfsize);
            break;
        case iop_ioerror:
            n_specified++;
            ioerror_specified = TRUE;
            ioerror = *(char *)(pp->str.addr + p_offset + 1);
            break;
        case iop_zlisten:
            n_specified++;
            listen_specified = TRUE;
            len = *(pp->str.addr + p_offset);
            if (len < SA_MAXLITLEN)
            {
                memcpy(sockaddr, (char *)(pp->str.addr + p_offset + 1), len);
                sockaddr[len] = '\0';
            } else
                rts_error(VARLSTCNT(6) ERR_ADDRTOOLONG,
                          4, len, pp->str.addr + p_offset + 1, len, SA_MAXLITLEN);
            break;
        case iop_socket:
            n_specified++;
            socket_specified = TRUE;
            handles_len = (int)(*(pp->str.addr + p_offset));
            memcpy(handles, (char *)(pp->str.addr + p_offset + 1), handles_len);
            break;
        case iop_ipchset:
#if defined(KEEP_zOS_EBCDIC) || defined(VMS)
            if ((iconv_t)0 != iod->input_conv_cd)
                ICONV_CLOSE_CD(iod->input_conv_cd);
            SET_CODE_SET(iod->in_code_set, (char *)(pp->str.addr + p_offset + 1));
            if (DEFAULT_CODE_SET != iod->in_code_set)
                ICONV_OPEN_CD(iod->input_conv_cd, INSIDE_CH_SET, (char *)(pp->str.addr + p_offset + 1));
#endif
            break;
        case iop_opchset:
#if defined(KEEP_zOS_EBCDIC) || defined(VMS)
            if ((iconv_t)0 != iod->output_conv_cd)
                ICONV_CLOSE_CD(iod->output_conv_cd);
            SET_CODE_SET(iod->out_code_set, (char *)(pp->str.addr + p_offset + 1));
            if (DEFAULT_CODE_SET != iod->out_code_set)
                ICONV_OPEN_CD(iod->output_conv_cd, (char *)(pp->str.addr + p_offset + 1), INSIDE_CH_SET);
#endif
            break;
        case iop_zff:
            if (MAX_ZFF_LEN >= (zff_len = (int4)(unsigned char)*(pp->str.addr + p_offset)))
                memcpy(zff_buffer, (char *)(pp->str.addr + p_offset + 1), zff_len);
            else
                rts_error(VARLSTCNT(4) ERR_ZFF2MANY, 2, zff_len, MAX_ZFF_LEN);
            break;
        case iop_znoff:
            zff_len = 0;
            break;
        case iop_length:
            GET_LONG(length, pp->str.addr + p_offset);
            if (length < 0)
                rts_error(VARLSTCNT(1) ERR_DEVPARMNEG);
            iod->length = length;
            break;
        case iop_width:
            /* SOCKET WIDTH is handled the same way as TERMINAL WIDTH */
            GET_LONG(width, pp->str.addr + p_offset);
            if (width < 0)
                rts_error(VARLSTCNT(1) ERR_DEVPARMNEG);
            if (0 == width)
            {
                iod->width = TCPDEF_WIDTH;
                iod->wrap = FALSE;
            } else
            {
                iod->width = width;
                iod->wrap = TRUE;
            }
            break;
        case iop_wrap:
            iod->wrap = TRUE;
            break;
        case iop_nowrap:
            iod->wrap = FALSE;
            break;
        case iop_morereadtime:
            /* Time in milliseconds socket read will wait for more data before returning */
            GET_LONG(moreread_timeout, pp->str.addr + p_offset);
            if (-1 == moreread_timeout)
                moreread_timeout = DEFAULT_MOREREAD_TIMEOUT;
            else if (-1 > moreread_timeout)
                rts_error(VARLSTCNT(1) ERR_DEVPARMNEG);
            else if (MAX_MOREREAD_TIMEOUT < moreread_timeout)
                rts_error(VARLSTCNT(3) ERR_MRTMAXEXCEEDED, 1, MAX_MOREREAD_TIMEOUT);
            moreread_specified = TRUE;
            break;
        default:
            /* ignore deviceparm */
            break;
        }
        p_offset += ((io_params_size[ch] == IOP_VAR_SIZE) ?
                     (unsigned char)*(pp->str.addr + p_offset) + 1 : io_params_size[ch]);
    }
    /* ------ return immediately if no flag, worth a check because it is mostly true ------------ */
    if (1 == p_offset)
        return;
    /* ------------------------------ compatibility verification -------------------------------- */
    if ((socket_specified) && ((n_specified > 2) || ((2 == n_specified) && (0 >= delimiter_len))))
    {
        rts_error(VARLSTCNT(8) ERR_ACOMPTBINC, 6, LEN_AND_LIT("SOCKET"), LEN_AND_LIT("DELIMITER"), LEN_AND_LIT("USE"));
        return;
    }
    if (connect_specified && listen_specified)
    {
        rts_error(VARLSTCNT(8) ERR_ABNCOMPTINC, 6, LEN_AND_LIT("CONNECT"), LEN_AND_LIT("ZLISTEN"), LEN_AND_LIT("USE"));
        return;
    }
    if (delay_specified && nodelay_specified)
    {
        rts_error(VARLSTCNT(8) ERR_ABNCOMPTINC, 6, LEN_AND_LIT("DELAY"), LEN_AND_LIT("NODELAY"), LEN_AND_LIT("OPEN"));
        return;
    }
    /* ------------------ make a local copy of device structure to play with -------------------- */
    d_socket_struct_len = SIZEOF(d_socket_struct) + (SIZEOF(socket_struct) * (gtm_max_sockets - 1));
    memcpy(newdsocket, dsocketptr, d_socket_struct_len);
    /* --------------- handle the two special cases attach/detach first ------------------------- */
    if (detach_specified)
    {
        if (1 < n_specified)
        {
            rts_error(VARLSTCNT(6) ERR_ANCOMPTINC, 4, LEN_AND_LIT("DETACH"), LEN_AND_LIT("USE"));
            return;
        }
        if (NULL == socket_pool)
            iosocket_poolinit();
        iosocket_switch(handled, handled_len, newdsocket, socket_pool);
        memcpy(dsocketptr, newdsocket, d_socket_struct_len);
        if (0 > dsocketptr->current_socket)
        {
            io_curr_device.in = io_std_device.in;
            io_curr_device.out = io_std_device.out;
        }
        return; /* detach can only be specified by itself */
    }
    if (attach_specified)
    {   /* NOTE: A socket could be moved from one device to another using DETACH/ATTACH. A socket does not carry I[O]CHSET with
         * it while being moved. Such a socket will use the I[O]CHSET of the device it is ATTACHed to. If there is input still
         * buffered, this may cause unintentional consequences in the application if I[O]CHSET changes. GT.M does not detect
         * (or report) a change in I[O]CHSET due to DETACH/ATTACH.
         */
        if (1 < n_specified)
        {
            rts_error(VARLSTCNT(6) ERR_ANCOMPTINC, 4, LEN_AND_LIT("ATTACH"), LEN_AND_LIT("USE"));
            return;
        }
        if (NULL == socket_pool)
        {
            rts_error(VARLSTCNT(4) ERR_SOCKNOTFND, 2, handlea_len, handlea);
            return;
        }
        iosocket_switch(handlea, handlea_len, socket_pool, newdsocket);
        memcpy(dsocketptr, newdsocket, d_socket_struct_len);
        return; /* attach can only be specified by itself */
    }
    /* ------------ create/identify the socket to work on and make a local copy ----------------- */
    if (create_new_socket = (listen_specified || connect_specified))	/* real "=" */
    {
        /* allocate the structure for a new socket */
        if (NULL == (socketptr = iosocket_create(sockaddr, bfsize, -1)))
            return;
        /* give the new socket a handle */
        iosocket_handle(handles, &handles_len, TRUE, dsocketptr);
        socketptr->handle_len = handles_len;
        memcpy(socketptr->handle, handles, handles_len);
        socketptr->dev = newdsocket;	/* use newdsocket temporarily for the sake of bind/connect */
    } else
    {
        if (socket_specified)
        {
            /* use the socket flag to identify which socket to apply changes */
            if (0 > (index = iosocket_handle(handles, &handles_len, FALSE, newdsocket)))
            {
                rts_error(VARLSTCNT(4) ERR_SOCKNOTFND, 2, handles_len, handles);
                return;
            }
            newdsocket->current_socket = index;
            socketptr = newdsocket->socket[index];
        } else
        {
            socketptr = newdsocket->socket[newdsocket->current_socket];
            if (newdsocket->n_socket <= newdsocket->current_socket)
            {
                assert(FALSE);
                rts_error(VARLSTCNT(4) ERR_CURRSOCKOFR, 2, newdsocket->current_socket, newdsocket->n_socket);
                return;
            }
        }
    }
    newsocket = *socketptr;
    /* ---------------------- apply changes to the local copy of the socket --------------------- */
    if (0 <= delimiter_len)
    {
        iosocket_delimiter(delimiter_buffer, delimiter_len, &newsocket, (0 == delimiter_len));
        /* The delimiter has changed. The iosocket_readfl/write routine won't notice so we have to do
           the UTF16xx conversion since we changed it.
        */
        DBGSOCK2((stdout, "socuse: Delimiter(s) replaced - num delims: %d  delimiter_len: %d  ichset: %d  ochset: %d\n",
                  newsocket.n_delimiter, delimiter_len, iod->ichset, iod->ochset));
        if  (0 < delimiter_len)
        {
            if (!newsocket.first_read && (CHSET_UTF16BE == iod->ichset || CHSET_UTF16LE == iod->ichset))
            {   /* We have been reading with this socket so convert this new delimiter set */
                DBGSOCK2((stdout, "socuse: Converting new delimiters for input\n"));
                iosocket_delim_conv(&newsocket, iod->ichset);
            }
            if (!newsocket.first_write && (CHSET_UTF16BE == iod->ochset || CHSET_UTF16LE == iod->ochset))
            {   /* We have been writing with this socket so convert the new default output delimiter */
                DBGSOCK2((stdout, "socuse: Converting new delimiters for output\n"));
                if (newsocket.first_read || (CHSET_UTF16BE != iod->ichset && CHSET_UTF16LE != iod->ichset))
                {   /* Need to do conversion as iosocket_delim_conv above didn't do it for us */
                    DBGSOCK2((stdout, "socuse: running convert for write since input didn't do it\n"));
                    new_len = gtm_conv(chset_desc[CHSET_UTF8], chset_desc[iod->ochset],
                                       &newsocket.delimiter[0], NULL, NULL);
                    if (MAX_DELIM_LEN < new_len)
                    {
                        rts_error(VARLSTCNT(1) ERR_DELIMSIZNA);
                        return;
                    }
                } else
                {
                    DBGSOCK2((stdout, "socuse: using previous length from read conversion\n"));
                    new_len = newsocket.idelimiter[0].len;
                }
                newsocket.odelimiter0.len = new_len;
                UNICODE_ONLY(newsocket.odelimiter0.char_len = newsocket.delimiter[0].char_len);
                newsocket.odelimiter0.addr = malloc(new_len);
                memcpy(newsocket.odelimiter0.addr,
                       (newsocket.first_read ? (char *)stringpool.free : newsocket.idelimiter[0].addr),
                       new_len);
            }
        }
    }
    if (iod->wrap && 0 != newsocket.n_delimiter && iod->width < newsocket.delimiter[0].len)
        rts_error(VARLSTCNT(4) ERR_DELIMWIDTH, 2, iod->width, newsocket.delimiter[0].len);
    if (0 <= zff_len && /* ZFF or ZNOFF specified */
            0 < (newsocket.zff.len = zff_len)) /* assign the new ZFF len, might be 0 from ZNOFF, or ZFF="" */
    {   /* ZFF="non-zero-len-string" specified */
        if (CHSET_UTF16BE == iod->ochset || CHSET_UTF16LE == iod->ochset) /* need conversion of ZFF */
        {
            DBGSOCK2((stdout, "socuse: Converting zff\n"));
            lcl_zff.addr = (char *)zff_buffer;
            lcl_zff.len = zff_len;
            new_len = gtm_conv(chset_desc[CHSET_UTF8], chset_desc[iod->ochset], &lcl_zff, NULL, NULL);
            if (MAX_ZFF_LEN < new_len)
                rts_error(VARLSTCNT(4) ERR_ZFF2MANY, 2, new_len, MAX_ZFF_LEN);
            if (NULL == newsocket.zff.addr) /* we rely on newsocket.zff.addr being set to 0 in iosocket_create() */
                newsocket.zff.addr = (char *)malloc(MAX_ZFF_LEN);
            newsocket.zff.len = new_len;
            UNICODE_ONLY(newsocket.zff.char_len = 0); /* don't care */
            memcpy(newsocket.zff.addr, stringpool.free, new_len);

        } else
        {   /* Store parm without conversion */
            if (gtm_utf8_mode) /* Check if ZFF has any invalid UTF-8 character */
            {   /* Note: the ZFF string originates from the source program, so is in UTF-8 mode or M mode
                   regardless of OCHSET of this device. ZFF is output on WRITE # command, and MUST contain
                   valid UTF-8 sequence. This validation is handled by gtm_conv in the path above.
                */
                utf8_len_strict(zff_buffer, zff_len);
            }
            if (NULL == newsocket.zff.addr) /* we rely on newsocket.zff.addr being set to 0 in iosocket_create() */
                newsocket.zff.addr = (char *)malloc(MAX_ZFF_LEN);
            memcpy(newsocket.zff.addr, zff_buffer, zff_len);
        }
    }
    if (ioerror_specified)
        newsocket.ioerror = ('T' == ioerror || 't' == ioerror);
    if (nodelay_specified || delay_specified)
        newsocket.nodelay = nodelay_specified;	/* defaults to DELAY */
    if (ibfsize_specified)
        newsocket.bufsiz = ibfsize;
    if (moreread_specified)
    {
        newsocket.moreread_timeout = moreread_timeout;
        newsocket.def_moreread_timeout = TRUE;	/* need to know this was user-defined in iosocket_readfl.c */
    }
    if (!create_new_socket)
    {
        /* these changes apply to only pre-existing sockets */
        if (bfsize_specified)
            newsocket.buffer_size = bfsize;
#ifdef TCP_NODELAY
        nodelay = newsocket.nodelay ? 1 : 0;
        if ((socketptr->nodelay != newsocket.nodelay) &&
                (-1 == tcp_routines.aa_setsockopt(newsocket.sd, IPPROTO_TCP,
                        TCP_NODELAY, &nodelay, SIZEOF(nodelay))))
        {
            save_errno = errno;
            errptr = (char *)STRERROR(save_errno);
            rts_error(VARLSTCNT(7) ERR_SETSOCKOPTERR, 5, LEN_AND_LIT("TCP_NODELAY"), save_errno, LEN_AND_STR(errptr));
            return;
        }
#endif
        if ((socketptr->bufsiz != newsocket.bufsiz) &&
                (-1 == tcp_routines.aa_setsockopt(newsocket.sd, SOL_SOCKET,
                        SO_RCVBUF, &newsocket.bufsiz, SIZEOF(newsocket.bufsiz))))
        {
            save_errno = errno;
            errptr = (char *)STRERROR(save_errno);
            rts_error(VARLSTCNT(7) ERR_SETSOCKOPTERR, 5, LEN_AND_LIT("SO_RCVBUF"), save_errno, LEN_AND_STR(errptr));
            return;
        }
        if (socketptr->buffer_size != newsocket.buffer_size)
        {
            if (socketptr->buffered_length > bfsize)
                rts_error(VARLSTCNT(4) ERR_SOCKBFNOTEMPTY, 2, bfsize, socketptr->buffered_length);
            newsocket.buffer = (char *)malloc(bfsize);
            if (0 < socketptr->buffered_length)
            {
                memcpy(newsocket.buffer, socketptr->buffer + socketptr->buffered_offset,
                       socketptr->buffered_length);
                newsocket.buffered_offset = 0;
            }
        }
    }
    /* -------------------------------------- action -------------------------------------------- */
    if ((listen_specified && (!iosocket_bind(&newsocket, NO_M_TIMEOUT, ibfsize_specified))) ||
            (connect_specified && (!iosocket_connect(&newsocket, 0, ibfsize_specified))))
    {   /* error message should be printed from bind/connect */
        if (socketptr->sd > 0)
            (void)tcp_routines.aa_close(socketptr->sd);
        iosocket_delimiter((unsigned char *)NULL, 0, &newsocket, TRUE);
        if (NULL != socketptr->zff.addr)
            free(socketptr->zff.addr);
        if (NULL != socketptr->buffer)
            free(socketptr->buffer);
        free(socketptr);
        return;
    }
    /* ------------------------------------ commit changes -------------------------------------- */
    if (create_new_socket)
    {
        if (gtm_max_sockets <= newdsocket->n_socket)
        {
            rts_error(VARLSTCNT(3) ERR_SOCKMAX, 1, gtm_max_sockets);
            return;
        }
        /* a new socket is created. so add to the list */
        newsocket.dev = dsocketptr;
        newdsocket->socket[newdsocket->n_socket++] = socketptr;
        newdsocket->current_socket = newdsocket->n_socket - 1;
    }
    else if (socketptr->buffer_size != newsocket.buffer_size)
        free(socketptr->buffer);
    *socketptr = newsocket;
    memcpy(dsocketptr, newdsocket, d_socket_struct_len);
    return;
}
Пример #15
0
int GetRules(struct sockaddr_in ServerID, struct rule_format rule[], int max_rules, struct htx_data * stats)
{
    SOCKET ToServerSock;
    struct CoordMsg CMsg;
    int rc;
    int i;
    int NoStanzas;
	char msg[1024]; 
	errno = 0;     

    ToServerSock = SetUpConnect(&ServerID, stats, 0); 
    memset(&CMsg, '\0', sizeof(CMsg));
    CMsg.msg_type = htonl(CM_REQ_RULES);
    CMsg.ID.Wsize.size  = htonl((uint32_t)sizeof(struct rule_format));
    rc = StreamWrite(ToServerSock, (char *) &CMsg, sizeof(CMsg));
    if(rc == -1) {
        sprintf(msg, "GetRules: Error writing to Server - %s\n", STRERROR(errno));
        hxfmsg(stats, HTXERROR(EX_RULE1,ERRNO), HTX_HE_SOFT_ERROR, msg);
        HE_exit(EX_RULE1);
    }
    StreamRead(ToServerSock, (char *) &CMsg, sizeof(CMsg));
    CMsg.msg_type = ntohl(CMsg.msg_type);
    CMsg.ID.Wsize.size  = ntohl(CMsg.ID.Wsize.size);
    if(CMsg.msg_type != CM_RULES_STANZA) {
        sprintf(msg, "GetRules: Illegal Packet recvd.\n"); 
        hxfmsg(stats, HTXERROR(EX_RULE3,0), HTX_HE_SOFT_ERROR, msg);
        HE_exit(EX_RULE3);
    }
	#ifdef __DEBUG__
		sprintf(msg, "GetRules: Sock = %d, Recvd msg = %x of size = %#x, rule_format size = %x, pid = %d \n", ToServerSock, CMsg.msg_type, sizeof(CMsg), (uint32_t)sizeof(struct rule_format), getpid()); 
		hxfmsg(stats, 0, 7, msg); 
	#endif 
    memset(rule, '\0', sizeof(struct rule_format) * max_rules);
	memset(&CMsg, '\0', sizeof(CMsg));
    for(i=0; i < max_rules; i++) {

        rc = StreamRead(ToServerSock, (char *) &CMsg.msg_type, sizeof(CMsg.msg_type));
        CMsg.msg_type = ntohl(CMsg.msg_type);
	#ifdef __DEBUG__
		sprintf(msg, "i = %#x, GetRules: Recvd msg = %x, of size = %x \n", i, CMsg.msg_type, sizeof(CMsg.msg_type)); 
		hxfmsg(stats, 0, 7, msg); 
	#endif 
        if(CMsg.msg_type == CM_RULES_FINISHED)
            break;
		 
        if(CMsg.msg_type != CM_RULES_STANZA) {
            sprintf(msg, "GetRules: Unable to obtain rules - type %x\n", (int)CMsg.msg_type);
            hxfmsg(stats, HTXERROR(EX_RULE2,ERRNO), HTX_HE_SOFT_ERROR, msg);
            HE_exit(EX_RULE2);
        }
		 
        rc = StreamRead(ToServerSock, (char*) &rule[i], sizeof(struct rule_format));
        if(rc != sizeof(struct rule_format)) {
            sprintf(msg, "GetRules: Unable to read rules from server - %s\n", STRERROR(errno));
            hxfmsg(stats, HTXERROR(EX_RULE4,ERRNO), HTX_HE_SOFT_ERROR, msg);
			HE_exit(EX_RULE3); 

        }

        NetToHostRules(&rule[i]);
    }
    NoStanzas = i;
    closesocket(ToServerSock);
    return NoStanzas;
}
Пример #16
0
int getlocaladdrs(char ip_addrs[][IP_ADDRESS_SIZE], \
	const int max_count, int *count)
{
	int s;
	struct ifconf ifconf;
	struct ifreq ifr[32];
	int if_count;
	int i;
	int result;

	*count = 0;
	s = socket(AF_INET, SOCK_STREAM, 0);
	if (s < 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"socket create fail, errno: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
		return errno != 0 ? errno : EMFILE;
	}

	ifconf.ifc_buf = (char *) ifr;
	ifconf.ifc_len = sizeof(ifr);
	if (ioctl(s, SIOCGIFCONF, &ifconf) < 0)
	{
		result = errno != 0 ? errno : EMFILE;
		logError("file: "__FILE__", line: %d, " \
			"call ioctl fail, errno: %d, error info: %s", \
			__LINE__, result, STRERROR(result));
 		close(s);
		return result;
	}

	if_count = ifconf.ifc_len / sizeof(ifr[0]);
	if (max_count < if_count)
	{
		logError("file: "__FILE__", line: %d, " \
			"max_count: %d < iterface count: %d", \
			__LINE__, max_count, if_count);
 		close(s);
		return ENOSPC;
	}

	for (i = 0; i < if_count; i++)
	{
		struct sockaddr_in *s_in;
    		s_in = (struct sockaddr_in *) &ifr[i].ifr_addr;
    		if (!inet_ntop(AF_INET, &s_in->sin_addr, \
			ip_addrs[*count], IP_ADDRESS_SIZE))
		{
			result = errno != 0 ? errno : EMFILE;
			logError("file: "__FILE__", line: %d, " \
				"call inet_ntop fail, " \
				"errno: %d, error info: %s", \
				__LINE__, result, STRERROR(result));
 			close(s);
			return result;
    		}
		(*count)++;
	}

	close(s);
	return *count > 0 ? 0 : ENOENT;
}
Пример #17
0
int gethostaddrs(char **if_alias_prefixes, const int prefix_count, \
	char ip_addrs[][IP_ADDRESS_SIZE], const int max_count, int *count)
{
	struct hostent *ent;
	char hostname[128];
	char *alias_prefixes1[1];
	char **true_alias_prefixes;
	int true_count;
	int i;
	int k;
	int sock;
	struct ifreq req;
	struct sockaddr_in *addr;
	int ret;

	*count = 0;
	if (prefix_count <= 0)
	{
		if (getlocaladdrs(ip_addrs, max_count, count) == 0)
		{
			return 0;
		}

#ifdef OS_FREEBSD
	#define IF_NAME_PREFIX    "bge"
#else
  #ifdef OS_SUNOS
	#define IF_NAME_PREFIX   "e1000g"
  #else
      #ifdef OS_AIX
          #define IF_NAME_PREFIX   "en"
      #else
          #define IF_NAME_PREFIX   "eth"
      #endif
  #endif
#endif

  		alias_prefixes1[0] = IF_NAME_PREFIX;
		true_count = 1;
		true_alias_prefixes = alias_prefixes1;
	}
	else
	{
		true_count = prefix_count;
		true_alias_prefixes = if_alias_prefixes;
	}

	sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock < 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"socket create failed, errno: %d, error info: %s.", \
			__LINE__, errno, STRERROR(errno));
		return errno != 0 ? errno : EMFILE;
	}

	for (i=0; i<true_count && *count<max_count; i++)
	{
	for (k=0; k<max_count; k++)
	{
		memset(&req, 0, sizeof(req));
		sprintf(req.ifr_name, "%s%d", true_alias_prefixes[i], k);
		ret = ioctl(sock, SIOCGIFADDR, &req);
		if (ret == -1)
		{
			break;
		}

		addr = (struct sockaddr_in*)&req.ifr_addr;
		if (inet_ntop(AF_INET, &addr->sin_addr, ip_addrs[*count], \
			IP_ADDRESS_SIZE) != NULL)
		{
			(*count)++;
			if (*count >= max_count)
			{
				break;
			}
		}
	}
	}

	close(sock);
	if (*count > 0)
	{
		return 0;
	}

	if (gethostname(hostname, sizeof(hostname)) != 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"call gethostname fail, " \
			"error no: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
		return errno != 0 ? errno : EFAULT;
	}

        ent = gethostbyname(hostname);
	if (ent == NULL)
	{
		logError("file: "__FILE__", line: %d, " \
			"call gethostbyname fail, " \
			"error no: %d, error info: %s", \
			__LINE__, h_errno, STRERROR(h_errno));
		return h_errno != 0 ? h_errno : EFAULT;
	}

	k = 0;
	while (ent->h_addr_list[k] != NULL)
	{
		if (*count >= max_count)
		{
			break;
		}

		if (inet_ntop(ent->h_addrtype, ent->h_addr_list[k], \
			ip_addrs[*count], IP_ADDRESS_SIZE) != NULL)
		{
			(*count)++;
		}

		k++;
	}

	return 0;
}
Пример #18
0
/* On OSF/1 (Digital Unix), pointers are 64 bits wide; the only exception to this is C programs for which one may
 * specify compiler and link editor options in order to use (and allocate) 32-bit pointers.  However, since C is
 * the only exception and, in particular because the operating system does not support such an exception, the argv
 * array passed to the main program is an array of 64-bit pointers.  Thus the C program needs to declare argv[]
 * as an array of 64-bit pointers and needs to do the same for any pointer it sets to an element of argv[].
 */
int main(int argc, char_ptr_t argv[])
{
	omi_fd	  	fd;
	char		buff[OMI_BUFSIZ], *bptr, *xptr, *end, *chr;
	int		cc, blen, bunches, i, n, len, buf[5], j, rdmr;
	omi_vi		mlen, xlen;
	omi_li		nx;
	omi_si		hlen;
	omi_req_hdr	rh;
	DCL_THREADGBL_ACCESS;

	GTM_THREADGBL_INIT;
	bunches = 0;
	if (argc == 3)
	{
		if (argv[1][0] != '-' || argv[1][1] != 'b' || argv[1][2] != '\0')
		{
			PRINTF("%s: bad command line arguments\n\t%s [ -b ] filename\n",
				argv[0], argv[0]);
			exit(-1);
		} else if (INV_FD_P((fd = open(argv[argc - 1], O_RDONLY))))
		{
			PRINTF("%s: open(\"%s\"): %s\n", argv[0], argv[argc - 1],
				STRERROR(errno));
			exit(-1);
		}
	} else if (argc == 2)
	{
		if (argv[1][0] == '-' && argv[1][1] == 'b' && argv[1][2] == '\0')
			fd = fileno(stdin);
		else if (INV_FD_P((fd = open(argv[argc - 1], O_RDONLY))))
		{
			PRINTF("%s: open(\"%s\"): %s\n", argv[0], argv[argc - 1],
				STRERROR(errno));
			exit(-1);
		}
	}
	else if (argc == 1)
		fd = fileno(stdin);
	else
	{
		PRINTF("%s: bad command line arguments\n\t%s [ -b ] [ filename ]\n", argv[0], argv[0]);
		exit(-1);
	}
	for (blen = 0, bptr = buff, n = 1, rdmr = 1; ; )
	{
		if (rdmr)
		{
			cc = (int)(ARRAYTOP(buff) - &bptr[blen]);
			if ((cc = (int)(read(fd, &bptr[blen], cc))) < 0)
			{
				PRINTF("%s: read(): %s", argv[0], STRERROR(errno));
				exit(-1);
			} else if (cc == 0)
				break;
			blen += cc;
			if (blen < OMI_VI_SIZ)
			{
				if (bptr != buff)
				{
					memmove(buff, bptr, blen);
					bptr = buff;
				}
				continue;
			}
		}
		xptr = bptr;
		OMI_VI_READ(&mlen, xptr);
		if (blen < mlen.value + 4)
		{
			if (bptr != buff)
			{
				memmove(buff, bptr, blen);
				bptr = buff;
			}
			rdmr = 1;
			continue;
		}
		rdmr = 0;
		PRINTF("Message %d, %ld bytes", n, (long)mlen.value);
		if (argc == 3 && bunches)
		{
			OMI_LI_READ(&nx, xptr);
			PRINTF(", %d transactions in bunch", nx.value);
			bptr += OMI_VI_SIZ + OMI_LI_SIZ;
			blen -= OMI_VI_SIZ + OMI_LI_SIZ;
		} else
		{
			nx.value = 1;
			xlen     = mlen;
		}
		puts("");
		for (i = 1; i <= nx.value; i++)
		{
			if (argc == 3 && bunches)
			{
				OMI_VI_READ(&xlen, xptr);
			}
			end = xptr + xlen.value;
			OMI_SI_READ(&hlen, xptr);
			OMI_LI_READ(&rh.op_class, xptr);
			OMI_SI_READ(&rh.op_type, xptr);
			OMI_LI_READ(&rh.user, xptr);
			OMI_LI_READ(&rh.group, xptr);
			OMI_LI_READ(&rh.seq, xptr);
			OMI_LI_READ(&rh.ref, xptr);
			if (rh.op_class.value == 1)
			{
				PRINTF("    %s (%ld bytes)", (omi_oprlist[rh.op_type.value])
				       ? omi_oprlist[rh.op_type.value] : "unknown",(long)xlen.value);
				if (argc == 3 && bunches)
				    PRINTF(", transaction #%d in bunch", i);
				puts("");
			} else
				PRINTF("    (%ld bytes)\n", (long)xlen.value);
			chr  = (char *)buf;
			while (xptr < end)
			{
				fputc('\t', stdout);
				if ((len = (int)(end - xptr)) > 20)
					len = 20;
				memcpy(chr, xptr, len);
				xptr += len;
				for (j = len; j < 20; j++)
					chr[j] = '\0';
				for (j = 0; j < 5; j++)
					PRINTF("%08x ", buf[j]);
				for (j = 0; j < 20; j++)
				{
					if (j >= len)
						chr[j] = ' ';
					else if (chr[j] < 32 || chr[j] > 126)
						chr[j] = '.';
				}
				PRINTF("%20s\n", chr);
			}
			bptr += xlen.value + 4;
			blen -= xlen.value + 4;
		}
		if (argc == 3)
			bunches = 1;
		n++;
	}
	return 0;
}
Пример #19
0
static int log_get_matched_files(LogContext *pContext,
        const int prefix_len, const int days_before,
        struct log_filename_array *filename_array)
{
    char rotate_time_format_prefix[32];
	char log_filepath[MAX_PATH_SIZE];
	char filename_prefix[MAX_PATH_SIZE + 32];
    int prefix_filename_len;
    int result;
    int len;
    char *p;
    char *log_filename;
    char *filename;
    DIR *dir;
    struct dirent ent;
    struct dirent *pEntry;
    time_t the_time;
	struct tm tm;

    filename_array->filenames = NULL;
    filename_array->count = 0;
    filename_array->size = 0;

    p = strrchr(pContext->log_filename, '/');
    if (p == NULL)
    {
        *log_filepath = '.';
        *(log_filepath + 1) = '/';
        *(log_filepath + 2) = '\0';
        log_filename = pContext->log_filename;
    }
    else
    {
        int path_len;
        path_len = (p - pContext->log_filename) + 1;
        memcpy(log_filepath, pContext->log_filename, path_len);
        *(log_filepath + path_len) = '\0';
        log_filename = p + 1;
    }

    memcpy(rotate_time_format_prefix, pContext->rotate_time_format, prefix_len);
    *(rotate_time_format_prefix + prefix_len) = '\0';

    dir = opendir(log_filepath);
    if (dir == NULL)
    {
        fprintf(stderr, "file: "__FILE__", line: %d, " \
                "opendir %s fail, errno: %d, error info: %s\n", \
                __LINE__, log_filepath, errno, STRERROR(errno));
        return errno != 0 ? errno : ENOENT;
    }

    result = 0;
    the_time = get_current_time() - days_before * 86400;
    localtime_r(&the_time, &tm);
    memset(filename_prefix, 0, sizeof(filename_prefix));
    len = sprintf(filename_prefix, "%s.", log_filename);
    strftime(filename_prefix + len, sizeof(filename_prefix) - len,
            rotate_time_format_prefix, &tm);
    prefix_filename_len = strlen(filename_prefix);
    while (readdir_r(dir, &ent, &pEntry) == 0)
    {
        if (pEntry == NULL)
        {
            break;
        }

        if ((int)strlen(pEntry->d_name) >= prefix_filename_len &&
                memcmp(pEntry->d_name, filename_prefix,
                    prefix_filename_len) == 0)
        {
            if ((result=log_check_filename_array_size(filename_array)) != 0)
            {
                break;
            }

            filename = strdup(pEntry->d_name);
            if (filename == NULL)
            {
                fprintf(stderr, "file: "__FILE__", line: %d, " \
                        "strdup %s fail, errno: %d, error info: %s\n", \
                        __LINE__, pEntry->d_name, errno, STRERROR(errno));
                break;
            }
            filename_array->filenames[filename_array->count] = filename;
            filename_array->count++;
        }
    }

    closedir(dir);
    return result;
}
Пример #20
0
boolean_t iosocket_wait(io_desc *iod, int4 timepar)
{
	struct 	timeval  	utimeout;
	ABS_TIME		cur_time, end_time;
	struct 	sockaddr_storage    	peer;           /* socket address + port */
	fd_set    		tcp_fd;
	d_socket_struct 	*dsocketptr;
	socket_struct   	*socketptr, *newsocketptr;
	socket_interrupt	*sockintr;
	char            	*errptr;
	int4            	errlen, ii, msec_timeout;
	int			rv, max_fd, len;
	GTM_SOCKLEN_TYPE	size;
	boolean_t		zint_restart;
	mv_stent		*mv_zintdev;
	int			retry_num;
	struct sockaddr		*peer_sa_ptr;
	char			port_buffer[NI_MAXSERV], ipaddr[SA_MAXLEN + 1];
	int			errcode;

	/* check for validity */
	assert(iod->type == gtmsocket);
	dsocketptr = (d_socket_struct *)iod->dev_sp;
	sockintr = &dsocketptr->sock_save_state;
	peer_sa_ptr = ((struct sockaddr *)(&peer));

	/* Check for restart */
	if (!dsocketptr->mupintr)
		/* Simple path, no worries*/
		zint_restart = FALSE;
	else
	{       /* We have a pending wait restart of some sort - check we aren't recursing on this device */
		if (sockwhich_invalid == sockintr->who_saved)
			GTMASSERT;	/* Interrupt should never have an invalid save state */
		if (dollar_zininterrupt)
			rts_error_csa(CSA_ARG(NULL) VARLSTCNT(1) ERR_ZINTRECURSEIO);
		if (sockwhich_wait != sockintr->who_saved)
			GTMASSERT;      /* ZINTRECURSEIO should have caught */
		DBGSOCK((stdout, "socwait: *#*#*#*#*#*#*#  Restarted interrupted wait\n"));
		mv_zintdev = io_find_mvstent(iod, FALSE);
		if (mv_zintdev)
		{
			if (sockintr->end_time_valid)
				/* Restore end_time for timeout */
				end_time = sockintr->end_time;

			/* Done with this mv_stent. Pop it off if we can, else mark it inactive. */
			if (mv_chain == mv_zintdev)
				POP_MV_STENT();         /* pop if top of stack */
			else
			{       /* else mark it unused */
				mv_zintdev->mv_st_cont.mvs_zintdev.buffer_valid = FALSE;
				mv_zintdev->mv_st_cont.mvs_zintdev.io_ptr = NULL;
			}
			zint_restart = TRUE;
			DBGSOCK((stdout, "socwait: mv_stent found - endtime: %d/%d\n", end_time.at_sec, end_time.at_usec));
		} else
			DBGSOCK((stdout, "socwait: no mv_stent found !!\n"));
		dsocketptr->mupintr = FALSE;
		sockintr->who_saved = sockwhich_invalid;
	}
	/* check for events */
	FD_ZERO(&tcp_fd);
	while (TRUE)
	{
		max_fd = 0;
		for (ii = 0; ii < dsocketptr->n_socket; ii++)
		{
			socketptr = dsocketptr->socket[ii];
			if ((socket_listening == socketptr->state) || (socket_connected == socketptr->state))
			{
				FD_SET(socketptr->sd, &tcp_fd);
				max_fd = MAX(max_fd, socketptr->sd);
			}
		}
		utimeout.tv_sec = timepar;
		utimeout.tv_usec = 0;
		msec_timeout = timeout2msec(timepar);
		sys_get_curr_time(&cur_time);
		if (!zint_restart || !sockintr->end_time_valid)
			add_int_to_abs_time(&cur_time, msec_timeout, &end_time);
		else
		{       /* end_time taken from restart data. Compute what msec_timeout should be so timeout timer
					   gets set correctly below.
			*/
			DBGSOCK((stdout, "socwait: Taking timeout end time from wait restart data\n"));
			cur_time = sub_abs_time(&end_time, &cur_time);
			if (0 > cur_time.at_sec)
			{
				msec_timeout = -1;
				utimeout.tv_sec = 0;
				utimeout.tv_usec = 0;
			} else
			{
				msec_timeout = (int4)(cur_time.at_sec * 1000 + cur_time.at_usec / 1000);
				utimeout.tv_sec = cur_time.at_sec;
				utimeout.tv_usec = (gtm_tv_usec_t)cur_time.at_usec;
			}
		}
		sockintr->end_time_valid = FALSE;
		for ( ; ; )
		{
			rv = select(max_fd + 1, (void *)&tcp_fd, (void *)0, (void *)0,
				    (timepar == NO_M_TIMEOUT ? (struct timeval *)0 : &utimeout));
			if (0 > rv && EINTR == errno)
			{
				if (0 != outofband)
				{
					DBGSOCK((stdout, "socwait: outofband interrupt received (%d) -- "
						 "queueing mv_stent for wait intr\n", outofband));
					PUSH_MV_STENT(MVST_ZINTDEV);
					mv_chain->mv_st_cont.mvs_zintdev.io_ptr = iod;
					mv_chain->mv_st_cont.mvs_zintdev.buffer_valid = FALSE;
					sockintr->who_saved = sockwhich_wait;
					sockintr->end_time = end_time;
					sockintr->end_time_valid = TRUE;
					dsocketptr->mupintr = TRUE;
					socketus_interruptus++;
					DBGSOCK((stdout, "socwait: mv_stent queued - endtime: %d/%d  interrupts: %d\n",
						 end_time.at_sec, end_time.at_usec, socketus_interruptus));
					outofband_action(FALSE);
					GTMASSERT;      /* Should *never* return from outofband_action */
					return FALSE;   /* For the compiler.. */
				}
				sys_get_curr_time(&cur_time);
				cur_time = sub_abs_time(&end_time, &cur_time);
				if (0 > cur_time.at_sec)
				{
					rv = 0;		/* time out */
					break;
				}
				utimeout.tv_sec = cur_time.at_sec;
				utimeout.tv_usec = (gtm_tv_usec_t)cur_time.at_usec;
			} else
				break;	/* either other error or done */
		}
		if (rv == 0)
		{
			iod->dollar.key[0] = '\0';
			return FALSE;
		} else  if (rv < 0)
		{
			errptr = (char *)STRERROR(errno);
			errlen = STRLEN(errptr);
			rts_error_csa(CSA_ARG(NULL) VARLSTCNT(6) ERR_SOCKWAIT, 0, ERR_TEXT, 2, errlen, errptr);
			return FALSE;
		}
		/* find out which socket is ready */
		for (ii = 0; ii < dsocketptr->n_socket; ii++)
		{
			socketptr = dsocketptr->socket[ii];
			if (0 != FD_ISSET(socketptr->sd, &tcp_fd))
				break;
		}
		assert(ii < dsocketptr->n_socket);
		if (socket_listening == socketptr->state)
		{
			if (gtm_max_sockets <= dsocketptr->n_socket)
			{
				rts_error_csa(CSA_ARG(NULL) VARLSTCNT(3) ERR_SOCKMAX, 1, gtm_max_sockets);
				return FALSE;
			}

			size = SIZEOF(struct sockaddr_storage);
			rv = tcp_routines.aa_accept(socketptr->sd, peer_sa_ptr, &size);
			if (-1 == rv)
			{
#				ifdef __hpux
				if (ENOBUFS == errno)
					continue;	/* On HP-UX, ENOBUFS may indicate a transient condition; retry */
#				endif
				errptr = (char *)STRERROR(errno);
				errlen = STRLEN(errptr);
				rts_error_csa(CSA_ARG(NULL) VARLSTCNT(6) ERR_SOCKACPT, 0, ERR_TEXT, 2, errlen, errptr);
				return FALSE;
			}
			SOCKET_DUP(socketptr, newsocketptr);
			newsocketptr->sd = rv;
			SOCKET_ADDR_COPY(newsocketptr->remote, peer_sa_ptr, size);
			/* translate internal address to numeric ip address */
			GETNAMEINFO(peer_sa_ptr, size, ipaddr, SA_MAXLEN, NULL, 0, NI_NUMERICHOST, errcode);
			if (0 != errcode)
			{
				SOCKET_FREE(newsocketptr);
				RTS_ERROR_ADDRINFO(NULL, ERR_GETNAMEINFO, errcode);
				return FALSE;
			}
			if (NULL != newsocketptr->remote.saddr_ip)
				free(newsocketptr->remote.saddr_ip);
			STRNDUP(ipaddr, SA_MAXLEN, newsocketptr->remote.saddr_ip);
			/* translate internal address to port number*/
			GETNAMEINFO(peer_sa_ptr, size, NULL, 0, port_buffer, NI_MAXSERV, NI_NUMERICSERV, errcode);
			if (0 != errcode)
			{
				SOCKET_FREE(newsocketptr);
				RTS_ERROR_ADDRINFO(NULL, ERR_GETNAMEINFO, errcode);
				return FALSE;
			}
			newsocketptr->remote.port = ATOI(port_buffer);
			newsocketptr->state = socket_connected;
			newsocketptr->passive = FALSE;
			newsocketptr->first_read = newsocketptr->first_write = TRUE;
			/* put the new-born socket to the list and create a handle for it */
			iosocket_handle(newsocketptr->handle, &newsocketptr->handle_len, TRUE, dsocketptr);
			dsocketptr->socket[dsocketptr->n_socket++] = newsocketptr;
			dsocketptr->current_socket = dsocketptr->n_socket - 1;
			len = SIZEOF(CONNECTED) - 1;
			memcpy(&iod->dollar.key[0], CONNECTED, len);
			iod->dollar.key[len++] = '|';
			memcpy(&iod->dollar.key[len], newsocketptr->handle, newsocketptr->handle_len);
			len += newsocketptr->handle_len;
			iod->dollar.key[len++] = '|';
			strncpy(&iod->dollar.key[len], newsocketptr->remote.saddr_ip, DD_BUFLEN - 1 - len);
			iod->dollar.key[DD_BUFLEN-1] = '\0';		/* In case we fill the buffer */
		} else
		{
			assert(socket_connected == socketptr->state);
			dsocketptr->current_socket = ii;
			len = SIZEOF(READ) - 1;
			memcpy(&iod->dollar.key[0], READ, len);
			iod->dollar.key[len++] = '|';
			memcpy(&iod->dollar.key[len], socketptr->handle, socketptr->handle_len);
			len += socketptr->handle_len;
			iod->dollar.key[len++] = '|';
			if (NULL != socketptr->remote.saddr_ip)
			{
				strncpy(&iod->dollar.key[len], socketptr->remote.saddr_ip, DD_BUFLEN - 1 - len);
				iod->dollar.key[DD_BUFLEN-1] = '\0';
			} else
				iod->dollar.key[len] = '\0';
		}
		break;
	}
Пример #21
0
static int log_fsync(LogContext *pContext, const bool bNeedLock)
{
	int result;
	int lock_res;
	int write_bytes;
    int written;

	if (pContext->pcurrent_buff - pContext->log_buff == 0)
	{
		if (!pContext->rotate_immediately)
		{
			return 0;
		}
		else
		{
            if (bNeedLock)
            {
                pthread_mutex_lock(&(pContext->log_thread_lock));
            }
            result = log_check_rotate(pContext);
            if (bNeedLock)
            {
                pthread_mutex_unlock(&(pContext->log_thread_lock));
            }
            return result;
		}
	}

	if (bNeedLock && ((lock_res=pthread_mutex_lock( \
			&(pContext->log_thread_lock))) != 0))
	{
		fprintf(stderr, "file: "__FILE__", line: %d, " \
			"call pthread_mutex_lock fail, " \
			"errno: %d, error info: %s", \
			__LINE__, lock_res, STRERROR(lock_res));
	}

	write_bytes = pContext->pcurrent_buff - pContext->log_buff;
    pContext->current_size += write_bytes;
	if (pContext->rotate_size > 0)
	{
		if (pContext->current_size > pContext->rotate_size)
		{
			pContext->rotate_immediately = true;
			log_check_rotate(pContext);
		}
	}

	result = 0;
    written = write(pContext->log_fd, pContext->log_buff, write_bytes);
	pContext->pcurrent_buff = pContext->log_buff;
	if (written != write_bytes)
	{
		result = errno != 0 ? errno : EIO;
		fprintf(stderr, "file: "__FILE__", line: %d, " \
			"call write fail, errno: %d, error info: %s\n",\
			 __LINE__, result, STRERROR(result));
	}

	if (pContext->rotate_immediately)
	{
		log_check_rotate(pContext);
	}

	if (bNeedLock && ((lock_res=pthread_mutex_unlock( \
			&(pContext->log_thread_lock))) != 0))
	{
		fprintf(stderr, "file: "__FILE__", line: %d, " \
			"call pthread_mutex_unlock fail, " \
			"errno: %d, error info: %s", \
			__LINE__, lock_res, STRERROR(lock_res));
	}

	return result;
}
Пример #22
0
int ldap_pvt_get_hname(
	const struct sockaddr *sa,
	int len,
	char *name,
	int namelen,
	char **err )
{
	int rc;
#if defined( HAVE_GETNAMEINFO )

#if defined( LDAP_R_COMPILE )
	ldap_pvt_thread_mutex_lock( &ldap_int_resolv_mutex );
#endif
	rc = getnameinfo( sa, len, name, namelen, NULL, 0, 0 );
#if defined( LDAP_R_COMPILE )
	ldap_pvt_thread_mutex_unlock( &ldap_int_resolv_mutex );
#endif
	if ( rc ) *err = (char *)AC_GAI_STRERROR( rc );
	return rc;

#else /* !HAVE_GETNAMEINFO */
	char *addr;
	int alen;
	struct hostent *hp = NULL;
#ifdef HAVE_GETHOSTBYADDR_R
	struct hostent hb;
	int buflen=BUFSTART, h_errno;
	char *buf=NULL;
#endif

#ifdef LDAP_PF_INET6
	if (sa->sa_family == AF_INET6) {
		struct sockaddr_in6 *sin = (struct sockaddr_in6 *)sa;
		addr = (char *)&sin->sin6_addr;
		alen = sizeof(sin->sin6_addr);
	} else
#endif
	if (sa->sa_family == AF_INET) {
		struct sockaddr_in *sin = (struct sockaddr_in *)sa;
		addr = (char *)&sin->sin_addr;
		alen = sizeof(sin->sin_addr);
	} else {
		rc = NO_RECOVERY;
		*err = (char *)HSTRERROR( rc );
		return rc;
	}
#if defined( HAVE_GETHOSTBYADDR_R )
	for(;buflen<BUFMAX;) {
		if (safe_realloc( &buf, buflen )==NULL) {
			*err = (char *)STRERROR( ENOMEM );
			return ENOMEM;
		}
#if (GETHOSTBYADDR_R_NARGS < 8)
		hp=gethostbyaddr_r( addr, alen, sa->sa_family,
			&hb, buf, buflen, &h_errno );
		rc = (hp == NULL) ? -1 : 0;
#else
		rc = gethostbyaddr_r( addr, alen, sa->sa_family,
			&hb, buf, buflen, 
			&hp, &h_errno );
#endif
#ifdef NETDB_INTERNAL
		if ((rc<0) &&
			(h_errno==NETDB_INTERNAL) &&
			(errno==ERANGE))
		{
			buflen*=2;
			continue;
		}
#endif
		break;
	}
	if (hp) {
		strncpy( name, hp->h_name, namelen );
	} else {
		*err = (char *)HSTRERROR( h_errno );
	}
	LDAP_FREE(buf);
#else /* HAVE_GETHOSTBYADDR_R */

#if defined( LDAP_R_COMPILE )
	ldap_pvt_thread_mutex_lock( &ldap_int_resolv_mutex );
#endif
	hp = gethostbyaddr( addr, alen, sa->sa_family );
	if (hp) {
		strncpy( name, hp->h_name, namelen );
		rc = 0;
	} else {
		rc = h_errno;
		*err = (char *)HSTRERROR( h_errno );
	}
#if defined( LDAP_R_COMPILE )
	ldap_pvt_thread_mutex_unlock( &ldap_int_resolv_mutex );
#endif

#endif	/* !HAVE_GETHOSTBYADDR_R */
	return rc;
#endif	/* !HAVE_GETNAMEINFO */
}
Пример #23
0
int main(int argc, char *argv[])
{
	char *conf_filename;
	char *local_filename;
	char group_name[FDFS_GROUP_NAME_MAX_LEN + 1];
	ConnectionInfo *pTrackerServer;
	int result;
	int store_path_index;
	ConnectionInfo storageServer;
	char file_id[128];
	
	if (argc < 3)
	{
		printf("Usage: %s <config_file> <local_filename>\n", argv[0]);
		return 1;
	}

	log_init();
	g_log_context.log_level = LOG_ERR;
	ignore_signal_pipe();

	conf_filename = argv[1];
	if ((result=fdfs_client_init(conf_filename)) != 0)
	{
		return result;
	}

	pTrackerServer = tracker_get_connection();
	if (pTrackerServer == NULL)
	{
		fdfs_client_destroy();
		return errno != 0 ? errno : ECONNREFUSED;
	}


	*group_name = '\0';
	store_path_index = 0;
	if ((result=tracker_query_storage_store(pTrackerServer, \
	                &storageServer, group_name, &store_path_index)) != 0)
	{
		fdfs_client_destroy();
		fprintf(stderr, "tracker_query_storage fail, " \
			"error no: %d, error info: %s\n", \
			result, STRERROR(result));
		return result;
	}

	local_filename = argv[2];
	result = storage_upload_appender_by_filename1(pTrackerServer, \
			&storageServer, store_path_index, \
			local_filename, NULL, \
			NULL, 0, group_name, file_id);
	if (result != 0)
	{
		fprintf(stderr, "upload file fail, " \
			"error no: %d, error info: %s\n", \
			result, STRERROR(result));

		tracker_disconnect_server_ex(pTrackerServer, true);
		fdfs_client_destroy();
		return result;
	}

	printf("%s\n", file_id);

	tracker_disconnect_server_ex(pTrackerServer, true);
	fdfs_client_destroy();

	return 0;
}
Пример #24
0
/* perform kick/kill a laggard readers */
static int
mdb_oom_handler(MDB_env *env, int pid, void* thread_id, size_t txnid, unsigned gap, int retry)
{
	uint64_t now_ns = ldap_now_steady_ns();
	struct mdb_info *mdb = mdb_env_get_userctx(env);

	if (retry < 0) {
		double elapsed = (now_ns - mdb->mi_oom_timestamp_ns) * 1e-9;
		const char* suffix = "s";
		if (elapsed < 1) {
			elapsed *= 1000;
			suffix = "ms";
		}

		if (gap) {
			Debug( LDAP_DEBUG_ANY, "oom-handler: done, txnid %zu, got/forward %u, elapsed/waited %.3f%s, %d retries\n",
				   txnid, gap, elapsed, suffix, -retry );
		} else {
			Debug( LDAP_DEBUG_ANY, "oom-handler: unable, txnid %zu, elapsed/waited %.3f%s, %d retries\n",
				   txnid, elapsed, suffix, -retry );
		}

		mdb->mi_oom_timestamp_ns = 0;
		return 0;
	}

	if (! mdb->mi_oom_flags)
		return -1;
	else if (! mdb->mi_oom_timestamp_ns) {
		mdb->mi_oom_timestamp_ns = now_ns;
		Debug( LDAP_DEBUG_ANY, "oom-handler: begin, txnid %zu lag %u\n",
			   txnid, gap );
	}

	if ( (mdb->mi_oom_flags & MDBX_OOM_KILL) && pid != getpid() ) {
		if ( kill( pid, SIGKILL ) == 0 ) {
			Debug( LDAP_DEBUG_ANY, "oom-handler: txnid %zu lag %u, KILLED pid %i\n",
				   txnid, gap, pid );
			ldap_pvt_thread_yield();
			return 2;
		}
		if ( errno == ESRCH )
			return 0;
		Debug( LDAP_DEBUG_ANY, "oom-handler: retry %d, UNABLE kill pid %i: %s\n",
			   retry, pid, STRERROR(errno) );
	}

	if ( (mdb->mi_oom_flags & MDBX_OOM_YIELD) && ! slapd_shutdown ) {
		if (retry == 0)
			Debug( LDAP_DEBUG_ANY, "oom-handler: txnid %zu lag %u, WAITING\n",
				   txnid, gap );
		if (retry < 42)
			ldap_pvt_thread_yield();
		else
			usleep(retry);
		return 0;
	}

	mdb->mi_oom_timestamp_ns = 0;
	return -1;
}
static struct mpool_node *malloc_mpool(const int total_alloc_size)
{
	struct fast_task_info *pTask;
	char *p;
	char *pCharEnd;
	struct mpool_node *mpool;

	mpool = (struct mpool_node *)malloc(sizeof(struct mpool_node));
	if (mpool == NULL)
	{
		logError("file: "__FILE__", line: %d, " \
			"malloc %d bytes fail, " \
			"errno: %d, error info: %s", \
			__LINE__, (int)sizeof(struct mpool_node), \
			errno, STRERROR(errno));
		return NULL;
	}

	mpool->next = NULL;
	mpool->blocks = (struct fast_task_info *)malloc(total_alloc_size);
	if (mpool->blocks == NULL)
	{
		logError("file: "__FILE__", line: %d, " \
			"malloc %d bytes fail, " \
			"errno: %d, error info: %s", \
			__LINE__, total_alloc_size, \
			errno, STRERROR(errno));
		free(mpool);
		return NULL;
	}
	memset(mpool->blocks, 0, total_alloc_size);

	pCharEnd = ((char *)mpool->blocks) + total_alloc_size;
	for (p=(char *)mpool->blocks; p<pCharEnd; p += g_free_queue.block_size)
	{
		pTask = (struct fast_task_info *)p;
		pTask->size = g_free_queue.min_buff_size;

		pTask->arg = p + ALIGNED_TASK_INFO_SIZE;
		if (g_free_queue.malloc_whole_block)
		{
			pTask->data = (char *)pTask->arg + \
					g_free_queue.arg_size;
		}
		else
		{
			pTask->data = (char *)malloc(pTask->size);
			if (pTask->data == NULL)
			{
				char *pt;

				logError("file: "__FILE__", line: %d, " \
					"malloc %d bytes fail, " \
					"errno: %d, error info: %s", \
					__LINE__, pTask->size, \
					errno, STRERROR(errno));

				for (pt=(char *)mpool->blocks; pt < p; \
					pt += g_free_queue.block_size)
				{
					free(((struct fast_task_info *)pt)->data);
				}

				free(mpool->blocks);
				free(mpool);
				return NULL;
			}
		}
	}

	mpool->last_block = (struct fast_task_info *)(pCharEnd - g_free_queue.block_size);
	for (p=(char *)mpool->blocks; p<(char *)mpool->last_block; p += g_free_queue.block_size)
	{
		pTask = (struct fast_task_info *)p;
		pTask->next = (struct fast_task_info *)(p + g_free_queue.block_size);
	}
	mpool->last_block->next = NULL;

	return mpool;
}
/**
 * We've received an on-demand encoded block from the datastore.
 * Attempt to do on-demand encoding and (if successful), call the
 * continuation with the resulting block.  On error, clean up and ask
 * the datastore for more results.
 *
 * @param key key for the content
 * @param size number of bytes in data
 * @param data content stored
 * @param type type of the content
 * @param priority priority of the content
 * @param anonymity anonymity-level for the content
 * @param expiration expiration time for the content
 * @param uid unique identifier for the datum;
 *        maybe 0 if no unique identifier is available
 * @param cont function to call with the actual block (at most once, on success)
 * @param cont_cls closure for cont
 * @return GNUNET_OK on success
 */
int
GNUNET_FS_handle_on_demand_block (const struct GNUNET_HashCode * key, uint32_t size,
                                  const void *data, enum GNUNET_BLOCK_Type type,
                                  uint32_t priority, uint32_t anonymity,
                                  struct GNUNET_TIME_Absolute expiration,
                                  uint64_t uid,
                                  GNUNET_DATASTORE_DatumProcessor cont,
                                  void *cont_cls)
{
  const struct OnDemandBlock *odb;
  struct GNUNET_HashCode nkey;
  struct GNUNET_CRYPTO_AesSessionKey skey;
  struct GNUNET_CRYPTO_AesInitializationVector iv;
  struct GNUNET_HashCode query;
  ssize_t nsize;
  char ndata[DBLOCK_SIZE];
  char edata[DBLOCK_SIZE];
  const char *fn;
  struct GNUNET_DISK_FileHandle *fh;
  uint64_t off;
  struct IndexInfo *ii;

  if (size != sizeof (struct OnDemandBlock))
  {
    GNUNET_break (0);
    GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1,
                             GNUNET_TIME_UNIT_FOREVER_REL, &remove_cont, NULL);
    return GNUNET_SYSERR;
  }
  odb = (const struct OnDemandBlock *) data;
  off = GNUNET_ntohll (odb->offset);
  ii = GNUNET_CONTAINER_multihashmap_get (ifm, &odb->file_id);
  if (NULL == ii)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  fn = ii->filename;
  if ((NULL == fn) || (0 != ACCESS (fn, R_OK)))
  {
    GNUNET_STATISTICS_update (GSF_stats,
                              gettext_noop
                              ("# index blocks removed: original file inaccessible"),
                              1, GNUNET_YES);
    GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1,
                             GNUNET_TIME_UNIT_FOREVER_REL, &remove_cont, NULL);
    return GNUNET_SYSERR;
  }
  if ((NULL ==
       (fh =
        GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ,
                               GNUNET_DISK_PERM_NONE))) ||
      (off != GNUNET_DISK_file_seek (fh, off, GNUNET_DISK_SEEK_SET)) ||
      (-1 == (nsize = GNUNET_DISK_file_read (fh, ndata, sizeof (ndata)))))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                _
                ("Could not access indexed file `%s' (%s) at offset %llu: %s\n"),
                GNUNET_h2s (&odb->file_id), fn, (unsigned long long) off,
                (fn == NULL) ? _("not indexed") : STRERROR (errno));
    if (fh != NULL)
      GNUNET_DISK_file_close (fh);
    GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1,
                             GNUNET_TIME_UNIT_FOREVER_REL, &remove_cont, NULL);
    return GNUNET_SYSERR;
  }
  GNUNET_DISK_file_close (fh);
  GNUNET_CRYPTO_hash (ndata, nsize, &nkey);
  GNUNET_CRYPTO_hash_to_aes_key (&nkey, &skey, &iv);
  GNUNET_CRYPTO_aes_encrypt (ndata, nsize, &skey, &iv, edata);
  GNUNET_CRYPTO_hash (edata, nsize, &query);
  if (0 != memcmp (&query, key, sizeof (struct GNUNET_HashCode)))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                _("Indexed file `%s' changed at offset %llu\n"), fn,
                (unsigned long long) off);
    GNUNET_DATASTORE_remove (dsh, key, size, data, -1, -1,
                             GNUNET_TIME_UNIT_FOREVER_REL, &remove_cont, NULL);
    return GNUNET_SYSERR;
  }
  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
              "On-demand encoded block for query `%s'\n", GNUNET_h2s (key));
  cont (cont_cls, key, nsize, edata, GNUNET_BLOCK_TYPE_FS_DBLOCK, priority,
        anonymity, expiration, uid);
  return GNUNET_OK;
}
Пример #27
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;
}
Пример #28
0
boolean_t iosocket_bind(socket_struct *socketptr, int4 timepar, boolean_t update_bufsiz)
{
	int			temp_1 = 1;
	char			*errptr;
	int4			errlen, msec_timeout, real_errno;
	short			len;
	in_port_t		actual_port;
	boolean_t		no_time_left = FALSE;
	d_socket_struct		*dsocketptr;
	struct addrinfo		*ai_ptr;
	char			port_buffer[NI_MAXSERV];
	int			errcode;
	ABS_TIME        	cur_time, end_time;
	GTM_SOCKLEN_TYPE	addrlen;
	GTM_SOCKLEN_TYPE	sockbuflen;

	dsocketptr = socketptr->dev;
	ai_ptr = (struct addrinfo*)(&socketptr->local.ai);
	assert(NULL != dsocketptr);
	dsocketptr->iod->dollar.key[0] = '\0';
	if (FD_INVALID != socketptr->temp_sd)
	{
		socketptr->sd = socketptr->temp_sd;
		socketptr->temp_sd = FD_INVALID;
	}
	if (timepar != NO_M_TIMEOUT)
	{
		msec_timeout = timeout2msec(timepar);
		sys_get_curr_time(&cur_time);
		add_int_to_abs_time(&cur_time, msec_timeout, &end_time);
	}

	do
	{
		temp_1 = 1;
		if (-1 == tcp_routines.aa_setsockopt(socketptr->sd,
				SOL_SOCKET, SO_REUSEADDR, &temp_1, SIZEOF(temp_1)))
		{
		        real_errno = errno;
			errptr = (char *)STRERROR(real_errno);
			errlen = STRLEN(errptr);
			SOCKET_FREE(socketptr);
			rts_error_csa(CSA_ARG(NULL) VARLSTCNT(7) ERR_SETSOCKOPTERR, 5,
					RTS_ERROR_LITERAL("SO_REUSEADDR"), real_errno, errlen, errptr);
			return FALSE;
		}
#ifdef TCP_NODELAY
		temp_1 = socketptr->nodelay ? 1 : 0;
		if (-1 == tcp_routines.aa_setsockopt(socketptr->sd,
				IPPROTO_TCP, TCP_NODELAY, &temp_1, SIZEOF(temp_1)))
		{
		        real_errno = errno;
			errptr = (char *)STRERROR(real_errno);
			errlen = STRLEN(errptr);
			SOCKET_FREE(socketptr);
			rts_error_csa(CSA_ARG(NULL) VARLSTCNT(7) ERR_SETSOCKOPTERR, 5,
					RTS_ERROR_LITERAL("TCP_NODELAY"), real_errno, errlen, errptr);
			return FALSE;
		}
#endif
		if (update_bufsiz)
		{
			if (-1 == tcp_routines.aa_setsockopt(socketptr->sd,
				SOL_SOCKET, SO_RCVBUF, &socketptr->bufsiz, SIZEOF(socketptr->bufsiz)))
			{
			        real_errno = errno;
				errptr = (char *)STRERROR(real_errno);
				errlen = STRLEN(errptr);
				SOCKET_FREE(socketptr);
				rts_error_csa(CSA_ARG(NULL) VARLSTCNT(7) ERR_SETSOCKOPTERR, 5,
						RTS_ERROR_LITERAL("SO_RCVBUF"), real_errno, errlen, errptr);
				return FALSE;
			}
		} else
		{
			sockbuflen = SIZEOF(socketptr->bufsiz);
			if (-1 == tcp_routines.aa_getsockopt(socketptr->sd,
				SOL_SOCKET, SO_RCVBUF, &socketptr->bufsiz, &sockbuflen))
			{
			        real_errno = errno;
				errptr = (char *)STRERROR(real_errno);
				errlen = STRLEN(errptr);
				SOCKET_FREE(socketptr);
				rts_error_csa(CSA_ARG(NULL) VARLSTCNT(7) ERR_GETSOCKOPTERR, 5,
					RTS_ERROR_LITERAL("SO_RCVBUF"), real_errno, errlen, errptr);
				return FALSE;
			}
		}
		temp_1 = tcp_routines.aa_bind(socketptr->sd, SOCKET_LOCAL_ADDR(socketptr), ai_ptr->ai_addrlen);
		if (temp_1 < 0)
		{
			real_errno = errno;
			no_time_left = TRUE;
			switch (real_errno)
			{
				case EADDRINUSE:
					if (NO_M_TIMEOUT != timepar)
					{
						sys_get_curr_time(&cur_time);
						cur_time = sub_abs_time(&end_time, &cur_time);
						if (cur_time.at_sec > 0)
							no_time_left = FALSE;
					}
					break;
				case EINTR:
					break;
				default:
					SOCKET_FREE(socketptr);
					rts_error_csa(CSA_ARG(NULL) VARLSTCNT(4) ERR_SOCKBIND, 0, real_errno, 0);
					break;
			}
			if (no_time_left)
				return FALSE;
			hiber_start(100);
			tcp_routines.aa_close(socketptr->sd);
			if (-1 == (socketptr->sd = tcp_routines.aa_socket(ai_ptr->ai_family,ai_ptr->ai_socktype,
									  ai_ptr->ai_protocol)))
			{
				real_errno = errno;
				errptr = (char *)STRERROR(real_errno);
				errlen = STRLEN(errptr);
				SOCKET_FREE(socketptr);
				rts_error_csa(CSA_ARG(NULL) VARLSTCNT(5) ERR_SOCKINIT, 3, real_errno, errlen, errptr);
				return FALSE;
			}
		}
	} while (temp_1 < 0);

	/* obtain actual port from the bound address if port 0 was specified */
	addrlen = SOCKET_ADDRLEN(socketptr, ai_ptr, local);
	if (-1 == tcp_routines.aa_getsockname(socketptr->sd, SOCKET_LOCAL_ADDR(socketptr), &addrlen))
	{
		real_errno = errno;
		errptr = (char *)STRERROR(real_errno);
		errlen = STRLEN(errptr);
		rts_error_csa(CSA_ARG(NULL) VARLSTCNT(5) ERR_GETSOCKNAMERR, 3, real_errno, errlen, errptr);
	        return FALSE;
	}
	assert(ai_ptr->ai_addrlen == addrlen);
	GETNAMEINFO(SOCKET_LOCAL_ADDR(socketptr), addrlen, NULL, 0, port_buffer, NI_MAXSERV, NI_NUMERICSERV, errcode);
	if (0 != errcode)
	{
		SOCKET_FREE(socketptr);
		RTS_ERROR_ADDRINFO(NULL, ERR_GETNAMEINFO, errcode);
		return FALSE;
	}
	actual_port = ATOI(port_buffer);
	if (0 == socketptr->local.port)
		socketptr->local.port = actual_port;
	assert(socketptr->local.port == actual_port);
	socketptr->state = socket_bound;
	len = SIZEOF(BOUND) - 1;
        memcpy(&dsocketptr->iod->dollar.key[0], BOUND, len);
        dsocketptr->iod->dollar.key[len++] = '|';
        memcpy(&dsocketptr->iod->dollar.key[len], socketptr->handle, socketptr->handle_len);
        len += socketptr->handle_len;
        dsocketptr->iod->dollar.key[len++] = '|';
        SPRINTF(&dsocketptr->iod->dollar.key[len], "%d", socketptr->local.port);
	return TRUE;
}
Пример #29
0
int main(int argc, char *argv[])
{
	char *conf_filename;
	int result;
	char *op_type;
	char *tracker_server;
	int arg_index;
	char *group_name;

	if (argc < 2)
	{
		usage(argv);
		return 1;
	}

	tracker_server = NULL;
	conf_filename = argv[1];
	arg_index = 2;

	if (arg_index >= argc)
	{
		op_type = "list";
	}
	else
	{
		int len;

		len = strlen(argv[arg_index]); 
		if (len >= 2 && strncmp(argv[arg_index], "-h", 2) == 0)
		{
			if (len == 2)
			{
				arg_index++;
				if (arg_index >= argc)
				{
					usage(argv);
					return 1;
				}

				tracker_server = argv[arg_index++];
			}
			else
			{
				tracker_server = argv[arg_index] + 2;
				arg_index++;
			}

			if (arg_index < argc)
			{
				op_type = argv[arg_index++];
			}
			else
			{
				op_type = "list";
			}
		}
		else
		{
			op_type = argv[arg_index++];
		}
	}

	log_init();
	g_log_context.log_level = LOG_DEBUG;
	ignore_signal_pipe();

	if ((result=fdfs_client_init(conf_filename)) != 0)
	{
		return result;
	}
	load_log_level_ex(conf_filename);

	if (tracker_server == NULL)
	{
		if (g_tracker_group.server_count > 1)
		{
			srand(time(NULL));
			rand();  //discard the first
			g_tracker_group.server_index = (int)( \
				(g_tracker_group.server_count * (double)rand()) \
				/ (double)RAND_MAX);
		}
	}
	else
	{
		int i;
		char ip_addr[IP_ADDRESS_SIZE];

		*ip_addr = '\0';
		if (getIpaddrByName(tracker_server, ip_addr, sizeof(ip_addr)) \
			 == INADDR_NONE)
		{
			printf("resolve ip address of tracker server: %s " \
				"fail!\n", tracker_server);
			return 2;
		}

		for (i=0; i<g_tracker_group.server_count; i++)
		{
			if (strcmp(g_tracker_group.servers[i].ip_addr, \
					ip_addr) == 0)
			{
				g_tracker_group.server_index = i;
				break;
			}
		}

		if (i == g_tracker_group.server_count)
		{
			printf("tracker server: %s not exists!\n", tracker_server);
			return 2;
		}
	}

	printf("server_count=%d, server_index=%d\n", g_tracker_group.server_count, g_tracker_group.server_index);

	pTrackerServer = tracker_get_connection();
	if (pTrackerServer == NULL)
	{
		fdfs_client_destroy();
		return errno != 0 ? errno : ECONNREFUSED;
	}
	printf("\ntracker server is %s:%d\n\n", pTrackerServer->ip_addr, pTrackerServer->port);

	if (arg_index < argc)
	{
		group_name = argv[arg_index++];
	}
	else
	{
		group_name = NULL;
	}

	if (strcmp(op_type, "list") == 0)
	{
		if (group_name == NULL)
		{
			result = list_all_groups(NULL);
		}
		else
		{
			result = list_all_groups(group_name);
		}
	}
	else if (strcmp(op_type, "delete") == 0)
	{
		char *storage_id;
		if (arg_index >= argc)
		{
			usage(argv);
			return 1;
		}

		storage_id = argv[arg_index++];

		if ((result=tracker_delete_storage(&g_tracker_group, \
				group_name, storage_id)) == 0)
		{
			printf("delete storage server %s::%s success\n", \
				group_name, storage_id);
		}
		else
		{
			printf("delete storage server %s::%s fail, " \
				"error no: %d, error info: %s\n", \
				group_name, storage_id, \
				result, STRERROR(result));
		}
	}
	else if (strcmp(op_type, "set_trunk_server") == 0)
	{
		char *storage_id;
		char new_trunk_server_id[FDFS_STORAGE_ID_MAX_SIZE];

		if (group_name == NULL)
		{
			usage(argv);
			return 1;
		}
		if (arg_index >= argc)
		{
			storage_id = "";
		}
		else
		{
			storage_id = argv[arg_index++];
		}

		if ((result=tracker_set_trunk_server(&g_tracker_group, \
			group_name, storage_id, new_trunk_server_id)) == 0)
		{
			printf("set trunk server %s::%s success, " \
				"new trunk server: %s\n", group_name, \
				storage_id, new_trunk_server_id);
		}
		else
		{
			printf("set trunk server %s::%s fail, " \
				"error no: %d, error info: %s\n", \
				group_name, storage_id, \
				result, STRERROR(result));
		}
	}
	else
	{
		printf("Invalid command %s\n\n", op_type);
		usage(argv);
	}

	tracker_disconnect_server_ex(pTrackerServer, true);
	fdfs_client_destroy();
	return 0;
}
Пример #30
0
int tcpsetserveropt(int fd, const int timeout)
{
	int flags;
	int result;

	struct linger linger;
	struct timeval waittime;

/*
	linger.l_onoff = 1;
#ifdef OS_FREEBSD
	linger.l_linger = timeout * 100;
#else
	linger.l_linger = timeout;
#endif
*/
	linger.l_onoff = 0;
	linger.l_linger = 0;
	if (setsockopt(fd, SOL_SOCKET, SO_LINGER, \
                &linger, (socklen_t)sizeof(struct linger)) < 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"setsockopt failed, errno: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
		return errno != 0 ? errno : ENOMEM;
	}

	waittime.tv_sec = timeout;
	waittime.tv_usec = 0;
	if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO,
               &waittime, (socklen_t)sizeof(struct timeval)) < 0)
	{
		logWarning("file: "__FILE__", line: %d, " \
			"setsockopt failed, errno: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
	}

	if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO,
               &waittime, (socklen_t)sizeof(struct timeval)) < 0)
	{
		logWarning("file: "__FILE__", line: %d, " \
			"setsockopt failed, errno: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
	}

	flags = 1;
	if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, \
		(char *)&flags, sizeof(flags)) < 0)
	{
		logError("file: "__FILE__", line: %d, " \
			"setsockopt failed, errno: %d, error info: %s", \
			__LINE__, errno, STRERROR(errno));
		return errno != 0 ? errno : EINVAL;
	}

	if ((result=tcpsetkeepalive(fd, 2 * timeout + 1)) != 0)
	{
		return result;
	}

	return 0;
}