Exemplo n.º 1
0
static NTSTATUS close_directory(struct smb_request *req, files_struct *fsp,
				enum file_close_type close_type)
{
	struct share_mode_lock *lck = NULL;
	bool delete_dir = False;
	NTSTATUS status = NT_STATUS_OK;
	NTSTATUS status1 = NT_STATUS_OK;
	const struct security_unix_token *del_token = NULL;

	/*
	 * NT can set delete_on_close of the last open
	 * reference to a directory also.
	 */

	lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL,
				  NULL);

	if (lck == NULL) {
		DEBUG(0, ("close_directory: Could not get share mode lock for "
			  "%s\n", fsp_str_dbg(fsp)));
		status = NT_STATUS_INVALID_PARAMETER;
		goto out;
	}

	if (!del_share_mode(lck, fsp)) {
		DEBUG(0, ("close_directory: Could not delete share entry for "
			  "%s\n", fsp_str_dbg(fsp)));
	}

	if (fsp->initial_delete_on_close) {
		bool became_user = False;

		/* Initial delete on close was set - for
		 * directories we don't care if anyone else
		 * wrote a real delete on close. */

		if (get_current_vuid(fsp->conn) != fsp->vuid) {
			become_user(fsp->conn, fsp->vuid);
			became_user = True;
		}
		send_stat_cache_delete_message(fsp->conn->sconn->msg_ctx,
					       fsp->fsp_name->base_name);
		set_delete_on_close_lck(fsp, lck, true,
				get_current_utok(fsp->conn));
		fsp->delete_on_close = true;
		if (became_user) {
			unbecome_user();
		}
	}

	del_token = get_delete_on_close_token(lck, fsp->name_hash);
	delete_dir = (del_token != NULL);

	if (delete_dir) {
		int i;
		/* See if others still have the dir open. If this is the
		 * case, then don't delete. If all opens are POSIX delete now. */
		for (i=0; i<lck->num_share_modes; i++) {
			struct share_mode_entry *e = &lck->share_modes[i];
			if (is_valid_share_mode_entry(e) &&
					e->name_hash == fsp->name_hash) {
				if (fsp->posix_open && (e->flags & SHARE_MODE_FLAG_POSIX_OPEN)) {
					continue;
				}
				delete_dir = False;
				break;
			}
		}
	}

	if ((close_type == NORMAL_CLOSE || close_type == SHUTDOWN_CLOSE) &&
				delete_dir) {
	
		/* Become the user who requested the delete. */

		if (!push_sec_ctx()) {
			smb_panic("close_directory: failed to push sec_ctx.\n");
		}

		set_sec_ctx(del_token->uid,
				del_token->gid,
				del_token->ngroups,
				del_token->groups,
				NULL);

		TALLOC_FREE(lck);

		status = rmdir_internals(talloc_tos(), fsp);

		DEBUG(5,("close_directory: %s. Delete on close was set - "
			 "deleting directory returned %s.\n",
			 fsp_str_dbg(fsp), nt_errstr(status)));

		/* unbecome user. */
		pop_sec_ctx();

		/*
		 * Ensure we remove any change notify requests that would
		 * now fail as the directory has been deleted.
		 */

		if(NT_STATUS_IS_OK(status)) {
			remove_pending_change_notify_requests_by_fid(fsp, NT_STATUS_DELETE_PENDING);
		}
	} else {
		TALLOC_FREE(lck);
		remove_pending_change_notify_requests_by_fid(
			fsp, NT_STATUS_OK);
	}

	status1 = fd_close(fsp);

	if (!NT_STATUS_IS_OK(status1)) {
		DEBUG(0, ("Could not close dir! fname=%s, fd=%d, err=%d=%s\n",
			  fsp_str_dbg(fsp), fsp->fh->fd, errno,
			  strerror(errno)));
	}

	/*
	 * Do the code common to files and directories.
	 */
	close_filestruct(fsp);
	file_free(req, fsp);

 out:
	TALLOC_FREE(lck);
	if (NT_STATUS_IS_OK(status) && !NT_STATUS_IS_OK(status1)) {
		status = status1;
	}
	return status;
}
Exemplo n.º 2
0
/************************************************************************
*									*
*  Get all files from directory "dirpath" and insert them into panel	*
*  list.  All directory files will be appended by '/' at the end.	*
*  Return OK or NOT_OK.							*
*									*/
static int
file_listing(char *dirpath)
{
    register struct dirent *dp; /* directory info pointer for each file */
    DIR *dirptr;			/* directory file pointer */
    struct stat statbuf;		/* status of a file */
    int nfile;				/* number of files */
    char fullname[MAXPATHLEN];
    char *filename[MAX_FILE];		/* pointer to a filename */

    /* open the directory */
    if ((dirptr = opendir(dirpath)) == NULL){
	err_msg("Can't open %s", short_path(dirpath));
	return (NOT_OK);
    }
    /* Read files from directory.  Add '/' for a directory file */
    nfile = 0;
    for (dp = readdir(dirptr); dp != NULL; dp = readdir(dirptr)){
	/* Don't list "hidden" files */
	if (*dp->d_name != '.'){
	    strcpy(fullname, dirname);
	    strcat(fullname, "/");
	    strcat(fullname, dp->d_name);
	    (void) stat(fullname, &statbuf);
	    if ((statbuf.st_mode & S_IFMT) == S_IFDIR){
		if ((filename[nfile] = (char *) malloc(strlen(dp->d_name) + 2))
		    == NULL)
		{
		    PERROR("file_listing:malloc");
		    file_free(filename, nfile);
		    closedir(dirptr);
		    return (NOT_OK);
		}
		(void) sprintf(filename[nfile], "%s/", dp->d_name);
	    }else{
		if ((filename[nfile] = strdup(dp->d_name)) == NULL){
		    PERROR("file_listing:strdup");
		    file_free(filename, nfile);
		    closedir(dirptr);
		    return (NOT_OK);
		}
	    }

	    if (nfile++ == (MAX_FILE - 2)){
		err_msg("Only can list %d maximum files", MAX_FILE);
		break;
	    }
	}
    }

    closedir(dirptr);

    /* Add the "../" so that the user can move up a directory */
    if ((filename[nfile] = strdup("../")) == NULL){
	PERROR("file_listing:strdup");
	file_free(filename, nfile);
	closedir(dirptr);
	return (NOT_OK);
    }
    nfile++;

    file_list_update(filename, nfile);
    file_free(filename, nfile);

    return (OK);
}
Exemplo n.º 3
0
/****************************************************************************
 Open a file with a share mode.
****************************************************************************/
files_struct *open_fake_file_shared1(enum FAKE_FILE_TYPE fake_file_type, connection_struct *conn,char *fname,
                                     SMB_STRUCT_STAT *psbuf,
                                     uint32 desired_access,
                                     int share_mode,int ofun, uint32 new_dos_attr, int oplock_request,
                                     int *Access,int *action)
{
    extern struct current_user current_user;
    int flags=0;
    files_struct *fsp = NULL;

    if (fake_file_type == 0) {
        return open_file_shared1(conn,fname,psbuf,desired_access,
                                 share_mode,ofun,new_dos_attr,
                                 oplock_request,Access,action);
    }

    /* access check */
    if (current_user.uid != 0) {
        DEBUG(1,("access_denied to service[%s] file[%s] user[%s]\n",
                 lp_servicename(SNUM(conn)),fname,conn->user));
        errno = EACCES;
        return NULL;
    }

    fsp = file_new(conn);
    if(!fsp)
        return NULL;

    DEBUG(5,("open_fake_file_shared1: fname = %s, FID = %d, share_mode = %x, ofun = %x, oplock request = %d\n",
             fname, fsp->fnum, share_mode, ofun, oplock_request ));

    if (!check_name(fname,conn)) {
        file_free(fsp);
        return NULL;
    }

    fsp->fd = -1;
    fsp->mode = psbuf->st_mode;
    fsp->inode = psbuf->st_ino;
    fsp->dev = psbuf->st_dev;
    fsp->vuid = current_user.vuid;
    fsp->size = psbuf->st_size;
    fsp->pos = -1;
    fsp->can_lock = True;
    fsp->can_read = ((flags & O_WRONLY)==0);
    fsp->can_write = ((flags & (O_WRONLY|O_RDWR))!=0);
    fsp->share_mode = 0;
    fsp->desired_access = desired_access;
    fsp->print_file = False;
    fsp->modified = False;
    fsp->oplock_type = NO_OPLOCK;
    fsp->sent_oplock_break = NO_BREAK_SENT;
    fsp->is_directory = False;
    fsp->is_stat = False;
    fsp->directory_delete_on_close = False;
    fsp->conn = conn;
    string_set(&fsp->fsp_name,fname);
    fsp->wcp = NULL; /* Write cache pointer. */

    fsp->fake_file_handle = init_fake_file_handle(fake_file_type);

    if (fsp->fake_file_handle==NULL) {
        file_free(fsp);
        return NULL;
    }

    conn->num_files_open++;
    return fsp;
}
Exemplo n.º 4
0
static NTSTATUS close_normal_file(struct smb_request *req, files_struct *fsp,
				  enum file_close_type close_type)
{
	NTSTATUS status = NT_STATUS_OK;
	NTSTATUS tmp;
	connection_struct *conn = fsp->conn;

