Esempio n. 1
0
File: ls.c Progetto: dreamer2018/C
int print_info_srv(int count,int flag,str_node_t *head)     //打印文件信息服务函数
{
    int i;
    str_node_t *p;
    sort(count,head);      //对文件名进行排序
    p=head;
    for(i=0;i<count;i++)
    {
        p=p->next;
        if(flag==-1 || flag==0)
        {
            if(!strcmp(p->str,".")||!strcmp(p->str,"..")||p->str[0]=='.')
            {
                continue;
            }
            my_stat(flag,p->str);
            if(i==count-1)
            {
                printf("\n");
            }
        }
        else
        {
           my_stat(flag,p->str);
        }
    }
}
Esempio n. 2
0
bool 
File_class::exists(const char* aFileName)
{
  MY_STAT stmp;

  return (my_stat(aFileName, &stmp, MYF(0))!=NULL);
}
Esempio n. 3
0
int my_rename(const char *from, const char *to, myf MyFlags)
{
  int error = 0;
  DBUG_ENTER("my_rename");
  DBUG_PRINT("my",("from %s to %s MyFlags %d", from, to, MyFlags));

#if defined(HAVE_FILE_VERSIONS)
  {				/* Check that there isn't a old file */
    int save_errno;
    MY_STAT my_stat_result;
    save_errno=my_errno;
    if (my_stat(to,&my_stat_result,MYF(0)))
    {
      my_errno=EEXIST;
      error= -1;
      if (MyFlags & MY_FAE+MY_WME)
      {
        char errbuf[MYSYS_STRERROR_SIZE];
        my_error(EE_LINK, MYF(ME_BELL+ME_WAITTANG), from, to,
                 my_errno, my_strerror(errbuf, sizeof(errbuf), my_errno));
      }
      DBUG_RETURN(error);
    }
    my_errno=save_errno;
  }
#endif
#if defined(__WIN__)
  if(!MoveFileEx(from, to, MOVEFILE_COPY_ALLOWED|
                           MOVEFILE_REPLACE_EXISTING))
  {
    my_osmaperr(GetLastError());
#else
  if (rename(from,to))
  {
#endif
    my_errno=errno;
    error = -1;
    if (MyFlags & (MY_FAE+MY_WME))
    {
      char errbuf[MYSYS_STRERROR_SIZE];
      my_error(EE_LINK, MYF(ME_BELL+ME_WAITTANG), from, to,
               my_errno, my_strerror(errbuf, sizeof(errbuf), my_errno));
    }
  }
  else if (MyFlags & MY_SYNC_DIR)
  {
#ifdef NEED_EXPLICIT_SYNC_DIR
    /* do only the needed amount of syncs: */
    char dir_from[FN_REFLEN], dir_to[FN_REFLEN];
    size_t dir_from_length, dir_to_length;
    dirname_part(dir_from, from, &dir_from_length);
    dirname_part(dir_to, to, &dir_to_length);
    if (my_sync_dir(dir_from, MyFlags) ||
        (strcmp(dir_from, dir_to) &&
         my_sync_dir(dir_to, MyFlags)))
      error= -1;
#endif
  }
  DBUG_RETURN(error);
} /* my_rename */
Esempio n. 4
0
int my_rename(const char *from, const char *to, myf MyFlags)
{
  int error = 0;
  DBUG_ENTER("my_rename");
  DBUG_PRINT("my",("from %s to %s MyFlags %d", from, to, MyFlags));

#if defined(HAVE_FILE_VERSIONS)
  {				/* Check that there isn't a old file */
    int save_errno;
    MY_STAT my_stat_result;
    save_errno=my_errno;
    if (my_stat(to,&my_stat_result,MYF(0)))
    {
      my_errno=EEXIST;
      error= -1;
      if (MyFlags & MY_FAE+MY_WME)
	my_error(EE_LINK, MYF(ME_BELL+ME_WAITTANG),from,to,my_errno);
      DBUG_RETURN(error);
    }
    my_errno=save_errno;
  }
#endif
#if defined(HAVE_RENAME)
#if defined(__WIN__)
  /*
    On windows we can't rename over an existing file:
    Remove any conflicting files:
  */
  (void) my_delete(to, MYF(0));
#endif
  if (rename(from,to))
#else
  if (link(from, to) || unlink(from))
#endif
  {
    my_errno=errno;
    error = -1;
    if (MyFlags & (MY_FAE+MY_WME))
      my_error(EE_LINK, MYF(ME_BELL+ME_WAITTANG),from,to,my_errno);
  }
  else if (MyFlags & MY_SYNC_DIR)
  {
#ifdef NEED_EXPLICIT_SYNC_DIR
    /* do only the needed amount of syncs: */
    char dir_from[FN_REFLEN], dir_to[FN_REFLEN];
    size_t dir_from_length, dir_to_length;
    dirname_part(dir_from, from, &dir_from_length);
    dirname_part(dir_to, to, &dir_to_length);
    if (my_sync_dir(dir_from, MyFlags) ||
        (strcmp(dir_from, dir_to) &&
         my_sync_dir(dir_to, MyFlags)))
      error= -1;
#endif
  }
  DBUG_RETURN(error);
} /* my_rename */
Esempio n. 5
0
/* hard links are also tested a bunch in test_rename */
void test_link(char *workdir) {
    char file1[1024], file2[1024], file3[1024];
    struct stat sb;

    printf("Testing link\n");

    sprintf(file1, "%s/original", workdir);
    sprintf(file2, "%s/link", workdir);

    my_create(file1);
    my_stat(file1, &sb);
    my_link(file1, file2);
    verify_inum(file2, &sb);
    my_unlink(file2);
    verify_inum(file1, &sb);

    /* Test deletion of the original file after a hard link has been
       created */
    my_link(file1, file2);
    my_unlink(file1);
    verify_inum(file2, &sb);
    /* Make sure the original file really isn't accessible */
    verify_no_exist(file1);
    my_unlink(file2);
    verify_no_exist(file2);

    /* Try renaming a hard link */
    my_create(file1);
    my_stat(file1, &sb);
    my_link(file1, file2);
    sprintf(file3, "%s/file3", workdir);
    my_rename(file2, file3);
    verify_inum(file3, &sb);
    verify_no_exist(file2);

    my_unlink(file3);
    verify_no_exist(file3);

    my_unlink(file1);

}
Esempio n. 6
0
//
// PUBLIC
//
time_t 
File_class::mtime(const char* aFileName)
{
  MY_STAT stmp;
  time_t rc = 0;

  if (my_stat(aFileName, &stmp, MYF(0)) != NULL) {
    rc = stmp.st_mtime;
  }

  return rc;
}
Esempio n. 7
0
void verify_inum(char *filename, struct stat *sb1) {
    struct stat sb2;

    my_stat(filename, &sb2);

    if (sb1->st_ino != sb2.st_ino) {
        printf("inode number of %s changed during rename operation.\n"
               "Expected %d but got %d\n",
               filename, sb1->st_ino, sb2.st_ino);

        exit(1);
    }
}
Esempio n. 8
0
int main(int argc, char **argv)
{
  struct stat st;
  int i;

  i = (argc == 1 ? 0 : 1);
  while (i < argc)
    {
      if (stat(argv[i], &st) == 0)
	my_stat(argv[i], &st);
      else
	printf("Failed to stat %s.\n", argv[i]);
      i++;
    }
  return (0);
}
Esempio n. 9
0
my_bool maria_log_remove(const char *testdir)
{
  MY_DIR *dirp;
  uint i;
  MY_STAT stat_buff;
  char file_name[FN_REFLEN];

  /* Removes control file */
  if (fn_format(file_name, CONTROL_FILE_BASE_NAME,
                maria_data_root, "", MYF(MY_WME)) == NullS)
    return 1;
  if (my_stat(file_name, &stat_buff, MYF(0)) &&
      my_delete(file_name, MYF(MY_WME)) != 0)
    return 1;

  /* Finds and removes transaction log files */
  if (!(dirp = my_dir(maria_data_root, MYF(MY_DONT_SORT))))
    return 1;

  for (i= 0; i < dirp->number_of_files; i++)
  {
    char *file= dirp->dir_entry[i].name;
    if (strncmp(file, "aria_log.", 9) == 0 &&
        file[9] >= '0' && file[9] <= '9' &&
        file[10] >= '0' && file[10] <= '9' &&
        file[11] >= '0' && file[11] <= '9' &&
        file[12] >= '0' && file[12] <= '9' &&
        file[13] >= '0' && file[13] <= '9' &&
        file[14] >= '0' && file[14] <= '9' &&
        file[15] >= '0' && file[15] <= '9' &&
        file[16] >= '0' && file[16] <= '9' &&
        file[17] == '\0')
    {
      if (fn_format(file_name, file,
                    maria_data_root, "", MYF(MY_WME)) == NullS ||
          my_delete(file_name, MYF(MY_WME)) != 0)
      {
        my_dirend(dirp);
        return 1;
      }
    }
  }
  my_dirend(dirp);
  if (testdir)
    rmdir(testdir);
  return 0;
}
Esempio n. 10
0
int my_copystat(const char *from, const char *to, int MyFlags)
{
  MY_STAT statbuf;

  if (my_stat(from, &statbuf, MyFlags) == NULL)
    return -1;				/* Can't get stat on input file */

  if ((statbuf.st_mode & S_IFMT) != S_IFREG)
    return 1;

  /* Copy modes */
  if (chmod(to, statbuf.st_mode & 07777))
  {
    my_errno= errno;
    if (MyFlags & (MY_FAE+MY_WME))
      my_error(EE_CHANGE_PERMISSIONS, MYF(ME_BELL+ME_WAITTANG), from, errno);
    return -1;
  }

#if !defined(__WIN__)
  if (statbuf.st_nlink > 1 && MyFlags & MY_LINK_WARNING)
  {
    if (MyFlags & MY_LINK_WARNING)
      my_error(EE_LINK_WARNING,MYF(ME_BELL+ME_WAITTANG),from,statbuf.st_nlink);
  }
  /* Copy ownership */
  if (chown(to, statbuf.st_uid, statbuf.st_gid))
  {
    my_errno= errno;
    if (MyFlags & MY_WME)
      my_error(EE_CHANGE_OWNERSHIP, MYF(ME_BELL+ME_WAITTANG), from, errno);
    if (MyFlags & MY_FAE)
      return -1;
  }
#endif /* !__WIN__ */

  if (MyFlags & MY_COPYTIME)
  {
    struct utimbuf timep;
    timep.actime  = statbuf.st_atime;
    timep.modtime = statbuf.st_mtime;
    (void) utime((char*) to, &timep);/* Update last accessed and modified times */
  }

  return 0;
} /* my_copystat */
Esempio n. 11
0
char		*get_bin_path_search(char **path, char *bin)
{
  char		*correct_bin;
  int		i;
  struct stat	file_stat;

  i = 0;
  while (path[i])
    {
      correct_bin = concat_two_str(path[i], bin, "/");
      file_stat = my_stat(correct_bin);
      if (!access(correct_bin, F_OK | X_OK) && S_ISREG(file_stat.st_mode))
	return (correct_bin);
      i++;
      free(correct_bin);
    }
  return (NULL);
}
Esempio n. 12
0
bool CFileBrowser::readDir(const std::string& dirname, CFileList* flist)
{
	dprintf(DEBUG_INFO, "CFileBrowser::readDir %s\n", dirname.c_str());
	
	stat_struct statbuf;
	dirent_struct **namelist;
	int n;

	n = my_scandir(dirname.c_str(), &namelist, 0, my_alphasort);
	if (n < 0)
	{
		perror(("Filebrowser scandir: " + dirname).c_str());
		return false;
	}
	
	for(int i = 0; i < n;i++)
	{
		CFile file;
		if(strcmp(namelist[i]->d_name, ".") != 0)
		{
			// name
			file.Name = dirname + namelist[i]->d_name;

			// stat
			if(my_stat((file.Name).c_str(),&statbuf) != 0)
				perror("stat error");
			else
			{
				file.Mode = statbuf.st_mode;
				file.Size = statbuf.st_size;
				file.Time = statbuf.st_mtime;
				
				flist->push_back(file);
			}
		}
		free(namelist[i]);
	}

	free(namelist);

	return true;
}
Esempio n. 13
0
static my_bool
my_read_charset_file(MY_CHARSET_LOADER *loader,
                     const char *filename,
                     myf myflags)
{
  uchar *buf;
  int  fd;
  size_t len, tmp_len;
  MY_STAT stat_info;
  
  if (!my_stat(filename, &stat_info, MYF(myflags)) ||
       ((len= (uint)stat_info.st_size) > MY_MAX_ALLOWED_BUF) ||
       !(buf= (uchar*) my_malloc(key_memory_charset_file,
                                 len,myflags)))
    return TRUE;
  
  if ((fd= mysql_file_open(key_file_charset, filename, O_RDONLY, myflags)) < 0)
    goto error;
  tmp_len= mysql_file_read(fd, buf, len, myflags);
  mysql_file_close(fd, myflags);
  if (tmp_len != len)
    goto error;
  
  if (my_parse_charset_xml(loader, (char *) buf, len))
  {
    my_printf_error(EE_UNKNOWN_CHARSET, "Error while parsing '%s': %s\n",
                    MYF(0), filename, loader->error);
    goto error;
  }
  
  my_free(buf);
  return FALSE;

error:
  my_free(buf);
  return TRUE;
}
Esempio n. 14
0
static my_bool my_read_charset_file(const char *filename, myf myflags)
{
  uchar *buf;
  int  fd;
  size_t len, tmp_len;
  MY_STAT stat_info;

  if (!my_stat(filename, &stat_info, MYF(myflags)) ||
       ((len= (uint)stat_info.st_size) > MY_MAX_ALLOWED_BUF) ||
       !(buf= (uchar*) my_malloc(len,myflags)))
    return TRUE;

  if ((fd= mysql_file_open(key_file_charset, filename, O_RDONLY, myflags)) < 0)
    goto error;
  tmp_len= mysql_file_read(fd, buf, len, myflags);
  mysql_file_close(fd, myflags);
  if (tmp_len != len)
    goto error;

  if (my_parse_charset_xml((char*) buf,len,add_collation))
  {
#ifdef NOT_YET
    printf("ERROR at line %d pos %d '%s'\n",
	   my_xml_error_lineno(&p)+1,
	   my_xml_error_pos(&p),
	   my_xml_error_string(&p));
#endif
  }

  my_free(buf);
  return FALSE;

error:
  my_free(buf);
  return TRUE;
}
Esempio n. 15
0
void test_rename(char *workdir) {
    char file1[1024], file2[1024], link[1024],
         subdir[1024], newdir[1024];
    struct stat sb1, sb2;
    int fd;

    printf("testing rename\n");

    sprintf(file1, "%s/file1", workdir);
    sprintf(file2, "%s/file2", workdir);

    /* test stat first.. since we need it to test rename */
    my_stat(file1, &sb1);

    /* Not much to look at, really..  how about making sure that
       the modification time of the file is not in the future.
       allow ten seconds of slack */
    if (sb1.st_mtime > time(NULL) + 10) {
        printf("Modification time of %s is in the future!\n",
               file1);
        exit(1);
    }

    my_rename(file1, file2);

    /* try repeat */
    if (!rename(file1, file2)) {
        printf("repeat rename(%s,%s) worked.. but it shouldn't have\n",
               file1, file2);
        exit(1);
    }


    /* inode number of file2 should be the same as it was for file1 */
    verify_inum(file2, &sb1);


    /* rename back */
    my_rename(file2, file1);

    verify_inum(file1, &sb1);

    /* Make a subdir, which will be renamed */
    sprintf(subdir, "%s/rename_this_dir", workdir);

    my_mkdir(subdir);
    my_stat(subdir, &sb2);

    /* Test moving a file into a subdir */
    sprintf(file2, "%s/file1", subdir);
    my_rename(file1, file2);
    verify_inum(file2, &sb1);

    /* Add in a hard link to spice things up */
    sprintf(link, "%s/link", subdir);
    my_link(file2, link);

    sprintf(newdir, "%s/newdirname", workdir);
    my_rename(subdir, newdir);
    verify_inum(newdir, &sb2);
    sprintf(file2, "%s/file1", newdir);
    verify_inum(file2, &sb1);
    sprintf(link, "%s/newdirname/link", workdir);
    verify_inum(link, &sb1);

    /* Test moving up in the tree */
    my_rename(file2,file1);
    verify_inum(file1, &sb1);

    my_unlink(link);

    my_rmdir(newdir);

}
Esempio n. 16
0
static int search_default_file_with_ext(Process_option_func opt_handler,
                                        void *handler_ctx,
                                        const char *dir,
                                        const char *ext,
                                        const char *config_file,
                                        int recursion_level)
{
  char name[FN_REFLEN + 10], buff[4096], curr_gr[4096], *ptr, *end, **tmp_ext;
  char *value, option[4096+2], tmp[FN_REFLEN];
  static const char includedir_keyword[]= "includedir";
  static const char include_keyword[]= "include";
  const int max_recursion_level= 10;
  MYSQL_FILE *fp;
  uint line=0;
  my_bool found_group=0;
  uint i;
  MY_DIR *search_dir;
  FILEINFO *search_file;

  if ((dir ? strlen(dir) : 0 )+strlen(config_file) >= FN_REFLEN-3)
    return 0;					/* Ignore wrong paths */
  if (dir)
  {
    end=convert_dirname(name, dir, NullS);
    if (dir[0] == FN_HOMELIB)		/* Add . to filenames in home */
      *end++='.';
    strxmov(end,config_file,ext,NullS);
  }
  else
  {
    strmov(name,config_file);
  }
  fn_format(name,name,"","",4);
#if !defined(__WIN__)
  {
    MY_STAT stat_info;
    if (!my_stat(name,&stat_info,MYF(0)))
      return 1;
    /*
      Ignore world-writable regular files.
      This is mainly done to protect us to not read a file created by
      the mysqld server, but the check is still valid in most context. 
    */
    if ((stat_info.st_mode & S_IWOTH) &&
	(stat_info.st_mode & S_IFMT) == S_IFREG)
    {
      fprintf(stderr, "Warning: World-writable config file '%s' is ignored\n",
              name);
      return 0;
    }
  }
#endif
  if (!(fp= mysql_file_fopen(key_file_cnf, name, O_RDONLY, MYF(0))))
    return 1;					/* Ignore wrong files */

  while (mysql_file_fgets(buff, sizeof(buff) - 1, fp))
  {
    line++;
    /* Ignore comment and empty lines */
    for (ptr= buff; my_isspace(&my_charset_latin1, *ptr); ptr++)
    {}

    if (*ptr == '#' || *ptr == ';' || !*ptr)
      continue;

    /* Configuration File Directives */
    if (*ptr == '!')
    {
      if (recursion_level >= max_recursion_level)
      {
        for (end= ptr + strlen(ptr) - 1; 
             my_isspace(&my_charset_latin1, *(end - 1));
             end--)
        {}
        end[0]= 0;
        fprintf(stderr,
                "Warning: skipping '%s' directive as maximum include"
                "recursion level was reached in file %s at line %d\n",
                ptr, name, line);
        continue;
      }

      /* skip over `!' and following whitespace */
      for (++ptr; my_isspace(&my_charset_latin1, ptr[0]); ptr++)
      {}

      if ((!strncmp(ptr, includedir_keyword,
                    sizeof(includedir_keyword) - 1)) &&
          my_isspace(&my_charset_latin1, ptr[sizeof(includedir_keyword) - 1]))
      {
	if (!(ptr= get_argument(includedir_keyword,
                                sizeof(includedir_keyword),
                                ptr, name, line)))
	  goto err;

        if (!(search_dir= my_dir(ptr, MYF(MY_WME))))
          goto err;

        for (i= 0; i < (uint) search_dir->number_of_files; i++)
        {
          search_file= search_dir->dir_entry + i;
          ext= fn_ext(search_file->name);

          /* check extension */
          for (tmp_ext= (char**) f_extensions; *tmp_ext; tmp_ext++)
          {
            if (!strcmp(ext, *tmp_ext))
              break;
          }

          if (*tmp_ext)
          {
            fn_format(tmp, search_file->name, ptr, "",
                      MY_UNPACK_FILENAME | MY_SAFE_PATH);

            search_default_file_with_ext(opt_handler, handler_ctx, "", "", tmp,
                                         recursion_level + 1);
          }
        }

        my_dirend(search_dir);
      }
      else if ((!strncmp(ptr, include_keyword, sizeof(include_keyword) - 1)) &&
               my_isspace(&my_charset_latin1, ptr[sizeof(include_keyword)-1]))
      {
	if (!(ptr= get_argument(include_keyword,
                                sizeof(include_keyword), ptr,
                                name, line)))
	  goto err;

        search_default_file_with_ext(opt_handler, handler_ctx, "", "", ptr,
                                     recursion_level + 1);
      }

      continue;
    }

    if (*ptr == '[')				/* Group name */
    {
      found_group=1;
      if (!(end=(char *) strchr(++ptr,']')))
      {
	fprintf(stderr,
		"error: Wrong group definition in config file: %s at line %d\n",
		name,line);
	goto err;
      }
      /* Remove end space */
      for ( ; my_isspace(&my_charset_latin1,end[-1]) ; end--) ;
      end[0]=0;

      strmake(curr_gr, ptr, MY_MIN((size_t) (end-ptr)+1, sizeof(curr_gr)-1));

      /* signal that a new group is found */
      opt_handler(handler_ctx, curr_gr, NULL);

      continue;
    }
    if (!found_group)
    {
      fprintf(stderr,
	      "error: Found option without preceding group in config file: %s at line: %d\n",
	      name,line);
      goto err;
    }
    
   
    end= remove_end_comment(ptr);
    if ((value= strchr(ptr, '=')))
      end= value;				/* Option without argument */
    for ( ; my_isspace(&my_charset_latin1,end[-1]) ; end--) ;
    if (!value)
    {
      strmake(strmov(option,"--"),ptr, (size_t) (end-ptr));
      if (opt_handler(handler_ctx, curr_gr, option))
        goto err;
    }
    else
    {
      /* Remove pre- and end space */
      char *value_end;
      for (value++ ; my_isspace(&my_charset_latin1,*value); value++) ;
      value_end=strend(value);
      /*
	We don't have to test for value_end >= value as we know there is
	an '=' before
      */
      for ( ; my_isspace(&my_charset_latin1,value_end[-1]) ; value_end--) ;
      if (value_end < value)			/* Empty string */
	value_end=value;

      /* remove quotes around argument */
      if ((*value == '\"' || *value == '\'') && /* First char is quote */
          (value + 1 < value_end ) && /* String is longer than 1 */
          *value == value_end[-1] ) /* First char is equal to last char */
      {
	value++;
	value_end--;
      }
      ptr=strnmov(strmov(option,"--"),ptr,(size_t) (end-ptr));
      *ptr++= '=';

      for ( ; value != value_end; value++)
      {
	if (*value == '\\' && value != value_end-1)
	{
	  switch(*++value) {
	  case 'n':
	    *ptr++='\n';
	    break;
	  case 't':
	    *ptr++= '\t';
	    break;
	  case 'r':
	    *ptr++ = '\r';
	    break;
	  case 'b':
	    *ptr++ = '\b';
	    break;
	  case 's':
	    *ptr++= ' ';			/* space */
	    break;
	  case '\"':
	    *ptr++= '\"';
	    break;
	  case '\'':
	    *ptr++= '\'';
	    break;
	  case '\\':
	    *ptr++= '\\';
	    break;
	  default:				/* Unknown; Keep '\' */
	    *ptr++= '\\';
	    *ptr++= *value;
	    break;
	  }
	}
	else
	  *ptr++= *value;
      }
      *ptr=0;
      if (opt_handler(handler_ctx, curr_gr, option))
        goto err;
    }
  }
  mysql_file_fclose(fp, MYF(0));
  return(0);

 err:
  mysql_file_fclose(fp, MYF(0));
  return -1;					/* Fatal error */
}
Esempio n. 17
0
int my_copy(const char *from, const char *to, myf MyFlags)
{
  size_t Count;
  my_bool new_file_stat= 0; /* 1 if we could stat "to" */
  int create_flag;
  File from_file,to_file;
  uchar buff[IO_SIZE];
  MY_STAT stat_buff,new_stat_buff;
  gid_t gid;
  DBUG_ENTER("my_copy");
  DBUG_PRINT("my",("from %s to %s MyFlags %d", from, to, MyFlags));

  from_file=to_file= -1;
  DBUG_ASSERT(!(MyFlags & (MY_FNABP | MY_NABP))); /* for my_read/my_write */
  if (MyFlags & MY_HOLD_ORIGINAL_MODES)		/* Copy stat if possible */
    new_file_stat= test(my_stat((char*) to, &new_stat_buff, MYF(0)));

  if ((from_file=my_open(from,O_RDONLY | O_SHARE,MyFlags)) >= 0)
  {
    if (!my_stat(from, &stat_buff, MyFlags))
    {
      my_errno=errno;
      goto err;
    }
    if (MyFlags & MY_HOLD_ORIGINAL_MODES && new_file_stat)
      stat_buff=new_stat_buff;
    create_flag= (MyFlags & MY_DONT_OVERWRITE_FILE) ? O_EXCL : O_TRUNC;

    if ((to_file=  my_create(to,(int) stat_buff.st_mode,
			     O_WRONLY | create_flag | O_BINARY | O_SHARE,
			     MyFlags)) < 0)
      goto err;

    while ((Count=my_read(from_file, buff, sizeof(buff), MyFlags)) != 0)
    {
	if (Count == (uint) -1 ||
	    my_write(to_file,buff,Count,MYF(MyFlags | MY_NABP)))
	goto err;
    }

    /* sync the destination file */
    if (MyFlags & MY_SYNC)
    {
      if (my_sync(to_file, MyFlags))
        goto err;
    }

    if (my_close(from_file,MyFlags) | my_close(to_file,MyFlags))
      DBUG_RETURN(-1);				/* Error on close */

    /* Copy modes if possible */

    if (MyFlags & MY_HOLD_ORIGINAL_MODES && !new_file_stat)
	DBUG_RETURN(0);			/* File copyed but not stat */

#if !defined(__WIN__) && !defined(__NETWARE__)
    /* Refresh the new_stat_buff */
    if (!my_stat((char*) to, &new_stat_buff, MYF(0)))
    {
      my_errno= errno;
      goto err;
    }

    /* Copy modes */
    if ((stat_buff.st_mode & 07777) != (new_stat_buff.st_mode & 07777) &&
        chmod(to, stat_buff.st_mode & 07777))
    {
      my_errno= errno;
      if (MyFlags & (MY_FAE+MY_WME))
        my_error(EE_CHANGE_PERMISSIONS, MYF(ME_BELL+ME_WAITTANG), from, errno);
      goto err;
    }

    /* Copy ownership */
    if (stat_buff.st_gid == new_stat_buff.st_gid)
      gid= -1;
    else
      gid= stat_buff.st_gid;
    if ((gid != (gid_t) -1 || stat_buff.st_uid != new_stat_buff.st_uid) &&
        chown(to, stat_buff.st_uid, gid))
    {
      my_errno= errno;
      if (MyFlags & (MY_FAE+MY_WME))
        my_error(EE_CHANGE_OWNERSHIP, MYF(ME_BELL+ME_WAITTANG), from, errno);
      goto err;
    }
#endif
#if !defined(VMS) && !defined(__ZTC__)
    if (MyFlags & MY_COPYTIME)
    {
      struct utimbuf timep;
      timep.actime  = stat_buff.st_atime;
      timep.modtime = stat_buff.st_mtime;
      VOID(utime((char*) to, &timep)); /* last accessed and modified times */
    }
#endif
    DBUG_RETURN(0);
  }

err:
  if (from_file >= 0) VOID(my_close(from_file,MyFlags));
  if (to_file >= 0)
  {
    VOID(my_close(to_file, MyFlags));
    /* attempt to delete the to-file we've partially written */
    VOID(my_delete(to, MyFlags));
  }
  DBUG_RETURN(-1);
} /* my_copy */
Esempio n. 18
0
static int myopen(const char *fname, int flags, struct dbengine **ret,
                  struct txn **tidptr)
{
    struct dbengine *db;
    int r, mr = 0;

    PDEBUG("cyrusdb_lmdb(%s)[open] flags=0x%x tidptr=%p *tidptr=%p",
            fname, flags, tidptr, tidptr ? *tidptr : NULL);
    assert(fname && ret);

    /* Create a new database engine */
    db = (struct dbengine *) xzmalloc(sizeof(struct dbengine));
    db->fname = xstrdup(fname);
    db->flags = flags;

    /* Assert that either the parent directory or the database exists */
    r = flags & CYRUSDB_CREATE ? my_mkparentdir(fname) : my_stat(fname);
    if (r) {
        /* Both my_stat and my_mkparentdir preserve errno */
        r = errno == ENOENT ? CYRUSDB_NOTFOUND : CYRUSDB_IOERROR;
        goto fail;
    }

    /* Create the environment for this database */
    mr = mdb_env_create(&db->env);
    if (mr) {
        r = CYRUSDB_INTERNAL;
        goto fail;
    }

    /* Size (or resize) the environment */
    mr = mdb_env_set_mapsize(db->env, maxdbsize);
    if (mr) {
        r = CYRUSDB_INTERNAL;
        goto fail;
    }

    /* Open the environment */
    mr = mdb_env_open(db->env, fname, MDB_NOSUBDIR, 0600);
    if (mr) {
        r = CYRUSDB_IOERROR;
        goto fail;
    }

    /* Lock the database, if requested */
    if (tidptr) {
        r = begin_txn(db, tidptr, 0);
        if (r) goto fail;
    }

    /* Keep database for internal bookkeeping */
    register_db(db);

    /* Return the database handle */
    *ret = db;
    return CYRUSDB_OK;

fail:
    if (mr)
        syslog(LOG_ERR, "cryusdb_lmdb(%s): %s", db->fname, mdb_strerror(mr));
    if (db->env)
        mdb_env_close(db->env);
    free(db->fname);
    free(db);
    return r;
}
int
main(int argc, char **argv)
{
	gcry_error_t 		gcry_error;
	File filein = 0;
	File fileout = 0;

	MY_INIT(argv[0]);

	if (get_options(&argc, &argv)) {
		goto err;
	}

	/* Acording to gcrypt docs (and my testing), setting up the threading
	   callbacks must be done first, so, lets give it a shot */
	gcry_error = gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
	if (gcry_error) {
		msg("%s: unable to set libgcrypt thread cbs - "
		    "%s : %s\n", my_progname,
		    gcry_strsource(gcry_error),
		    gcry_strerror(gcry_error));
		return 1;
	}

	/* Version check should be the very first call because it
	makes sure that important subsystems are intialized. */
	if (!gcry_control(GCRYCTL_ANY_INITIALIZATION_P)) {
		const char	*gcrypt_version;
		gcrypt_version = gcry_check_version(NULL);
		/* No other library has already initialized libgcrypt. */
		if (!gcrypt_version) {
			msg("%s: failed to initialize libgcrypt\n",
			    my_progname);
			return 1;
		} else if (opt_verbose) {
			msg("%s: using gcrypt %s\n", my_progname,
			    gcrypt_version);
		}
	}
	gcry_control(GCRYCTL_DISABLE_SECMEM, 0);
	gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);

	/* Determine the algorithm */
	encrypt_algo = encrypt_algos[opt_encrypt_algo];

	/* Set up the iv length */
	encrypt_iv_len = gcry_cipher_get_algo_blklen(encrypt_algo);

	/* Now set up the key */
	if (opt_encrypt_key == NULL && opt_encrypt_key_file == NULL) {
		msg("%s: no encryption key or key file specified.\n",
		    my_progname);
		return 1;
	} else if (opt_encrypt_key && opt_encrypt_key_file) {
		msg("%s: both encryption key and key file specified.\n",
		    my_progname);
		return 1;
	} else if (opt_encrypt_key_file) {
		if (!xb_crypt_read_key_file(opt_encrypt_key_file,
					    &opt_encrypt_key,
					    &encrypt_key_len)) {
			msg("%s: unable to read encryption key file \"%s\".\n",
			    opt_encrypt_key_file, my_progname);
			return 1;
		}
	} else {
		encrypt_key_len = strlen(opt_encrypt_key);
	}

	if (opt_input_file) {
		MY_STAT 	mystat;

		if (opt_verbose)
			msg("%s: input file \"%s\".\n", my_progname,
			    opt_input_file);

		if (my_stat(opt_input_file, &mystat, MYF(MY_WME)) == NULL) {
			goto err;
		}
		if (!MY_S_ISREG(mystat.st_mode)) {
			msg("%s: \"%s\" is not a regular file, exiting.\n",
			    my_progname, opt_input_file);
			goto err;
		}
		if ((filein = my_open(opt_input_file, O_RDONLY, MYF(MY_WME)))
		     < 0) {
			msg("%s: failed to open \"%s\".\n", my_progname,
			     opt_input_file);
			goto err;
		}
	} else {
		if (opt_verbose)
			msg("%s: input from standard input.\n", my_progname);
		filein = fileno(stdin);
	}

	if (opt_output_file) {
		if (opt_verbose)
			msg("%s: output file \"%s\".\n", my_progname,
			    opt_output_file);

		if ((fileout = my_create(opt_output_file, 0,
					 O_WRONLY|O_BINARY|O_EXCL|O_NOFOLLOW,
					 MYF(MY_WME))) < 0) {
			msg("%s: failed to create output file \"%s\".\n",
			    my_progname, opt_output_file);
			goto err;
		}
	} else {
		if (opt_verbose)
			msg("%s: output to standard output.\n", my_progname);
		fileout = fileno(stdout);
	}

	if (opt_run_mode == RUN_MODE_DECRYPT
	    && mode_decrypt(filein, fileout)) {
		goto err;
	} else if (opt_run_mode == RUN_MODE_ENCRYPT
		   && mode_encrypt(filein, fileout)) {
		goto err;
	}

	if (opt_input_file && filein) {
		my_close(filein, MYF(MY_WME));
	}
	if (opt_output_file && fileout) {
		my_close(fileout, MYF(MY_WME));
	}

	my_cleanup_options(my_long_options);

	my_end(0);

	return EXIT_SUCCESS;
err:
	if (opt_input_file && filein) {
		my_close(filein, MYF(MY_WME));
	}
	if (opt_output_file && fileout) {
		my_close(fileout, MYF(MY_WME));
	}

	my_cleanup_options(my_long_options);

	my_end(0);

	exit(EXIT_FAILURE);

}
Esempio n. 20
0
MY_DIR	*my_dir(const char *path, myf MyFlags)
{
  char          *buffer;
  MY_DIR        *result= 0;
  FILEINFO      finfo;
  DYNAMIC_ARRAY *dir_entries_storage;
  MEM_ROOT      *names_storage;
  DIR		*dirp;
  struct dirent *dp;
  char		tmp_path[FN_REFLEN+1],*tmp_file;
#ifdef THREAD
  char	dirent_tmp[sizeof(struct dirent)+_POSIX_PATH_MAX+1];
#endif
  DBUG_ENTER("my_dir");
  DBUG_PRINT("my",("path: '%s' MyFlags: %d",path,MyFlags));

#if defined(THREAD) && !defined(HAVE_READDIR_R)
  mysql_mutex_lock(&THR_LOCK_open);
#endif

  dirp = opendir(directory_file_name(tmp_path,(char *) path));
#if defined(__amiga__)
  if ((dirp->dd_fd) < 0)			/* Directory doesn't exists */
    goto error;
#endif
  if (dirp == NULL || 
      ! (buffer= my_malloc(ALIGN_SIZE(sizeof(MY_DIR)) + 
                           ALIGN_SIZE(sizeof(DYNAMIC_ARRAY)) +
                           sizeof(MEM_ROOT), MyFlags)))
    goto error;

  dir_entries_storage= (DYNAMIC_ARRAY*)(buffer + ALIGN_SIZE(sizeof(MY_DIR))); 
  names_storage= (MEM_ROOT*)(buffer + ALIGN_SIZE(sizeof(MY_DIR)) +
                             ALIGN_SIZE(sizeof(DYNAMIC_ARRAY)));
  
  if (my_init_dynamic_array(dir_entries_storage, sizeof(FILEINFO),
                            ENTRIES_START_SIZE, ENTRIES_INCREMENT))
  {
    my_free(buffer);
    goto error;
  }
  init_alloc_root(names_storage, NAMES_START_SIZE, NAMES_START_SIZE);
  
  /* MY_DIR structure is allocated and completly initialized at this point */
  result= (MY_DIR*)buffer;

  tmp_file=strend(tmp_path);

#ifdef THREAD
  dp= (struct dirent*) dirent_tmp;
#else
  dp=0;
#endif
  
  while (!(READDIR(dirp,(struct dirent*) dirent_tmp,dp)))
  {
    if (!(finfo.name= strdup_root(names_storage, dp->d_name)))
      goto error;
    
    if (MyFlags & MY_WANT_STAT)
    {
      if (!(finfo.mystat= (MY_STAT*)alloc_root(names_storage, 
                                               sizeof(MY_STAT))))
        goto error;
      
      bzero(finfo.mystat, sizeof(MY_STAT));
      (void) strmov(tmp_file,dp->d_name);
      (void) my_stat(tmp_path, finfo.mystat, MyFlags);
      if (!(finfo.mystat->st_mode & MY_S_IREAD))
        continue;
    }
    else
      finfo.mystat= NULL;

    if (push_dynamic(dir_entries_storage, (uchar*)&finfo))
      goto error;
  }

  (void) closedir(dirp);
#if defined(THREAD) && !defined(HAVE_READDIR_R)
  mysql_mutex_unlock(&THR_LOCK_open);
#endif
  result->dir_entry= (FILEINFO *)dir_entries_storage->buffer;
  result->number_off_files= dir_entries_storage->elements;
  
  if (!(MyFlags & MY_DONT_SORT))
    my_qsort((void *) result->dir_entry, result->number_off_files,
          sizeof(FILEINFO), (qsort_cmp) comp_names);
  DBUG_RETURN(result);

 error:
#if defined(THREAD) && !defined(HAVE_READDIR_R)
  mysql_mutex_unlock(&THR_LOCK_open);
#endif
  my_errno=errno;
  if (dirp)
    (void) closedir(dirp);
  my_dirend(result);
  if (MyFlags & (MY_FAE | MY_WME))
    my_error(EE_DIR,MYF(ME_BELL+ME_WAITTANG),path,my_errno);
  DBUG_RETURN((MY_DIR *) NULL);
} /* my_dir */
/*----------------------------------------------------------------------*/
extern int ls_main(int argc, char **argv)
{
	struct dnode **dnf, **dnd;
	int dnfiles, dndirs;
	struct dnode *dn, *cur, **dnp;
	int i, nfiles;
	int opt;
	int oi, ac;
	char **av;
#ifdef BB_FEATURE_AUTOWIDTH
	struct winsize win = { 0, 0, 0, 0 };
#endif

	disp_opts= DISP_NORMAL;
	style_fmt= STYLE_AUTO;
	list_fmt=  LIST_SHORT;
#ifdef BB_FEATURE_LS_SORTFILES
	sort_opts= SORT_NAME;
	sort_order=	SORT_FORWARD;
#endif
#ifdef BB_FEATURE_LS_TIMESTAMPS
	time_fmt= TIME_MOD;
#endif
#ifdef BB_FEATURE_AUTOWIDTH
	ioctl(fileno(stdout), TIOCGWINSZ, &win);
	if (win.ws_row > 4)
		column_width = win.ws_row - 2;
	if (win.ws_col > 0)
		terminal_width = win.ws_col - 1;
#endif
	nfiles=0;

	/* process options */
	while ((opt = getopt(argc, argv, "1AaCdgilnsx"
#ifdef BB_FEATURE_AUTOWIDTH
"T:w:"
#endif
#ifdef BB_FEATURE_LS_FILETYPES
"Fp"
#endif
#ifdef BB_FEATURE_LS_RECURSIVE
"R"
#endif
#ifdef BB_FEATURE_LS_SORTFILES
"rSvX"
#endif
#ifdef BB_FEATURE_LS_TIMESTAMPS
"cetu"
#endif
#ifdef BB_FEATURE_LS_FOLLOWLINKS
"L"
#endif
#ifdef BB_FEATURE_HUMAN_READABLE
"h"
#endif
"k")) > 0) {
		switch (opt) {
			case '1': style_fmt = STYLE_SINGLE; break;
			case 'A': disp_opts |= DISP_HIDDEN; break;
			case 'a': disp_opts |= DISP_HIDDEN | DISP_DOT; break;
			case 'C': style_fmt = STYLE_COLUMNS; break;
			case 'd': disp_opts |= DISP_NOLIST; break;
			case 'g': /* ignore -- for ftp servers */ break;
			case 'i': list_fmt |= LIST_INO; break;
			case 'l':
				style_fmt = STYLE_LONG;
				list_fmt |= LIST_LONG;
#ifdef BB_FEATURE_HUMAN_READABLE
				ls_disp_hr = FALSE;
#endif
			break;
			case 'n': list_fmt |= LIST_ID_NUMERIC; break;
			case 's': list_fmt |= LIST_BLOCKS; break;
			case 'x': disp_opts = DISP_ROWS; break;
#ifdef BB_FEATURE_LS_FILETYPES
			case 'F': list_fmt |= LIST_FILETYPE | LIST_EXEC; break;
			case 'p': list_fmt |= LIST_FILETYPE; break;
#endif
#ifdef BB_FEATURE_LS_RECURSIVE
			case 'R': disp_opts |= DISP_RECURSIVE; break;
#endif
#ifdef BB_FEATURE_LS_SORTFILES
			case 'r': sort_order |= SORT_REVERSE; break;
			case 'S': sort_opts= SORT_SIZE; break;
			case 'v': sort_opts= SORT_VERSION; break;
			case 'X': sort_opts= SORT_EXT; break;
#endif
#ifdef BB_FEATURE_LS_TIMESTAMPS
			case 'e': list_fmt |= LIST_FULLTIME; break;
			case 'c':
				time_fmt = TIME_CHANGE;
#ifdef BB_FEATURE_LS_SORTFILES
				sort_opts= SORT_CTIME;
#endif
				break;
			case 'u':
				time_fmt = TIME_ACCESS;
#ifdef BB_FEATURE_LS_SORTFILES
				sort_opts= SORT_ATIME;
#endif
				break;
			case 't':
#ifdef BB_FEATURE_LS_SORTFILES
				sort_opts= SORT_MTIME;
#endif
				break;
#endif
#ifdef BB_FEATURE_LS_FOLLOWLINKS
			case 'L': follow_links= TRUE; break;
#endif
#ifdef BB_FEATURE_AUTOWIDTH
			case 'T': tabstops= atoi(optarg); break;
			case 'w': terminal_width= atoi(optarg); break;
#endif
#ifdef BB_FEATURE_HUMAN_READABLE
			case 'h': ls_disp_hr = TRUE; break;
#endif
			case 'k': break;
			default:
				goto print_usage_message;
		}
	}

	/* sort out which command line options take precedence */
#ifdef BB_FEATURE_LS_RECURSIVE
	if (disp_opts & DISP_NOLIST)
		disp_opts &= ~DISP_RECURSIVE;   /* no recurse if listing only dir */
#endif
#if defined (BB_FEATURE_LS_TIMESTAMPS) && defined (BB_FEATURE_LS_SORTFILES)
	if (time_fmt & TIME_CHANGE) sort_opts= SORT_CTIME;
	if (time_fmt & TIME_ACCESS) sort_opts= SORT_ATIME;
#endif
	if (style_fmt != STYLE_LONG)
			list_fmt &= ~LIST_ID_NUMERIC;  /* numeric uid only for long list */
#ifdef BB_FEATURE_LS_USERNAME
	if (style_fmt == STYLE_LONG && (list_fmt & LIST_ID_NUMERIC))
			list_fmt &= ~LIST_ID_NAME;  /* don't list names if numeric uid */
#endif

	/* choose a display format */
	if (style_fmt == STYLE_AUTO)
		style_fmt = isatty(fileno(stdout)) ? STYLE_COLUMNS : STYLE_SINGLE;

	/*
	 * when there are no cmd line args we have to supply a default "." arg.
	 * we will create a second argv array, "av" that will hold either
	 * our created "." arg, or the real cmd line args.  The av array
	 * just holds the pointers- we don't move the date the pointers
	 * point to.
	 */
	ac= argc - optind;   /* how many cmd line args are left */
	if (ac < 1) {
		av= (char **)xcalloc((size_t)1, (size_t)(sizeof(char *)));
		av[0]= ".";
		ac=1;
	} else {
		av= (char **)xcalloc((size_t)ac, (size_t)(sizeof(char *)));
		for (oi=0 ; oi < ac; oi++) {
			av[oi]= argv[optind++];  /* copy pointer to real cmd line arg */
		}
	}

	/* now, everything is in the av array */
	if (ac > 1)
		disp_opts |= DISP_DIRNAME;   /* 2 or more items? label directories */

	/* stuff the command line file names into an dnode array */
	dn=NULL;
	for (oi=0 ; oi < ac; oi++) {
		cur= (struct dnode *)xmalloc(sizeof(struct dnode));
		cur->fullname= xstrdup(av[oi]);
		cur->name= cur->fullname;
		if (my_stat(cur))
			continue;
		cur->next= dn;
		dn= cur;
		nfiles++;
	}

	/* now that we know how many files there are
	** allocate memory for an array to hold dnode pointers
	*/
	dnp= dnalloc(nfiles);
	for (i=0, cur=dn; i<nfiles; i++) {
		dnp[i]= cur;   /* save pointer to node in array */
		cur= cur->next;
	}


	if (disp_opts & DISP_NOLIST) {
#ifdef BB_FEATURE_LS_SORTFILES
		shellsort(dnp, nfiles);
#endif
		if (nfiles > 0) showfiles(dnp, nfiles);
	} else {
		dnd= splitdnarray(dnp, nfiles, SPLIT_DIR);
		dnf= splitdnarray(dnp, nfiles, SPLIT_FILE);
		dndirs= countdirs(dnp, nfiles);
		dnfiles= nfiles - dndirs;
		if (dnfiles > 0) {
#ifdef BB_FEATURE_LS_SORTFILES
			shellsort(dnf, dnfiles);
#endif
			showfiles(dnf, dnfiles);
		}
		if (dndirs > 0) {
#ifdef BB_FEATURE_LS_SORTFILES
			shellsort(dnd, dndirs);
#endif
			showdirs(dnd, dndirs);
		}
		if (dnd)
			free(dnd);
		if (dnf)
			free(dnf);
	}
	free(av);
	if (dnp)
		dfree(dnp, nfiles);


	return(status);

  print_usage_message:
	show_usage();
}
Esempio n. 22
0
int test_file(PAGECACHE_FILE file, char *file_name,
              off_t size, size_t buff_size, struct file_desc *desc)
{
  unsigned char *buffr= my_malloc(buff_size, MYF(0));
  off_t pos= 0;
  size_t byte;
  int step= 0;
  int res= 1;                                   /* ok */

#ifdef __WIN__
  /*
    On Windows, the info returned by stat(), specifically file length
    is not necessarily current, because this is the behavior of
    underlying FindFirstFile() function.
  */
  WIN32_FILE_ATTRIBUTE_DATA file_attr;
  LARGE_INTEGER li;
  if(GetFileAttributesEx(file_name, GetFileExInfoStandard, &file_attr) == 0)
  {
    diag("Can't GetFileAttributesEx %s (errno: %d)\n", file_name,
      GetLastError());
    res= 0;
    goto err;
  }
  li.HighPart= file_attr.nFileSizeHigh;
  li.LowPart=  file_attr.nFileSizeLow;
  if(li.QuadPart !=  size)
  {
    diag("file %s size is %llu (should be %llu)\n",
      file_name, (ulonglong)size, (ulonglong)li.QuadPart);
    res= 0;                                       /* failed */
    /* continue to get more information */
  }
#else
  MY_STAT stat_buff, *stat;
  if ((stat= my_stat(file_name, &stat_buff, MYF(0))) == NULL)
  {
    diag("Can't stat() %s (errno: %d)\n", file_name, errno);
    res= 0;
    goto err;
  }
  if (stat->st_size != size)
  {
    diag("file %s size is %lu (should be %lu)\n",
         file_name, (ulong) stat->st_size, (ulong) size);
    res= 0;                                       /* failed */
    /* continue to get more information */
  }
#endif

  /* check content */
  my_seek(file.file, 0, SEEK_SET, MYF(MY_WME));
  while (desc[step].length != 0)
  {
    if (my_read(file.file, buffr, desc[step].length, MYF(0)) !=
        desc[step].length)
    {
      diag("Can't read %u bytes from %s (file: %d  errno: %d)\n",
           (uint)desc[step].length, file_name, file.file, errno);
      res= 0;
      goto err;
    }
    for (byte= 0; byte < desc[step].length; byte++)
    {
      if (buffr[byte] != desc[step].content)
      {
        diag("content of %s mismatch 0x%x in position %lu instead of 0x%x\n",
             file_name, (uint) buffr[byte], (ulong) (pos + byte),
             desc[step].content);
        res= 0;
        goto err;
      }
    }
    pos+= desc[step].length;
    step++;
  }

err:
  my_free(buffr);
  return res;
}
Esempio n. 23
0
MY_DIR	*my_dir(const char *path, myf MyFlags)
{
  DIR		*dirp;
  struct dirent *dp;
  struct fileinfo *fnames;
  char	       *buffer, *obuffer, *tempptr;
  uint		fcnt,i,size,firstfcnt, maxfcnt,length;
  char		tmp_path[FN_REFLEN+1],*tmp_file;
  my_ptrdiff_t	diff;
  bool		eof;
#ifdef THREAD
  char	dirent_tmp[sizeof(struct dirent)+_POSIX_PATH_MAX+1];
#endif
  DBUG_ENTER("my_dir");
  DBUG_PRINT("my",("path: '%s' stat: %d  MyFlags: %d",path,MyFlags));

#if defined(THREAD) && !defined(HAVE_READDIR_R)
  pthread_mutex_lock(&THR_LOCK_open);
#endif

  dirp = opendir(directory_file_name(tmp_path,(my_string) path));
  size = STARTSIZE;
  if (dirp == NULL || ! (buffer = (char *) my_malloc(size, MyFlags)))
    goto error;

  fcnt = 0;
  tmp_file=strend(tmp_path);
  firstfcnt = maxfcnt = (size - sizeof(MY_DIR)) /
    (sizeof(struct fileinfo) + FN_LEN);
  fnames=   (struct fileinfo *) (buffer + sizeof(MY_DIR));
  tempptr = (char *) (fnames + maxfcnt);

#ifdef THREAD
  dp= (struct dirent*) dirent_tmp;
#else
  dp=0;
#endif
  eof=0;
  for (;;)
  {
    while (fcnt < maxfcnt &&
	   !(eof= READDIR(dirp,(struct dirent*) dirent_tmp,dp)))
    {
      bzero((gptr) (fnames+fcnt),sizeof(fnames[0])); /* for purify */
      fnames[fcnt].name = tempptr;
      tempptr = strmov(tempptr,dp->d_name) + 1;
      if (MyFlags & MY_WANT_STAT)
      {
	VOID(strmov(tmp_file,dp->d_name));
	VOID(my_stat(tmp_path, &fnames[fcnt].mystat, MyFlags));
      }
      ++fcnt;
    }
    if (eof)
      break;
    size += STARTSIZE; obuffer = buffer;
    if (!(buffer = (char *) my_realloc((gptr) buffer, size,
				       MyFlags | MY_FREE_ON_ERROR)))
      goto error;			/* No memory */
    length= (uint) (sizeof(struct fileinfo ) * firstfcnt);
    diff=    PTR_BYTE_DIFF(buffer , obuffer) + (int) length;
    fnames=  (struct fileinfo *) (buffer + sizeof(MY_DIR));
    tempptr= ADD_TO_PTR(tempptr,diff,char*);
    for (i = 0; i < maxfcnt; i++)
      fnames[i].name = ADD_TO_PTR(fnames[i].name,diff,char*);

    /* move filenames upp a bit */
    maxfcnt += firstfcnt;
    bmove_upp(tempptr,tempptr-length,
	      (uint) (tempptr- (char*) (fnames+maxfcnt)));
  }

  (void) closedir(dirp);
  {
    MY_DIR * s = (MY_DIR *) buffer;
    s->number_off_files = (uint) fcnt;
    s->dir_entry = fnames;
  }
  if (!(MyFlags & MY_DONT_SORT))
    qsort((void *) fnames, (size_s) fcnt, sizeof(struct fileinfo),
	  (qsort_cmp) comp_names);
#if defined(THREAD) && !defined(HAVE_READDIR_R)
  pthread_mutex_unlock(&THR_LOCK_open);
#endif
  DBUG_RETURN((MY_DIR *) buffer);

 error:
#if defined(THREAD) && !defined(HAVE_READDIR_R)
  pthread_mutex_unlock(&THR_LOCK_open);
#endif
  my_errno=errno;
  if (dirp)
    (void) closedir(dirp);
  if (MyFlags & (MY_FAE+MY_WME))
    my_error(EE_DIR,MYF(ME_BELL+ME_WAITTANG),path,my_errno);
  DBUG_RETURN((MY_DIR *) NULL);
} /* my_dir */
Esempio n. 24
0
static my_bool search_default_file(DYNAMIC_ARRAY *args, MEM_ROOT *alloc,
				   const char *dir, const char *config_file,
				   const char *ext, TYPELIB *group)
{
  char name[FN_REFLEN+10],buff[4096],*ptr,*end,*value,*tmp;
  FILE *fp;
  uint line=0;
  my_bool read_values=0,found_group=0;

  if ((dir ? strlen(dir) : 0 )+strlen(config_file) >= FN_REFLEN-3)
    return 0;					/* Ignore wrong paths */
  if (dir)
  {
    strmov(name,dir);
    convert_dirname(name);
    if (dir[0] == FN_HOMELIB)		/* Add . to filenames in home */
      strcat(name,".");
    strxmov(strend(name),config_file,ext,NullS);
  }
  else
  {
    strmov(name,config_file);
  }
  fn_format(name,name,"","",4);
#if !defined(_WIN32) && !defined(OS2)
  {
    MY_STAT stat_info;
    if (!my_stat(name,&stat_info,MYF(0)))
      return 0;
    if (stat_info.st_mode & S_IWOTH) /* ignore world-writeable files */
    {
      fprintf(stderr, "warning: World-writeable config file %s is ignored\n",
              name);
      return 0;
    }
  }
#endif
  if (!(fp = my_fopen(fn_format(name,name,"","",4),O_RDONLY,MYF(0))))
    return 0;					/* Ignore wrong files */

  while (fgets(buff,sizeof(buff)-1,fp))
  {
    line++;
    /* Ignore comment and empty lines */
    for (ptr=buff ; isspace(*ptr) ; ptr++ ) ;
    if (*ptr == '#' || *ptr == ';' || !*ptr)
      continue;
    if (*ptr == '[')				/* Group name */
    {
      found_group=1;
      if (!(end=(char *) strchr(++ptr,']')))
      {
	fprintf(stderr,
		"error: Wrong group definition in config file: %s at line %d\n",
		name,line);
	goto err;
      }
      for ( ; isspace(end[-1]) ; end--) ;	/* Remove end space */
      end[0]=0;
      read_values=find_type(ptr,group,3) > 0;
      continue;
    }
    if (!found_group)
    {
      fprintf(stderr,
	      "error: Found option without preceding group in config file: %s at line: %d\n",
	      name,line);
      goto err;
    }
    if (!read_values)
      continue;
    if (!(end=value=strchr(ptr,'=')))
      end=strend(ptr);				/* Option without argument */
    for ( ; isspace(end[-1]) ; end--) ;
    if (!value)
    {
      if (!(tmp=alloc_root(alloc,(uint) (end-ptr)+3)))
	goto err;
      strmake(strmov(tmp,"--"),ptr,(uint) (end-ptr));
      if (insert_dynamic(args,(gptr) &tmp))
	goto err;
    }
    else
    {
      /* Remove pre- and end space */
      char *value_end;
      for (value++ ; isspace(*value); value++) ;
      value_end=strend(value);
      for ( ; isspace(value_end[-1]) ; value_end--) ;
      if (value_end < value)			/* Empty string */
	value_end=value;
      if (!(tmp=alloc_root(alloc,(uint) (end-ptr)+3 +
			   (uint) (value_end-value)+1)))
	goto err;
      if (insert_dynamic(args,(gptr) &tmp))
	goto err;
      ptr=strnmov(strmov(tmp,"--"),ptr,(uint) (end-ptr));
      *ptr++= '=';
      for ( ; value != value_end; value++)
      {
	if (*value == '\\' && value != value_end-1)
	{
	  switch(*++value) {
	  case 'n':
	    *ptr++='\n';
	    break;
	  case 't':
	    *ptr++= '\t';
	    break;
	  case 'r':
	    *ptr++ = '\r';
	    break;
	  case 'b':
	    *ptr++ = '\b';
	    break;
	  case 's':
	    *ptr++= ' ';			/* space */
	    break;
	  case '\\':
	    *ptr++= '\\';
	    break;
	  default:				/* Unknown; Keep '\' */
	    *ptr++= '\\';
	    *ptr++= *value;
	    break;
	  }
	}
	else
	  *ptr++= *value;
      }
      *ptr=0;
    }
  }
  my_fclose(fp,MYF(0));
  return(0);

 err:
  my_fclose(fp,MYF(0));
  return 1;
}
Esempio n. 25
0
static int create_sys_files(struct languages *lang_head,
                            struct errors *error_head, uint row_count)
{
    FILE *to;
    uint csnum= 0, length, i, row_nr;
    uchar head[32];
    char outfile[FN_REFLEN], *outfile_end;
    long start_pos;
    struct message *tmp;
    struct languages *tmp_lang;
    struct errors *tmp_error;

