Пример #1
0
static int global_9p_mount(struct fs_mounter* mounter, int16_t fsuid, int16_t fsgid) {	
	int err = 0;
	char mount_buffer[MAX_MOUNT_ROOT_PATH], root_buffer[MAX_MOUNT_ROOT_PATH+6];
	struct nameidata nd;
	get_mount_root(mounter->params.mount_device, fsuid, fsgid, mount_buffer);
	err = path_lookup(mount_buffer, LOOKUP_FOLLOW | LOOKUP_DIRECTORY ,&nd);
	if ( err ) {
		minfo(ERR1, "Failed to lookup path %s: %d. Trying to create", mount_buffer, err);
		err = mk_dir(mount_buffer, 777);
	}
	if ( err ) {
		// TODO: For now, the dirs for mount have to be precreated.. they can be for example
		// auto created via a user-space controller. In kernel, we do not have access to mkdir, right?
		minfo(ERR1, "Failed to lookup path %s: %d. Creation failed.", mount_buffer, err);
		return err;
	}
	sprintf(root_buffer, "%s/root", mount_buffer);
	// TODO: In critical section so that we do not do multiple mounts
	err = path_lookup(root_buffer, LOOKUP_FOLLOW | LOOKUP_DIRECTORY ,&nd);	
	if ( err ) {
		// We've checked that "root"/root does not exist (We assume existence of a root dir in root of fs
		// => 9p is not yet globally mount => mount
		if ( (err = mount_9p_fs(mount_buffer, mounter, fsuid, fsgid)) ) {
			minfo(ERR1, "Mount failed with err %d", err);
			return err;
		}
	}		

	return 0;
}
Пример #2
0
int main()
{
    int sock;
    struct sockaddr_in server;

    char buffer[MAXBUF];
    //Создание сокета
    sock = socket(AF_INET , SOCK_STREAM , 0);
    if (sock == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created\n");

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons( 1234 );

    //Connect to remote server
    if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        perror("connect failed. Error");
        return 1;
    }

        bzero(buffer, MAXBUF);
        recv(sock , buffer , MAXBUF , 0); // прием слова
        puts(buffer);
        printf("Для получения справки введите команду help\n");
        while(1){
            bzero(buffer, MAXBUF);
            printf("Cmd: ");
            scanf("%s" , buffer);
            // команды
             if(strcmp(buffer, "view") == 0)
                    view_dir(buffer, sock, MAXBUF);
             else if(strcmp(buffer, "view_dir") == 0)
                    view_dir(buffer, sock, MAXBUF);
             else if(strcmp(buffer, "help") == 0)
                     get_help();
             else if(strcmp(buffer, "get_dir") == 0)
                    get_dir(buffer, sock, MAXBUF);
             else if(strcmp(buffer, "ch_dir") == 0)
                    ch_dir(buffer, sock, MAXBUF);
             else if(strcmp(buffer, "upload") == 0)
                    upload(buffer, MAXBUF, sock);
             else if(strcmp(buffer, "mk_dir") == 0)
                    mk_dir(buffer, MAXBUF, sock);
             else if(strcmp(buffer, "rm_dir") == 0)
                    rm_dir(buffer, MAXBUF, sock);
             else
                    printf("unknown comand\n");
             printf("Для получения справки введите команду help\n");
         }

         close(sock);
         return 0;
}
Пример #3
0
int Index::dump(const char *path)
{
    P_WARNING("start to dump Index");

    std::string path2;
    if (NULL == path) {
        path2 = m_dual_dir.writeable_path();
    } else {
        path2 = path;
    }
    for (size_t i = 0; i < m_index.size(); ++i)
    {
        if (m_index[i])
        {
            std::string dir = path2 + "/" + m_level2dirname[i];
            if (mk_dir(dir))
            {
                if (this->is_base_mode())
                {
                    m_index[i]->try2merge(true);
                }
                P_WARNING("start to dump at: %s", dir.c_str());
                m_index[i]->dump(dir.c_str());
                P_WARNING("dump ok at: %s", dir.c_str());
            }
        }
    }

    if (m_inc_reader.dumpMeta(path2.c_str(), m_conf.index_meta_file.c_str()) < 0)
    {
        P_WARNING("failed to dump increment reader meta");
        return -1;
    }
    FILE *fp = ::fopen((path2 + "/" + m_conf.index_meta_file.c_str()).c_str(), "a+");
    if (fp)
    {
        ::fprintf(fp, "\n");
        for (size_t i = 0; i < m_index.size(); ++i)
        {
            if (m_index[i])
            {
                ::fprintf(fp, "doc num of %s: %d\n",
                        m_level2dirname[i].c_str(), int(m_index[i]->doc_num()));
            }
        }
        ::fclose(fp);
    }

    if (NULL == path && m_dual_dir.switch_using() < 0)
    {
        P_WARNING("failed to switch using file");
    }

    P_WARNING("dump Index ok");
    return 0;
}
Пример #4
0
  void Forwarder::write_to_directory(const std::string &directory) const {
    std::string wd = get_working_directory();
    std::string absolute_dir_name;
    if(!directory[0] != '/')
      absolute_dir_name = wd + "/" + directory;
    else
      absolute_dir_name = directory;
    std::string data_structure_filename = absolute_dir_name + "/data_structure";
    std::string nStates2seq_absolute_dir_name = absolute_dir_name + "/nStates2seq";
    
    // create directory
    mk_dir(absolute_dir_name);
    mk_dir(nStates2seq_absolute_dir_name);

    // write basic data structure
    write_data_structure(data_structure_filename);

    // write nStates2seq
    write_seqs(nStates2seq_absolute_dir_name);
  }
