示例#1
0
文件: gamin.c 项目: GNOME/gamin
static void
do_connection(void)
{
    FAMConnection fc;
    FAMRequest fr;
    int data;
    int loop;
    int ret;

    ret = FAMOpen(&fc);

    if (ret < 0) {
        fprintf(stderr, "Failed to connect to the FAM server\n");
        exit(1);
    }
    for (loop = 0; loop < 1; loop++) {

        ret = FAMMonitorDirectory(&fc, "/u/veillard/test", &fr, &data);
        if (ret != 0) {
            fprintf(stderr, "Failed register monitor for /tmp\n");
            exit(1);
        }
        sleep(1);
        check_event(&fc);
    }
    ret = FAMClose(&fc);
    if (ret < 0) {
        fprintf(stderr, "Failed to close connection to the FAM server\n");
        exit(1);
    }
}
示例#2
0
static int fhs_event_add_resource(struct fe_handler *feh, char *res, FAMEvent *fe)
{
        FAMRequest fr;
        SaHpiRptEntryT *rpt;
        DIR *pdir;
        struct dirent *pd;
        char  *path, *root_path;
        int len;
        

#ifndef UNIT_TEST
        root_path = g_hash_table_lookup(feh->ohh->config, "root_path");
#else
        root_path = "/home/guorj/HPI/openhpi/src/plugins/simulator/test/resources";
#endif
        len = strlen(root_path) + strlen(fe->filename) + 30;
        path = g_malloc(len);

        sprintf(path, "%s/%s", root_path, fe->filename);
        pdir = opendir(path);
        if (!pdir) {
            printf("%s is not directory\n", path);
            g_free(path);
            return -1;
        }
  
        rpt = g_malloc0(sizeof(*rpt));
#if 0
        parse rpt entry(contain entity path, then calulate resource id)
        
        insert resource event into event queue;
#else
        printf("add resource:%s\n", fe->filename);
#endif
        feh->ids = sim_util_add_res_id(feh->ids, fe->filename, rpt->EntryId, 
                                       &rpt->ResourceEntity);
        for (pd = readdir(pdir); pd; pd = readdir(pdir)) {
                DIR *tmp;
                unsigned int index;

                if (str2uint32(pd->d_name, &index)) continue;
#if 0
                insert rdr event into event queue; 
#else
                printf("add rdr:%s\n", pd->d_name);
#endif
                sprintf(path, "%s/%s/%s/sensor", root_path, res, pd->d_name); 
                tmp = opendir(path);
                if (tmp) {
                        FAMMonitorDirectory(fe->fc, path, &fr, (void *)req_rdr);
                        sim_util_add_rdr_id(feh->ids, fe->filename, fr.reqnum, index);
                        printf("monitor sensor:%s\n", pd->d_name);
                        close(tmp);
                }
        }
        closedir(pdir);
        g_free(path);
        return 0;
}
示例#3
0
static void* fhs_event_process(void *data)
{
        struct fe_handler *feh = (struct fe_handler*)data;
        FAMEvent fe;
        FAMRequest fr;
        FAMConnection fc;
        char*  root_path;

        root_path = g_hash_table_lookup(feh->ohh->config, "root_path");

        FAMOpen(&fc);
        FAMMonitorDirectory(&fc, root_path, &fr, REQ_RES);

        while(!feh->closing) { 
/*
        The old code is:
               FAMNextEvent(&fc, &fe);
        The new code is
                if (1 == FAMPending(&fc)) {
                        FAMNextEvent(&fc, &fe);
                }else  continue;

        In the old code, if this thread is processing FAMNextEvent and 
        then feh->closing is set by another thread, this thread is still
        hung up. so the synchronized call is changed as asychronized call
        (polling call) though I don't like this mode.
 
*/  
                if (1 == FAMPending(&fc)) {
                        FAMNextEvent(&fc, &fe);
                }else  continue; 

                if ((fe.userdata == REQ_RES) &&
                    ((fe.code == FAMCreated) || (fe.code == FAMExists))) {
                        if (!IS_DIR(fe.filename))
                                fhs_event_add_resource(feh, fe.filename, &fe);
                }else if ((fe.userdata == REQ_RDR) && (fe.code == FAMDeleted)) {
                     	if (!IS_DIR(fe.filename))
                             	fhs_event_remove_resource(feh, &fe);
                      	else
                  		printf("faint! why delete root path\n");
                }else if (fe.userdata == REQ_RDR) {
                        if (((fe.code == FAMChanged) || (fe.code == FAMExists))&&
                            ((!strcmp(fe.filename, "reading"))||
                             (!strcmp(fe.filename, "thres")))) {
                                fhs_event_sensor_update(feh, &fe);
                        }
                }
        } 
        FAMClose(&fc);

        return 0;
}
示例#4
0
static void reconnect_fam( gpointer key,
                           gpointer value,
                           gpointer user_data )
{
    struct stat file_stat;   // skip stat64
    VFSFileMonitor* monitor = ( VFSFileMonitor* ) value;
    const char* path = ( const char* ) key;
    if ( lstat( path, &file_stat ) != -1 )
    {
#ifdef USE_INOTIFY /* Linux inotify */
        monitor->wd = inotify_add_watch ( inotify_fd, path,
                                          IN_MODIFY | IN_CREATE | IN_DELETE | IN_MOVE );
        if ( monitor->wd < 0 )
        {
            /*
                  * FIXME: add monitor to an ancestor which does actually exist,
                  *        or do the equivalent of inotify-missing.c by maintaining
                  *        a list of monitors on non-existent files/directories
                  *        which you retry in a timeout.
            */
            g_warning ( "Failed to add monitor on '%s': %s",
                        path,
                        g_strerror ( errno ) );
            return ;
        }
#else
        if ( S_ISDIR( file_stat.st_mode ) )
        {
            FAMMonitorDirectory( &fam,
                                 path,
                                 &monitor->request,
                                 monitor );
        }
        else
        {
            FAMMonitorFile( &fam,
                            path,
                            &monitor->request,
                            monitor );
        }
#endif

    }
}
示例#5
0
static void* fhs_event_process(void *data)
{
        struct fe_handler *feh = (struct fe_handler*)data;
        FAMEvent fe;
        FAMRequest fr;
        FAMConnection fc;
        char*  root_path;

#ifndef UNIT_TEST 
        root_path = g_hash_table_lookup(feh->ohh->config, "root_path");
#else
        root_path = "/home/guorj/HPI/openhpi/src/plugins/simulator/test/resources";
#endif

        FAMOpen(&fc);
        FAMMonitorDirectory(&fc, root_path, &fr, (void*)req_res);

        while(!feh->done) {   

                FAMNextEvent(&fc, &fe);
                if ((fe.userdata == (void *)req_res) &&
                    ((fe.code == FAMCreated) || (fe.code == FAMExists))) {
                        if (!IS_DIR(fe.filename))
                                fhs_event_add_resource(feh, fe.filename, &fe);
                }else if ((fe.userdata == (void*) req_res) && (fe.code == FAMDeleted)) {
                     	if (!IS_DIR(fe.filename))
                             	fhs_event_remove_resource(feh, &fe);
                      	else
                  		printf("faint! why delete root path\n");
                }else if (fe.userdata == (void *)req_rdr) {
                        if (((fe.code == FAMChanged) || (fe.code == FAMExists))&&
                            ((!strcmp(fe.filename, "reading"))||
                             (!strcmp(fe.filename, "thres")))) {
                                fhs_event_sensor_update(feh, &fe);
                        }
                }
        } 
        FAMClose(&fc);
#if 0
        free all resource id and rdr id;
#endif
        return 0;
}
示例#6
0
static void
g_fam_file_monitor_start (GLocalFileMonitor  *local_monitor,
                          const gchar        *dirname,
                          const gchar        *basename,
                          const gchar        *filename,
                          GFileMonitorSource *source)
{
  GFamFileMonitor *gffm = G_FAM_FILE_MONITOR (local_monitor);

  g_mutex_lock (&fam_lock);

  g_assert (fam_initialised);

  g_source_ref ((GSource *) source);

  if (dirname)
    FAMMonitorDirectory (&fam_connection, dirname, &gffm->request, source);
  else
    FAMMonitorFile (&fam_connection, filename, &gffm->request, source);

  g_mutex_unlock (&fam_lock);
}
示例#7
0
handler_t stat_cache_get_entry(server *srv, connection *con, buffer *name, stat_cache_entry **ret_sce) {
#ifdef HAVE_FAM_H
	fam_dir_entry *fam_dir = NULL;
	int dir_ndx = -1;
	splay_tree *dir_node = NULL;
#endif
	stat_cache_entry *sce = NULL;
	stat_cache *sc;
	struct stat st;
	size_t k;
	int fd;
	struct stat lst;
#ifdef DEBUG_STAT_CACHE
	size_t i;
#endif

	int file_ndx;
	splay_tree *file_node = NULL;

	*ret_sce = NULL;

	/*
	 * check if the directory for this file has changed
	 */

	sc = srv->stat_cache;

	buffer_copy_buffer(sc->hash_key, name);
	buffer_append_int(sc->hash_key, con->conf.follow_symlink);

	file_ndx = hashme(sc->hash_key);
	sc->files = splaytree_splay(sc->files, file_ndx);

#ifdef DEBUG_STAT_CACHE
	for (i = 0; i < ctrl.used; i++) {
		if (ctrl.ptr[i] == file_ndx) break;
	}
#endif

	if (sc->files && (sc->files->key == file_ndx)) {
#ifdef DEBUG_STAT_CACHE
		/* it was in the cache */
		force_assert(i < ctrl.used);
#endif

		/* we have seen this file already and
		 * don't stat() it again in the same second */

		file_node = sc->files;

		sce = file_node->data;

		/* check if the name is the same, we might have a collision */

		if (buffer_is_equal(name, sce->name)) {
			if (srv->srvconf.stat_cache_engine == STAT_CACHE_ENGINE_SIMPLE) {
				if (sce->stat_ts == srv->cur_ts) {
					*ret_sce = sce;
					return HANDLER_GO_ON;
				}
			}
		} else {
			/* oops, a collision,
			 *
			 * file_node is used by the FAM check below to see if we know this file
			 * and if we can save a stat().
			 *
			 * BUT, the sce is not reset here as the entry into the cache is ok, we
			 * it is just not pointing to our requested file.
			 *
			 *  */

			file_node = NULL;
		}
	} else {
#ifdef DEBUG_STAT_CACHE
		if (i != ctrl.used) {
			log_error_write(srv, __FILE__, __LINE__, "xSB",
				file_ndx, "was already inserted but not found in cache, ", name);
		}
		force_assert(i == ctrl.used);
#endif
	}

#ifdef HAVE_FAM_H
	/* dir-check */
	if (srv->srvconf.stat_cache_engine == STAT_CACHE_ENGINE_FAM) {
		if (0 != buffer_copy_dirname(sc->dir_name, name)) {
			log_error_write(srv, __FILE__, __LINE__, "sb",
				"no '/' found in filename:", name);
			return HANDLER_ERROR;
		}

		buffer_copy_buffer(sc->hash_key, sc->dir_name);
		buffer_append_int(sc->hash_key, con->conf.follow_symlink);

		dir_ndx = hashme(sc->hash_key);

		sc->dirs = splaytree_splay(sc->dirs, dir_ndx);

		if (sc->dirs && (sc->dirs->key == dir_ndx)) {
			dir_node = sc->dirs;
		}

		if (dir_node && file_node) {
			/* we found a file */

			sce = file_node->data;
			fam_dir = dir_node->data;

			if (fam_dir->version == sce->dir_version) {
				/* the stat()-cache entry is still ok */

				*ret_sce = sce;
				return HANDLER_GO_ON;
			}
		}
	}
#endif

	/*
	 * *lol*
	 * - open() + fstat() on a named-pipe results in a (intended) hang.
	 * - stat() if regular file + open() to see if we can read from it is better
	 *
	 * */
	if (-1 == stat(name->ptr, &st)) {
		return HANDLER_ERROR;
	}


	if (S_ISREG(st.st_mode)) {
		/* fix broken stat/open for symlinks to reg files with appended slash on freebsd,osx */
		if (name->ptr[buffer_string_length(name) - 1] == '/') {
			errno = ENOTDIR;
			return HANDLER_ERROR;
		}

		/* try to open the file to check if we can read it */
		if (-1 == (fd = open(name->ptr, O_RDONLY))) {
			return HANDLER_ERROR;
		}
		close(fd);
	}

	if (NULL == sce) {
#ifdef DEBUG_STAT_CACHE
		int osize = splaytree_size(sc->files);
#endif

		sce = stat_cache_entry_init();
		buffer_copy_buffer(sce->name, name);

		sc->files = splaytree_insert(sc->files, file_ndx, sce);
#ifdef DEBUG_STAT_CACHE
		if (ctrl.size == 0) {
			ctrl.size = 16;
			ctrl.used = 0;
			ctrl.ptr = malloc(ctrl.size * sizeof(*ctrl.ptr));
		} else if (ctrl.size == ctrl.used) {
			ctrl.size += 16;
			ctrl.ptr = realloc(ctrl.ptr, ctrl.size * sizeof(*ctrl.ptr));
		}

		ctrl.ptr[ctrl.used++] = file_ndx;

		force_assert(sc->files);
		force_assert(sc->files->data == sce);
		force_assert(osize + 1 == splaytree_size(sc->files));
#endif
	}

	sce->st = st;
	sce->stat_ts = srv->cur_ts;

	/* catch the obvious symlinks
	 *
	 * this is not a secure check as we still have a race-condition between
	 * the stat() and the open. We can only solve this by
	 * 1. open() the file
	 * 2. fstat() the fd
	 *
	 * and keeping the file open for the rest of the time. But this can
	 * only be done at network level.
	 *
	 * per default it is not a symlink
	 * */
#ifdef HAVE_LSTAT
	sce->is_symlink = 0;

	/* we want to only check for symlinks if we should block symlinks.
	 */
	if (!con->conf.follow_symlink) {
		if (stat_cache_lstat(srv, name, &lst)  == 0) {
#ifdef DEBUG_STAT_CACHE
				log_error_write(srv, __FILE__, __LINE__, "sb",
						"found symlink", name);
#endif
				sce->is_symlink = 1;
		}

		/*
		 * we assume "/" can not be symlink, so
		 * skip the symlink stuff if our path is /
		 **/
		else if (buffer_string_length(name) > 1) {
			buffer *dname;
			char *s_cur;

			dname = buffer_init();
			buffer_copy_buffer(dname, name);

			while ((s_cur = strrchr(dname->ptr, '/'))) {
				buffer_string_set_length(dname, s_cur - dname->ptr);
				if (dname->ptr == s_cur) {
#ifdef DEBUG_STAT_CACHE
					log_error_write(srv, __FILE__, __LINE__, "s", "reached /");
#endif
					break;
				}
#ifdef DEBUG_STAT_CACHE
				log_error_write(srv, __FILE__, __LINE__, "sbs",
						"checking if", dname, "is a symlink");
#endif
				if (stat_cache_lstat(srv, dname, &lst)  == 0) {
					sce->is_symlink = 1;
#ifdef DEBUG_STAT_CACHE
					log_error_write(srv, __FILE__, __LINE__, "sb",
							"found symlink", dname);
#endif
					break;
				};
			};
			buffer_free(dname);
		};
	};
#endif

	if (S_ISREG(st.st_mode)) {
		/* determine mimetype */
		buffer_reset(sce->content_type);
#if defined(HAVE_XATTR) || defined(HAVE_EXTATTR)
		if (con->conf.use_xattr) {
			stat_cache_attr_get(sce->content_type, name->ptr);
		}
#endif
		/* xattr did not set a content-type. ask the config */
		if (buffer_string_is_empty(sce->content_type)) {
			size_t namelen = buffer_string_length(name);

			for (k = 0; k < con->conf.mimetypes->used; k++) {
				data_string *ds = (data_string *)con->conf.mimetypes->data[k];
				buffer *type = ds->key;
				size_t typelen = buffer_string_length(type);

				if (buffer_is_empty(type)) continue;

				/* check if the right side is the same */
				if (typelen > namelen) continue;

				if (0 == strncasecmp(name->ptr + namelen - typelen, type->ptr, typelen)) {
					buffer_copy_buffer(sce->content_type, ds->value);
					break;
				}
			}
		}
		etag_create(sce->etag, &(sce->st), con->etag_flags);
	} else if (S_ISDIR(st.st_mode)) {
		etag_create(sce->etag, &(sce->st), con->etag_flags);
	}

#ifdef HAVE_FAM_H
	if (srv->srvconf.stat_cache_engine == STAT_CACHE_ENGINE_FAM) {
		/* is this directory already registered ? */
		if (!dir_node) {
			fam_dir = fam_dir_entry_init();

			buffer_copy_buffer(fam_dir->name, sc->dir_name);

			fam_dir->version = 1;

			fam_dir->req = calloc(1, sizeof(FAMRequest));

			if (0 != FAMMonitorDirectory(&sc->fam, fam_dir->name->ptr,
						     fam_dir->req, fam_dir)) {

				log_error_write(srv, __FILE__, __LINE__, "sbsbs",
						"monitoring dir failed:",
						fam_dir->name, 
						"file:", name,
						FamErrlist[FAMErrno]);

				fam_dir_entry_free(&sc->fam, fam_dir);
				fam_dir = NULL;
			} else {
				int osize = 0;

				if (sc->dirs) {
					osize = sc->dirs->size;
				}

				sc->dirs = splaytree_insert(sc->dirs, dir_ndx, fam_dir);
				force_assert(sc->dirs);
				force_assert(sc->dirs->data == fam_dir);
				force_assert(osize == (sc->dirs->size - 1));
			}
		} else {
			fam_dir = dir_node->data;
		}

		/* bind the fam_fc to the stat() cache entry */

		if (fam_dir) {
			sce->dir_version = fam_dir->version;
		}
	}
#endif

	*ret_sce = sce;

	return HANDLER_GO_ON;
}
示例#8
0
VFSFileMonitor* vfs_file_monitor_add( char* path,
                                      gboolean is_dir,
                                      VFSFileMonitorCallback cb,
                                      gpointer user_data )
{
    VFSFileMonitor * monitor;
    VFSFileMonitorCallbackEntry cb_ent;
    struct stat file_stat;   // skip stat64
    gchar* real_path = NULL;

//printf( "vfs_file_monitor_add  %s\n", path );

    if ( ! monitor_hash )
        return NULL;

    monitor = ( VFSFileMonitor* ) g_hash_table_lookup ( monitor_hash, path );
    if ( ! monitor )
    {
        monitor = g_slice_new0( VFSFileMonitor );
        monitor->path = g_strdup( path );

        monitor->callbacks = g_array_new ( FALSE, FALSE, sizeof( VFSFileMonitorCallbackEntry ) );
        g_hash_table_insert ( monitor_hash,
                              monitor->path,
                              monitor );

        /* NOTE: Since gamin, FAM and inotify don't follow symlinks,
                 we need to do some special processing here. */
        if ( lstat( path, &file_stat ) == 0 )
        {
            const char* link_file = path;
            while( G_UNLIKELY( S_ISLNK(file_stat.st_mode) ) )
            {
                char* link = g_file_read_link( link_file, NULL );
                char* dirname = g_path_get_dirname( link_file );
                real_path = vfs_file_resolve_path( dirname, link );
                g_free( link );
                g_free( dirname );
                if( lstat( real_path, &file_stat ) == -1 )
                    break;
                link_file = real_path;
            }
        }

#ifdef USE_INOTIFY /* Linux inotify */
        monitor->wd = inotify_add_watch ( inotify_fd, real_path ? real_path : path,
                                            IN_MODIFY | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MOVE | IN_MOVE_SELF | IN_UNMOUNT | IN_ATTRIB);
        if ( monitor->wd < 0 )
        {
            g_warning ( "Failed to add monitor on '%s': %s",
                        path,
                        g_strerror ( errno ) );
            return NULL;
        }
#else /* Use FAM|gamin */
//MOD see NOTE1 in vfs-mime-type.c - what happens here if path doesn't exist?
//    inotify returns NULL - does fam?
        if ( is_dir )
        {
            FAMMonitorDirectory( &fam,
                                    real_path ? real_path : path,
                                    &monitor->request,
                                    monitor );
        }
        else
        {
            FAMMonitorFile( &fam,
                            real_path ? real_path : path,
                            &monitor->request,
                            monitor );
        }
#endif
        g_free( real_path );
    }

    if( G_LIKELY(monitor) )
    {
        /* g_debug( "monitor installed: %s, %p", path, monitor ); */
        if ( cb )
        { /* Install a callback */
            cb_ent.callback = cb;
            cb_ent.user_data = user_data;
            monitor->callbacks = g_array_append_val( monitor->callbacks, cb_ent );
        }
        g_atomic_int_inc( &monitor->n_ref );
    }
    return monitor;
}
示例#9
0
文件: testing.c 项目: GNOME/gamin
static int
processCommand(char *line, int no)
{
    int ret, args;
    char *command = NULL;
    char *arg = NULL;
    char *arg2 = NULL;

    if (line == NULL)
        return (-1);
    if (line[0] == '#')
        return (0);

    args = scanCommand(line, &command, &arg, &arg2);
    if (args < 0)
        return (-1);
    if (args == 0)
        return (0);

    if (!strcmp(command, "connect")) {
        if (testState.connected) {
            fprintf(stderr, "connect line %d: already connected\n", no);
            return (-1);
        }
        if (arg != NULL) {
#ifdef HAVE_SETENV
            setenv("GAM_CLIENT_ID", arg, 1);
#elif HAVE_PUTENV
            char *client_id = malloc (strlen (arg) + sizeof "GAM_CLIENT_ID=");
              if (client_id)
              {
                strcpy (client_id, "GAM_CLIENT_ID=");
                strcat (client_id, arg);
                putenv (client_id);
              }
#endif /* HAVE_SETENV */
        }
        ret = FAMOpen(&(testState.fc));
        if (ret < 0) {
            fprintf(stderr, "connect line %d: failed to connect\n", no);
            return (-1);
        }
        testState.connected = 1;
        if (arg != NULL)
            printf("connected to %s\n", arg);
        else
            printf("connected\n");
    } else if (!strcmp(command, "kill")) {
        /*
         * okay, it's heavy but that's the simplest way since we do not have
         * the pid(s) of the servers running.
         */
        ret = system("killall gam_server");
        if (ret < 0) {
            fprintf(stderr, "kill line %d: failed to killall gam_server\n",
                    no);
            return (-1);
        }
        printf("killall gam_server\n");
    } else if (!strcmp(command, "disconnect")) {
        if (testState.connected == 0) {
            fprintf(stderr, "disconnect line %d: not connected\n", no);
            return (-1);
        }
        ret = FAMClose(&(testState.fc));
        if (ret < 0) {
            fprintf(stderr, "connect line %d: failed to disconnect\n", no);
            return (-1);
        }
        testState.connected = 0;
        printf("disconnected\n");
    } else if (!strcmp(command, "mondir")) {
        if (args >= 2) {
            if (arg[0] != '/')
                snprintf(filename, sizeof(filename), "%s/%s", pwd, arg);
            else
                snprintf(filename, sizeof(filename), "%s", arg);
        }
        if (args == 2) {
            ret = FAMMonitorDirectory(&(testState.fc), filename,
                                      &(testState.
                                        fr[testState.nb_requests]), NULL);
        } else if (args == 3) {
            int index;

            if (sscanf(arg2, "%d", &index) <= 0) {
                fprintf(stderr, "mondir line %d: invalid index value %s\n",
                        no, arg2);
                return (-1);
            }
            testState.fr[testState.nb_requests].reqnum = index;
            ret = FAMMonitorDirectory2(&(testState.fc), filename,
                                       &(testState.
                                         fr[testState.nb_requests]));
        } else {
            fprintf(stderr, "mondir line %d: invalid format\n", no);
            return (-1);
        }
        if (ret < 0) {
            fprintf(stderr, "mondir line %d: failed to monitor %s\n", no,
                    arg);
            return (-1);
        }
        printf("mondir %s %d\n", arg, testState.nb_requests);
        testState.nb_requests++;
    } else if (!strcmp(command, "monfile")) {
        if (args != 2) {
            fprintf(stderr, "monfile line %d: lacks name\n", no);
            return (-1);
        }
        if (arg[0] != '/')
            snprintf(filename, sizeof(filename), "%s/%s", pwd, arg);
        else
            snprintf(filename, sizeof(filename), "%s", arg);
        ret = FAMMonitorFile(&(testState.fc), filename,
                             &(testState.fr[testState.nb_requests]), NULL);
        if (ret < 0) {
            fprintf(stderr, "monfile line %d: failed to monitor %s\n", no,
                    arg);
            return (-1);
        }
        printf("monfile %s %d\n", arg, testState.nb_requests);
        testState.nb_requests++;
    } else if (!strcmp(command, "pending")) {
        if (args != 1) {
            fprintf(stderr, "pending line %d: extra argument %s\n", no,
                    arg);
            return (-1);
        }
        ret = FAMPending(&(testState.fc));
        if (ret < 0) {
            fprintf(stderr, "pending line %d: failed\n", no);
            return (-1);
        }
        printf("pending %d\n", ret);
    } else if (!strcmp(command, "mkdir")) {
        if (args != 2) {
            fprintf(stderr, "mkdir line %d: lacks name\n", no);
            return (-1);
        }
        ret = mkdir(arg, 0755);
        if (ret < 0) {
            fprintf(stderr, "mkdir line %d: failed to create %s\n", no,
                    arg);
            return (-1);
        }
        printf("mkdir %s\n", arg);
    } else if (!strcmp(command, "chmod")) {
        if (args != 3) {
            fprintf(stderr, "chmod line %d: lacks path and mode\n", no);
            return (-1);
        }
        ret = chmod(arg, strtol (arg2, NULL, 8));
        if (ret < 0) {
            fprintf(stderr, "chmod line %d: failed to chmod %s to %s\n", no,
                    arg, arg2);
            return (-1);
        }
        printf("chmod %s to %s\n", arg, arg2);
    } else if (!strcmp(command, "chown")) {
        if (args != 3) {
            fprintf(stderr, "chown line %d: lacks path and owner\n", no);
            return (-1);
        }
		struct stat sb;
		if (!lstat (arg, &sb)) {
			ret = (S_ISLNK (sb.st_mode)) ?
				lchown(arg, strtol(arg2, NULL, 10), -1) :
				chown(arg, strtol(arg2, NULL, 10), -1);
		} else
			ret=-1;
        if (ret < 0) {
            fprintf(stderr, "chown line %d: failed to chown %s to %s\n", no,
                    arg, arg2);
            return (-1);
        }
        printf("chown %s to %s\n", arg, arg2);
    } else if (!strcmp(command, "mkfile")) {
        if (args != 2) {
            fprintf(stderr, "mkfile line %d: lacks name\n", no);
            return (-1);
        }
        ret = open(arg, O_CREAT | O_WRONLY, 0666);
        if (ret < 0) {
            fprintf(stderr, "mkfile line %d: failed to open %s\n", no,
                    arg);
            return (-1);
        }
        close(ret);
        printf("mkfile %s\n", arg);
    } else if (!strcmp(command, "append")) {
        if (args != 2) {
            fprintf(stderr, "mkfile line %d: lacks name\n", no);
            return (-1);
        }
        ret = open(arg, O_RDWR | O_APPEND);
        if (ret < 0) {
            fprintf(stderr, "append line %d: failed to open %s\n", no,
                    arg);
            return (-1);
        }
        write(ret, "a", 1);
        close(ret);
        printf("append %s\n", arg);
    } else if (!strcmp(command, "rmdir")) {
        if (args != 2) {
            fprintf(stderr, "rmdir line %d: lacks name\n", no);
            return (-1);
        }
        ret = rmdir(arg);
        if (ret < 0) {
            fprintf(stderr, "rmdir line %d: failed to remove %s\n", no,
                    arg);
            return (-1);
        }
        printf("rmdir %s\n", arg);
    } else if (!strcmp(command, "rmfile")) {
        if (args != 2) {
            fprintf(stderr, "rmfile line %d: lacks name\n", no);
            return (-1);
        }
        ret = unlink(arg);
        if (ret < 0) {
            fprintf(stderr, "rmfile line %d: failed to unlink %s\n", no,
                    arg);
            return (-1);
        }
        printf("rmfile %s\n", arg);
	} else if (!strcmp(command, "move")) {
		if (args != 3)
		{
			fprintf(stderr, "move line %d: lacks something\n", no);
			return (-1);
		}
		ret = rename(arg, arg2);
		if (ret < 0) {
			fprintf(stderr, "move line %d: failed to move %s\n", no, arg);
			return (-1);
		}
		printf("move %s %s\n", arg, arg2);
	} else if (!strcmp(command, "link")) {
		if (args != 3) {
		fprintf(stderr, "link line %d: lacks target and name\n", no); return (-1);
		}
		ret = symlink(arg, arg2);
		if (ret < 0) {
			fprintf(stderr, "link line %d: failed to link to %s\n", no, arg);
			return (-1);
		}
		printf("link %s to %s\n", arg2, arg);
    } else if (!strcmp(command, "event")) {
        printEvent(no);
    } else if (!strcmp(command, "events")) {
        printEvents(no);
    } else if (!strcmp(command, "expect")) {
        int count;
        int delay = 0;
        int nb_events = testState.nb_events;

        if (args != 2) {
            fprintf(stderr, "expect line %d: lacks number\n", no);
            return (-1);
        }

        if (sscanf(arg, "%d", &count) <= 0) {
            fprintf(stderr, "expect line %d: invalid number value %s\n",
                    no, arg);
            return (-1);
        }
        /*
         * wait at most 3 secs before declaring failure
         */
        while ((delay < 30) && (testState.nb_events < nb_events + count)) {
            debugLoop(100);

/*	    printf("+"); fflush(stdout); */
            delay++;
        }
        if (testState.nb_events < nb_events + count) {
            printf("expect line %d: got %d of %d expected events\n",
                   no, testState.nb_events - nb_events, count);
            return (-1);
        }
    } else if (!strcmp(command, "sleep")) {
        int i;

        for (i = 0; (i < 30) && (FAMPending(&(testState.fc)) == 0); i++)
            usleep(50000);
    } else if (!strcmp(command, "wait")) {
        sleep(1);
    } else if (!strcmp(command, "cancel")) {
        if (args == 2) {
            int req_index = 0;

            if (sscanf(arg, "%d", &req_index) <= 0
                || req_index >= testState.nb_requests) {
                fprintf(stderr,
                        "cancel line %d: invalid req_index value %s\n", no,
                        arg);
                return (-1);
            }
            ret = FAMCancelMonitor(&(testState.fc),
                                   &(testState.fr[req_index]));

        } else {
            fprintf(stderr, "cancel line %d: invalid format\n", no);
            return (-1);
        }
        if (ret < 0) {
            fprintf(stderr,
                    "cancel line %d: failed to cancel req_index %s\n", no,
                    arg);
            return (-1);
        }
        printf("cancel %s %d\n", arg, testState.nb_requests);
    } else {
        fprintf(stderr, "Unable to parse line %d: %s\n", no, line);
        return (-1);
    }
    return (0);
}
示例#10
0
文件: doodled.c 项目: prachpub/doodle
static int do_index(const char * filename,
		    DIC * dic) {
  int i;
  int j;
  int k;
  struct stat sbuf;

  if (0 == strncmp(filename,
		   dic->ename,
		   strlen(dic->ename)))
    return 0; /* database (and database-temp file) is always pruned! */

  if (isPruned(filename))
    return 0;
  for (i=dic->deferredCount-1;i>=0;i--) {
    if (0 == strcmp(filename,
		    dic->deferredTruncations[i])) {
      free(dic->deferredTruncations[i]);
      dic->deferredTruncations[i]
	= dic->deferredTruncations[dic->deferredCount-1];
      GROW(dic->deferredTruncations,
	   dic->deferredCount,
	   dic->deferredCount-1);
    }
  }

  j = -1;
  for (i=DOODLE_getFileCount(dic->tree)-1;i>=0;i--) {
    if (0 == strcmp(filename,
		    DOODLE_getFileAt(dic->tree,i)->filename)) {
      j = i;
      break;
    }
  }

  k = -1;
  for (i=0;i<dic->frPos;i++) {
    if (0 == strcmp(filename,
		    dic->frNames[i])) {
      k=i;
      break;
    }
  }

  if (0 != lstat(filename,
		 &sbuf)) {
    dic->log(dic->logContext,
	     DOODLE_LOG_VERY_VERBOSE,
	     _("Call to '%s' for file '%s' failed: %s\n"),
	     "stat",
	     filename,
	     strerror(errno));
    if (j != -1) {
      /* remove old keywords, file no longer there? */
      GROW(dic->deferredTruncations,
	   dic->deferredCount,
	   dic->deferredCount + 1);
      dic->deferredTruncations[dic->deferredCount-1]
	= strdup(filename);
    }
    if (k != -1) {
      if (-1 == FAMCancelMonitor(&dic->fc,
				 &dic->fr[k])) {
	dic->log(dic->logContext,
		 DOODLE_LOG_CRITICAL,
		 _("Call to '%s' for file '%s' failed: %s\n"),
		 "FAMCancelMonitor",
		 filename,
		 FamErrlist[FAMErrno]);
      }
      free(dic->frNames[k]);
      dic->fr[k] = dic->fr[dic->frPos-1];
      dic->frNames[k] = dic->frNames[dic->frPos-1];
      dic->frNames[dic->frPos-1] = NULL;
      dic->frPos--;
    }
    return 0;
  }

  if ( (S_ISDIR(sbuf.st_mode)) &&
#ifdef S_ISLNK
       (! S_ISLNK(sbuf.st_mode)) &&
#endif
#ifdef S_ISSOCK
       (! S_ISSOCK(sbuf.st_mode)) &&
#endif
       (k == -1) ) {
    char * fn;
    if (dic->frPos == dic->frSize) {
      unsigned int s = dic->frSize;
      GROW(dic->fr,
	   dic->frSize,
	   dic->frSize * 2);
      GROW(dic->frNames,
	   s,
	   s * 2);
    }
    dic->log(dic->logContext,
	     DOODLE_LOG_VERY_VERBOSE,
	     _("Will monitor directory '%s' for changes.\n"),
	     filename);
    fn = STRDUP(filename);
    if (0 == FAMMonitorDirectory(&dic->fc,
				 filename,
				 &dic->fr[dic->frPos],
				 fn)) {
      dic->frNames[dic->frPos] = fn;
      dic->frPos++;
    } else {
      dic->log(dic->logContext,
	       DOODLE_LOG_CRITICAL,
	       _("Call to '%s' for file '%s' failed: %s\n"),
	       "FAMMonitorDirectory",
	       filename,
	       FamErrlist[FAMErrno]);
      free(fn);
    }
  }

  if (j != -1) {
    if (DOODLE_getFileAt(dic->tree,j)->mod_time == (unsigned int) sbuf.st_mtime) {
      return 0; /* already processed! */
    } else {
      /* remove old keywords, file changed! */
      /* we must do the new truncation now, so
	 we also do all of those that were
	 deferred */
      GROW(dic->deferredTruncations,
	   dic->deferredCount,
	   dic->deferredCount + 2);
      dic->deferredTruncations[dic->deferredCount-2]
	= strdup(filename);

      DOODLE_tree_truncate_multiple(dic->tree,
				    (const char**)dic->deferredTruncations);
      for (i=dic->deferredCount-2;i>=0;i--)
	free(dic->deferredTruncations[i]);
      GROW(dic->deferredTruncations,
	   dic->deferredCount,
	   0);
    }
  }

  if (S_ISREG(sbuf.st_mode)) {
    dic->log(dic->logContext,
	     DOODLE_LOG_VERY_VERBOSE,
	     _("Processing file '%s'.\n"),
	     filename);
    return buildIndex(dic->elist,
		      NULL, 
		      filename,
		      dic->tree,
		      do_filenames);
  }

  return 0;
}
示例#11
0
static int fhs_event_add_resource(struct fe_handler *feh, char *res, FAMEvent *fe)
{
        FAMRequest fr;
        DIR *pdir;
        struct dirent *pd;
        char  *path, *root_path;
        int len;
        struct oh_event *event;
        SaHpiResourceIdT  rid;
        SaHpiRptEntryT *rpt;
        
 
        root_path = g_hash_table_lookup(feh->ohh->config, "root_path");
        len = strlen(root_path) + strlen(fe->filename) + 30;
        path = g_malloc(len);

        sprintf(path, "%s/%s", root_path, fe->filename);
        pdir = opendir(path);
        if (!pdir) {
            printf("%s is not directory\n", path);
            g_free(path);
            return -1;
        }

        event = g_malloc0(sizeof(*event));
        event->type = OH_ET_RESOURCE;
        rpt = &event->u.res_event.entry;
        sprintf(path, "%s/%s/rpt", root_path, fe->filename);
        sim_parser_get_rpt(path, rpt);
        rid = oh_uid_from_entity_path(&rpt->ResourceEntity);
        rpt->ResourceId = rid;

        sim_util_add_resource(feh->ohh->rptcache, rpt, g_strdup(fe->filename));
        sim_util_insert_event(&feh->ohh->eventq, event);

        for (pd = readdir(pdir); pd; pd = readdir(pdir)) {
                DIR *tmp;
                unsigned int index;
                sim_rdr_id_t  *sid = NULL;
                SaHpiRdrT *rdr;

                if (str2uint32(pd->d_name, &index)) continue;

                event = g_malloc0(sizeof(*event));
                event->type = OH_ET_RDR;
                rdr = &event->u.rdr_event.rdr;
                sprintf(path, "%s/%s/%s/rdr", root_path, fe->filename,pd->d_name);
                sim_parser_get_rdr(path, rdr);
                sim_util_insert_event(&feh->ohh->eventq, event);
                sprintf(path, "%s/%s/%s/sensor", root_path, res, pd->d_name); 
                tmp = opendir(path);
                if (tmp) {
                        closedir(tmp);
                        FAMMonitorDirectory(fe->fc, path, &fr, REQ_RDR);
                        sid = g_malloc0(sizeof(*sid));
                        sid->rid = rid;
                        sid->index = index;
                        sid->reqnum = fe->fr.reqnum;
                        printf("monitor sensor:%s\n", pd->d_name);
                }
                sim_util_add_rdr(feh->ohh->rptcache, rid, rdr, sid);
        }
        closedir(pdir);
        g_free(path);
        return 0;
}