	if (close_type == ERROR_CLOSE) {
		cancel_aio_by_fsp(fsp);
	} else {
		/*
	 	 * If we're finishing async io on a close we can get a write
		 * error here, we must remember this.
		 */
		int ret = wait_for_aio_completion(fsp);
		if (ret) {
			status = ntstatus_keeperror(
				status, map_nt_error_from_unix(ret));
		}
	}

	/*
	 * If we're flushing on a close we can get a write
	 * error here, we must remember this.
	 */

	tmp = close_filestruct(fsp);
	status = ntstatus_keeperror(status, tmp);

	if (fsp->print_file) {
		/* FIXME: return spool errors */
		print_spool_end(fsp, close_type);
		file_free(req, fsp);
		return NT_STATUS_OK;
	}

	/* Remove the oplock before potentially deleting the file. */
	if(fsp->oplock_type) {
		release_file_oplock(fsp);
	}

	/* If this is an old DOS or FCB open and we have multiple opens on
	   the same handle we only have one share mode. Ensure we only remove
	   the share mode on the last close. */

	if (fsp->fh->ref_count == 1) {
		/* Should we return on error here... ? */
		tmp = close_remove_share_mode(fsp, close_type);
		status = ntstatus_keeperror(status, tmp);
	}

	locking_close_file(conn->sconn->msg_ctx, fsp, close_type);

	tmp = fd_close(fsp);
	status = ntstatus_keeperror(status, tmp);

	/* check for magic scripts */
	if (close_type == NORMAL_CLOSE) {
		tmp = check_magic(fsp);
		status = ntstatus_keeperror(status, tmp);
	}

	/*
	 * Ensure pending modtime is set after close.
	 */

	tmp = update_write_time_on_close(fsp);
	if (NT_STATUS_EQUAL(tmp, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
		/* Someone renamed the file or a parent directory containing
		 * this file. We can't do anything about this, we don't have
		 * an "update timestamp by fd" call in POSIX. Eat the error. */

		tmp = NT_STATUS_OK;
	}

	status = ntstatus_keeperror(status, tmp);

	DEBUG(2,("%s closed file %s (numopen=%d) %s\n",
		conn->session_info->unix_info->unix_name, fsp_str_dbg(fsp),
		conn->num_files_open - 1,
		nt_errstr(status) ));

	file_free(req, fsp);
	return status;
}
Exemplo n.º 5
0
static long MS_CALLBACK file_ctrl(BIO *b, int cmd, long num, void *ptr)
	{
	long ret=1;
	FILE *fp=(FILE *)b->ptr;
	FILE **fpp;
	char p[4];

	switch (cmd)
		{
	case BIO_C_FILE_SEEK:
	case BIO_CTRL_RESET:
		if (b->flags&BIO_FLAGS_UPLINK)
			ret=(long)UP_fseek(b->ptr,num,0);
		else
			ret=(long)fseek(fp,num,0);
		break;
	case BIO_CTRL_EOF:
		if (b->flags&BIO_FLAGS_UPLINK)
			ret=(long)UP_feof(fp);
		else
			ret=(long)feof(fp);
		break;
	case BIO_C_FILE_TELL:
	case BIO_CTRL_INFO:
		if (b->flags&BIO_FLAGS_UPLINK)
			ret=UP_ftell(b->ptr);
		else
			ret=ftell(fp);
		break;
	case BIO_C_SET_FILE_PTR:
		file_free(b);
		b->shutdown=(int)num&BIO_CLOSE;
		b->ptr=ptr;
		b->init=1;
#if BIO_FLAGS_UPLINK!=0
#if defined(__MINGW32__) && defined(__MSVCRT__) && !defined(_IOB_ENTRIES)
#define _IOB_ENTRIES 20
#endif
#if defined(_IOB_ENTRIES)
		/* Safety net to catch purely internal BIO_set_fp calls */
		if ((size_t)ptr >= (size_t)stdin &&
		    (size_t)ptr <  (size_t)(stdin+_IOB_ENTRIES))
			BIO_clear_flags(b,BIO_FLAGS_UPLINK);
#endif
#endif
#ifdef UP_fsetmode
		if (b->flags&BIO_FLAGS_UPLINK)
			UP_fsetmode(b->ptr,num&BIO_FP_TEXT?'t':'b');
		else
#endif
		{
#if defined(OPENSSL_SYS_WINDOWS)
		int fd = _fileno((FILE*)ptr);
		if (num & BIO_FP_TEXT)
			_setmode(fd,_O_TEXT);
		else
			_setmode(fd,_O_BINARY);
#elif defined(OPENSSL_SYS_NETWARE) && defined(NETWARE_CLIB)
		int fd = fileno((FILE*)ptr);
		/* Under CLib there are differences in file modes */
		if (num & BIO_FP_TEXT)
			setmode(fd,O_TEXT);
		else
			setmode(fd,O_BINARY);
#elif defined(OPENSSL_SYS_MSDOS)
		int fd = fileno((FILE*)ptr);
		/* Set correct text/binary mode */
		if (num & BIO_FP_TEXT)
			_setmode(fd,_O_TEXT);
		/* Dangerous to set stdin/stdout to raw (unless redirected) */
		else
			{
			if (fd == STDIN_FILENO || fd == STDOUT_FILENO)
				{
				if (isatty(fd) <= 0)
					_setmode(fd,_O_BINARY);
				}
			else
				_setmode(fd,_O_BINARY);
			}
#elif defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_WIN32_CYGWIN)
		int fd = fileno((FILE*)ptr);
		if (num & BIO_FP_TEXT)
			setmode(fd, O_TEXT);
		else
			setmode(fd, O_BINARY);
#endif
		}
		break;
	case BIO_C_SET_FILENAME:
		file_free(b);
		b->shutdown=(int)num&BIO_CLOSE;
		if (num & BIO_FP_APPEND)
			{
			if (num & BIO_FP_READ)
				BUF_strlcpy(p,"a+",sizeof p);
			else	BUF_strlcpy(p,"a",sizeof p);
			}
		else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE))
			BUF_strlcpy(p,"r+",sizeof p);
		else if (num & BIO_FP_WRITE)
			BUF_strlcpy(p,"w",sizeof p);
		else if (num & BIO_FP_READ)
			BUF_strlcpy(p,"r",sizeof p);
		else
			{
			BIOerr(BIO_F_FILE_CTRL,BIO_R_BAD_FOPEN_MODE);
			ret=0;
			break;
			}
#if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_OS2) || defined(OPENSSL_SYS_WIN32_CYGWIN)
		if (!(num & BIO_FP_TEXT))
			strcat(p,"b");
		else
			strcat(p,"t");
#endif
#if defined(OPENSSL_SYS_NETWARE)
		if (!(num & BIO_FP_TEXT))
			strcat(p,"b");
		else
			strcat(p,"t");
#endif
		fp=fopen(ptr,p);
		if (fp == NULL)
			{
			SYSerr(SYS_F_FOPEN,get_last_sys_error());
			ERR_add_error_data(5,"fopen('",ptr,"','",p,"')");
			BIOerr(BIO_F_FILE_CTRL,ERR_R_SYS_LIB);
			ret=0;
			break;
			}
		b->ptr=fp;
		b->init=1;
		BIO_clear_flags(b,BIO_FLAGS_UPLINK); /* we did fopen -> we disengage UPLINK */
		break;
	case BIO_C_GET_FILE_PTR:
		/* the ptr parameter is actually a FILE ** in this case. */
		if (ptr != NULL)
			{
			fpp=(FILE **)ptr;
			*fpp=(FILE *)b->ptr;
			}
		break;
	case BIO_CTRL_GET_CLOSE:
		ret=(long)b->shutdown;
		break;
	case BIO_CTRL_SET_CLOSE:
		b->shutdown=(int)num;
		break;
	case BIO_CTRL_FLUSH:
		if (b->flags&BIO_FLAGS_UPLINK)
			UP_fflush(b->ptr);
		else
			fflush((FILE *)b->ptr);
		break;
	case BIO_CTRL_DUP:
		ret=1;
		break;

	case BIO_CTRL_WPENDING:
	case BIO_CTRL_PENDING:
	case BIO_CTRL_PUSH:
	case BIO_CTRL_POP:
	default:
		ret=0;
		break;
		}
	return(ret);
	}