Пример #5
0
static void inotify_delete_self(const char *name, const char *path)
{
	char filepath[PATH_MAX];

	mk_filename(filepath, PATH_MAX, path, "inotify_dir");
	if (mk_dir(name, filepath) < 0)
		return;
	inotify_exercise(name, filepath, filepath, "inotify_dir", inotify_delete_self_helper, IN_DELETE_SELF, NULL);
	/* We remove (again) in case the test failed */
	(void)rm_dir(name, filepath);
}
Пример #6
0
Файл: fs-up.c Проект: dpc/rdup
/* make (or delete) an object in the filesystem */
gboolean
mk_obj(FILE * in, char *p, struct rdup * e, GHashTable * uidhash,
       GHashTable * gidhash)
{
	if (opt_verbose >= 1 && e->f_name) {
		if (S_ISLNK(e->f_mode) || e->f_lnk)
			fprintf(stderr, "%s -> %s\n", e->f_name, e->f_target);
		else
			fprintf(stderr, "%s\n", e->f_name);
	}
	if (opt_table)
		rdup_write_table(e, stdout);

	/* split here - or above - return when path is zero length
	 * for links check that the f_size is zero */
	switch (e->plusmin) {
	case MINUS:
		if (opt_dry || !e->f_name)
			return TRUE;

		return rm(e->f_name);
	case PLUS:
		/* opt_dry handled within the subfunctions */

		/* only files, no hardlinks! */
		if (S_ISREG(e->f_mode) && !e->f_lnk)
			return mk_reg(in, e, uidhash, gidhash);

		/* no name, we can exit here - for files this is handled
		 * in mk_reg, because we may need to suck in data */
		if (e->f_name == NULL)
			return TRUE;

		if (S_ISDIR(e->f_mode))
			return mk_dir(e, uidhash, gidhash);

		/* First sym and hardlinks and then regular files */
		if (S_ISLNK(e->f_mode) || e->f_lnk)
			return mk_link(e, p, uidhash, gidhash);

		if (S_ISBLK(e->f_mode) || S_ISCHR(e->f_mode))
			return mk_dev(e, uidhash, gidhash);

		// There's no way to restore a named socket
		if (S_ISSOCK(e->f_mode))
			return TRUE;

		if (S_ISFIFO(e->f_mode))
			return mk_sock(e, uidhash, gidhash);
	}
	/* only reached during the heat death of the universe */
	return TRUE;
}
Пример #7
0
/* Create a new external memory list. */
static int em_list_create(em_list_t *self)
{
    mapped_file_t *mf;
    em_list_index_hdr_t index_hdr;
    em_list_values_hdr_t values_hdr;
    size_t size;
    char *filename;

    const char *dirname = self->dirname;

    /* Compute initial external memory list index size. */
    size = EM_LIST_E2S(0);

    /* Create directory to hold external memory list files. */
    if(mk_dir(dirname) != 0)
        goto _err1;

    /* Create "index.bin" and write file header. */
    filename = path_combine(dirname, "index.bin");
    if((mf = mapped_file_create(filename, size)) == NULL)
        goto _err2;

    index_hdr.magic = MAGIC;
    index_hdr.used = 0;
    index_hdr.capacity = 0;
    mapped_file_write(mf, &index_hdr, sizeof(em_list_index_hdr_t));

    self->index = mf;

    /* Create "values.bin" and write file header. */
    filename = path_combine(dirname, "values.bin");
    if((mf = mapped_file_create(filename, size)) == NULL)
        goto _err3;

    values_hdr.magic = MAGIC;
    mapped_file_write(mf, &values_hdr, sizeof(em_list_values_hdr_t));

    self->values = mf;
    return 0;

_err3:
    mapped_file_unlink(self->index);
    mapped_file_close(self->index);

_err2:
    rm_dir(dirname);

_err1:
    PyErr_SetString(PyExc_RuntimeError, "Cannot open EMList");
    return -1;
}
Пример #8
0
  void Forwarder::write_seqs(const std::string &nstates2seq_absolute_dir_name) const {
    for(std::map<size_t, std::vector<std::vector<unsigned> > >::const_iterator it = nStates2seqs.begin(); it != nStates2seqs.end(); ++it) {
      size_t nStates = (*it).first;
      const std::vector<std::vector<unsigned> > &sequences = (*it).second;      

      std::stringstream nStatesDirname_stream;
      nStatesDirname_stream << nstates2seq_absolute_dir_name << "/" << nStates;
      std::string nStatesDirname = nStatesDirname_stream.str();
      mk_dir(nStatesDirname);

      for(size_t i = 0; i < sequences.size(); ++i) {
	std::stringstream seq_filename_stream;
	seq_filename_stream << nStatesDirname << "/" << i << ".seq";
	
	write_seq(seq_filename_stream.str(), nStates, i);
      }
    }
  }