    MY_STAT stat_info;
    DBUG_ENTER("create_sys_files");

    /*
       going over all languages and assembling corresponding error messages
    */
    for (tmp_lang= lang_head; tmp_lang; tmp_lang= tmp_lang->next_lang)
    {

        /* setting charset name */
        if (!(csnum= get_charset_number(tmp_lang->charset, MY_CS_PRIMARY)))
        {
            fprintf(stderr, "Unknown charset '%s' in '%s'\n", tmp_lang->charset,
                    TXTFILE);
            DBUG_RETURN(1);
        }

        outfile_end= strxmov(outfile, DATADIRECTORY,
                             tmp_lang->lang_long_name, NullS);
        if (!my_stat(outfile, &stat_info,MYF(0)))
        {
            if (my_mkdir(outfile, 0777,MYF(0)) < 0)
            {
                fprintf(stderr, "Can't create output directory for %s\n",
                        outfile);
                DBUG_RETURN(1);
            }
        }

        strxmov(outfile_end, FN_ROOTDIR, OUTFILE, NullS);

        if (!(to= my_fopen(outfile, O_WRONLY | FILE_BINARY, MYF(MY_WME))))
            DBUG_RETURN(1);

        /* 4 is for 4 bytes to store row position / error message */
        start_pos= (long) (HEADER_LENGTH + row_count * 4);
        fseek(to, start_pos, 0);
        row_nr= 0;
        for (tmp_error= error_head; tmp_error; tmp_error= tmp_error->next_error)
        {
            /* dealing with messages */
            tmp= find_message(tmp_error, tmp_lang->lang_short_name, FALSE);

            if (!tmp)
            {
                fprintf(stderr,
                        "Did not find message for %s neither in %s nor in default "
                        "language\n", tmp_error->er_name, tmp_lang->lang_short_name);
                goto err;
            }
            if (copy_rows(to, tmp->text, row_nr, start_pos))
            {
                fprintf(stderr, "Failed to copy rows to %s\n", outfile);
                goto err;
            }
            row_nr++;
        }

        /* continue with header of the errmsg.sys file */
        length= ftell(to) - HEADER_LENGTH - row_count * 4;
        memset(head, 0, HEADER_LENGTH);
        memmove(head, file_head, 4);
        head[4]= 1;
        int4store(head + 6, length);
        int4store(head + 10, row_count);
        head[30]= csnum;

        my_fseek(to, 0l, MY_SEEK_SET, MYF(0));
        if (my_fwrite(to, (uchar*) head, HEADER_LENGTH, MYF(MY_WME | MY_FNABP)))
            goto err;

        for (i= 0; i < row_count; i++)
        {
            int4store(head, file_pos[i]);
            if (my_fwrite(to, (uchar*) head, 4, MYF(MY_WME | MY_FNABP)))
                goto err;
        }
        my_fclose(to, MYF(0));
    }
    DBUG_RETURN(0);

err:
    my_fclose(to, MYF(0));
    DBUG_RETURN(1);
}
Esempio n. 26
0
MY_DIR	*my_dir(const char *path, myf MyFlags)
{
  char          *buffer;
  MY_DIR        *result= 0;
  FILEINFO      finfo;
  DYNAMIC_ARRAY *dir_entries_storage;
  MEM_ROOT      *names_storage;
  DIR		*dirp;
  struct dirent *dp;
  char		tmp_path[FN_REFLEN + 2], *tmp_file;
  char	dirent_tmp[sizeof(struct dirent)+_POSIX_PATH_MAX+1];

  DBUG_ENTER("my_dir");
  DBUG_PRINT("my",("path: '%s' MyFlags: %d",path,MyFlags));

#if !defined(HAVE_READDIR_R)
  mysql_mutex_lock(&THR_LOCK_open);
#endif

  dirp = opendir(directory_file_name(tmp_path,(char *) path));
  if (dirp == NULL || 
      ! (buffer= my_malloc(key_memory_MY_DIR,
                           ALIGN_SIZE(sizeof(MY_DIR)) + 
                           ALIGN_SIZE(sizeof(DYNAMIC_ARRAY)) +
                           sizeof(MEM_ROOT), MyFlags)))
    goto error;

  dir_entries_storage= (DYNAMIC_ARRAY*)(buffer + ALIGN_SIZE(sizeof(MY_DIR))); 
  names_storage= (MEM_ROOT*)(buffer + ALIGN_SIZE(sizeof(MY_DIR)) +
                             ALIGN_SIZE(sizeof(DYNAMIC_ARRAY)));
  
  if (my_init_dynamic_array(dir_entries_storage, sizeof(FILEINFO),
                            NULL,               /* init_buffer */
                            ENTRIES_START_SIZE, ENTRIES_INCREMENT))
  {
    my_free(buffer);
    goto error;
  }
  init_alloc_root(key_memory_MY_DIR, names_storage, NAMES_START_SIZE, NAMES_START_SIZE);
  
  /* MY_DIR structure is allocated and completly initialized at this point */
  result= (MY_DIR*)buffer;

  tmp_file=strend(tmp_path);

  dp= (struct dirent*) dirent_tmp;
  
  while (!(READDIR(dirp,(struct dirent*) dirent_tmp,dp)))
  {
    if (!(finfo.name= strdup_root(names_storage, dp->d_name)))
      goto error;
    
    if (MyFlags & MY_WANT_STAT)
    {
      if (!(finfo.mystat= (MY_STAT*)alloc_root(names_storage, 
                                               sizeof(MY_STAT))))
        goto error;
      
      memset(finfo.mystat, 0, sizeof(MY_STAT));
      (void) my_stpcpy(tmp_file,dp->d_name);
      (void) my_stat(tmp_path, finfo.mystat, MyFlags);
      if (!(finfo.mystat->st_mode & MY_S_IREAD))
        continue;
    }
    else
      finfo.mystat= NULL;

    if (insert_dynamic(dir_entries_storage, (uchar*)&finfo))
      goto error;
  }

  (void) closedir(dirp);
#if !defined(HAVE_READDIR_R)
  mysql_mutex_unlock(&THR_LOCK_open);
#endif
  result->dir_entry= (FILEINFO *)dir_entries_storage->buffer;
  result->number_off_files= dir_entries_storage->elements;
  
  if (!(MyFlags & MY_DONT_SORT))
    my_qsort((void *) result->dir_entry, result->number_off_files,
          sizeof(FILEINFO), (qsort_cmp) comp_names);
  DBUG_RETURN(result);

 error:
#if !defined(HAVE_READDIR_R)
  mysql_mutex_unlock(&THR_LOCK_open);
#endif
  my_errno=errno;
  if (dirp)
    (void) closedir(dirp);
  my_dirend(result);
  if (MyFlags & (MY_FAE | MY_WME))
  {
    char errbuf[MYSYS_STRERROR_SIZE];
    my_error(EE_DIR, MYF(0), path,
             my_errno, my_strerror(errbuf, sizeof(errbuf), my_errno));
  }
  DBUG_RETURN((MY_DIR *) NULL);
} /* my_dir */
Esempio n. 27
0
bool my_chmod (const TCHAR *name, uae_u32 mode)
{
  // return result of mystat so invalid file will return false
  struct mystat ms;
  return my_stat(name, &ms);
}
Esempio n. 28
0
extern int ls_main(int argc, char **argv)
{
	struct dnode **dnd;
	struct dnode **dnf;
	struct dnode **dnp;
	struct dnode *dn;
	struct dnode *cur;
	long opt;
	int nfiles = 0;
	int dnfiles;
	int dndirs;
	int oi;
	int ac;
	int i;
	char **av;
#ifdef CONFIG_FEATURE_AUTOWIDTH
	char *tabstops_str = NULL;
	char *terminal_width_str = NULL;
#endif

#ifdef CONFIG_SELINUX
	is_flask_enabled_flag = is_flask_enabled();
#endif

	all_fmt = LIST_SHORT | DISP_NORMAL | STYLE_AUTO
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
		| TIME_MOD
#endif
#ifdef CONFIG_FEATURE_LS_SORTFILES
		| SORT_NAME | SORT_ORDER_FORWARD
#endif
		;

#ifdef CONFIG_FEATURE_AUTOWIDTH
	/* Obtain the terminal width.  */
	get_terminal_width_height(0, &terminal_width, NULL);
	/* Go one less... */
	terminal_width--;
#endif

#ifdef CONFIG_FEATURE_LS_COLOR
	if (isatty(fileno(stdout)))
		show_color = 1;
#endif

	/* process options */
#ifdef CONFIG_FEATURE_AUTOWIDTH
	opt = bb_getopt_ulflags(argc, argv, ls_options, &tabstops_str, &terminal_width_str);
	if (tabstops_str) {
		tabstops = atoi(tabstops_str);
	}
	if (terminal_width_str) {
		terminal_width = atoi(terminal_width_str);
	}
#else
	opt = bb_getopt_ulflags(argc, argv, ls_options);
#endif
	/* 16 = maximum options minus tabsize and screewn width */
	for (i = 0; i < 16; i++) {
		if (opt & (1 << i)) {
			unsigned int flags = opt_flags[i];
			if (flags & LIST_MASK_TRIGGER) {
				all_fmt &= ~LIST_MASK;
			}
			if (flags & STYLE_MASK_TRIGGER) {
				all_fmt &= ~STYLE_MASK;
			}
#ifdef CONFIG_FEATURE_LS_SORTFILES
			if (flags & SORT_MASK_TRIGGER) {
				all_fmt &= ~SORT_MASK;
			}
#endif
			if (flags & DISP_MASK_TRIGGER) {
				all_fmt &= ~DISP_MASK;
			}
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
			if (flags & TIME_MASK_TRIGGER) {
				all_fmt &= ~TIME_MASK;
			}
#endif
			if (flags & LIST_CONTEXT) {
				all_fmt |= STYLE_SINGLE;
			}
#ifdef CONFIG_FEATURE_HUMAN_READABLE
			if (opt == 'l') {
				all_fmt &= ~LS_DISP_HR;
			}
#endif
			all_fmt |= flags;
		}
	}

	/* sort out which command line options take precedence */
#ifdef CONFIG_FEATURE_LS_RECURSIVE
	if (all_fmt & DISP_NOLIST)
		all_fmt &= ~DISP_RECURSIVE;	/* no recurse if listing only dir */
#endif
#if defined (CONFIG_FEATURE_LS_TIMESTAMPS) && defined (CONFIG_FEATURE_LS_SORTFILES)
	if (all_fmt & TIME_CHANGE)
		all_fmt = (all_fmt & ~SORT_MASK) | SORT_CTIME;
	if (all_fmt & TIME_ACCESS)
		all_fmt = (all_fmt & ~SORT_MASK) | SORT_ATIME;
#endif
	if ((all_fmt & STYLE_MASK) != STYLE_LONG) /* only for long list */
		all_fmt &= ~(LIST_ID_NUMERIC|LIST_FULLTIME|LIST_ID_NAME|LIST_ID_NUMERIC);
#ifdef CONFIG_FEATURE_LS_USERNAME
	if ((all_fmt & STYLE_MASK) == STYLE_LONG && (all_fmt & LIST_ID_NUMERIC))
		all_fmt &= ~LIST_ID_NAME;	/* don't list names if numeric uid */
#endif
			
	/* choose a display format */
	if ((all_fmt & STYLE_MASK) == STYLE_AUTO)
#if STYLE_AUTO != 0
		all_fmt = (all_fmt & ~STYLE_MASK)
				| (isatty(fileno(stdout)) ? STYLE_COLUMNS : STYLE_SINGLE);
#else
		all_fmt |= (isatty(fileno(stdout)) ? STYLE_COLUMNS : STYLE_SINGLE);
#endif

	/*
	 * when there are no cmd line args we have to supply a default "." arg.
	 * we will create a second argv array, "av" that will hold either
	 * our created "." arg, or the real cmd line args.  The av array
	 * just holds the pointers- we don't move the date the pointers
	 * point to.
	 */
	ac = argc - optind;	/* how many cmd line args are left */
	if (ac < 1) {
		av = (char **) xcalloc((size_t) 1, (size_t) (sizeof(char *)));
		av[0] = bb_xstrdup(".");
		ac = 1;
	} else {
		av = (char **) xcalloc((size_t) ac, (size_t) (sizeof(char *)));
		for (oi = 0; oi < ac; oi++) {
			av[oi] = argv[optind++];	/* copy pointer to real cmd line arg */
		}
	}

	/* now, everything is in the av array */
	if (ac > 1)
		all_fmt |= DISP_DIRNAME;	/* 2 or more items? label directories */

	/* stuff the command line file names into an dnode array */
	dn = NULL;
	for (oi = 0; oi < ac; oi++) {
		char *fullname = bb_xstrdup(av[oi]);

		cur = my_stat(fullname, fullname);
		if (!cur)
			continue;
		cur->next = dn;
		dn = cur;
		nfiles++;
	}

	/* now that we know how many files there are
	   ** allocate memory for an array to hold dnode pointers
	 */
	dnp = dnalloc(nfiles);
	for (i = 0, cur = dn; i < nfiles; i++) {
		dnp[i] = cur;	/* save pointer to node in array */
		cur = cur->next;
	}


	if (all_fmt & DISP_NOLIST) {
#ifdef CONFIG_FEATURE_LS_SORTFILES
		shellsort(dnp, nfiles);
#endif
		if (nfiles > 0)
			showfiles(dnp, nfiles);
	} else {
		dnd = splitdnarray(dnp, nfiles, SPLIT_DIR);
		dnf = splitdnarray(dnp, nfiles, SPLIT_FILE);
		dndirs = countdirs(dnp, nfiles);
		dnfiles = nfiles - dndirs;
		if (dnfiles > 0) {
#ifdef CONFIG_FEATURE_LS_SORTFILES
			shellsort(dnf, dnfiles);
#endif
			showfiles(dnf, dnfiles);
		}
		if (dndirs > 0) {
#ifdef CONFIG_FEATURE_LS_SORTFILES
			shellsort(dnd, dndirs);
#endif
			showdirs(dnd, dndirs);
		}
	}
	return (status);
}