Exemplo n.º 6
0
static int llrar_handler(lion_t *handle, void *user_data,
						 int status, int size, char *line)
{
	request_t *node = (request_t *) user_data;
	int directory;
	char list[1024];
	char *name, *fsize, *packed, *ratio, *date, *thyme, *attr;
	char *ar, *path, *slash, *root;
    llrar_cache_entry_t *runner, *next;
    llrar_cache_t *cache;

	// If node isn't set, it's b0rken.
	if (!node) return 0;

	switch(status) {

	case LION_CONNECTION_CONNECTED:
		debugf("[llrar] connected to external process, issuing root for /%s\n",
			   node->path);
		break;


	case LION_PIPE_RUNNING:
		debugf("[llrar] unrar is running\n");
		//lion_printf(handle, "HELLO THERE\r\n");

        debugf("[llrar] clearing cache slot %d.\n", llrar_cache_index);

        // Set up RAR cache here.
        cache = &llrar_cache[ llrar_cache_index ];
        node->llrar_cacher = (void *) cache;
        // If this entry is in use, free it.
        SAFE_FREE(cache->path);
        cache->path = strdup(node->disk_path);
        for (runner = cache->files; runner; runner = next) {
            next = runner->next;
            file_free(&runner->file);
            SAFE_FREE(runner);
        }
        cache->files = NULL;

        // Increase cache pointer
        llrar_cache_index++;
        if (llrar_cache_index >= LLRAR_CACHE_SIZE)
            llrar_cache_index = 0;

		break;
	case LION_PIPE_FAILED:
		debugf("[llrar] unrar failed to launch: %d:%s\n", size, line);
        node->llrar_cacher = NULL;
		node->althandle = NULL;
		SAFE_FREE(node->rar_name);
		request_finishdir(node);
		break;
	case LION_PIPE_EXIT:
		debugf("[llrar] unrar finished: %d\n", size);
		if (size == -1) {
			lion_want_returncode(handle);
			break;
		}
        node->llrar_cacher = NULL;
		node->althandle = NULL;
		SAFE_FREE(node->rar_name);
		request_finishdir(node);

        //llrar_dumpcache();
		break;

	case LION_INPUT:
// Name             Size   Packed Ratio  Date   Time     Attr      CRC   Meth Ver
//-------------------------------------------------------------------------------
// aaf-rc.s03e13.avi 105119744 14999906  --> 11-11-07 23:52  .....A.   78AF2535 m0g 2.0
//-------------------------------------------------------------------------------
		debugf("[llrar] >> '%s'\n", line);

		switch(node->unrar_parse) {
		case 0:  // start of unrar list, waiting for line with -----
			if (!strncmp("--------------------", line, 20))
				node->unrar_parse++;
			break;

		case 1:  // woohooo, actually parsing entries
			// This is the filename part
			// " directory1/directory2/file2.avi"

			if (!strncmp("--------------------", line, 20)) {
				node->unrar_parse = 0;
				break;
			}

			if (*line != ' ') {
				debugf("[llrar] unable to parse: '%s'\n", line);
				break;
			}

			// Skip that leading space.
			if (*line == ' ')
				line++;

			// Remember this line until next parsing line.
			node->rar_name = strdup(line);

			node->unrar_parse++;
			break;

		case 2: // parse out filesize, type etc.
			// "   7       17 242% 04-12-07 14:11 -rw-r--r-- 16B28489 m3b 2.9"

			// Alternate filename/data lines, change back to filename
			node->unrar_parse = 1;

			ar = line;

			// node->rar_name hold the FULL path name.
			fsize  = misc_digtoken(&ar, " \r\n");
			packed = misc_digtoken(&ar, " \r\n");
			ratio  = misc_digtoken(&ar, " \r\n");
			date   = misc_digtoken(&ar, " \r\n");
			thyme  = misc_digtoken(&ar, " \r\n");
			attr   = misc_digtoken(&ar, " \r\n");

			if (!node->rar_name ||
				!fsize|| !*fsize||
				!attr || !*attr) {
				debugf("[llrar] unable to parse -- skipping\n");
				break;
			}

			// Files spanning Volumes will be repeated, but we can tell by
			// lookip at "ratio" column.
			if (!mystrccmp("<->", ratio) ||
				!mystrccmp("<--", ratio)) {

				SAFE_FREE(node->rar_name);
				break;
			}


			debugf("[llrar] parsed name '%s'\n", node->rar_name);

			// Now we need to look at the rar_file fullname, and
			// split it into directory/filename
			// Find last slash. Will windows use '\' ?
#ifdef WIN32
			for (name = node->rar_name; *name; name++)
				if (*name == '\\') *name = '/';
#endif
			slash = strrchr(node->rar_name, '/');
			if (!slash) { // We are in root.
				path = "/";
				name = node->rar_name;
			} else { // We are in a subdir
				*slash = 0;
				name = &slash[1];
				path = node->rar_name;
			}
			// Now "path" should hold full path, and "name" just the
			// entry name.
			if (node->rar_directory) {
				root = node->rar_directory;
				// Skip leading "/" as unrar wont start with /
				while (*root == '/') root++;
			} else
				root = "/";

			debugf("[llrar] Checking '%s' == '%s'\n",
				   path, root);


			//  Now check if it is for a path we care about
            // and not in cachefill-only mode
			if (!node->llrar_cache_fill && !mystrccmp(path, root)) {
				// It is

				//rar attributes. If DOS format, it will be
				// .D.....    : 7 chars.
				// Unix format:
				// d--------- :  10 chars
				directory = 0;
				if ((tolower(*attr) == 'd') ||
					(tolower(attr[1]) == 'd'))
					directory = 1;

                if (node->dvdread_file) {

                    if (directory)
                        snprintf(list, sizeof(list),
              "drwxr-xr-x  1 unrar unrar %s Jun 7 %s %s?fv=%"PRIu64",%s&d=%s/%s",
                                 fsize,
                                 thyme,
                                 node->path,

                                 node->bytes_size,
                                 node->dvdread_file,

                                 node->rar_directory ? node->rar_directory : "",
                                 name);
                    else
                        snprintf(list, sizeof(list),
             "-rwxr-xr-x  1 unrar unrar %s Jun 7 %s %s?fv=%"PRIu64",%s&f=%s,%s/%s",
                                 fsize,
                                 thyme,
                                 node->path,

                                 node->bytes_size,
                                 node->dvdread_file,

                                 fsize,
                                 node->rar_directory ? node->rar_directory : "",
                                 name);

                } else { // No dvdread_file (RARISO)

                    if (directory)
                        snprintf(list, sizeof(list),
                                 "drwxr-xr-x  1 unrar unrar %s Jun 7 %s %s?d=%s/%s",
                                 fsize,
                                 thyme,
                                 node->path,
                                 node->rar_directory ? node->rar_directory : "",
                                 name);
                    else
                        snprintf(list, sizeof(list),
                                 "-rwxr-xr-x  1 unrar unrar %s Jun 7 %s %s?f=%s,%s/%s",
                                 fsize,
                                 thyme,
                                 node->path,
                                 fsize,
                                 node->rar_directory ? node->rar_directory : "",
                                 name);
                } // dvdread_file

				skin_write_type(node, list);

			} // directory we care about (in our path)


            // RAR cache.
            if (node->llrar_cacher) {
                llrar_cache_entry_t *nfile;
                nfile = (llrar_cache_entry_t *)malloc(sizeof(llrar_cache_entry_t));
                if (nfile) {
                    memset(nfile, 0, sizeof(*nfile));
                    nfile->file.name = misc_strjoin(path,
                                                    name);
                    nfile->file.size = strtoull(fsize, NULL, 10);
                    nfile->file.directory = YNA_NO;
                    // Link in
                    nfile->next = ((llrar_cache_t *)(node->llrar_cacher))->files;
                    ((llrar_cache_t *)(node->llrar_cacher))->files = nfile;
                } // malloc
            } // cacher


			// Release the filename from previous line.
			SAFE_FREE(node->rar_name);

			break;

		case 3:  // seen ----- the rest is fluff
			break;
		}




		break;

	}

	return 0;
}
Exemplo n.º 7
0
static
int fatfs_close (int fd)
{
    int ret;
    struct fd *pfd;

    pfd = file_struct_get(fd);

    if (pfd == NULL)
    {
        errno = EBADF;
        ret = -1;
    }
    else if (pfd->opaque == NULL)
    {
        errno = EBADF;
        ret = -1;
    }
    else if (S_ISREG(pfd->stat.st_mode))
    {
        FIL *filp;
        FRESULT result;

        filp = pfd->opaque;

        result = f_close(filp);
        if (result == FR_OK)
        {
            fatfs_fil_free(filp);
            file_free(fd);
            ret = 0;
        }
        else
        {
            errno = fresult2errno(result);
            ret = -1;
        }
    }
    else if (S_ISDIR(pfd->stat.st_mode))
    {
        DIR *dp;
        FRESULT result;

        dp = pfd->opaque;

        result = f_closedir(&dp->ffdir);
        if (result == FR_OK)
        {
            fatfs_dir_free(dp);
            file_free(fd);
            ret = 0;
        }
        else
        {
            errno = fresult2errno(result);
            ret = -1;
        }
    }
    else
    {
        errno = EBADF;
        ret = -1;
    }

    return ret;
}
/*
* This is a co-operative task. This function must NEVER return
*/
void uip_task_main(void)
{
    //initialise all the connections to point to the invalid handle
    for( i = 0 ; i  < UIP_CONNS; i++)
    {
        uip_conns[i].appstate[0] = FILE_INVALID_HANDLE;
    }

    while(1) {

        task_yield();

        if( UIP_DMA_RX_PACKET_READY )
        {
            UIP_DMA_RX_PACKET_READY = 0;
            uip_len = uip_dma_rx_last_packet_length;
            // packet received - buffer is already acquired

            // process an IP packet
            if(BUF->type == HTONS(UIP_ETHTYPE_IP)) {
                // add the source to the ARP cache
                // also correctly set the ethernet packet length before processing
                uip_arp_ipin();
                uip_input();

                // transmit a packet, if one is ready
                if(uip_len > 0) {
                    uip_arp_out();
                    nic_send();
                }
                else nic_rx_maybe();
            }
            else if(BUF->type == HTONS(UIP_ETHTYPE_ARP)) {

                // process an ARP packet
                uip_arp_arpin();

                // transmit a packet, if one is ready
                if(uip_len > 0) {

                    nic_send();
                }
                else {

                    nic_rx_maybe();
                }
            }
            else //don't know how to process this packet. Discard
            {
                puts("Unknown packet discarded");
                nic_rx_maybe();
            }
        }
        else if(UIP_DMA_PERIODIC_TIMEOUT && uip_acquireBuffer()) {
            if( next_conn_id != UIP_CONNS )
            {
                uip_len = 0;
                while( uip_len == 0 && next_conn_id < UIP_CONNS )
                {
                    uip_periodic( next_conn_id );
                    // transmit a packet, if one is ready
                    if(uip_len > 0) {
                        uip_arp_out();
                        nic_send();
                    }
                    next_conn_id++;
                }
            }
            if( next_conn_id == UIP_CONNS )
            {

                UIP_DMA_PERIODIC_TIMEOUT=0;

                //blink LED to show we're alive
                LD1_O = !LD1_O;
                next_conn_id = 0;

                /* Call the ARP timer function every 10 seconds. */
                if(++arptimer == 20) {
                    uip_arp_timer();
                    arptimer = 0;
                }
                uip_releaseBuffer();
//possibly change test below to if( uip_len == 0)??
                if( ENC_DMACONbits.CHEN == 0 ) nic_rx_maybe();
            }
        }
        else
        {
            //anyone need to send something or close?
            unsigned char loop_end = next_send_id;

            do
            {
                struct uip_conn *connptr = &uip_conns[next_send_id];
                file_handle_t fh = connptr->appstate[0];
                struct file_t *f = file_get_by_handle(fh);
                if(f != NULL &&
                        ( f->state == ClosePending ||
                          (f->write_buffer != NULL && buffer_available( f->write_buffer) > 0 &&
                           connptr->len == 0
                          )
                        )
                  )
                {
#ifdef __DEBUG
                    printf("\n TCP conn id: %hhd state: %hhd. File State: %hhx", next_send_id, connptr->tcpstateflags, f->state);
#endif
                    if(  connptr->tcpstateflags == CLOSED )
                    {
#ifdef __DEBUG
                        puts("\r\nFreed tcp conn and file ");
#endif
                        file_free( fh );
                        connptr->appstate[0] = FILE_INVALID_HANDLE;
                    }
                    if( uip_acquireBuffer() )
                    {
                        uip_periodic_conn(connptr);
                        if(uip_len > 0) {
#ifdef __DEBUG
                            printf("\n id %hhd sending", next_send_id);
#endif
                            uip_arp_out();
                            nic_send();
                            break;
                        }
                        else uip_releaseBuffer();
                    }
                    break; //this connection wants to write. try again later
                }

                next_send_id = ++next_send_id < UIP_CONNS ? next_send_id : 0;

            } while( next_send_id != loop_end );
        }


    } //end while

}
Exemplo n.º 9
0
static long MS_CALLBACK file_ctrl(BIO *b, int cmd, long num, void *ptr)
{
    long ret=1;
    FILE *fp=(FILE *)b->ptr;
    FILE **fpp;
    char p[4];

    switch (cmd)
    {
    case BIO_C_FILE_SEEK:
    case BIO_CTRL_RESET:
        ret=(long)fseek(fp,num,0);
        break;
    case BIO_CTRL_EOF:
        ret=(long)feof(fp);
        break;
    case BIO_C_FILE_TELL:
    case BIO_CTRL_INFO:
        ret=ftell(fp);
        break;
    case BIO_C_SET_FILE_PTR:
        file_free(b);
        b->shutdown=(int)num&BIO_CLOSE;
        b->ptr=(char *)ptr;
        b->init=1;
#if defined(OPENSSL_SYS_WINDOWS)
        if (num & BIO_FP_TEXT)
            _setmode(fileno((FILE *)ptr),_O_TEXT);
        else
            _setmode(fileno((FILE *)ptr),_O_BINARY);
#elif defined(OPENSSL_SYS_MSDOS)
        {
            int fd = fileno((FILE*)ptr);
            /* Set correct text/binary mode */
            if (num & BIO_FP_TEXT)
                _setmode(fd,_O_TEXT);
            /* Dangerous to set stdin/stdout to raw (unless redirected) */
            else
            {
                if (fd == STDIN_FILENO || fd == STDOUT_FILENO)
                {
                    if (isatty(fd) <= 0)
                        _setmode(fd,_O_BINARY);
                }
                else
                    _setmode(fd,_O_BINARY);
            }
        }
#elif defined(OPENSSL_SYS_OS2)
        if (num & BIO_FP_TEXT)
            setmode(fileno((FILE *)ptr), O_TEXT);
        else
            setmode(fileno((FILE *)ptr), O_BINARY);
#endif
        break;
    case BIO_C_SET_FILENAME:
        file_free(b);
        b->shutdown=(int)num&BIO_CLOSE;
        if (num & BIO_FP_APPEND)
        {
            if (num & BIO_FP_READ)
                BUF_strlcpy(p,"a+",sizeof p);
            else	BUF_strlcpy(p,"a",sizeof p);
        }
        else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE))
            BUF_strlcpy(p,"r+",sizeof p);
        else if (num & BIO_FP_WRITE)
            BUF_strlcpy(p,"w",sizeof p);
        else if (num & BIO_FP_READ)
            BUF_strlcpy(p,"r",sizeof p);
        else
        {
            BIOerr(BIO_F_FILE_CTRL,BIO_R_BAD_FOPEN_MODE);
            ret=0;
            break;
        }