Пример #9
0
int main(int argc, char** argv) {
    int N = 256;
    std::string root;

    for (int i = 1; i < argc; ++i) {
        if (0 == strcmp(argv[i], "--size") && i+1 < argc) {
            N = atoi(argv[++i]);
        }
        if (0 == strcmp(argv[i], "--write") && i+1 < argc) {
            root = argv[++i];
        }
        
    }
    if (N < 1 || N > 1024) {
        fprintf(stderr, "specify a reasonable size for the image (e.g. 256)\n");
        return -1;
    }

    if (root.size() > 0 && root[root.size() - 1] != '/') {
        root += "/";
        if (!mk_dir(root.c_str())) {
            return -1;
        }
    }
    
    GBitmap bitmap;
    bitmap.fWidth = N;
    bitmap.fHeight = N;
    bitmap.fRowBytes = N * sizeof(GPixel);
    bitmap.fPixels = (GPixel*)malloc(bitmap.rowBytes() * bitmap.height());

    for (int i = 0; i < GARRAY_COUNT(gRec); ++i) {
        handle_proc(bitmap, gRec[i].fProc, root, gRec[i].fName);
    }
    
    free(bitmap.fPixels);
    return 0;
}
Пример #10
0
Файл: cd.c Проект: oleiade/Ash
int		built_in_cd(char **argv, t_sllist **myenv)
{
  char		*dir;

  if (argv[1] == 0)
    {
      if (xchdir(my_getenv("HOME", *myenv), myenv) == EXIT_FAILURE)
	return (EXIT_FAILURE);
    }
  else if (argv[2] == 0)
    {
      dir = mk_dir(argv[1], *myenv);
      if (xchdir(dir, myenv) == EXIT_FAILURE)
	return (EXIT_FAILURE);
      free(dir);
    }
  else if (argv[2] != 0)
    {
      fprintf(stderr, ERR_CDTOO_MANY);
      return (EXIT_FAILURE);
    }
  return (EXIT_SUCCESS);
}
Пример #11
0
static int
init_file_locking(struct lib_context *lc)
{
	int ret = 0;
	char *dir;

	if (!(dir = get_dirname(lc, lock_file)))
		return 0;

	if (!mk_dir(lc, dir))
		goto out;

	/* Fail on read-only file system. */
	if (access(dir, R_OK | W_OK) && errno == EROFS)
		goto out;

	lc->lock = &file_locking;
	ret = 1;

out:
	dbg_free(dir);

	return ret;
}
Пример #12
0
static void dump_data(struct dump_manager *manager, int section) {
	char buffer[256];
	char buffer1[256];
	FILE * file = NULL;
	struct dump* pdump = NULL;
	struct block * pblock = NULL;
	int i;
	int ack = 0;
	struct record_manager * record_manager = get_record_manager();
	struct block_filter * filter = manager->manager.fliters;
	if (section < 0 || section > 2)
		return;
	sprintf(buffer, "%s/%s/", MOUNT_POINT, manager->ID);

	if (mk_dir(buffer) == 0) {
		struct tm *tNow;
		tNow=&(manager->time_export);
		sprintf(buffer1, "%s/%04d-%02d-%02d %02d,%02d,%02d/",buffer, tNow->tm_year+1900, tNow->tm_mon+1, tNow->tm_mday, tNow->tm_hour, tNow->tm_min, tNow->tm_sec);
		if (mk_dir(buffer1) == 0) {

			switch (section) {
						case 0:
							sprintf(buffer, "%s/Menu.bin", buffer1);
							break;
						case 1:
							sprintf(buffer, "%s/Data.bin", buffer1);
							break;
						case 2:
							sprintf(buffer, "%s/Wave.bin", buffer1);
							break;
						}
		} else {
			switch (section) {
			case 0:
				sprintf(buffer, "%s/%s/Menu.bin", MOUNT_POINT, manager->ID);
				break;
			case 1:
				sprintf(buffer, "%s/%s/Data.bin", MOUNT_POINT, manager->ID);
				break;
			case 2:
				sprintf(buffer, "%s/%s/Wave.bin", MOUNT_POINT, manager->ID);
				break;
			}
		}

	} else {
		switch (section) {
		case 0:
			sprintf(buffer, "%s/Menu.bin", MOUNT_POINT);
			break;
		case 1:
			sprintf(buffer, "%s/Data.bin", MOUNT_POINT);
			break;
		case 2:
			sprintf(buffer, "%s/Wave.bin", MOUNT_POINT);
			break;
		}
	}

	for (i = 0; i < 3; i++) { //尝试3次
		request_data(record_manager, section, (char*) manager,
				sizeof(struct dump_manager));
		pblock = get_block(filter, 1000, BLOCK_FULL);
		if (pblock != NULL) {
			pdump = (struct dump*) pblock->data;
			if (pdump->type == section * 3) {
				ack = 1;
				put_block(pblock, BLOCK_EMPTY);
				break;
			} else {
				printf("ack type%d!\n", (char) pdump->type);
			}
			put_block(pblock, BLOCK_EMPTY);
		} else {
			printf("ack err%d!\n", i);
		}

	}
	if (ack == 0) {
		printf("ack err!\n");
		return;
	}

	file = fopen(buffer, "w+");

	if (file == NULL)
		return;
	while (1) {
		pblock = get_block(filter, 1000, BLOCK_FULL);
		if (pblock != NULL) {
			pdump = (struct dump*) pblock->data;
			if (pdump->type == (section * 3 + 2)) { //finished
				put_block(pblock, BLOCK_EMPTY);
				break;
			} else if (pdump->type == (section * 3 + 1)) {

				fwrite(pdump->data, pdump->length, 1, file);
				fflush(file);
			}
			put_block(pblock, BLOCK_EMPTY);
		} else {
			//printf("dump is null\n");
		}
	}

	fclose(file);

}
Пример #13
0
/**
 * This function will set a hook function, which will be invoked when a memory 
 * block is allocated from heap memory.
 * 
 * @param hook the hook function
 */
