Example #1
0
APR_DECLARE(apr_status_t) apr_file_buffer_set(apr_file_t *file, 
                                              char * buffer,
                                              apr_size_t bufsize)
{
    apr_status_t rv;

    file_lock(file);

    if(file->buffered) {
        /* Flush the existing buffer */
        rv = apr_file_flush_locked(file);
        if (rv != APR_SUCCESS) {
            file_unlock(file);
            return rv;
        }
    }
        
    file->buffer = buffer;
    file->bufsize = bufsize;
    file->buffered = 1;
    file->bufpos = 0;
    file->direction = 0;
    file->dataRead = 0;
 
    if (file->bufsize == 0) {
            /* Setting the buffer size to zero is equivalent to turning 
             * buffering off. 
             */
            file->buffered = 0;
    }

    file_unlock(file);

    return APR_SUCCESS;
}
Example #2
0
APR_DECLARE(apr_status_t) apr_file_writev(apr_file_t *thefile, const struct iovec *vec,
                                          apr_size_t nvec, apr_size_t *nbytes)
{
#ifdef HAVE_WRITEV
    apr_status_t rv;
    int bytes;

    if (thefile->buffered) {
        file_lock(thefile);

        rv = apr_file_flush_locked(thefile);
        if (rv != APR_SUCCESS) {
            file_unlock(thefile);
            return rv;
        }
        if (thefile->direction == 0) {
            /* Position file pointer for writing at the offset we are
             * logically reading from
             */
            apr_int64_t offset = thefile->filePtr - thefile->dataRead +
                                 thefile->bufpos;
            if (offset != thefile->filePtr)
                lseek(thefile->filedes, offset, SEEK_SET);
            thefile->bufpos = thefile->dataRead = 0;
        }

        file_unlock(thefile);
    }

    if ((bytes = writev(thefile->filedes, vec, nvec)) < 0) {
        *nbytes = 0;
        rv = errno;
    }
    else {
        *nbytes = bytes;
        rv = APR_SUCCESS;
    }
    return rv;
#else
    /**
     * The problem with trying to output the entire iovec is that we cannot
     * maintain the behavoir that a real writev would have.  If we iterate
     * over the iovec one at a time, we loose the atomic properties of 
     * writev().  The other option is to combine the entire iovec into one
     * buffer that we could then send in one call to write().  This is not 
     * reasonable since we do not know how much data an iovec could contain.
     *
     * The only reasonable option, that maintains the semantics of a real 
     * writev(), is to only write the first iovec.  Callers of file_writev()
     * must deal with partial writes as they normally would. If you want to 
     * ensure an entire iovec is written, use apr_file_writev_full().
     */

    *nbytes = vec[0].iov_len;
    return apr_file_write(thefile, vec[0].iov_base, nbytes);
#endif
}
Example #3
0
APR_DECLARE(apr_status_t) apr_file_gets(char *str, int len, apr_file_t *thefile)
{
    apr_status_t rv = APR_SUCCESS; /* get rid of gcc warning */
    apr_size_t nbytes;
    const char *str_start = str;
    char *final = str + len - 1;

    if (len <= 1) {  
        /* sort of like fgets(), which returns NULL and stores no bytes 
         */
        return APR_SUCCESS;
    }

    /* If we have an underlying buffer, we can be *much* more efficient
     * and skip over the apr_file_read calls.
     */
    if (thefile->buffered) {

        file_lock(thefile);

        if (thefile->direction == 1) {
            rv = apr_file_flush_locked(thefile);
            if (rv) {
                file_unlock(thefile);
                return rv;
            }

            thefile->direction = 0;
            thefile->bufpos = 0;
            thefile->dataRead = 0;
        }

        while (str < final) { /* leave room for trailing '\0' */
            /* Force ungetc leftover to call apr_file_read. */
            if (thefile->bufpos < thefile->dataRead &&
                thefile->ungetchar == -1) {
                *str = thefile->buffer[thefile->bufpos++];
            }
            else {
                nbytes = 1;
                rv = file_read_buffered(thefile, str, &nbytes);
                if (rv != APR_SUCCESS) {
                    break;
                }
            }
            if (*str == '\n') {
                ++str;
                break;
            }
            ++str;
        }

        file_unlock(thefile);
    }
Example #4
0
        /**
         *  @return 成功:文件ID 失败:-1
         */
        int get_lock()
        {
            int li_lck_st = -1;
            file_ = open("/tmp/dbinit", O_RDWR|O_CREAT, 0777);
            if( file_ <= 0 )
            {
                //perror("file open error");
                return -1;
            }
            if(-1 == (li_lck_st = file_lock()))
            {
                close(file_);
                file_ = 0;
                //perror("lock file fail");
                return -1;
            }
            if(-1 == lseek(file_, 0, SEEK_SET))
            {
                perror("lseek faild");
                file_unlock();
                return -1;
            }
            if(-1 == read(file_, &status_, sizeof(int)))
            {
                //perror("read faild");
            }

            printf("read status %d\n", status_);
            return li_lck_st;
        }
Example #5
0
 ~FileLock()
 {
     if (file_ != 0)
     {
         file_unlock();
     }
 }
Example #6
0
apr_status_t apr_file_trunc(apr_file_t *fp, apr_off_t offset)
{
    if (fp->buffered) {
        int rc = 0;
        file_lock(fp);
        if (fp->direction == 1 && fp->bufpos != 0) {
            apr_off_t len = fp->filePtr + fp->bufpos;
            if (offset < len) {
                /* New file end fall below our write buffer limit.
                 * Figure out if and what needs to be flushed.
                 */
                apr_off_t off = len - offset;
                if (off >= 0 && off <= fp->bufpos)
                    fp->bufpos = fp->bufpos - (size_t)off;
                else
                    fp->bufpos = 0;
            }
            rc = apr_file_flush_locked(fp);
            /* Reset buffer positions for write mode */
            fp->bufpos = fp->direction = fp->dataRead = 0;
        }
        file_unlock(fp);
        if (rc) {
            return rc;
        }
    }
    if (ftruncate(fp->filedes, offset) == -1) {
        return errno;
    }
    return apr_file_seek(fp, APR_SET, &offset);
}
/* Finds the next element of the given directory and stores the element's name
   in the given buffer. Returns true if an element was found, false if not.
   NOTE : "." and ".." are not considered true elements, and will never be
   returned by this function. */
bool
dir_readdir (struct file *dir, char *buf)
{
  ASSERT (file_is_dir (dir));
  bool locked = file_lock (dir);

  /* If the cursor is before the third entry, then it's pointing at "." or "..",
     since these are *always* the first two directory entries. Seek to beyond
     them, since we don't want to return them. */
  off_t min_cursor = 2 * sizeof (struct dir_entry);
  if (file_tell (dir) < min_cursor)
    file_seek (dir, min_cursor);

  bool success = false;
  while (true)
    {
      struct dir_entry e;
      if (file_read (dir, &e, sizeof e) != sizeof e)
        goto done;
      if (e.in_use)
        {
          strlcpy (buf, e.name, NAME_MAX + 1);
          return true;
          goto done;
        }
    }
    
done:
  if (locked) file_unlock (dir);
  return success;
}
Example #8
0
static int log_print_header(LogContext *pContext)
{
    int result;

    if (!pContext->use_file_write_lock)
    {
        if ((result=file_write_lock(pContext->log_fd)) != 0)
        {
            return result;
        }
    }

    pContext->current_size = lseek(pContext->log_fd, 0, SEEK_END);
    if (pContext->current_size < 0)
    {
        result = errno != 0 ? errno : EACCES;
        fprintf(stderr, "lseek file \"%s\" fail, " \
                "errno: %d, error info: %s\n", \
                pContext->log_filename, result, STRERROR(result));
    }
    else {
        result = 0;
        if (pContext->current_size == 0) {
            pContext->print_header_callback(pContext);
        }
    }

    if (!pContext->use_file_write_lock)
    {
        file_unlock(pContext->log_fd);
    }

    return result;
}
void mail_transaction_log_file_unlock(struct mail_transaction_log_file *file,
				      const char *lock_reason)
{
	unsigned int lock_time;

	if (!file->locked)
		return;

	file->locked = FALSE;
	file->locked_sync_offset_updated = FALSE;

	if (MAIL_TRANSACTION_LOG_FILE_IN_MEMORY(file))
		return;

	lock_time = time(NULL) - file->lock_created;
	if (lock_time >= MAIL_TRANSACTION_LOG_LOCK_WARN_SECS && lock_reason != NULL) {
		i_warning("Transaction log file %s was locked for %u seconds (%s)",
			  file->filepath, lock_time, lock_reason);
	}

	if (file->log->index->lock_method == FILE_LOCK_METHOD_DOTLOCK) {
		(void)mail_transaction_log_file_undotlock(file);
		return;
	}

	file_unlock(&file->file_lock);
}
Example #10
0
static void
file_unlock_cleanup(int argc, void **argv)
{
	int lockfd = *(int *)argv[0];
	const char *lock_desc = argv[1];

	file_unlock(lockfd, lock_desc);
}
Example #11
0
/***************************************************************
 End enumeration of the file.
****************************************************************/
void endfilepwent(void *vp, int *file_lock_depth)
{
  FILE *fp = (FILE *)vp;

  file_unlock(fileno(fp), file_lock_depth);
  fclose(fp);
  DEBUG(7, ("endfilepwent: closed file.\n"));
}
Example #12
0
int sfx_play(context_t* p_Ctx, const std::string & p_FileName, int p_Channel,
		int p_Loops)
{
	auto l_It = g_SoundList.find(p_FileName);

	if (l_It != g_SoundList.end())
	{
		return Mix_PlayChannel(p_Channel, l_It->second, p_Loops);
	}

	const std::string l_TableFilename = std::string(SFX_TABLE)
			+ std::string("/") + p_FileName;
	const std::string l_FullName = std::string(base_directory) + "/"
			+ l_TableFilename;

	file_lock(l_TableFilename.c_str());

	SDL_RWops * l_pFileDesc = SDL_RWFromFile(l_FullName.c_str(), "r");
	if (l_pFileDesc == nullptr)
	{
		std::string l_Err = std::string("sfx_play: cannot open ")
				+ l_FullName.c_str();
		werr(LOGDESIGNER, l_Err.c_str());
		file_update(p_Ctx, l_TableFilename.c_str());
		file_unlock(l_TableFilename.c_str());
		return -1;
	}

	Mix_Chunk * l_pChunk = Mix_LoadWAV_RW(l_pFileDesc, 1);
	if (l_pChunk == nullptr)
	{
		std::string l_Err = std::string("sfx_play: cannot read ")
				+ l_FullName.c_str();
		werr(LOGDESIGNER, l_Err.c_str());
		file_update(p_Ctx, l_TableFilename.c_str());
		file_unlock(l_TableFilename.c_str());
		return -1;
	}

	g_SoundList[p_FileName] = l_pChunk;

	file_unlock(l_TableFilename.c_str());

	return Mix_PlayChannel(p_Channel, l_pChunk, p_Loops);
}
Example #13
0
void PG_file_close(struct logfile *lf)
{
  if (logbuf.ptr != logbuf.base) {
    fwrite(logbuf.base, (logbuf.ptr-logbuf.base), 1, lf->file);
    logbuf.ptr = logbuf.base;
  }
  file_unlock(fileno(lf->file));
  fclose(lf->file);
}
Example #14
0
int mdev_lp_main(int argc, char **argv)
{
	int isLock;
	const char *device_name, *action;

	if(argc != 3){
		printf("Usage: %s [device_name] [action]\n", argv[0]);
		return 0;
	}

	device_name = argv[1];
	action = argv[2];

	usb_dbg("(%s): action=%s.\n", device_name, action);

	if(get_device_type_by_device(device_name) != DEVICE_TYPE_PRINTER){
		usb_dbg("(%s): The device is not a printer.\n", device_name);
		return 0;
	}

	// Check Lock.
	if((isLock = file_lock((char *)device_name)) == -1){
		usb_dbg("(%s): Can't set the file lock!\n", device_name);
		return 0;
	}

	// If remove the device?
	if(!check_hotplug_action(action)){
		int ports_used_usblp = usb_port_module_used("usblp");
		if (!ports_used_usblp)
			stop_usb_printer_spoolers();
		
		file_unlock(isLock);
		return 0;
	}

	notify_rc("on_hotplug_usb_printer");

	usb_dbg("(%s): Success!\n", device_name);

	file_unlock(isLock);

	return 1;
}
Example #15
0
QuillErrCode FILESQL::file_updateEvent(const char *eventType, 
									   AttrList *info, 
									   AttrList *condition) {
	int retval = 0;
	struct stat file_status;

    if (is_dummy) return QUILL_SUCCESS;
	if(!is_open)
	{
		dprintf(D_ALWAYS,"Error in logging event to Quill SQL Log : File not open\n");
		return QUILL_FAILURE;
	}

	if(file_lock() == QUILL_FAILURE) {
		return QUILL_FAILURE;
	}

	fstat(outfiledes, &file_status);

		// only write to the log if it's not exceeding the log size limit
	if (file_status.st_size < FILESIZELIMT) {
		retval = write(outfiledes,"UPDATE ", strlen("UPDATE "));
		retval = write(outfiledes,eventType, strlen(eventType));
		retval = write(outfiledes,"\n", strlen("\n"));

		MyString temp, temp1;
		const char *tempv;

		retval = sPrintAd(temp, *info);
		tempv = temp.Value();
		retval = write(outfiledes,tempv, strlen(tempv));

		retval = write(outfiledes,"***",3); /* Now the delimitor*/
		retval = write(outfiledes,"\n",1); /* Now the newline*/

		retval = sPrintAd(temp1, *condition);
		tempv = temp1.Value();
		retval = write(outfiledes,tempv, strlen(tempv));
		
		retval = write(outfiledes,"***",3); /* Now the delimitor*/
		retval = write(outfiledes,"\n",1); /* Now the newline*/	
	}

	if(file_unlock() == QUILL_FAILURE) {
		return QUILL_FAILURE;
	}

	if (retval < 0) {
		return QUILL_FAILURE;	
	} else {
		return QUILL_SUCCESS;	
	}
}
Example #16
0
/*********************
returned config should not be freed
*********************/
static const config_t * get_config(const char * table, const char * file)
{
	char * filename;
	const config_t * config;

	if( table == NULL ) {
		filename = strdup(file);
	} else {
		filename = strconcat(table,"/",file,NULL);
	}

//	wlog(LOGDEBUG,"Entry get : %s",filename);

	config = (config_t*)list_find(entry_list,filename);

	if(config) {
//		wlog(LOGDEBUG,"Entry found : %s",filename);
		free(filename);
		return config;
	}

	file_lock(filename);

//	wlog(LOGDEBUG,"Entry asked : %s",filename);
	file_update(context_get_player(),filename);

	if( (config=load_config(filename)) == NULL ) {
		file_unlock(filename);
		free(filename);
		return NULL;
	}
	file_unlock(filename);

//	wlog(LOGDEBUG,"Entry loaded : %s",filename);
	list_update(&entry_list,filename,(config_t*)config);
	free(filename);

	return config;
}
Example #17
0
int mdev_wdm_main(int argc, char **argv)
{
	FILE *fp;
	int isLock;
	char node_fname[64];
	const char *device_name, *action;

	if(argc != 3){
		printf("Usage: %s [device_name] [action]\n", argv[0]);
		return 0;
	}

	device_name = argv[1];
	action = argv[2];

	usb_dbg("(%s): action=%s.\n", device_name, action);
	
	if(!isWDMNode(device_name))
		return 0;
	
	sprintf(node_fname, "%s/%s", MODEM_NODE_DIR, device_name);
	
	// Check Lock.
	if((isLock = file_lock((char *)device_name)) == -1)
		return 0;
	
	unlink(QMI_CLIENT_ID);
	
	// If remove the device?
	if(!check_hotplug_action(action)){
		unlink(node_fname);
		goto out_unlock;
	}
	
	// Write node file.
	mkdir_if_none(MODEM_NODE_DIR);
	fp = fopen(node_fname, "w+");
	if (fp) {
		fprintf(fp, "pref=%d\n", 1);
		fprintf(fp, "devnum=%d\n", 0); // todo
		fclose(fp);
	}
	
	usb_dbg("(%s): Success!\n", device_name);
	
out_unlock:
	file_unlock(isLock);
	
	return 1;
}
Example #18
0
APR_DECLARE(apr_status_t) apr_file_flush(apr_file_t *thefile)
{
    apr_status_t rv = APR_SUCCESS;

    if (thefile->buffered) {
        file_lock(thefile);
        rv = apr_file_flush_locked(thefile);
        file_unlock(thefile);
    }
    /* There isn't anything to do if we aren't buffering the output
     * so just return success.
     */
    return rv; 
}
Example #19
0
void MY_Unlock(struct BE_descs *bed)
{
  if (bed->p->connected) mysql_query(bed->p->desc, unlock_clause);
  if (bed->b->connected) mysql_query(bed->b->desc, unlock_clause);

  if (bed->lf->open) {
    if (logbuf.ptr != logbuf.base) {
      fwrite(logbuf.base, (logbuf.ptr-logbuf.base), 1, bed->lf->file);
      logbuf.ptr = logbuf.base;
    }
    file_unlock(fileno(bed->lf->file));
    fclose(bed->lf->file);
    bed->lf->open = FALSE;
  }
}
Example #20
0
int mdev_sg_main(int argc, char **argv)
{
	int isLock;
	const char *device_name, *action;

	if(argc < 3){
		printf("Usage: %s [device_name] [action]\n", argv[0]);
		return 0;
	}

	device_name = argv[1];
	action = argv[2];

	usb_dbg("(%s): action=%s.\n", device_name, action);

	if(get_device_type_by_device(device_name) != DEVICE_TYPE_SG)
		return 0;

	// If remove the device?
	if(!check_hotplug_action(action)){
		usb_dbg("(%s): Remove sg device.\n", device_name);
		return 0;
	}

	// Check Lock.
	if((isLock = file_lock((char *)device_name)) == -1){
		usb_dbg("(%s): Can't set the file lock!\n", device_name);
		return 0;
	}

	if (nvram_get_int("modem_zcd") != 0) {
		if (module_smart_load("sr_mod"))
			sleep(1);
	}
	else {
		char vid[8] = {0}, pid[8] = {0};
		char usb_port_id[64] = {0};
		if (get_usb_port_by_device(device_name, usb_port_id, sizeof(usb_port_id))) {
			if (get_usb_vid(usb_port_id, vid, sizeof(vid)) && get_usb_pid(usb_port_id, pid, sizeof(pid)))
				perform_usb_modeswitch(vid, pid);
		}
	}

	usb_dbg("(%s): Success!\n", device_name);
	file_unlock(isLock);

	return 1;
}
Example #21
0
 int release_lock()
 {
     if (file_ != 0)
     {
         if(-1 == lseek(file_, 0, SEEK_SET))
         {
             perror("lseek faild");
         }
         if(-1 == write(file_, &status_, sizeof(int)))
         {
             perror("write faile");
         }
         return file_unlock();
     }
     return -1;
 }
Example #22
0
static void write_config(const config_t * config,const char * table, const char * file)
{
	char * filename;
	char * fullname;

	filename = strconcat(table,"/",file,NULL);

	fullname = strconcat(base_directory,"/",filename,NULL);

	file_lock(filename);
	config_write_file((config_t*)config,fullname);
	file_unlock(filename);

	free(filename);
	free(fullname);
}
Example #23
0
static int squat_uidlist_lock(struct squat_uidlist *uidlist)
{
	int ret;

	for (;;) {
		i_assert(uidlist->fd != -1);
		i_assert(uidlist->file_lock == NULL);
		i_assert(uidlist->dotlock == NULL);

		if (uidlist->trie->lock_method != FILE_LOCK_METHOD_DOTLOCK) {
			ret = file_wait_lock(uidlist->fd, uidlist->path,
					     F_WRLCK,
					     uidlist->trie->lock_method,
					     SQUAT_TRIE_LOCK_TIMEOUT,
					     &uidlist->file_lock);
		} else {
			ret = file_dotlock_create(&uidlist->trie->dotlock_set,
						  uidlist->path, 0,
						  &uidlist->dotlock);
		}
		if (ret == 0) {
			i_error("squat uidlist %s: Locking timed out",
				uidlist->path);
			return 0;
		}
		if (ret < 0)
			return -1;

		ret = squat_uidlist_is_file_stale(uidlist);
		if (ret == 0)
			break;

		if (uidlist->file_lock != NULL)
			file_unlock(&uidlist->file_lock);
		else
			file_dotlock_delete(&uidlist->dotlock);
		if (ret < 0)
			return -1;

		squat_uidlist_close(uidlist);
		uidlist->fd = squat_trie_create_fd(uidlist->trie,
						   uidlist->path, 0);
		if (uidlist->fd == -1)
			return -1;
	}
	return 1;
}
Example #24
0
APR_DECLARE(apr_status_t) apr_file_seek(apr_file_t *thefile, apr_seek_where_t where, apr_off_t *offset)
{
    apr_off_t rv;

    thefile->eof_hit = 0;

    if (thefile->buffered) {
        int rc = EINVAL;
        apr_finfo_t finfo;

        file_lock(thefile);

        switch (where) {
        case APR_SET:
            rc = setptr(thefile, *offset);
            break;

        case APR_CUR:
            rc = setptr(thefile, thefile->filePtr - thefile->dataRead + thefile->bufpos + *offset);
            break;

        case APR_END:
            rc = apr_file_info_get_locked(&finfo, APR_FINFO_SIZE, thefile);
            if (rc == APR_SUCCESS)
                rc = setptr(thefile, finfo.size + *offset);
            break;
        }

        *offset = thefile->filePtr - thefile->dataRead + thefile->bufpos;

        file_unlock(thefile);

        return rc;
    }
    else {
        rv = lseek(thefile->filedes, *offset, where);
        if (rv == -1) {
            *offset = -1;
            return errno;
        }
        else {
            *offset = rv;
            return APR_SUCCESS;
        }
    }
}
/* Adds a file named NAME to DIR, which must not already contain a
   file by that name.  The file's inode is in sector
   INODE_SECTOR.
   Returns true if successful, false on failure.
   Fails if NAME is invalid (i.e. too long) or a disk or memory
   error occurs. */
bool
dir_add (struct file *dir, const char *name, block_sector_t inode_sector)
{
  ASSERT (file_is_dir (dir));
  struct dir_entry e;
  size_t ofs;
  bool success = false;

  ASSERT (dir != NULL);
  ASSERT (name != NULL);

  /* Check NAME for validity. */
  if (*name == '\0' || strlen (name) > NAME_MAX)
    return false;

  bool locked = file_lock (dir);
  /* Check that NAME is not in use. */
  if (dir_lookup (dir, name) >= 0)
    goto done;

  /* Set OFS to offset of free slot.
     If there are no free slots, then it will be set to the
     current end-of-file.
     
     inode_read_at() will only return a short read at end of file.
     Otherwise, we'd need to verify that we didn't get a short
     read due to something intermittent such as low memory. */
  size_t dir_size = inode_length (dir->inode);
  for (ofs = 0; ofs < dir_size; ofs += sizeof e) 
    {
      inode_read_at (dir->inode, &e, sizeof e, ofs);
      if (!e.in_use)
        break;
    }

  /* Write slot. */
  e.in_use = true;
  strlcpy (e.name, name, sizeof e.name);
  e.inode_sector = inode_sector;
  success = inode_write_at (dir->inode, &e, sizeof e, ofs) == sizeof e;

 done:
  if (locked) file_unlock (dir);
  return success;
}
Example #26
0
int squat_uidlist_build_init(struct squat_uidlist *uidlist,
			     struct squat_uidlist_build_context **ctx_r)
{
	struct squat_uidlist_build_context *ctx;
	int ret;

	i_assert(!uidlist->building);

	ret = squat_uidlist_open_or_create(uidlist);
	if (ret == 0 &&
	    lseek(uidlist->fd, uidlist->hdr.used_file_size, SEEK_SET) < 0) {
		i_error("lseek(%s) failed: %m", uidlist->path);
		ret = -1;
	}

	if (ret < 0) {
		if (uidlist->file_lock != NULL)
			file_unlock(&uidlist->file_lock);
		if (uidlist->dotlock != NULL)
			file_dotlock_delete(&uidlist->dotlock);
		return -1;
	}

	ctx = i_new(struct squat_uidlist_build_context, 1);
	ctx->uidlist = uidlist;
	ctx->output = o_stream_create_fd(uidlist->fd, 0);
	if (ctx->output->offset == 0) {
		struct squat_uidlist_file_header hdr;

		memset(&hdr, 0, sizeof(hdr));
		o_stream_nsend(ctx->output, &hdr, sizeof(hdr));
	}
	o_stream_cork(ctx->output);
	i_array_init(&ctx->lists, 10240);
	i_array_init(&ctx->block_offsets, 128);
	i_array_init(&ctx->block_end_indexes, 128);
	ctx->list_start_idx = uidlist->hdr.count;
	ctx->build_hdr = uidlist->hdr;

	uidlist->building = TRUE;
	*ctx_r = ctx;
	return 0;
}
Example #27
0
int mdev_sr_main(int argc, char **argv)
{
	int isLock;
	const char *device_name, *action;

	if(argc != 3){
		printf("Usage: %s [device_name] [action]\n", argv[0]);
		return 0;
	}

	device_name = argv[1];
	action = argv[2];

	usb_dbg("(%s): action=%s.\n", device_name, action);

	if(get_device_type_by_device(device_name) != DEVICE_TYPE_CD){
		usb_dbg("(%s): The device is not a CD one.\n", device_name);
		return 0;
	}

	// If remove the device?
	if(!check_hotplug_action(action)){
		usb_dbg("(%s): Remove CD device.\n", device_name);
		return 0;
	}

	// Check Lock.
	if((isLock = file_lock((char *)device_name)) == -1){
		usb_dbg("(%s): Can't set the file lock!\n", device_name);
		return 0;
	}

	doSystem("eject -s /dev/%s", device_name);
	sleep(1);
	module_smart_unload("sr_mod", 1);

	usb_dbg("(%s): Success!\n", device_name);
	file_unlock(isLock);

	return 1;
}
Example #28
0
File: test_wr.c Project: Og192/CPro
int main(void)
{
	int fd;

	if((fd = open("Og", O_RDONLY | O_CREAT, 0644)) < 0){
		perror("open");
		exit(EXIT_FAILURE);
	}

	file_lock(fd);
	printf("get the read lock\n");
	sleep(10);
	file_unlock(fd);

	if(close(fd) < 0){
		perror("close");
		exit(EXIT_FAILURE);
	}

	exit(EXIT_SUCCESS);
}
/* Removes any entry for NAME in DIR.
   Returns true if successful, false on failure,
   which occurs only if there is no file with the given NAME. */
bool
dir_remove (struct file *dir, const char *name) 
{
  ASSERT (file_is_dir (dir));
  struct dir_entry e;
  struct inode *inode = NULL;
  bool success = false;
  off_t ofs;
  int sector;

  ASSERT (dir != NULL);
  ASSERT (name != NULL);

  bool locked = file_lock (dir);
  /* Find directory entry. */
  if ((sector = lookup (dir, name, &ofs, &e)) < 0)
    goto done;

  /* Open inode. */
  inode = inode_open (sector);
  if (inode == NULL)
    goto done;

  /* Erase directory entry. */
  e.in_use = false;
  if (inode_write_at (dir->inode, &e, sizeof e, ofs) != sizeof e) 
    goto done;

  /* Remove inode. */
  inode_remove (inode);
  success = true;

 done:
  if (locked) file_unlock (dir);
  if (inode)  inode_close (inode);
  return success;
}
Example #30
0
int main(int argc, char *argv[])
{
    int                 sockfd , clisockfd;
    unsigned int        clilen;
    int                 childpid;
    struct sockaddr_in  serv_addr,cli_addr;
    int err_select;//JY1113

#ifdef LPR_with_ASUS//JY1112
    int 		LPRflag = 0;
    fd_set		rfds, afds;
    int			nfds;
    int			sockfd_ASUS;
    unsigned int        clilen_ASUS;
    int                 childpid_ASUS;
    struct sockaddr_in  serv_addr_ASUS,cli_addr_ASUS;
#endif
#ifdef Raw_Printing_with_ASUS  //Lisa
	int		netfd, fd, clientlen, one = 1;
	struct sockaddr_in	netaddr, client;
#endif
	int lock;
	int pid = 0;
	FILE *fp;

	fp = fopen("/var/run/lpdparent.pid", "r");
	if (fp) {
		fscanf(fp, "%d", &pid);
		fclose(fp);
	}

	if ((pid > 1) && (kill(pid, 0) == 0 || errno != ESRCH)) {
		syslog(LOGOPTS, "another lpd daemon exists!!\n");
		exit(0);
	}

	update_pidfile();

    //Initial the server the not busy
    lptstatus.busy = FALSE;

    sigset_t sigs_to_catch;
    sigemptyset(&sigs_to_catch);
    sigaddset(&sigs_to_catch, SIGCLD);
    sigaddset(&sigs_to_catch, SIGINT);
    sigaddset(&sigs_to_catch, SIGQUIT);
    sigaddset(&sigs_to_catch, SIGKILL);
    sigaddset(&sigs_to_catch, SIGUSR2);
    sigprocmask(SIG_UNBLOCK, &sigs_to_catch, NULL);

    //Setup the signal handler
    signal(SIGCLD, sig_child); 
    signal(SIGINT, sig_cleanup); 
    signal(SIGQUIT, sig_cleanup); 
    signal(SIGKILL, sig_cleanup);
    signal(SIGUSR2, sig_remove);//JY1110 
    
    if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0 )
    {
        syslog(LOGOPTS, "can't open stream socket: %m");
        exit(0);
    }
    
    bzero((char *)&serv_addr , sizeof(serv_addr));
    serv_addr.sin_family        = AF_INET;
    serv_addr.sin_addr.s_addr   = htonl(INADDR_ANY);
    serv_addr.sin_port          = htons(PNT_SVR_PORT_LPR);

    
    if(bind(sockfd,(struct sockaddr *)&serv_addr , sizeof(serv_addr)) < 0 )
    {
        syslog(LOGOPTS, "can't bind socket with port %d: %m", PNT_SVR_PORT_LPR);
        exit(0);
    }
    /*JY1111*/
    int windowsize=2920;
    setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (char *)&windowsize, sizeof(windowsize));
    int no_delay=1;
    setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &no_delay, sizeof(no_delay));	// by Jiahao. 20080808.

    listen(sockfd , 15);