#if defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_OS2)
        if (!(num & BIO_FP_TEXT))
            strcat(p,"b");
        else
            strcat(p,"t");
#endif
        fp=fopen(ptr,p);
        if (fp == NULL)
        {
            SYSerr(SYS_F_FOPEN,get_last_sys_error());
            ERR_add_error_data(5,"fopen('",ptr,"','",p,"')");
            BIOerr(BIO_F_FILE_CTRL,ERR_R_SYS_LIB);
            ret=0;
            break;
        }
        b->ptr=(char *)fp;
        b->init=1;
        break;
    case BIO_C_GET_FILE_PTR:
        /* the ptr parameter is actually a FILE ** in this case. */
        if (ptr != NULL)
        {
            fpp=(FILE **)ptr;
            *fpp=(FILE *)b->ptr;
        }
        break;
    case BIO_CTRL_GET_CLOSE:
        ret=(long)b->shutdown;
        break;
    case BIO_CTRL_SET_CLOSE:
        b->shutdown=(int)num;
        break;
    case BIO_CTRL_FLUSH:
        fflush((FILE *)b->ptr);
        break;
    case BIO_CTRL_DUP:
        ret=1;
        break;

    case BIO_CTRL_WPENDING:
    case BIO_CTRL_PENDING:
    case BIO_CTRL_PUSH:
    case BIO_CTRL_POP:
    default:
        ret=0;
        break;
    }
    return(ret);
}
Exemplo n.º 10
0
static void
dump_region_item(struct subdivision *sub, struct file *rgn, struct map_rect_priv *mr)
{
	int offset,item_offset,i,j;
	unsigned short count=0;
	unsigned short *offsets[4];
	unsigned short *file_offsets;
	struct rgn_point *pnt;

	offset=triple_u(&sub->rgn_offset)+mr->rgn_hdr->offset_len.offset;
	file_offsets=file_read(rgn, offset, 90*sizeof(unsigned short));
	printf("0x%x ", offset); dump_hex(file_offsets, 90);
	for (i=0 ; i < 4 ; i++) {
		printf("i=%d\n", i);
		if (sub->types & (0x10 << i)) {
			if (count) {	
				offsets[i]=&file_offsets[count-1];
			} else
				offsets[i]=&count;
			count++;
		} else
			offsets[i]=NULL;
		
	}
	count--;
	count*=2;
	for (i=0 ; i < 4 ; i++) {
		printf("i=%d\n", i);
		if (offsets[i]) {
			printf("offset[%d]=0x%x(%d)\n", i, *offsets[i], *offsets[i]);
			switch (i) {
			case 0:
				printf("point\n");
				break;
			case 1:
				printf("indexed point\n");
				break;
			case 2:
				printf("polyline\n");
				break;
			case 3:
				printf("polygon\n");
				break;
			}
			item_offset=offset+*offsets[i];
			switch (i) {
			case 0:
			case 1:
				for (j = 0 ; j < 10 ; j++) {
					struct coord_geo g;
					char buffer[1024];
					double conv=180.0/(1UL<<23);
					pnt=file_read(rgn, item_offset, sizeof(*pnt)*20);
					// printf("0x%x ", item_offset); dump_hex(pnt, 32);
					dump_point(pnt);
					g.lng=(triple(&sub->center.lng)+(pnt->lng_delta << shift))*conv;
					g.lat=(triple(&sub->center.lat)+(pnt->lat_delta << shift))*conv;
					printf("%f %f\n", g.lng, g.lat);
					transform_geo_text(&g, buffer);
					printf("%s\n", buffer);
					dump_label_offset(mr, triple_u(&pnt->lbl_offset));
					if (pnt->info & 0x80) 
						item_offset+=sizeof(*pnt);
					else
						item_offset+=sizeof(*pnt)-1;
				}
			}
		} else {
			printf("offset[%d] doesn't exist\n", i);
		}
	}
	file_free(file_offsets);
}
Exemplo n.º 11
0
static long
file_ctrl(BIO *b, int cmd, long num, void *ptr)
{
	long ret = 1;
	FILE *fp = (FILE *)b->ptr;
	FILE **fpp;
	char p[4];

	switch (cmd) {
	case BIO_C_FILE_SEEK:
	case BIO_CTRL_RESET:
		ret = (long)fseek(fp, num, 0);
		break;
	case BIO_CTRL_EOF:
		ret = (long)feof(fp);
		break;
	case BIO_C_FILE_TELL:
	case BIO_CTRL_INFO:
		ret = ftell(fp);
		break;
	case BIO_C_SET_FILE_PTR:
		file_free(b);
		b->shutdown = (int)num&BIO_CLOSE;
		b->ptr = ptr;
		b->init = 1;
		break;
	case BIO_C_SET_FILENAME:
		file_free(b);
		b->shutdown = (int)num&BIO_CLOSE;
		if (num & BIO_FP_APPEND) {
			if (num & BIO_FP_READ)
				strlcpy(p, "a+", sizeof p);
			else	strlcpy(p, "a", sizeof p);
		} else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE))
			strlcpy(p, "r+", sizeof p);
		else if (num & BIO_FP_WRITE)
			strlcpy(p, "w", sizeof p);
		else if (num & BIO_FP_READ)
			strlcpy(p, "r", sizeof p);
		else {
			BIOerr(BIO_F_FILE_CTRL, BIO_R_BAD_FOPEN_MODE);
			ret = 0;
			break;
		}
		fp = fopen(ptr, p);
		if (fp == NULL) {
			SYSerr(SYS_F_FOPEN, errno);
			ERR_asprintf_error_data("fopen('%s', '%s')", ptr, p);
			BIOerr(BIO_F_FILE_CTRL, ERR_R_SYS_LIB);
			ret = 0;
			break;
		}
		b->ptr = fp;
		b->init = 1;
		break;
	case BIO_C_GET_FILE_PTR:
		/* the ptr parameter is actually a FILE ** in this case. */
		if (ptr != NULL) {
			fpp = (FILE **)ptr;
			*fpp = (FILE *)b->ptr;
		}
		break;
	case BIO_CTRL_GET_CLOSE:
		ret = (long)b->shutdown;
		break;
	case BIO_CTRL_SET_CLOSE:
		b->shutdown = (int)num;
		break;
	case BIO_CTRL_FLUSH:
		fflush((FILE *)b->ptr);
		break;
	case BIO_CTRL_DUP:
		ret = 1;
		break;

	case BIO_CTRL_WPENDING:
	case BIO_CTRL_PENDING:
	case BIO_CTRL_PUSH:
	case BIO_CTRL_POP:
	default:
		ret = 0;
		break;
	}
	return (ret);
}
Exemplo n.º 12
0
void sites_compare(void)
{
	int i,j;
	site_t *site;
	file_t *file, **tmp;

	// Sort it
	for (i = 0; i < num_sites; i++) {

		site = sites[i];

		printf("Sorting '%s'...\n", site->name);

		qsort(site->files, site->num_files, sizeof(file_t *), sort_by_date);

	}


	// Build new list.
	for (i = 0; i < num_sites; i++) {

		site = sites[i];

		for (j = 0; j < site->num_files; j++) {

			// Is it newer than last time we checked? OR
			// Is it part of incpattern?
			if ((conf_incpattern &&
				 file_listmatch(conf_incpattern, site->files[j]->name)) ||
				(site->files[j]->date > site->last_check)) {

				if (site->use_lists && site_listsok(site, site->files[j]))
					continue;

				// If file already in the new list?
				if (file_find(new_files, num_new, site->files[j]->name))
					continue;

				file = file_dupe(site->files[j]);
				if (!file) continue;

				tmp = realloc(new_files,
							  sizeof(file_t *)*(num_new + 1));
				if (!tmp) {
					file_free(file);
					return;
				}

				new_files = tmp;

				new_files[ num_new ] = file;
				num_new++;

				continue;

			}

			// Older, since its sorted, stop. Unless
			// we are searching for something
			if (!conf_incpattern)
				break;

		} // all files

	} // all sites.

	printf("Sorting new list...%u\n", num_new);

	qsort(new_files, num_new, sizeof(file_t *), sort_by_date);



	printf("\n\n-----======> DISPLAY MATRIX <======-----\n\n");


	printf("T |");
	for(i = 0; i < num_sites; i++)
		printf("%-5.5s|", sites[i] ? sites[i]->name : "fail1");
	printf(" New Items");
	printf("\n");
	printf("--+");
	for(i = 0; i < num_sites; i++)
		printf("-----+");
	printf("-----------");
	printf("\n");

	for (j = 0; j < num_new; j++) {

        printf("%c |", new_files[j]->type ? 'd' : 'f');

        for(i = 0; i < num_sites; i++)
            printf("%-5.5s|",
                   status2str( site_status(sites[i], new_files[j]) ));

        printf(" %s", new_files[j]->name);

        printf("\n");

	}

	printf("\n\n");

}
Exemplo n.º 13
0
//<< DIRLIST|SID=1|FID=0|NAME=giana_sounds|DATE=1057590000|SIZE=512|USER=nobody|GROUP=nobody|PERM=drwxrwxrwx|type=directory
void site_cmd_dirlist(char **keys, char **values, int items,void *optarg)
{
	fxpone_t *the_engine = optarg;
	char *sid, *name, *fid, *date, *size, *type, *end, *begin;
	int i;
	unsigned int id;
	site_t *site;
	file_t *file, **tmp;

	sid    = parser_findkey(keys, values, items, "SID");
	name   = parser_findkey(keys, values, items, "NAME");
	fid    = parser_findkey(keys, values, items, "FID");
	date   = parser_findkey(keys, values, items, "DATE");
	size   = parser_findkey(keys, values, items, "SIZE");
	type   = parser_findkey(keys, values, items, "FTYPE");
	begin  = parser_findkey(keys, values, items, "BEGIN");
	end    = parser_findkey(keys, values, items, "END");

	if (!sid) return;

	if (begin) return;

	id = atoi(sid);

	for (i = 0; i < num_sites; i++) {

		if (!sites[i]) continue;

		if (sites[i]->sid == id) {

			site = sites[i];

			if (end) {

				site->current_dir++;
				if (site->current_dir >= site->num_dirs) {
					site_ready(the_engine->handle, site);
					return;
				}

				printf("Site %s processing dir '%s'\n", sites[i]->name,
					   sites[i]->dirs[sites[i]->current_dir]);

				lion_printf(the_engine->handle, "CWD|SID=%u|PATH=%s\r\n",
							sites[i]->sid,
							sites[i]->dirs[sites[i]->current_dir]);

				return;

			}


            // Don't show entries in HIDE
            if (sites[i]->hide && file_listmatch(sites[i]->hide, name)) return;


			//			SAFE_COPY(sites[i]->name, name);
			file = file_new();
			if (!file) return;

			tmp = realloc(site->files, sizeof(file_t *)*(site->num_files + 1));
			if (!tmp) {
				file_free(file);
				return;
			}

			site->files = tmp;

			site->files[ site->num_files ] = file;
			site->num_files++;

			SAFE_COPY(file->name, name);
            if (date)
                file->date = strtoul(date, NULL, 10);
            if (size)
                file->size = strtoull(size, NULL, 10);
			if (type && !mystrccmp("directory", type))
				file->type = 1;

			// Remember the source path we came from
			file->current_dir = site->current_dir;

		}

	}

}
Exemplo n.º 14
0
/************************************************************************
*									*
*  User has entered part of the filename, and this routine tries to     *
*  complete a filename from the current directory.  If it finds more    *
*  than one filename to complete,  it will list them in the panel list
*  window.								*
*									*/
static void
file_complete_name(void)
{
    char fractname[128];		/* fraction user name */
    int fractnamlen;			/* fraction user name length */
    register struct dirent *dp; /* directory info pointer for each file */
    DIR *dirptr;			/* directory file pointer */
    struct stat statbuf;		/* status of a file */
    int nfile;				/* number of files */
    char *filename[MAX_FILE];		/* pointer to a filename */
    int i;				/* loop counter */

    (void) strcpy(fractname, (char *) xv_get(fhdl->filename, PANEL_VALUE));
    if ((fractnamlen = strlen(fractname)) == 0)
	return;

    /* open the directory */
    if ((dirptr = opendir(dirname)) == NULL){
	char dirbuf[MAXPATHLEN];

	err_msg("Cannot open %s", short_path(getcwd(dirbuf,MAXPATHLEN)));
	return;
    }
    nfile = 0;
    for (dp = readdir(dirptr); dp != NULL; dp = readdir(dirptr)){
	if (strncmp(dp->d_name, fractname, fractnamlen) == 0){
	    (void) stat(dp->d_name, &statbuf);
	    if ((statbuf.st_mode & S_IFMT) == S_IFDIR){
		if ((filename[nfile] = (char *) malloc(strlen(dp->d_name) + 2))
		    == NULL) {
		    PERROR("file_complte_name:malloc");
		    file_free(filename, nfile);
		    closedir(dirptr);
		    return;
		}
		(void) sprintf(filename[nfile], "%s/", dp->d_name);
	    }else{
		if ((filename[nfile] = strdup(dp->d_name)) == NULL){
		    PERROR("file_complte_name:strdup");
		    file_free(filename, nfile);
		    closedir(dirptr);
		    return;
		}
	    }
	    if (nfile++ == (MAX_FILE - 2)){
		err_msg("Only can list %d maximum files", MAX_FILE);
		break;
	    }
	}
    }

    if (nfile == 0){			/* NO such fractional filename */
	err_msg("No such fractional filename: %s", fractname);
	return;
    }
    if (nfile == 1){			/* We can complete filename */
	xv_set(fhdl->filename, PANEL_VALUE, filename[0], NULL);
    }else{				/* More than one filename found */
	char c0;			/* the first filename character */
	char ch;			/* the rest of the filename
					   character */

	/* Try to complete the fractional filename as many characters  */
	/* as possible.  The idea is to compare all the filenames      */
	/* starting at the position of the 'fractnamlen'.              */
	while (1){
	    /* A character to be checked (for the first filename) */
	    if ((c0 = *(filename[0] + fractnamlen)) == 0)
		break;

	    for (i = 1; i < nfile; i++){
		ch = *(filename[i] + fractnamlen);
		if ((ch == 0) || (ch != c0))
		    goto STOP_COMPLETE;
	    }

	    /* All filenames have the same character at 'fractnamlen' */
	    fractname[fractnamlen++] = c0;
	    fractname[fractnamlen] = 0;
	}

STOP_COMPLETE:

	/* Update the user fractional filename */
	xv_set(fhdl->filename, PANEL_VALUE, fractname, NULL);

	/* Update the panel list to all matching filenames */
	file_list_update(filename, nfile);
    }

    /* Free the filenames */
    file_free(filename, nfile);
}
Exemplo n.º 15
0
/* Find an unused file structure and return a pointer to it.
 * Returns an error pointer if some error happend e.g. we over file
 * structures limit, run out of memory or operation is not permitted.
 *
 * Be very careful using this.  You are responsible for
 * getting write access to any mount that you might assign
 * to this filp, if it is opened for write.  If this is not
 * done, you will imbalance int the mount's writer count
 * and a warning at __fput() time.
 */