int efs_open(struct dfs_fd* file)
{
	File* efsfile;
	DirList* efsdir;
	efsl_fs* efsfs = (efsl_fs*)(file->fs->data);
	int result = 0;
	
	/* parameter check */
	if ( file == RT_NULL || file->fs == RT_NULL || 
		file->fs->data == RT_NULL ) 
	{	
		dfs_log(DFS_DEBUG_INFO, ("Invalid argument"));		
		return -DFS_STATUS_EINVAL;
	}

	/* open directory */
	if(file->flags & DFS_O_DIRECTORY)
	{
		/* write directory is not supported */
		if(file->flags & DFS_O_WRONLY || file->flags & DFS_O_RDWR)
		{
			dfs_log(DFS_DEBUG_INFO, ("write directory isn't supported"));			
			return -DFS_STATUS_EISDIR;
		}
		
		/* create directory */
		if(file->flags & DFS_O_CREAT)
		{
			dfs_log(DFS_DEBUG_INFO, ("create directory"));
			result = mk_dir(&efsfs->filesystem, file->path);
			if(result < 0) 
			{
				dfs_log(DFS_DEBUG_INFO, ("directory %s has existed", file->path));
				return -DFS_STATUS_EEXIST;
			}	
		}
		
		efsdir = (DirList*)rt_malloc(sizeof(DirList));
		if(efsdir == RT_NULL) 
		{
			dfs_log(DFS_DEBUG_INFO, ("memory alloc failed"));
			return -DFS_STATUS_ENOMEM;		
		}
		
		result = ls_openDir(efsdir, &efsfs->filesystem, file->path);
		if(result < 0)
		{
			dfs_log(DFS_DEBUG_INFO, ("open directory %s failed", file->path));
			rt_free(efsdir);
		}	
		else 
		{
			file->data = efsdir;
		}	
	}
	/* open file */
	else
	{
		efsfile = (File *)rt_malloc(sizeof(File));
		if (efsfile == RT_NULL) 
		{
			dfs_log(DFS_DEBUG_INFO, ("memory alloc failed"));			
			return -DFS_STATUS_ENOMEM;		
		}

		result = file_fopen(efsfile, &efsfs->filesystem, file->path, file->flags);
		if(result < 0)	
		{	
			dfs_log(DFS_DEBUG_INFO, ("open file %s failed", file->path));
			rt_free(efsfile);
		}	
		else
		{
			file->pos  = efsfile->FilePtr;
			file->size = efsfile->FileSize;
			file->data = efsfile;
		}
	}

	return result;
}
Пример #14
0
Файл: main.c Проект: alemic/zimg
/**
 * @brief main The entrance of zimg.
 *
 * @param argc Count of args.
 * @param argv Arg list.
 *
 * @return It returns a int to system.
 */