#ifdef Raw_Printing_with_ASUS //Lisa
	if ((netfd = socket(AF_INET, SOCK_STREAM, IPPROTO_IP)) < 0)
	{
		syslog(LOGOPTS, "cannot open stream socket for raw printing: %m\n");
		exit(1);
	}
	if (setsockopt(netfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
	{
		syslog(LOGOPTS, "cannot setsocketopt for raw printing: %m\n");
		exit(1);
	}
	netaddr.sin_family = AF_INET;
	netaddr.sin_port = htons(BASEPORT);
	netaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	memset(netaddr.sin_zero, 0, sizeof(netaddr.sin_zero));
	if (bind(netfd, (struct sockaddr*) &netaddr, sizeof(netaddr)) < 0)
	{
		syslog(LOGOPTS, "cannot bind socket with port %d for raw printing: %m\n", BASEPORT);
		exit(1);
	}
	if (listen(netfd, 5) < 0)
	{
		syslog(LOGOPTS, "cannot listen socket for raw printing: %m\n");
		exit(1);
	}
	//clientlen = sizeof(client);
	//memset(&client, 0, sizeof(client));
#endif

#ifdef LPR_with_ASUS//JY1112
	if((sockfd_ASUS = socket(AF_INET,SOCK_STREAM,0)) < 0 )
	{
	        syslog(LOG_ERR, "can't open stream socket for LPR: %m");
	        exit(0);
	}
    	bzero((char *)&serv_addr_ASUS , sizeof(serv_addr_ASUS));
    	serv_addr_ASUS.sin_family        = AF_INET;
    	serv_addr_ASUS.sin_addr.s_addr   = htonl(INADDR_ANY);
    	serv_addr_ASUS.sin_port          = htons(PNT_SVR_PORT_ASUS);

    	if(bind(sockfd_ASUS,(struct sockaddr *)&serv_addr_ASUS , sizeof(serv_addr_ASUS)) < 0 )
    	{
		syslog(LOG_ERR, "can't bind socket for LPR: %m");
		exit(0);
   	}

    	setsockopt(sockfd_ASUS, SOL_SOCKET, SO_RCVBUF, (char *)&windowsize, sizeof(windowsize));

    	listen(sockfd_ASUS , 15);
    
    	/*set the fds*/
    	nfds=MAX(sockfd, sockfd_ASUS);
    	FD_ZERO(&afds);
#endif
    
    while(TRUE)
    {
	//if (busy) syslog(LOG_NOTICE, "busying %d %d\n", lptstatus.busy, busy);

	lock = file_lock("printer");				// by Jiahao for U2EC. 20080808.
	if (lptstatus.busy==FALSE && nvram_invmatch("MFP_busy", "2"))
	{
		busy=FALSE;
		nvram_set_int_temp("MFP_busy", 0);

		nvram_set_temp("u2ec_busyip", "");
	}
	file_unlock(lock);

#ifdef Raw_Printing_with_ASUS //Lisa
	FD_SET(netfd, &afds);
#endif
#ifdef LPR_with_ASUS//JY1112
	FD_SET(sockfd, &afds);
	FD_SET(sockfd_ASUS, &afds);
	memcpy(&rfds, &afds, sizeof(rfds));

	if((err_select=select(nfds+1, &rfds, (fd_set *)0, (fd_set *)0, (struct timeval *)0 )) < 0) 
	{
//JY1120	printf("select error on sockfd: error=%d\n", errno);
		/**/
//		printf("sockfd_FD_ISSET=%d\n", FD_ISSET(sockfd, &rfds));
//JY1120		printf("sockfd_ASUS FD_ISSET=%d\n", FD_ISSET(sockfd_ASUS, &rfds));
		/**/
//		if(errno != 4)//JY1113: delete
		//syslog(LOG_NOTICE, "select error %d\n", err_select);
		continue;
	}
#endif
        clilen = sizeof(cli_addr);

	if(FD_ISSET(sockfd_ASUS, &rfds))
	{
		LPRflag = 0;
		clisockfd   = accept(sockfd_ASUS,(struct sockaddr *)&cli_addr, &clilen);
	}
#ifdef LPR_with_ASUS//JY1112 
	else if(FD_ISSET(sockfd, &rfds))
	{
		LPRflag = 1;
		clisockfd   = accept(sockfd,(struct sockaddr *)&cli_addr, &clilen);
	}
#endif
#ifdef Raw_Printing_with_ASUS //Lisa
//	else if(FD_ISSET(netfd, &rfds) && busy==FALSE)
	else if(FD_ISSET(netfd, &rfds))
	{
		lock = file_lock("printer");	// by Jiahao for U2EC. 20080808.
		if (nvram_match("MFP_busy", "0"))
		{
			file_unlock(lock);
			LPRflag = 2;
			clisockfd = accept(netfd, (struct sockaddr*) &cli_addr, &clilen);
		}
		else
		{
			file_unlock(lock);
			sleep(2);
			continue;
		}
	}
#endif
	else
        {
		//syslog(LOG_NOTICE, "No select\n");
		sleep(2);
		continue;
	}

	strcpy(clientaddr , inet_ntoa(cli_addr.sin_addr));
	
	if(clisockfd < 0)
        {
	     //syslog(LOG_NOTICE, "LPD error: No clisockfd %d\n", LPRflag);
             continue;
        }

	lock = file_lock("printer");
//	if (busy!=FALSE)	/* 2004/09/10 by Joey, process nack in parent for LPR and Remote Prot */
	if (nvram_invmatch("MFP_busy", "0"))		// by Jiahao for U2EC. 20080808.
	{
		file_unlock(lock);
		//syslog(LOG_NOTICE, "Printing others 1 %d %d\n", LPRflag, clisockfd);
		if (LPRflag==0) processReq(clisockfd);
		else if (LPRflag==1) processReq_LPR(clisockfd, 0);
		//syslog(LOG_NOTICE, "Printing others %d %d\n", LPRflag, clisockfd);
		close(clisockfd);
		// For Raw printing, don't resonse to client while busy
		sleep(5);
		continue;
	}

	nvram_set_int_temp("MFP_busy", 1);

	if (nvram_match("lan_ipaddr_t", ""))
		nvram_set_temp("u2ec_busyip", nvram_safe_get("lan_ipaddr"));
	else
		nvram_set_temp("u2ec_busyip", nvram_safe_get("lan_ipaddr_t"));

	file_unlock(lock);

        if( (childpid = fork() ) < 0)
        {
        }
        else if(childpid == 0) 
        {
		//syslog(LOG_NOTICE, "Printing %d\n", LPRflag);

		if(LPRflag==0) processReq(clisockfd); 
#ifdef LPR_with_ASUS//JY1114 
		else if(LPRflag==1) processReq_LPR(clisockfd, 1);
#endif
#ifdef Raw_Printing_with_ASUS //Lisa
		else if(LPRflag == 2) processReq_Raw(clisockfd);
#endif
		close(sockfd);
		close(sockfd_ASUS);
#ifdef Raw_Printing_with_ASUS
		close(netfd);
#endif
        	exit(0);
        }
              
	//syslog(0, "Printing Process %d %d %d\n", busy, lptstatus.busy, childpid);

        //parents process goes on here
        //remark PRINT("fork -- childpid %d\n",childpid);

	if(lptstatus.busy == FALSE)
	{
		lptstatus.busy = TRUE;
//		busy = TRUE;				// remarked by Jiahao for U2EC. 20080808.
		strcpy(lptstatus.addr , inet_ntoa(cli_addr.sin_addr));
		lptstatus.pid = childpid;
	}

        close(clisockfd);
    }

}