struct file *get_empty_filp(void)
{
	const struct cred *cred = current_cred();
	static long old_max;
	struct file *f;
	int error;

	/*
	 * Privileged users can go above max_files
	 */
	if (get_nr_files() >= files_stat.max_files && !capable(CAP_SYS_ADMIN)) {
		/*
		 * percpu_counters are inaccurate.  Do an expensive check before
		 * we go and fail.
		 */
		if (percpu_counter_sum_positive(&nr_files) >= files_stat.max_files)
			goto over;
	}

	f = kmem_cache_zalloc(filp_cachep, GFP_KERNEL);
	if (unlikely(!f))
		return ERR_PTR(-ENOMEM);

	percpu_counter_inc(&nr_files);
	f->f_cred = get_cred(cred);
	error = security_file_alloc(f);
	if (unlikely(error)) {
		file_free(f);
		return ERR_PTR(error);
	}

	INIT_LIST_HEAD(&f->f_u.fu_list);
	atomic_long_set(&f->f_count, 1);
	rwlock_init(&f->f_owner.lock);
	spin_lock_init(&f->f_lock);
	eventpoll_init_file(f);
	/* f->f_version: 0 */
	return f;

over:
	/* Ran out of filps - report that */
	if (get_nr_files() > old_max) {
#ifdef FILE_OVER_MAX
        static int fd_dump_all_files = 0;     
        if(!fd_dump_all_files) { 
	        struct task_struct *p;
	        xlog_printk(ANDROID_LOG_INFO, FS_TAG, "(PID:%d)files %d over old_max:%d", current->pid, get_nr_files(), old_max);
	        for_each_process(p) {
	            pid_t pid = p->pid;
	            struct files_struct *files = p->files;
	            struct fdtable *fdt = files_fdtable(files);
	            if(files && fdt) {
	                fd_show_open_files(pid, files, fdt);
	            }
	        }
	        fd_dump_all_files = 0x1;
        }
#endif
		pr_info("VFS: file-max limit %lu reached\n", get_max_files());
		old_max = get_nr_files();
	}
	return ERR_PTR(-ENFILE);
}
//This is the implementation of the UIPAPP that uIP will call when
//something network data related happens.
//The purpose of this app is to move buffer data to and from the network
void uip_socket_app(void)
{
    int i;
    file_handle_t file_handle =  (uip_conn->appstate)[0];
    struct file_t* file = NULL;
    struct buffer_t *rxbuf = NULL;
    struct buffer_t *txbuf = NULL;
    bool may_send = true;

#ifdef __DEBUG
    printf("\r\napp: process conn @ %p", uip_conn);
#endif


    if(uip_connected())
    {
#ifdef __DEBUG
        printf("\r\napp: connected. Ports %hd:%hd", uip_conn->lport, uip_conn->rport);
#endif
        if( file_handle == FILE_INVALID_HANDLE )
        {
            //it's an incoming connection (no assigned handle)
            //find the index of the listening port
            for( i = 0; i < UIP_LISTENPORTS ; i++ )
            {
                if( uip_listenports[i] == uip_conn->lport )
                {
                    file_handle = listenports[i](uip_conn->lport, uip_conn->ripaddr, uip_conn->rport);
                    if( file_handle != FILE_INVALID_HANDLE )
                    {
                        uip_conn->appstate[0] = file_handle;
                    }
                    break;
                }
            }
        }
    }
    if( file_handle == FILE_INVALID_HANDLE)
    {
        goto close_or_abort;
    }

    file =  file_get_by_handle(file_handle);
    rxbuf = file->read_buffer;
    txbuf = file->write_buffer;


    if( file->state == ClosePending )
    {
#ifdef __DEBUG
        printf("\r\napp: freeing handle %hhd",uip_conn->appstate[0]);
#endif
        file_free(uip_conn->appstate[0]);
        uip_conn->appstate[0] = FILE_INVALID_HANDLE;
        goto close_or_abort;
    }


    if( rxbuf == NULL || txbuf == NULL )
    {
        goto close_or_abort;
    }

    if( uip_connected() ) file->state = Open;

    if( uip_acked() ) {
#ifdef __DEBUG
        printf("\r\napp: acked %d bytes", uip_this_ack);
#endif
        buffer_seek( txbuf, uip_this_ack );
    }

    int free = buffer_free( rxbuf );//free to write to
    int available = buffer_available( txbuf );//available to read

    if(uip_rexmit()) {
//#ifdef __DEBUG
        printf("\r\napp: rexmit. Handle: %hhd", file_handle);
//#endif
        buffer_peek( txbuf, (char*)uip_appdata, uip_conn->len);
        uip_send(uip_appdata, uip_conn->len);
        may_send = false;
    }
    else if(uip_newdata())
    {
#ifdef __DEBUG
        printf("\r\napp: newdata. Handle: %hhd. len=%u\n", file_handle, uip_datalen() );
#endif
        if( free >= uip_datalen() )
        {
            free -= buffer_write( rxbuf, (char*)uip_appdata, uip_datalen() );
        }
        else {
            puts("buffer overflow\n");
        }
    }
    else if( uip_closed() )
    {
#ifdef __DEBUG
        printf("\r\napp: connection id %hhd closed\n", file_handle );
#endif
        file->state = Closed;
        may_send = false;
    }
    else if( uip_aborted() )
    {
#ifdef __DEBUG
        printf("\r\napp: connection id %hhd aborted\n", file_handle );
#endif
        file->state = Aborted;
        may_send = false;
    }
    else if( uip_timedout() )
    {
#ifdef __DEBUG
        printf("\r\napp: connection id %hhd timed out\n", file_handle );
#endif
        file->state = TimedOut;
        may_send = false;
    }
//	if( available >  0 && file->state > Open )
//	{
//		buffer_seek( txbuf, available);
//	}
    if( available > 0 && may_send && uip_conn->len == 0) {
        //we can send the smaller of what's available or the connection mss
        int size = available < uip_mss() ? available : uip_mss() ;
        int peek = buffer_peek( txbuf, (char*)uip_appdata, size);
        uip_appdata[peek] = '\0';
#ifdef __DEBUG
        printf("\r\napp: sending %d of %d available bytes: [%s] ", peek,available, (char*)uip_appdata);
#endif
        uip_send(uip_appdata, peek);

    }
    /*
    This code prevents the "silly-window" TCP problem
    The problem is though, that we want to fill our rx buffer entirely
    sometimes before acting on it.
    I've disabled this code in the meantime, until we can
    set the behaviour on a connection basis
    ...Or it becomes apparent that we just don't need it.

    if( free < rxbuf->size / 2 )
    {
    	puts("\napp: stopping rx\n");
    	uip_stop();
    }
    else if( uip_stopped(uip_conn) )
    {
    	puts("\napp: restarting rx\n");
    	uip_restart(); //TODO NEED to be able to set the window size?
    }
    */
    //...instead let's try setting the window size
    uip_receive_window = free;
    return;

close_or_abort:
    if( uip_closed() || uip_aborted() || uip_timedout() )
    {
        puts("\r\napp: abort chosen");
        uip_abort();
    }
    else
    {
        puts("\r\napp: close chosen");
        uip_close();
    }

}
Exemplo n.º 17
0
NTSTATUS smbXsrv_open_close(struct smbXsrv_open *op, NTTIME now)
{
    struct smbXsrv_open_table *table;
    struct db_record *local_rec = NULL;
    struct db_record *global_rec = NULL;
    NTSTATUS status;
    NTSTATUS error = NT_STATUS_OK;

    if (op->table == NULL) {
        return NT_STATUS_OK;
    }

    table = op->table;
    op->table = NULL;

    op->status = NT_STATUS_FILE_CLOSED;
    op->global->disconnect_time = now;
    server_id_set_disconnected(&op->global->server_id);

    global_rec = op->global->db_rec;
    op->global->db_rec = NULL;
    if (global_rec == NULL) {
        uint8_t key_buf[SMBXSRV_OPEN_GLOBAL_TDB_KEY_SIZE];
        TDB_DATA key;

        key = smbXsrv_open_global_id_to_key(
                  op->global->open_global_id,
                  key_buf);

        global_rec = dbwrap_fetch_locked(table->global.db_ctx,
                                         op->global, key);
        if (global_rec == NULL) {
            DEBUG(0, ("smbXsrv_open_close(0x%08x): "
                      "Failed to lock global key '%s'\n",
                      op->global->open_global_id,
                      hex_encode_talloc(global_rec, key.dptr,
                                        key.dsize)));
            error = NT_STATUS_INTERNAL_ERROR;
        }
    }

    if (global_rec != NULL && op->global->durable) {
        /*
         * If it is a durable open we need to update the global part
         * instead of deleting it
         */
        op->global->db_rec = global_rec;
        status = smbXsrv_open_global_store(op->global);
        if (NT_STATUS_IS_OK(status)) {
            /*
             * smbXsrv_open_global_store does the free
             * of op->global->db_rec
             */
            global_rec = NULL;
        }
        if (!NT_STATUS_IS_OK(status)) {
            DEBUG(0,("smbXsrv_open_close(0x%08x)"
                     "smbXsrv_open_global_store() failed - %s\n",
                     op->global->open_global_id,
                     nt_errstr(status)));
            error = status;
        }

        if (NT_STATUS_IS_OK(status) && CHECK_DEBUGLVL(10)) {
            struct smbXsrv_openB open_blob;

            ZERO_STRUCT(open_blob);
            open_blob.version = SMBXSRV_VERSION_0;
            open_blob.info.info0 = op;

            DEBUG(10,("smbXsrv_open_close(0x%08x): "
                      "stored disconnect\n",
                      op->global->open_global_id));
            NDR_PRINT_DEBUG(smbXsrv_openB, &open_blob);
        }
    }

    if (global_rec != NULL) {
        status = dbwrap_record_delete(global_rec);
        if (!NT_STATUS_IS_OK(status)) {
            TDB_DATA key = dbwrap_record_get_key(global_rec);

            DEBUG(0, ("smbXsrv_open_close(0x%08x): "
                      "failed to delete global key '%s': %s\n",
                      op->global->open_global_id,
                      hex_encode_talloc(global_rec, key.dptr,
                                        key.dsize),
                      nt_errstr(status)));
            error = status;
        }
    }
    TALLOC_FREE(global_rec);

    local_rec = op->db_rec;
    if (local_rec == NULL) {
        uint8_t key_buf[SMBXSRV_OPEN_LOCAL_TDB_KEY_SIZE];
        TDB_DATA key;

        key = smbXsrv_open_local_id_to_key(op->local_id, key_buf);

        local_rec = dbwrap_fetch_locked(table->local.db_ctx,
                                        op, key);
        if (local_rec == NULL) {
            DEBUG(0, ("smbXsrv_open_close(0x%08x): "
                      "Failed to lock local key '%s'\n",
                      op->global->open_global_id,
                      hex_encode_talloc(local_rec, key.dptr,
                                        key.dsize)));
            error = NT_STATUS_INTERNAL_ERROR;
        }
    }

    if (local_rec != NULL) {
        status = dbwrap_record_delete(local_rec);
        if (!NT_STATUS_IS_OK(status)) {
            TDB_DATA key = dbwrap_record_get_key(local_rec);

            DEBUG(0, ("smbXsrv_open_close(0x%08x): "
                      "failed to delete local key '%s': %s\n",
                      op->global->open_global_id,
                      hex_encode_talloc(local_rec, key.dptr,
                                        key.dsize),
                      nt_errstr(status)));
            error = status;
        }
        table->local.num_opens -= 1;
    }
    if (op->db_rec == NULL) {
        TALLOC_FREE(local_rec);
    }
    op->db_rec = NULL;

    if (op->compat) {
        op->compat->op = NULL;
        file_free(NULL, op->compat);
        op->compat = NULL;
    }

    return error;
}
Exemplo n.º 18
0
static long file_ctrl(BIO *b, int cmd, long num, void *ptr) {
  long ret = 1;
  FILE *fp = (FILE *)b->ptr;
  FILE **fpp;
  char p[4];

  switch (cmd) {
    case BIO_CTRL_RESET:
      num = 0;
    case BIO_C_FILE_SEEK:
      ret = (long)fseek(fp, num, 0);
      break;
    case BIO_CTRL_EOF:
      ret = (long)feof(fp);
      break;
    case BIO_C_FILE_TELL:
    case BIO_CTRL_INFO:
      ret = ftell(fp);
      break;
    case BIO_C_SET_FILE_PTR:
      file_free(b);
      b->shutdown = (int)num & BIO_CLOSE;
      b->ptr = ptr;
      b->init = 1;
      break;
    case BIO_C_SET_FILENAME:
      file_free(b);
      b->shutdown = (int)num & BIO_CLOSE;
      if (num & BIO_FP_APPEND) {
        if (num & BIO_FP_READ) {
          BUF_strlcpy(p, "a+", sizeof(p));
        } else {
          BUF_strlcpy(p, "a", sizeof(p));
        }
      } else if ((num & BIO_FP_READ) && (num & BIO_FP_WRITE)) {
        BUF_strlcpy(p, "r+", sizeof(p));
      } else if (num & BIO_FP_WRITE) {
        BUF_strlcpy(p, "w", sizeof(p));
      } else if (num & BIO_FP_READ) {
        BUF_strlcpy(p, "r", sizeof(p));
      } else {
        OPENSSL_PUT_ERROR(BIO, BIO_R_BAD_FOPEN_MODE);
        ret = 0;
        break;
      }
      fp = fopen(ptr, p);
      if (fp == NULL) {
        OPENSSL_PUT_SYSTEM_ERROR();
        ERR_add_error_data(5, "fopen('", ptr, "','", p, "')");
        OPENSSL_PUT_ERROR(BIO, ERR_R_SYS_LIB);
        ret = 0;
        break;
      }
      b->ptr = fp;
      b->init = 1;
      break;
    case BIO_C_GET_FILE_PTR:
      /* the ptr parameter is actually a FILE ** in this case. */
      if (ptr != NULL) {
        fpp = (FILE **)ptr;
        *fpp = (FILE *)b->ptr;
      }
      break;
    case BIO_CTRL_GET_CLOSE:
      ret = (long)b->shutdown;
      break;
    case BIO_CTRL_SET_CLOSE:
      b->shutdown = (int)num;
      break;
    case BIO_CTRL_FLUSH:
      ret = 0 == fflush((FILE *)b->ptr);
      break;
    case BIO_CTRL_WPENDING:
    case BIO_CTRL_PENDING:
    default:
      ret = 0;
      break;
  }
  return ret;
}
Exemplo n.º 19
0
static NTSTATUS close_normal_file(struct smb_request *req, files_struct *fsp,
				  enum file_close_type close_type)
{
	NTSTATUS status = NT_STATUS_OK;
	NTSTATUS tmp;
	connection_struct *conn = fsp->conn;
	bool is_durable = false;