int main(int argc, char **argv)
{
    int c;
    _init_path = getcwd(NULL, 0);
    LOG_PRINT(LOG_INFO, "Get init-path: %s", _init_path);

    /* Set signal handlers */
    sigset_t sigset;
    sigemptyset(&sigset);
    struct sigaction siginfo = {
        .sa_handler = sighandler,
        .sa_mask = sigset,
        .sa_flags = SA_RESTART,
    };
    sigaction(SIGINT, &siginfo, NULL);
    sigaction(SIGTERM, &siginfo, NULL);


    settings_init();
    while (-1 != (c = getopt(argc, argv,
                    "p:"
                    "t:"
                    "l"
                    "c"
                    "M:"
                    "m:"
                    "b:"
                    "h"
                    "k:"
                    )))
    {
        switch(c)
        {
            case 'p':
                settings.port = atoi(optarg);
                break;
            case 't':
                settings.num_threads = atoi(optarg);
                if (settings.num_threads <= 0) {
                    fprintf(stderr, "Number of threads must be greater than 0\n");
                    return 1;
                }
                /* There're other problems when you get above 64 threads.
                 * In the future we should portably detect # of cores for the
                 * default.
                 */
                if (settings.num_threads > 64) {
                    fprintf(stderr, "WARNING: Setting a high number of worker"
                            "threads is not recommended.\n"
                            " Set this value to the number of cores in"
                            " your machine or less.\n");
                }
                break;
            case 'l':
                settings.log = true;
                break;
            case 'c':
                settings.cache_on = true;
                break;
            case 'M':
                strcpy(settings.cache_ip, optarg);
                break;
            case 'm':
                settings.cache_port = atoi(optarg);
                break;
            case 'b':
                settings.backlog = atoi(optarg);
                break;
            case 'k':
                settings.max_keepalives = atoll(optarg);
                break;
            case 'h':
                printf("Usage: ./zimg -p port -t thread_num -M memcached_ip -m memcached_port -l[og] -c[ache] -b backlog_num -k max_keepalives -h[elp]\n");
                exit(1);
            default:
                fprintf(stderr, "Illegal argument \"%c\"\n", c);
                return 1;
        }
    }
    //init the Path zimg need to use.
    LOG_PRINT(LOG_INFO, "Begin to Init the Path zimg Using...");
//    if(is_dir(settings.root_path) != 1)
//    {
//        if(mk_dir(settings.root_path) != 1)
//        {
//            LOG_PRINT(LOG_ERROR, "root_path[%s] Create Failed!", settings.root_path);
//            return -1;
//        }
//    }
//
//
    //start log module... ./log/zimg.log
    if(settings.log)
    {
        const char *log_path = "./log";
        if(is_dir(log_path) != 1)
        {
            if(mk_dir(log_path) != 1)
            {
                LOG_PRINT(LOG_ERROR, "log_path[%s] Create Failed!", log_path);
                return -1;
            }
        }
        log_init();
    }

    if(is_dir(settings.img_path) != 1)
    {
        if(mk_dir(settings.img_path) != 1)
        {
            LOG_PRINT(LOG_ERROR, "img_path[%s] Create Failed!", settings.img_path);
            return -1;
        }
    }
    LOG_PRINT(LOG_INFO,"Paths Init Finished.");

   
    //init memcached connection...
    if(settings.cache_on == true)
    {
        LOG_PRINT(LOG_INFO, "Begin to Init Memcached Connection...");
        memcached_st *memc;
        memc= memcached_create(NULL);

        char mserver[32];
        sprintf(mserver, "%s:%d", settings.cache_ip, settings.cache_port);
        memcached_server_st *servers = memcached_servers_parse(mserver);

        memcached_server_push(memc, servers);
        memcached_server_list_free(servers);
        memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0);
        //使用NO-BLOCK,防止memcache倒掉时挂死          
        memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_NO_BLOCK, 1); 
        LOG_PRINT(LOG_INFO, "Memcached Connection Init Finished.");
        if(set_cache("zimg", "1") == -1)
        {
            LOG_PRINT(LOG_WARNING, "Memcached[%s] Connect Failed!", mserver);
            settings.cache_on = false;
        }
        else
        {
            LOG_PRINT(LOG_INFO, "memcached connection to: %s", mserver);
            settings.cache_on = true;
        }
        memcached_free(memc);
    }
    else
        LOG_PRINT(LOG_INFO, "Don't use memcached as cache.");
    //init magickwand
    MagickWandGenesis();

    //begin to start httpd...
    LOG_PRINT(LOG_INFO, "Begin to Start Httpd Server...");
    evbase = event_base_new();
    evhtp_t  * htp    = evhtp_new(evbase, NULL);

    evhtp_set_cb(htp, "/dump", dump_request_cb, NULL);
    evhtp_set_cb(htp, "/upload", post_request_cb, NULL);
    //evhtp_set_gencb(htp, echo_cb, NULL);
    evhtp_set_gencb(htp, send_document_cb, NULL);