	if (fsp->num_aio_requests != 0) {

		if (close_type != SHUTDOWN_CLOSE) {
			/*
			 * reply_close and the smb2 close must have
			 * taken care of this. No other callers of
			 * close_file should ever have created async
			 * I/O.
			 *
			 * We need to panic here because if we close()
			 * the fd while we have outstanding async I/O
			 * requests, in the worst case we could end up
			 * writing to the wrong file.
			 */
			DEBUG(0, ("fsp->num_aio_requests=%u\n",
				  fsp->num_aio_requests));
			smb_panic("can not close with outstanding aio "
				  "requests");
		}

		/*
		 * For shutdown close, just drop the async requests
		 * including a potential close request pending for
		 * this fsp. Drop the close request first, the
		 * destructor for the aio_requests would execute it.
		 */
		TALLOC_FREE(fsp->deferred_close);

		while (fsp->num_aio_requests != 0) {
			/*
			 * The destructor of the req will remove
			 * itself from the fsp.
			 * Don't use TALLOC_FREE here, this will overwrite
			 * what the destructor just wrote into
			 * aio_requests[0].
			 */
			talloc_free(fsp->aio_requests[0]);
		}
	}

	/*
	 * If we're flushing on a close we can get a write
	 * error here, we must remember this.
	 */

	tmp = close_filestruct(fsp);
	status = ntstatus_keeperror(status, tmp);

	if (NT_STATUS_IS_OK(status) && fsp->op != NULL) {
		is_durable = fsp->op->global->durable;
	}

	if (close_type != SHUTDOWN_CLOSE) {
		is_durable = false;
	}

	if (is_durable) {
		DATA_BLOB new_cookie = data_blob_null;

		tmp = SMB_VFS_DURABLE_DISCONNECT(fsp,
					fsp->op->global->backend_cookie,
					fsp->op,
					&new_cookie);
		if (NT_STATUS_IS_OK(tmp)) {
			struct timeval tv;
			NTTIME now;

			if (req != NULL) {
				tv = req->request_time;
			} else {
				tv = timeval_current();
			}
			now = timeval_to_nttime(&tv);

			data_blob_free(&fsp->op->global->backend_cookie);
			fsp->op->global->backend_cookie = new_cookie;

			fsp->op->compat = NULL;
			tmp = smbXsrv_open_close(fsp->op, now);
			if (!NT_STATUS_IS_OK(tmp)) {
				DEBUG(1, ("Failed to update smbXsrv_open "
					  "record when disconnecting durable "
					  "handle for file %s: %s - "
					  "proceeding with normal close\n",
					  fsp_str_dbg(fsp), nt_errstr(tmp)));
			}
			scavenger_schedule_disconnected(fsp);
		} else {
			DEBUG(1, ("Failed to disconnect durable handle for "
				  "file %s: %s - proceeding with normal "
				  "close\n", fsp_str_dbg(fsp), nt_errstr(tmp)));
		}
		if (!NT_STATUS_IS_OK(tmp)) {
			is_durable = false;
		}
	}