#ifndef EVHTP_DISABLE_EVTHR
    evhtp_use_threads(htp, NULL, settings.num_threads, NULL);
#endif
    evhtp_set_max_keepalive_requests(htp, settings.max_keepalives);
    evhtp_bind_socket(htp, "0.0.0.0", settings.port, settings.backlog);

    event_base_loop(evbase, 0);

    evhtp_unbind_socket(htp);
    evhtp_free(htp);
    event_base_free(evbase);
    MagickWandTerminus();

    fprintf(stdout, "\nByebye!\n");
    return 0;
}
Пример #15
0
/**
 * @brief main The entrance of zimg.
 *
 * @param argc Count of args.
 * @param argv Arg list.
 *
 * @return It returns a int to system.
 */
int main(int argc, char **argv)
{
    int i;
    retry_sleep.tv_sec = 0;
    retry_sleep.tv_nsec = RETRY_TIME_WAIT;      //1000 ns = 1 us

    /* Set signal handlers */
    sigset_t sigset;
    sigemptyset(&sigset);
    struct sigaction siginfo = {
        .sa_handler = sighandler,
        .sa_mask = sigset,
        .sa_flags = SA_RESTART,
    };
    sigaction(SIGINT, &siginfo, NULL);
    sigaction(SIGTERM, &siginfo, NULL);

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

    settings_init();
    const char *conf_file = NULL;
    for(i=1; i<argc; i++)
    {
        if(strcmp(argv[i], "-d") == 0){
            settings.is_daemon = 1;
        }else{
            conf_file = argv[i];
        }
    }

    if(conf_file == NULL)
    {
        usage(argc, argv);
        return -1;
    }

    if(is_file(conf_file) == -1)
    {
        fprintf(stderr, "'%s' is not a file or not exists!\n", conf_file);
        return -1;
    }

    if(load_conf(conf_file) == -1)
    {
        fprintf(stderr, "'%s' load failed!\n", conf_file);
        return -1;
    }


    if(settings.is_daemon == 1)
    {
        if(daemon(1, 1) < 0)
        {
            fprintf(stderr, "Create daemon failed!\n");
            return -1;
        }
        else
        {
            fprintf(stdout, "zimg %s\n", settings.version);
            fprintf(stdout, "Copyright (c) 2013-2014 zimg.buaa.us\n");
            fprintf(stderr, "\n");
        }
    }
    //init the Path zimg need to use.
    LOG_PRINT(LOG_DEBUG, "Begin to Init the Path zimg Using...");
    //start log module... ./log/zimg.log
    if(settings.log)
    {
        const char *log_path = "./log";
        if(is_dir(log_path) != 1)
        {
            if(mk_dir(log_path) != 1)
            {
                LOG_PRINT(LOG_DEBUG, "log_path[%s] Create Failed!", log_path);
                fprintf(stderr, "log_path[%s] Create Failed!\n", log_path);
                return -1;
            }
        }
        log_init();
    }

    if(is_dir(settings.img_path) != 1)
    {
        if(mk_dir(settings.img_path) != 1)
        {
            LOG_PRINT(LOG_DEBUG, "img_path[%s] Create Failed!", settings.img_path);
            fprintf(stderr, "%s Create Failed!\n", settings.img_path);
            return -1;
        }
    }
    LOG_PRINT(LOG_DEBUG,"Paths Init Finished.");

    if(settings.mode == 2)
    {
        LOG_PRINT(LOG_DEBUG, "Begin to Test Memcached Connection...");
        memcached_st *beans = memcached_create(NULL);
        char mserver[32];
        snprintf(mserver, 32, "%s:%d", settings.beansdb_ip, settings.beansdb_port);
        memcached_server_st *servers = memcached_servers_parse(mserver);
        servers = memcached_servers_parse(mserver);
        memcached_server_push(beans, servers);
        memcached_server_list_free(servers);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_BINARY_PROTOCOL, 0);
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_NO_BLOCK, 1); 
        memcached_behavior_set(beans, MEMCACHED_BEHAVIOR_TCP_KEEPALIVE, 1); 
        LOG_PRINT(LOG_DEBUG, "beansdb Connection Init Finished.");
        if(set_cache(beans, "zimg", "1") == -1)
        {
            LOG_PRINT(LOG_DEBUG, "Beansdb[%s] Connect Failed!", mserver);
            fprintf(stderr, "Beansdb[%s] Connect Failed!\n", mserver);
            memcached_free(beans);
            return -1;
        }
        else
        {
            LOG_PRINT(LOG_DEBUG, "beansdb connected to: %s", mserver);
        }
        memcached_free(beans);
    }
    else if(settings.mode == 3)
    {
        redisContext* c = redisConnect(settings.ssdb_ip, settings.ssdb_port);
        if(c->err)
        {
            redisFree(c);
            LOG_PRINT(LOG_DEBUG, "Connect to ssdb server faile");
            fprintf(stderr, "SSDB[%s:%d] Connect Failed!\n", settings.ssdb_ip, settings.ssdb_port);
            return -1;
        }
        else
        {
            LOG_PRINT(LOG_DEBUG, "Connect to ssdb server Success");
        }
    }

    //init magickwand
    MagickWandGenesis();

    //begin to start httpd...
    LOG_PRINT(LOG_DEBUG, "Begin to Start Httpd Server...");
    LOG_PRINT(LOG_INFO, "zimg started");
    evbase = event_base_new();
    evhtp_t *htp = evhtp_new(evbase, NULL);

    evhtp_set_cb(htp, "/dump", dump_request_cb, NULL);
    evhtp_set_cb(htp, "/upload", post_request_cb, NULL);
    //evhtp_set_gencb(htp, echo_cb, NULL);
    evhtp_set_gencb(htp, send_document_cb, NULL);