	if (is_durable) {
		/*
		 * This is the case where we successfully disconnected
		 * a durable handle and closed the underlying file.
		 * In all other cases, we proceed with a genuine close.
		 */
		DEBUG(10, ("%s disconnected durable handle for file %s\n",
			   conn->session_info->unix_info->unix_name,
			   fsp_str_dbg(fsp)));
		file_free(req, fsp);
		return NT_STATUS_OK;
	}

	if (fsp->op != NULL) {
		/*
		 * Make sure the handle is not marked as durable anymore
		 */
		fsp->op->global->durable = false;
	}

	if (fsp->print_file) {
		/* FIXME: return spool errors */
		print_spool_end(fsp, close_type);
		file_free(req, fsp);
		return NT_STATUS_OK;
	}

	/* Remove the oplock before potentially deleting the file. */
	if(fsp->oplock_type) {
		remove_oplock(fsp);
	}

	/* If this is an old DOS or FCB open and we have multiple opens on
	   the same handle we only have one share mode. Ensure we only remove
	   the share mode on the last close. */

	if (fsp->fh->ref_count == 1) {
		/* Should we return on error here... ? */
		tmp = close_remove_share_mode(fsp, close_type);
		status = ntstatus_keeperror(status, tmp);
	}

	locking_close_file(conn->sconn->msg_ctx, fsp, close_type);

	tmp = fd_close(fsp);
	status = ntstatus_keeperror(status, tmp);

	/* check for magic scripts */
	if (close_type == NORMAL_CLOSE) {
		tmp = check_magic(fsp);
		status = ntstatus_keeperror(status, tmp);
	}

	/*
	 * Ensure pending modtime is set after close.
	 */

	tmp = update_write_time_on_close(fsp);
	if (NT_STATUS_EQUAL(tmp, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
		/* Someone renamed the file or a parent directory containing
		 * this file. We can't do anything about this, we don't have
		 * an "update timestamp by fd" call in POSIX. Eat the error. */

		tmp = NT_STATUS_OK;
	}

	status = ntstatus_keeperror(status, tmp);

	DEBUG(2,("%s closed file %s (numopen=%d) %s\n",
		conn->session_info->unix_info->unix_name, fsp_str_dbg(fsp),
		conn->num_files_open - 1,
		nt_errstr(status) ));

	file_free(req, fsp);
	return status;
}
Exemplo n.º 20
0
static int close_normal_file(files_struct *fsp, BOOL normal_close)
{
	share_mode_entry *share_entry = NULL;
	size_t share_entry_count = 0;
	BOOL delete_on_close = False;
	connection_struct *conn = fsp->conn;
	int err = 0;
	int err1 = 0;

	remove_pending_lock_requests_by_fid(fsp);

	/*
	 * If we're flushing on a close we can get a write
	 * error here, we must remember this.
	 */

	if (close_filestruct(fsp) == -1)
		err1 = -1;

	if (fsp->print_file) {
		print_fsp_end(fsp, normal_close);
		file_free(fsp);
		return 0;
	}

	/*
	 * Lock the share entries, and determine if we should delete
	 * on close. If so delete whilst the lock is still in effect.
	 * This prevents race conditions with the file being created. JRA.
	 */

	lock_share_entry_fsp(fsp);

	if (fsp->delete_on_close) {

		/*
		 * Modify the share mode entry for all files open
		 * on this device and inode to tell other smbds we have
		 * changed the delete on close flag. The last closer will delete the file
		 * if flag is set.
		 */

		NTSTATUS status =set_delete_on_close_over_all(fsp, fsp->delete_on_close);
		if (NT_STATUS_V(status) !=  NT_STATUS_V(NT_STATUS_OK))
			DEBUG(0,("close_normal_file: failed to change delete on close flag for file %s\n",
				fsp->fsp_name ));
	}

	share_entry_count = del_share_mode(fsp, &share_entry);

	DEBUG(10,("close_normal_file: share_entry_count = %lu for file %s\n",
		(unsigned long)share_entry_count, fsp->fsp_name ));

	/*
	 * We delete on close if it's the last open, and the
	 * delete on close flag was set in the entry we just deleted.
	 */

	if ((share_entry_count == 0) && share_entry && 
			GET_DELETE_ON_CLOSE_FLAG(share_entry->share_mode) )
		delete_on_close = True;

	SAFE_FREE(share_entry);

	/*
	 * NT can set delete_on_close of the last open
	 * reference to a file.
	 */

	if (normal_close && delete_on_close) {
		DEBUG(5,("close_file: file %s. Delete on close was set - deleting file.\n",
			fsp->fsp_name));
		if(SMB_VFS_UNLINK(conn,fsp->fsp_name) != 0) {
			/*
			 * This call can potentially fail as another smbd may have
			 * had the file open with delete on close set and deleted
			 * it when its last reference to this file went away. Hence
			 * we log this but not at debug level zero.
			 */

		DEBUG(5,("close_file: file %s. Delete on close was set and unlink failed \
with error %s\n", fsp->fsp_name, strerror(errno) ));
		}
Exemplo n.º 21
0
/* process file named fname
   this is the `boss' function
   returns 0 on succes, 1 on failure, 2 on troubles */
static int
process_file(EncaAnalyser an,
             const char *fname)
{
  static int utf8 = ENCA_CS_UNKNOWN;
  static Buffer *buffer = NULL; /* persistent i/o buffer */
  int ot_is_convert = (options.output_type == OTYPE_CONVERT);

  EncaEncoding result; /* the guessed encoding */
  File *file; /* the processed file */

  if (!an) {
    buffer_free(buffer);
    return 0;
  }

  /* Initialize when we are called the first time. */
  if (buffer == NULL)
    buffer = buffer_new(buffer_size);

  if (!enca_charset_is_known(utf8)) {
    utf8 = enca_name_to_charset("utf8");
    assert(enca_charset_is_known(utf8));
  }

  /* Read sample. */
  file = file_new(fname, buffer);
  if (file_open(file, ot_is_convert ? "r+b" : "rb") != 0) {
    file_free(file);
    return EXIT_TROUBLE;
  }
  if (file_read(file) == -1) {
    file_free(file);
    return EXIT_TROUBLE;
  }
  if (!ot_is_convert)
    file_close(file);

  /* Guess encoding. */
  dwim_libenca_options(an, file);
  if (ot_is_convert)
    result = enca_analyse_const(an, buffer->data, buffer->pos);
  else
    result = enca_analyse(an, buffer->data, buffer->pos);

  /* Is conversion required? */
  if (ot_is_convert) {
    int err = 0;

    if (enca_charset_is_known(result.charset))
      err = convert(file, result);
    else {
      if (enca_errno(an) != ENCA_EEMPTY) {
        fprintf(stderr, "%s: Cannot convert `%s' from unknown encoding\n",
                        program_name,
                        ffname_r(file->name));
      }
      /* Copy stdin to stdout unchanged. */
      if (file->name == NULL)
        err = copy_and_convert(file, file, NULL);
    }

    file_free(file);
    if ((err == ERR_OK && !enca_charset_is_known(result.charset)
         && enca_errno(an) != ENCA_EEMPTY)
        || err == ERR_CANNOT)
      return EXIT_FAILURE;

    return (err == ERR_OK) ? EXIT_SUCCESS : EXIT_TROUBLE;
  }

  /* Print results. */
  print_results(file->name, an, result, enca_errno(an));
  if (result.charset == utf8)
    double_utf8_chk(an, buffer->data, buffer->pos);

  file_free(file);

  return enca_charset_is_known(result.charset) ? EXIT_SUCCESS : EXIT_FAILURE;
}