#ifndef EVHTP_DISABLE_EVTHR
    evhtp_use_threads(htp, init_thread, settings.num_threads, NULL);
#endif
    evhtp_set_max_keepalive_requests(htp, settings.max_keepalives);
    evhtp_bind_socket(htp, "0.0.0.0", settings.port, settings.backlog);

    event_base_loop(evbase, 0);

    evhtp_unbind_socket(htp);
    evhtp_free(htp);
    event_base_free(evbase);
    MagickWandTerminus();
    free_access_conf(settings.up_access);
    free_access_conf(settings.down_access);

    fprintf(stdout, "\nByebye!\n");
    return 0;
}
Пример #16
0
  int main()
  {
    setlocale(LC_ALL, "Russian");
	  char buffer[MAXBUF];

    //инициализация библиотеки Winsock
    if (WSAStartup(0x202,(WSADATA *)&buffer[0]))
    {
      printf("WSAStart error %d\n",WSAGetLastError());
	  _getch();
      return -1;
    }

    //создание сокета
    SOCKET sock;
    sock=socket(AF_INET,SOCK_STREAM,0);
    if (sock < 0)
    {
      printf("Socket() error %d\n",WSAGetLastError());
	  _getch();
      return -1;
    }

    //установка соединения
    // заполнение структуры sockaddr_in
    // указание адреса и порта сервера
    sockaddr_in dest_addr;
    dest_addr.sin_family=AF_INET;
    dest_addr.sin_port=htons(PORT);
    HOSTENT *hst;

    // преобразование IP адреса из символьного в
    // сетевой формат
    if (inet_addr(SERVERADDR)!=INADDR_NONE)
      dest_addr.sin_addr.s_addr=inet_addr(SERVERADDR);
    else
      // попытка получить IP адрес по доменному
      // имени сервера
      if (hst=gethostbyname(SERVERADDR))
      // hst->h_addr_list содержит не массив адресов,
      // а массив указателей на адреса
      ((unsigned long *)&dest_addr.sin_addr)[0]=
        ((unsigned long **)hst->h_addr_list)[0][0];
      else 
      {
        printf("Invalid address %s\n",SERVERADDR);
        closesocket(sock);
        WSACleanup();
		_getch();
        return -1;
      }

    if (connect(sock,(sockaddr *)&dest_addr,
                sizeof(dest_addr)))
    {
      printf("Connect error %d\n",WSAGetLastError());
	  _getch();
      return -1;
    }

	//-----------------------------------------------
	memset(buffer, 0, MAXBUF);
    recv(sock , buffer , MAXBUF , 0); // прием слова
    puts(buffer);
    printf("Для получения справки введите команду help\n");
    while(1){
		memset(buffer, 0, MAXBUF);
        printf("Cmd: ");
        scanf("%s" , buffer);
        // команды
        if(strcmp(buffer, "view") == 0)
			view_dir(buffer, sock, MAXBUF);
        else if(strcmp(buffer, "view_dir") == 0)
            view_dir(buffer, sock, MAXBUF);
        else if(strcmp(buffer, "help") == 0)
            get_help();
        else if(strcmp(buffer, "get_dir") == 0)
            get_dir(buffer, sock, MAXBUF);
        else if(strcmp(buffer, "ch_dir") == 0)
            ch_dir(buffer, sock, MAXBUF);
        else if(strcmp(buffer, "upload") == 0)
            upload(buffer, MAXBUF, sock);
		else if(strcmp(buffer, "download") == 0)
            download(buffer, MAXBUF, sock);
        else if(strcmp(buffer, "mk_dir") == 0)
            mk_dir(buffer, MAXBUF, sock);
        else if(strcmp(buffer, "rm_dir") == 0)
            rm_dir(buffer, MAXBUF, sock);
		else if(strcmp(buffer, "echo") == 0)
            echo(buffer, sock, MAXBUF);
		else if(strcmp(buffer, "disconnect") == 0){
            send(sock, "disconnect", 10, 0);
			break;
		}
        else
            printf("unknown comand\n");
        printf("Для получения справки введите команду help\n");
    }
	//-----------------------------------------------
	printf("\nExit\n");
    closesocket(sock);
    WSACleanup();
	_getch();
    return 0;
  }