Пример #1
0
Файл: ls.c Проект: akat1/impala
void
long_entry(const char *file, const struct stat *st)
{
    printf("%s%s %2u %7s %7s %10u %s\n",
        print_serial(st),
        mode2str(st->st_mode),
        st->st_nlink,
        print_uid(st),
        print_gid(st),
        st->st_size,
        print_name(file, st)
     );
}
Пример #2
0
static void conf_rfc(void *ptr, int len, int in, uint16_t cid)
{
	uint8_t mode;

	mode = *((uint8_t *) ptr);
	set_mode(in, cid, mode);

	printf("RFC 0x%02x (%s", mode, mode2str(mode));
	if (mode == 0x01 || mode == 0x02) {
		uint8_t txwin, maxtrans;
		uint16_t rto, mto, mps;
		txwin = *((uint8_t *) (ptr + 1));
		maxtrans = *((uint8_t *) (ptr + 2));
		rto = btohs(bt_get_unaligned((uint16_t *) (ptr + 3)));
		mto = btohs(bt_get_unaligned((uint16_t *) (ptr + 5)));
		mps = btohs(bt_get_unaligned((uint16_t *) (ptr + 7)));
		printf(", TxWin %d, MaxTx %d, RTo %d, MTo %d, MPS %d",
					txwin, maxtrans, rto, mto, mps);
	}
	printf(")");
}
Пример #3
0
static void
lsfile_l (Npcfid *dir, char *name)
{
    Npcfid *fid = NULL;
    struct stat sb;
    struct passwd *pw;
    struct group *gr;
    char uid[16], gid[16];
    char *mtime;

    if (!(fid = npc_walk (dir, name))) {
        errn (np_rerror (), "npc_walk %s\n", name);
        goto error;
    }
    if (npc_fstat (fid, &sb) < 0) {
        errn (np_rerror (), "npc_fstat %s\n", name);
        goto error;
    }
    if (npc_clunk (fid) < 0) {
        errn (np_rerror (), "npc_clunk %s\n", name);
        goto error;
    }
    if (!(pw = getpwuid (sb.st_uid)))
        snprintf (uid, sizeof (uid), "%d", sb.st_uid);
    if (!(gr = getgrgid (sb.st_gid)))
        snprintf (gid, sizeof (gid), "%d", sb.st_gid);
    mtime = ctime( &sb.st_mtime);
    printf ("%10s %4lu %s %s %12lu %.*s %s\n",
            mode2str (sb.st_mode),
            sb.st_nlink,
            pw ? pw->pw_name : uid,
            gr ? gr->gr_name : gid,
            sb.st_size,
            (int)strlen (mtime) - 13, mtime + 4,
            name);
    return;
error:
    if (fid)
        (void)npc_clunk (fid);
}
Пример #4
0
int main(int argc, char* argv[])// dir
{
	DIR* pdir;
	char* ptm ;
	char perm[11] ;
	char path[256];
	struct stat my_stat ;
	struct dirent* pent;
	pdir = opendir(argv[1]);
	if(pdir == NULL)
	{
		perror("opendir");
		exit(1);
	}
	while( (pent = readdir(pdir) ) != NULL )
	{
		//	printf("inode: %d\n", pent ->d_ino);
		//	printf("offset: %u\n", pent ->d_off);
		//	printf("reclen: %d\n", pent ->d_reclen);
		//	printf("type: %d\n", pent ->d_type);
		memset(path, 0, 256);
		sprintf(path, "%s/%s", argv[1], pent -> d_name);

		memset(&my_stat, 0, sizeof(my_stat));

		if(stat(path, &my_stat) == -1 )
		{
			perror("stat");
			exit(1);
		}
		ptm = ctime(&my_stat.st_mtime);
		time_handle(ptm);
		
		mode2str(my_stat.st_mode, perm);
		printf("%10s %d %5s %5s %5d %15s %10s\n", perm, my_stat.st_nlink, getpwuid(my_stat.st_uid) ->pw_name, getgrgid(my_stat.st_gid) -> gr_name, my_stat.st_size, ptm + 4 , pent ->d_name );

	}
	closedir(pdir);
	return 0 ;
}
Пример #5
0
static void conf_rfc(void *ptr, int len, int in, uint16_t handle,
								uint16_t cid)
{
	uint8_t mode;

	mode = *((uint8_t *) ptr);
	set_mode(!in, handle, cid, mode);

	printf("RFC 0x%02x (%s", mode, mode2str(mode));
	if (mode >= 0x01 && mode <= 0x04) {
		uint8_t txwin, maxtrans;
		uint16_t rto, mto, mps;
		txwin = *((uint8_t *) (ptr + 1));
		maxtrans = *((uint8_t *) (ptr + 2));
		rto = bt_get_le16(ptr + 3);
		mto = bt_get_le16(ptr + 5);
		mps = bt_get_le16(ptr + 7);
		printf(", TxWin %d, MaxTx %d, RTo %d, MTo %d, MPS %d",
					txwin, maxtrans, rto, mto, mps);
	}
	printf(")");
}
Пример #6
0
/*
 * Convert a vdpnl_vsi to string.
 */
int vdp_vdpnl2str(struct vdpnl_vsi *p, char *s, size_t length)
{
	int c, i;
	size_t total = 0;
	char instance[VDP_UUID_STRLEN + 2];

	mgrid2str(instance, p, sizeof(instance));
	c = snprintf(s, length, "%s,%s,%ld,%d,",
		     mode2str(p->request), instance, p->vsi_typeid,
		     p->vsi_typeversion);
	s = check_and_update(&total, &length, s, c);
	if (!s)
		goto out;

	vdp_uuid2str(p->vsi_uuid, instance, sizeof(instance));
	c = snprintf(s, length, "%s,%d,", instance, p->response);
	s = check_and_update(&total, &length, s, c);
	if (!s)
		goto out;

	/* Add Filter information data */
	for (i = 0; i < p->macsz; ++i) {
		c = fid2str(s, length, p->filter_fmt, &p->maclist[i]);
		s = check_and_update(&total, &length, s, c);
		if (!c)
			goto out;
		if (p->macsz > 1 && i < p->macsz - 1) {
			c = snprintf(s, length, ",");
			s = check_and_update(&total, &length, s, c);
			if (!s)
				goto out;
		}
	}
out:
	return s ? total : 0;
}
Пример #7
0
static int listfile_long(const char *path, int flags)
{
    struct stat s;
    char date[32];
    char mode[16];
    char user[16];
    char group[16];
    const char *name;

    /* name is anything after the final '/', or the whole path if none*/
    name = strrchr(path, '/');
    if(name == 0) {
        name = path;
    } else {
        name++;
    }

    if(lstat(path, &s) < 0) {
        return -1;
    }

    mode2str(s.st_mode, mode);
    user2str(s.st_uid, user);
    group2str(s.st_gid, group);

    strftime(date, 32, "%Y-%m-%d %H:%M", localtime((const time_t*)&s.st_mtime));
    date[31] = 0;
    
// 12345678901234567890123456789012345678901234567890123456789012345678901234567890
// MMMMMMMM UUUUUUUU GGGGGGGGG XXXXXXXX YYYY-MM-DD HH:MM NAME (->LINK)

    switch(s.st_mode & S_IFMT) {
    case S_IFBLK:
    case S_IFCHR:
        printf("%s %-8s %-8s %3d, %3d %s %s\n",
               mode, user, group, 
               (int) MAJOR(s.st_rdev), (int) MINOR(s.st_rdev),
               date, name);
        break;
    case S_IFREG:
        printf("%s %-8s %-8s %8d %s %s\n",
               mode, user, group, (int) s.st_size, date, name);
        break;
    case S_IFLNK: {
        char linkto[256];
        int len;

        len = readlink(path, linkto, 256);
        if(len < 0) return -1;
        
        if(len > 255) {
            linkto[252] = '.';
            linkto[253] = '.';
            linkto[254] = '.';
            linkto[255] = 0;
        } else {
            linkto[len] = 0;
        }
        
        printf("%s %-8s %-8s          %s %s -> %s\n",
               mode, user, group, date, name, linkto);
        break;
    }
    default:
        printf("%s %-8s %-8s          %s %s\n",
               mode, user, group, date, name);

    }
    return 0;
}
Пример #8
0
/*
*****************************************************************************
*                             MAIN PROGRAM 
*****************************************************************************
*/
int main (int argc, char *argv[])
{
  char *progname = argv[0];
  char *modeStr = NULL;
  char *usedModeStr = NULL;
  char *fileName = NULL;
  char *modefileName = NULL;
  char *serialFileName = NULL;
  
  FILE *file_speech = NULL;           /* File of speech data               */
  FILE *file_serial = NULL;           /* File of coded bits                */
  FILE *file_modes = NULL;            /* File with mode information        */
  
  Word16 new_speech[L_FRAME];         /* Pointer to new speech data        */
  Word16 serial[SERIAL_FRAMESIZE];    /* Output bitstream buffer           */

#ifdef MMS_IO
  UWord8 packed_bits[MAX_PACKED_SIZE];
  Word16 packed_size;
#endif

  Word32 frame;
  Word16 dtx = 0;                     /* enable encoder DTX                */
  
  /* changed eedodr */
  Word16 reset_flag;

  int i;
  enum Mode mode;
  enum Mode used_mode;
  enum TXFrameType tx_type;

  int useModeFile = 0;
  
  Speech_Encode_FrameState *speech_encoder_state = NULL;
  sid_syncState *sid_state = NULL;

  proc_head ("Encoder");
  fprintf(stderr, "Code compiled with VAD option: %s\n\n", get_vadname());

  /*----------------------------------------------------------------------*
   * Process command line options                                         *
   *----------------------------------------------------------------------*/
  while (argc > 1) {
      if (strcmp(argv[1], "-dtx") == 0) {
          dtx = 1;
      } else if (strncmp(argv[1], "-modefile=", 10) == 0) {
          useModeFile = 1;
          modefileName = argv[1]+10;
      } else
          break;
      argc--;
      argv++;
  }
  
  /*----------------------------------------------------------------------*
   * Check number of arguments                                            *
   *----------------------------------------------------------------------*/
  if (   (argc != 4 && !useModeFile)
      || (argc != 3 &&  useModeFile))
  {
    fprintf (stderr,
      " Usage:\n\n"
      "   %s [-dtx] amr_mode            speech_file  bitstream_file\n\n"
      " or \n\n"
      "   %s [-dtx] -modefile=mode_file speech_file  bitstream_file\n\n"
      " -dtx                enables DTX mode\n"
      " -modefile=mode_file reads AMR modes from text file (one line per frame)\n\n",
             progname, progname);
      exit (1);
  }

  /*----------------------------------------------------------------------*
   * Open mode file or convert mode string                                *
   *----------------------------------------------------------------------*/
  if (useModeFile) {
      fileName = argv[1];
      serialFileName = argv[2];
      
      /* Open mode control file */
      if (strcmp(modefileName, "-") == 0) {
          file_modes = stdin;
      }
      else if ((file_modes = fopen (modefileName, "rt")) == NULL)
      {
          fprintf (stderr, "Error opening mode control file  %s !!\n",
                   modefileName);
          exit (1);
      }
      fprintf (stderr, " Mode control file:      %s\n", modefileName);

  } else {
      
      modeStr = argv[1];
      fileName = argv[2];
      serialFileName = argv[3];
      
      /* check and convert mode string */
      if (str2mode(modeStr, &mode) != 0 && mode != MRDTX) {
          fprintf(stderr, "Invalid amr_mode specified: '%s'\n",
                  modeStr);
          exit(1);
      }
  }
  

  /*----------------------------------------------------------------------*
   * Open speech file and result file (output serial bit stream)          *
   *----------------------------------------------------------------------*/
  if (strcmp(fileName, "-") == 0) {
     file_speech = stdin;
  }
  else if ((file_speech = fopen (fileName, "rb")) == NULL)
  {
      fprintf (stderr, "Error opening input file  %s !!\n", fileName);
      exit (1);
  }
  fprintf (stderr, " Input speech file:      %s\n", fileName);

  if (strcmp(serialFileName, "-") == 0) {
     file_serial = stdout;
  }
  else if ((file_serial = fopen (serialFileName, "wb")) == NULL)
  {
      fprintf (stderr,"Error opening output bitstream file %s !!\n",serialFileName);
      exit (1);
  }
  fprintf (stderr, " Output bitstream file:  %s\n", serialFileName);


  /*-----------------------------------------------------------------------*
   * Initialisation of the coder.                                          *
   *-----------------------------------------------------------------------*/
  if (   Speech_Encode_Frame_init(&speech_encoder_state, dtx, "encoder")
      || sid_sync_init (&sid_state))
      exit(-1);

#ifdef MMS_IO
  /* write magic number to indicate single channel AMR file storage format */
  fwrite(AMR_MAGIC_NUMBER, sizeof(UWord8), strlen(AMR_MAGIC_NUMBER), file_serial);
#endif

  /*-----------------------------------------------------------------------*
   * Process speech frame by frame                                         *
   *-----------------------------------------------------------------------*/
  frame = 0;
  while (fread (new_speech, sizeof (Word16), L_FRAME, file_speech) == L_FRAME)
  {
     /* read new mode string from file if required */
     if (useModeFile) {
         int res;
         if ((res = read_mode(file_modes, &mode)) == EOF) {
             fprintf(stderr, "\nend of mode control file reached");
             break;
         } else if (res == 1)
             exit(-1);
     }
      
     frame++;
     
     /* zero flags and parameter bits */
     for (i = 0; i < SERIAL_FRAMESIZE; i++)
         serial[i] = 0;

     /* check for homing frame */
     reset_flag = encoder_homing_frame_test(new_speech);
     
     /* encode speech */
     Speech_Encode_Frame(speech_encoder_state, mode,
                         new_speech, &serial[1], &used_mode); 

     /* print frame number and mode information */
     mode2str(mode, &modeStr);
     mode2str(used_mode, &usedModeStr);
     if ( (frame%50) == 0) {
        fprintf (stderr, "\rframe=%-8d mode=%-5s used_mode=%-5s",
                 frame, modeStr, usedModeStr);
     }

     /* include frame type and mode information in serial bitstream */
     sid_sync (sid_state, used_mode, &tx_type);

#ifndef MMS_IO
     serial[0] = tx_type;
     if (tx_type != TX_NO_DATA) {
       serial[1+MAX_SERIAL_SIZE] = mode;
     }
     else {
       serial[1+MAX_SERIAL_SIZE] = -1;
     }

     /* write bitstream to output file */
     if (fwrite (serial, sizeof (Word16), SERIAL_FRAMESIZE, file_serial)
         != SERIAL_FRAMESIZE) {
         fprintf(stderr, "\nerror writing output file: %s\n",
                 strerror(errno));
         exit(-1);
     }
#else

     packed_size = PackBits(used_mode, mode, tx_type, &serial[1], packed_bits);

     /* write file storage format bitstream to output file */
     if (fwrite (packed_bits, sizeof (UWord8), packed_size, file_serial)
         != packed_size) {
         fprintf(stderr, "\nerror writing output file: %s\n",
                 strerror(errno));
         exit(-1);
     }
#endif

     fflush(file_serial);

     /* perform homing if homing frame was detected at encoder input */
     if (reset_flag != 0)
     {
         Speech_Encode_Frame_reset(speech_encoder_state);
         sid_sync_reset(sid_state);
     }
  }
  fprintf (stderr, "\n%d frame(s) processed\n", frame);
  
  /*-----------------------------------------------------------------------*
   * Close down speech coder                                               *
   *-----------------------------------------------------------------------*/
  Speech_Encode_Frame_exit(&speech_encoder_state);
  sid_sync_exit (&sid_state);
  
  return (0);
}
Пример #9
0
int amrcoder(char *src,ssize_t src_size,char *dst,ssize_t *dst_size,int armmode,int channels){
	char *modeStr = NULL;
  	char *usedModeStr = NULL;
  
  	Word16 new_speech[L_FRAME];         /* Pointer to new speech data        */
  	Word16 serial[SERIAL_FRAMESIZE];    /* Output bitstream buffer           */
	Word16 *psrc;

  	UWord8 packed_bits[MAX_PACKED_SIZE];
 	 Word16 packed_size;

  	Word32 frame;                  
  
  /* changed eedodr */
  	Word16 reset_flag;

  	int i;
	int y;
  	enum Mode mode;
  	enum Mode used_mode;
  	enum TXFrameType tx_type;
	
	*dst_size=0;
	if(armmode<0||armmode>7)
		mode=DEFAULT_MODE;
	else
		mode=(enum Mode)armmode;
   /*-----------------------------------------------------------------------*
   * Initialisation of the coder.                                          *
   *-----------------------------------------------------------------------*/
   
  /*
  	if (   Speech_Encode_Frame_init(&speech_encoder_state, dtx, "encoder")
     		 || sid_sync_init (&sid_state))
      		return -1;
 */
  frame = 0;
  psrc=(Word16 *)src;
  /*16 bits 2channels each pcm frame occupy 4bytes*/
  pthread_mutex_lock(&amr_encode_lock);
  while (src_size>=2*channels*L_FRAME)
  {
     /*use left channel  */
      for(y=0;y<L_FRAME;y++){
	  	new_speech[y]=psrc[0];
		psrc+=channels;
      }
      src_size-=L_FRAME*2*channels;
      frame++;
     
     /* zero flags and parameter bits */
     for (i = 0; i < SERIAL_FRAMESIZE; i++)
         serial[i] = 0;

     /* check for homing frame */
     reset_flag = encoder_homing_frame_test(new_speech);
     
     /* encode speech */
     Speech_Encode_Frame(speech_encoder_state, mode,
                         new_speech, &serial[1], &used_mode); 

     /* print frame number and mode information */
     mode2str(mode, &modeStr);
     mode2str(used_mode, &usedModeStr);
     if ( (frame%50) == 0) {
        fprintf (stderr, "\rframe=%-8d mode=%-5s used_mode=%-5s",
                 frame, modeStr, usedModeStr);
     }

     /* include frame type and mode information in serial bitstream */
     sid_sync (sid_state, used_mode, &tx_type);

     packed_size = PackBits(used_mode, mode, tx_type, &serial[1], packed_bits);

     /* write file storage format bitstream to output file */
	 memcpy(dst,packed_bits,sizeof(UWord8)*packed_size);
	 dst+=sizeof(UWord8)*packed_size;
	 *dst_size+=sizeof(UWord8)*packed_size;
	 /*
     if (fwrite (packed_bits, sizeof (UWord8), packed_size, file_serial)
         != packed_size) {
         fprintf(stderr, "\nerror writing output file: %s\n",
                 strerror(errno));
         exit(-1);
     }
     fflush(file_serial);
	*/
     /* perform homing if homing frame was detected at encoder input */
     if (reset_flag != 0)
     {
         Speech_Encode_Frame_reset(speech_encoder_state);
         sid_sync_reset(sid_state);
     }
  }
  pthread_mutex_unlock(&amr_encode_lock);
  
  /*-----------------------------------------------------------------------*
   * Close down speech coder                                               *
   *-----------------------------------------------------------------------*/
/*
  	Speech_Encode_Frame_exit(&speech_encoder_state);
 	 sid_sync_exit (&sid_state);
 
  */
  return (0);
}
Пример #10
0
static int analyze_file(char *filename)
{
	struct sbc_frame_hdr hdr;
	unsigned char buf[64];
	double rate;
	int bitpool[SIZE], frame_len[SIZE];
	int subbands, blocks, freq, mode, method;
	int n, p1, p2, fd, len, size, num;
	unsigned int count;

	if (strcmp(filename, "-")) {
		printf("Filename\t\t%s\n", basename(filename));

		fd = open(filename, O_RDONLY);
		if (fd < 0) {
			perror("Can't open file");
			return -1;
		}
	} else
		fd = fileno(stdin);

	len = __read(fd, &hdr, sizeof(hdr));
	if (len != sizeof(hdr) || hdr.syncword != 0x9c) {
		fprintf(stderr, "Not a SBC audio file\n");
		return -1;
	}

	subbands = (hdr.subbands + 1) * 4;
	blocks = (hdr.blocks + 1) * 4;
	freq = hdr.sampling_frequency;
	mode = hdr.channel_mode;
	method = hdr.allocation_method;

	count = calc_frame_len(&hdr);

	bitpool[0] = hdr.bitpool;
	frame_len[0] = count + 4;

	for (n = 1; n < SIZE; n++) {
		bitpool[n] = 0;
		frame_len[n] = 0;
	}

	if (lseek(fd, 0, SEEK_SET) < 0) {
		num = 1;
		rate = calc_bit_rate(&hdr);
		while (count) {
			size = count > sizeof(buf) ? sizeof(buf) : count;
			len = __read(fd, buf, size);
			if (len < 0)
				break;
			count -= len;
		}
	} else {
		num = 0;
		rate = 0;
	}

	while (1) {
		len = __read(fd, &hdr, sizeof(hdr));
		if (len < 0) {
			fprintf(stderr, "Unable to read frame header"
					" (error %d)\n", errno);
			break;
		}

		if (len == 0)
			break;

		if (len < (int) sizeof(hdr) || hdr.syncword != 0x9c) {
			fprintf(stderr, "Corrupted SBC stream "
					"(len %d syncword 0x%02x)\n",
					len, hdr.syncword);
			break;
		}

		count = calc_frame_len(&hdr);
		len = count + 4;

		p1 = -1;
		p2 = -1;
		for (n = 0; n < SIZE; n++) {
			if (p1 < 0 && (bitpool[n] == 0 || bitpool[n] == hdr.bitpool))
				p1 = n;
			if (p2 < 0 && (frame_len[n] == 0 || frame_len[n] == len))
				p2 = n;
		}
		if (p1 >= 0)
			bitpool[p1] = hdr.bitpool;
		if (p2 >= 0)
			frame_len[p2] = len;

		while (count) {
			size = count > sizeof(buf) ? sizeof(buf) : count;

			len = __read(fd, buf, size);
			if (len != size) {
				fprintf(stderr, "Unable to read frame data "
						"(error %d)\n", errno);
				break;
			}

			count -= len;
		}

		rate += calc_bit_rate(&hdr);
		num++;
	}

	printf("Subbands\t\t%d\n", subbands);
	printf("Block length\t\t%d\n", blocks);
	printf("Sampling frequency\t%s\n", freq2str(freq));
	printf("Channel mode\t\t%s\n", mode2str(hdr.channel_mode));
	printf("Allocation method\t%s\n", method ? "SNR" : "Loudness");
	printf("Bitpool\t\t\t%d", bitpool[0]);
	for (n = 1; n < SIZE; n++)
		if (bitpool[n] > 0)
			printf(", %d", bitpool[n]);
	printf("\n");
	printf("Number of frames\t%d\n", num);
	printf("Frame length\t\t%d", frame_len[0]);
	for (n = 1; n < SIZE; n++)
		if (frame_len[n] > 0)
			printf(", %d", frame_len[n]);
	printf(" Bytes\n");
	if (num > 0)
		printf("Bit rate\t\t%.3f kbps\n", rate / num);

	if (fd > fileno(stderr))
		close(fd);

	printf("\n");

	return 0;
}
Пример #11
0
static void proto_handle_get(conn_t* cn, const char* line) {
	struct stat st;

	// Reject filenames with just "." and ".."
	if(memcmp(line, ".\0", 2) == 0 || memcmp(line, "..\0", 3) == 0) {
		conn_printf(cn, "ERROR Protocol violation (%d)\n", __LINE__);
		conn_abort(cn);
		return;
	}

	if(lstat(line,&st) == 0) {
		if(S_ISREG(st.st_mode)) {
			int fd;
			md5_state_t md5_state;
			md5_init(&md5_state);
			char buffer[PATH_MAX];
			ssize_t size;
			char md5str[33];
			char modestr[11];

#ifdef O_NOATIME
			if((fd = open(line,O_RDONLY|O_NOATIME))==-1) {
#else
			if((fd = open(line,O_RDONLY))==-1) {
#endif

				conn_perror(cn, "WARNING open()");
				conn_printf(cn, "WARNING Can't open file: %s\n", line);
				return;
			}

			// Calcuate MD5
			{
				unsigned char md5bin[16];
				while((size = read(fd, buffer, sizeof buffer)))
					md5_append(&md5_state, (unsigned char*)buffer, size);
				md5_finish(&md5_state, (unsigned char*)md5bin);

				if(lseek(fd, SEEK_SET, 0)==-1) {
					conn_perror(cn, "ERROR lseek()");
					conn_abort(cn);
					return;
				}

				md5bin2str(md5bin, md5str);
			}

			mode2str(st.st_mode, modestr);
			conn_printf(cn, "PUT %ld %s %s %ld %ld %ld %s\n", 
				(long int)st.st_size,
				md5str,
				modestr,
				st.st_atime,
				st.st_ctime,
				st.st_mtime,
				line);
			while((size = read(fd, buffer, sizeof buffer))) 
				conn_write(cn, buffer, size);
			close(fd);
		}
		else if(S_ISDIR(st.st_mode)) {
			char modestr[11];
			mode2str(st.st_mode, modestr);
			conn_printf(cn, "MKDIR %s %ld %ld %ld %s\n",
				modestr,
				st.st_atime,
				st.st_ctime,
				st.st_mtime,
				line);
		}
		else if(S_ISLNK(st.st_mode)) {
			char buffer[PATH_MAX];
			conn_printf(cn, "SLNK %s\n", line);

			ssize_t l;
			if((l=readlink(line, buffer, sizeof buffer))==-1) {
				conn_perror(cn, "WARNING readlink()");
				return;
			}
			buffer[l] = '\0';
			conn_printf(cn, "%s\n", buffer);
		}
		else {
			conn_printf(cn, "WARNING Ignored %s\n", line);
		}
	}
}

static void proto_handle_put(conn_t* cn, const char* line) {
	const char* delim = " ";
	char* saveptr = NULL;
	char* token;
	char* ptr = (char*)line;
	int c = 0;

	ssize_t size = 0;
	mode_t mode = 0;
	time_t mtime = 0;
	time_t ctime = 0;
	time_t atime = 0;
	char* name = NULL;
	char* md5  = NULL;

	while((token = strtok_r(ptr, delim, &saveptr))) {
		switch(c) {
			case 0: size = atol(token); break;
			case 1: md5 = token; break;
			case 2: mode = str2mode(token); break;
			case 3: atime = atol(token); break; 
			case 4: ctime = atol(token); break;
			case 5: mtime = atol(token); break;
			case 6: name = token; break;
		}
		c++;
		ptr = NULL;
	}

	if(c != 7) {
		conn_printf(cn, "ERROR Protocol violation (%d)\n", __LINE__);
		conn_abort(cn);
		return ;
	}

	int fd = creat(name, O_CREAT|O_TRUNC);
	if(fd == -1) {
		conn_perror(cn, "WARNING creat()");
		return;
	}

	if(chmod(name,mode)==-1) {
		perror("WARNING chmod()");
	}

	struct utimbuf t;
	t.actime = atime;
	t.modtime = mtime;
	if(utime(name,&t)==-1) {
		perror("WARNING utime");
	}

	// CONTENT
	int bytes_left = size;
	int r;
	md5_state_t md5_state;
	unsigned char md5bin[16];
	char md5str[33];
	md5_init(&md5_state);
	while(!cn->abort && bytes_left) {
		if(cn->rbuf_len == 0) 
			(void)conn_read(cn);

		r = MIN(bytes_left, cn->rbuf_len);
		if(r) {
			write(fd, cn->rbuf, r);
			md5_append(&md5_state, (unsigned char*)cn->rbuf, r);
			conn_shift(cn,r);
			bytes_left -= r;
		}

		assert(bytes_left >= 0);
	}

	close(fd);
	md5_finish(&md5_state, (unsigned char*)md5bin);
	md5bin2str(md5bin, md5str);

	// Check md5
	if(strcmp(md5str,md5)!=0) {
		// Mismatch!
		conn_printf(cn, "WARNING %s md5-mismatch (%s <-> %s), removing file\n", 
			name,
			md5str, md5);
		if(unlink(name)==-1) {
			perror("WARNING: unlink()");
		}
	}
	else {
		struct utimbuf t;
		t.actime = atime;
		t.modtime = mtime;
		if(utime(name,&t)==-1) {
			perror("utime");
			conn_printf(cn, "WARNING Can't timestamp on directory: %s\n", name);
		}
		// md5 is fine
		conn_printf(cn, "GET %s\n", name);
	}
}

static void proto_handle_slnk(conn_t* cn, const char* line) {
	char curdir[PATH_MAX];

	// read next line to get target
	char target[PATH_MAX];
	if(!conn_readline(cn, target, sizeof target))
		return;

	getcwd(curdir, sizeof curdir);

	// Make sure it dosnt exist
	unlink(line);

	if(chdir(my_dirname(line))==-1) {
		conn_perror(cn, "WARNING chdir()");
		return;
	}

	if(symlink(target, my_basename(line))==-1) {
		conn_perror(cn, "ERROR symlink()");
		conn_abort(cn);
		return;
	}

	chdir(curdir);

	conn_printf(cn, "GET %s\n", line);
}
Пример #12
0
int
main(int argc, char **argv)
{
    int fd;

    if (argc < 2)
        usage();

    if (!strcmp(argv[1], "mode") && (argc == 3 || argc == 4)) {
        int disk, mode;
        char device[64];

        if (!(sscanf(argv[2], "ad%d", &disk) == 1 ||
                sscanf(argv[2], "acd%d", &disk) == 1 ||
                sscanf(argv[2], "afd%d", &disk) == 1 ||
                sscanf(argv[2], "ast%d", &disk) == 1)) {
            fprintf(stderr, "natacontrol: Invalid device %s\n",
                    argv[2]);
            exit(EX_USAGE);
        }
        sprintf(device, "/dev/%s", argv[2]);
        if ((fd = open(device, O_RDONLY)) < 0)
            err(1, "device not found");
        if (argc == 4) {
            mode = str2mode(argv[3]);
            if (ioctl(fd, IOCATASMODE, &mode) < 0)
                warn("ioctl(IOCATASMODE)");
        }
        if (argc == 3 || argc == 4) {
            if (ioctl(fd, IOCATAGMODE, &mode) < 0)
                err(1, "ioctl(IOCATAGMODE)");
            printf("current mode = %s\n", mode2str(mode));
        }
        exit(EX_OK);
    }
    if (!strcmp(argv[1], "cap") && argc == 3) {
        int disk;
        char device[64];

        if (!(sscanf(argv[2], "ad%d", &disk) == 1 ||
                sscanf(argv[2], "acd%d", &disk) == 1 ||
                sscanf(argv[2], "afd%d", &disk) == 1 ||
                sscanf(argv[2], "ast%d", &disk) == 1)) {
            fprintf(stderr, "natacontrol: Invalid device %s\n",
                    argv[2]);
            exit(EX_USAGE);
        }
        sprintf(device, "/dev/%s", argv[2]);
        if ((fd = open(device, O_RDONLY)) < 0)
            err(1, "device not found");
        ata_cap_print(fd);
        exit(EX_OK);
    }

    if ((fd = open("/dev/ata", O_RDWR)) < 0)
        err(1, "control device not found");

    if (!strcmp(argv[1], "list") && argc == 2) {
        int maxchannel, channel;

        if (ioctl(fd, IOCATAGMAXCHANNEL, &maxchannel) < 0)
            err(1, "ioctl(IOCATAGMAXCHANNEL)");
        for (channel = 0; channel < maxchannel; channel++)
            info_print(fd, channel, 1);
        exit(EX_OK);
    }
    if (!strcmp(argv[1], "info") && argc == 3) {
        int channel;

        if (!(sscanf(argv[2], "ata%d", &channel) == 1)) {
            fprintf(stderr,
                    "natacontrol: Invalid channel %s\n", argv[2]);
            exit(EX_USAGE);
        }
        info_print(fd, channel, 0);
        exit(EX_OK);
    }
    if (!strcmp(argv[1], "detach") && argc == 3) {
        int channel;

        if (!(sscanf(argv[2], "ata%d", &channel) == 1)) {
            fprintf(stderr,
                    "natacontrol: Invalid channel %s\n", argv[2]);
            exit(EX_USAGE);
        }
        if (ioctl(fd, IOCATADETACH, &channel) < 0)
            err(1, "ioctl(IOCATADETACH)");
        exit(EX_OK);
    }
    if (!strcmp(argv[1], "attach") && argc == 3) {
        int channel;

        if (!(sscanf(argv[2], "ata%d", &channel) == 1)) {
            fprintf(stderr,
                    "natacontrol: Invalid channel %s\n", argv[2]);
            exit(EX_USAGE);
        }
        if (ioctl(fd, IOCATAATTACH, &channel) < 0)
            err(1, "ioctl(IOCATAATTACH)");
        info_print(fd, channel, 0);
        exit(EX_OK);
    }
    if (!strcmp(argv[1], "reinit") && argc == 3) {
        int channel;

        if (!(sscanf(argv[2], "ata%d", &channel) == 1)) {
            fprintf(stderr,
                    "natacontrol: Invalid channel %s\n", argv[2]);
            exit(EX_USAGE);
        }
        if (ioctl(fd, IOCATAREINIT, &channel) < 0)
            warn("ioctl(IOCATAREINIT)");
        info_print(fd, channel, 0);
        exit(EX_OK);
    }
    if (!strcmp(argv[1], "create")) {
        int disk, dev, offset;
        struct ata_ioc_raid_config config;

        bzero(&config, sizeof(config));
        if (argc > 2) {
            if (!strcasecmp(argv[2], "RAID0") ||
                    !strcasecmp(argv[2], "stripe"))
                config.type = AR_RAID0;
            if (!strcasecmp(argv[2], "RAID1") ||
                    !strcasecmp(argv[2],"mirror"))
                config.type = AR_RAID1;
            if (!strcasecmp(argv[2], "RAID0+1") ||
                    !strcasecmp(argv[2],"RAID10"))
                config.type = AR_RAID01;
            if (!strcasecmp(argv[2], "RAID5"))
                config.type = AR_RAID5;
            if (!strcasecmp(argv[2], "SPAN"))
                config.type = AR_SPAN;
            if (!strcasecmp(argv[2], "JBOD"))
                config.type = AR_JBOD;
        }
        if (!config.type) {
            fprintf(stderr, "natacontrol: Invalid RAID type %s\n",
                    argv[2]);
            fprintf(stderr, "natacontrol: Valid RAID types: \n");
            fprintf(stderr, "             stripe | mirror | "
                    "RAID0 | RAID1 | RAID0+1 | RAID5 | "
                    "SPAN | JBOD\n");
            exit(EX_USAGE);
        }

        if (config.type == AR_RAID0 ||
                config.type == AR_RAID01 ||
                config.type == AR_RAID5) {
            if (argc < 4 ||
                    !sscanf(argv[3], "%d", &config.interleave) == 1) {
                fprintf(stderr,
                        "natacontrol: Invalid interleave %s\n",
                        argv[3]);
                exit(EX_USAGE);
            }
            offset = 4;
        }
        else
            offset = 3;

        for (disk = 0; disk < 16 && (offset + disk) < argc; disk++) {
            if (!(sscanf(argv[offset + disk], "ad%d", &dev) == 1)) {
                fprintf(stderr,
                        "natacontrol: Invalid disk %s\n",
                        argv[offset + disk]);
                exit(EX_USAGE);
            }
            config.disks[disk] = dev;
        }

        if ((config.type == AR_RAID1 || config.type == AR_RAID01) &&
                disk < 2) {
            fprintf(stderr, "natacontrol: At least 2 disks must be "
                    "specified\n");
            exit(EX_USAGE);
        }

        config.total_disks = disk;
        if (ioctl(fd, IOCATARAIDCREATE, &config) < 0)
            err(1, "ioctl(IOCATARAIDCREATE)");
        else
            printf("ar%d created\n", config.lun);
        exit(EX_OK);
    }
    if (!strcmp(argv[1], "delete") && argc == 3) {
        int array;

        if (!(sscanf(argv[2], "ar%d", &array) == 1)) {
            fprintf(stderr,
                    "natacontrol: Invalid array %s\n", argv[2]);
            exit(EX_USAGE);
        }
        if (ioctl(fd, IOCATARAIDDELETE, &array) < 0)
            warn("ioctl(IOCATARAIDDELETE)");
        exit(EX_OK);
    }
    if (!strcmp(argv[1], "addspare") && argc == 4) {
        struct ata_ioc_raid_config config;

        if (!(sscanf(argv[2], "ar%d", &config.lun) == 1)) {
            fprintf(stderr,
                    "natacontrol: Invalid array %s\n", argv[2]);
            usage();
        }
        if (!(sscanf(argv[3], "ad%d", &config.disks[0]) == 1)) {
            fprintf(stderr,
                    "natacontrol: Invalid disk %s\n", argv[3]);
            usage();
        }
        if (ioctl(fd, IOCATARAIDADDSPARE, &config) < 0)
            warn("ioctl(IOCATARAIDADDSPARE)");
        exit(EX_OK);
    }
    if (!strcmp(argv[1], "rebuild") && argc == 3) {
        int array;

        if (!(sscanf(argv[2], "ar%d", &array) == 1)) {
            fprintf(stderr,
                    "natacontrol: Invalid array %s\n", argv[2]);
            usage();
        }
        if (ioctl(fd, IOCATARAIDREBUILD, &array) < 0)
            warn("ioctl(IOCATARAIDREBUILD)");
        else {
            char device[64];
            char *buffer;
            ssize_t len;
            int arfd;

            if (daemon(0, 1) == -1)
                err(1, "daemon");
            nice(20);
            snprintf(device, sizeof(device), "/dev/ar%d",
                     array);
            if ((arfd = open(device, O_RDONLY)) == -1)
                err(1, "open %s", device);
            if ((buffer = malloc(1024 * 1024)) == NULL)
                err(1, "malloc");
            while ((len = read(arfd, buffer, 1024 * 1024)) > 0)
                ;
            if (len == -1)
                err(1, "read");
            else
                fprintf(stderr,
                        "atacontrol: ar%d rebuild completed\n",
                        array);
            free(buffer);
            close(arfd);
        }
        exit(EX_OK);
    }
    if (!strcmp(argv[1], "status") && argc == 3) {
        struct ata_ioc_raid_config config;
        int i;

        if (!(sscanf(argv[2], "ar%d", &config.lun) == 1)) {
            fprintf(stderr,
                    "natacontrol: Invalid array %s\n", argv[2]);
            usage();
        }
        if (ioctl(fd, IOCATARAIDSTATUS, &config) < 0)
            err(1, "ioctl(IOCATARAIDSTATUS)");

        printf("ar%d: ATA ", config.lun);
        switch (config.type) {
        case AR_RAID0:
            printf("RAID0 stripesize=%d", config.interleave);
            break;
        case AR_RAID1:
            printf("RAID1");
            break;
        case AR_RAID01:
            printf("RAID0+1 stripesize=%d", config.interleave);
            break;
        case AR_RAID5:
            printf("RAID5 stripesize=%d", config.interleave);
            break;
        case AR_JBOD:
            printf("JBOD");
        case AR_SPAN:
            printf("SPAN");
            break;
        }
        printf(" subdisks: ");
        for (i = 0; i < config.total_disks; i++) {
            if (config.disks[i] >= 0)
                printf("ad%d ", config.disks[i]);
            else
                printf("DOWN ");
        }
        printf("status: ");
        switch (config.status) {
        case AR_READY:
            printf("READY\n");
            break;
        case AR_READY | AR_DEGRADED:
            printf("DEGRADED\n");
            break;
        case AR_READY | AR_DEGRADED | AR_REBUILDING:
            printf("REBUILDING %d%% completed\n",
                   config.progress);
            break;
        default:
            printf("BROKEN\n");
        }
        exit(EX_OK);
    }
    usage();
    exit(EX_OK);
}
Пример #13
0
int
main(int argc, char **argv)
{
	struct ata_cmd iocmd;
	int fd;

	if ((fd = open("/dev/ata", O_RDWR)) < 0)
		err(1, "control device not found");

	if (argc < 2)
		usage();

	bzero(&iocmd, sizeof(struct ata_cmd));

	if (argc > 2 && strcmp(argv[1], "create")) {
		int chan;

		if (!strcmp(argv[1], "delete") ||
		    !strcmp(argv[1], "status") ||
		    !strcmp(argv[1], "rebuild")) {
			if (!(sscanf(argv[2], "%d", &chan) == 1 ||
			      sscanf(argv[2], "ar%d", &chan) == 1))
				usage();
		}
		else {
			if (!(sscanf(argv[2], "%d", &chan) == 1 ||
			      sscanf(argv[2], "ata%d", &chan) == 1))
				usage();
		}
		iocmd.channel = chan;
	}

	if (!strcmp(argv[1], "list") && argc == 2) {
		int unit = 0;

		while (info_print(fd, unit++, 1) != ENXIO);
	}
	else if (!strcmp(argv[1], "info") && argc == 3) {
		info_print(fd, iocmd.channel, 0);
	}
	else if (!strcmp(argv[1], "cap") && argc == 4) {
		ata_cap_print(fd, iocmd.channel, atoi(argv[3]));
	}
	else if (!strcmp(argv[1], "enclosure") && argc == 4) {
		iocmd.device = atoi(argv[3]);
		iocmd.cmd = ATAENCSTAT;
		if (ioctl(fd, IOCATA, &iocmd) < 0)
			err(1, "ioctl(ATAENCSTAT)");
		printf("fan RPM: %d temp: %.1f 5V: %.2f 12V: %.2f\n",
			iocmd.u.enclosure.fan,
			(double)iocmd.u.enclosure.temp / 10,
			(double)iocmd.u.enclosure.v05 / 1000,
			(double)iocmd.u.enclosure.v12 / 1000);
	}
	else if (!strcmp(argv[1], "detach") && argc == 3) {
		iocmd.cmd = ATADETACH;
		if (ioctl(fd, IOCATA, &iocmd) < 0)
			err(1, "ioctl(ATADETACH)");
	}
	else if (!strcmp(argv[1], "attach") && argc == 3) {
		iocmd.cmd = ATAATTACH;
		if (ioctl(fd, IOCATA, &iocmd) < 0)
			err(1, "ioctl(ATAATTACH)");
		info_print(fd, iocmd.channel, 0);
	}
	else if (!strcmp(argv[1], "reinit") && argc == 3) {
		iocmd.cmd = ATAREINIT;
		if (ioctl(fd, IOCATA, &iocmd) < 0)
			warn("ioctl(ATAREINIT)");
		info_print(fd, iocmd.channel, 0);
	}
	else if (!strcmp(argv[1], "create")) {
		int disk, dev, offset;

		iocmd.cmd = ATARAIDCREATE;
		if (!strcmp(argv[2], "RAID0") || !strcmp(argv[2], "stripe"))
			iocmd.u.raid_setup.type = 1;
		if (!strcmp(argv[2], "RAID1") || !strcmp(argv[2],"mirror"))
			iocmd.u.raid_setup.type = 2;
		if (!strcmp(argv[2], "RAID0+1"))
			iocmd.u.raid_setup.type = 3;
		if (!strcmp(argv[2], "SPAN") || !strcmp(argv[2], "JBOD"))
			iocmd.u.raid_setup.type = 4;
		if (!iocmd.u.raid_setup.type)
		     usage();
		
		if (iocmd.u.raid_setup.type & 1) {
			if (!sscanf(argv[3], "%d",
				    &iocmd.u.raid_setup.interleave) == 1)
				usage();
			offset = 4;
		}
		else
			offset = 3;
		
		for (disk = 0; disk < 16 && (offset + disk) < argc; disk++) {
			if (!(sscanf(argv[offset + disk], "%d", &dev) == 1 ||
			      sscanf(argv[offset + disk], "ad%d", &dev) == 1))
				usage();
			iocmd.u.raid_setup.disks[disk] = dev;
		}
		iocmd.u.raid_setup.total_disks = disk;
		if (ioctl(fd, IOCATA, &iocmd) < 0)
			err(1, "ioctl(ATARAIDCREATE)");
		else
			printf("ar%d created\n", iocmd.u.raid_setup.unit);
	}
	else if (!strcmp(argv[1], "delete") && argc == 3) {
		iocmd.cmd = ATARAIDDELETE;
		if (ioctl(fd, IOCATA, &iocmd) < 0)
			warn("ioctl(ATARAIDDELETE)");
	}
	else if (!strcmp(argv[1], "rebuild") && argc == 3) {
		iocmd.cmd = ATARAIDREBUILD;
		if (ioctl(fd, IOCATA, &iocmd) < 0)
			warn("ioctl(ATARAIDREBUILD)");
	}
	else if (!strcmp(argv[1], "status") && argc == 3) {
		int i;

		iocmd.cmd = ATARAIDSTATUS;
		if (ioctl(fd, IOCATA, &iocmd) < 0)
			err(1, "ioctl(ATARAIDSTATUS)");
		printf("ar%d: ATA ", iocmd.channel);
		switch (iocmd.u.raid_status.type) {
		case AR_RAID0:
			printf("RAID0");
			break;
		case AR_RAID1:
			printf("RAID1");
			break;
		case AR_RAID0 | AR_RAID1:
			printf("RAID0+1");
			break;
		case AR_SPAN:
			printf("SPAN");
			break;
		}
		printf(" subdisks: ");
		for (i = 0; i < iocmd.u.raid_status.total_disks; i++) {
			if (iocmd.u.raid_status.disks[i] >= 0)
				printf("ad%d ", iocmd.u.raid_status.disks[i]);
			else
				printf("DOWN ");
		}
		printf("status: ");
		switch (iocmd.u.raid_status.status) {
		case AR_READY:
			printf("READY\n");
			break;
		case AR_READY | AR_DEGRADED:
			printf("DEGRADED\n");
			break;
		case AR_READY | AR_DEGRADED | AR_REBUILDING:
			printf("REBUILDING %d%% completed\n",
				iocmd.u.raid_status.progress);
			break;
		default:
			printf("BROKEN\n");
		}
	}
	else if (!strcmp(argv[1], "mode") && (argc == 3 || argc == 5)) {
		if (argc == 5) {
			iocmd.cmd = ATASMODE;
			iocmd.device = -1;
			iocmd.u.mode.mode[0] = str2mode(argv[3]);
			iocmd.u.mode.mode[1] = str2mode(argv[4]);
			if (ioctl(fd, IOCATA, &iocmd) < 0)
				warn("ioctl(ATASMODE)");
		}
		if (argc == 3 || argc == 5) {
			iocmd.cmd = ATAGMODE;
			iocmd.device = -1;
			if (ioctl(fd, IOCATA, &iocmd) < 0)
				err(1, "ioctl(ATAGMODE)");
			printf("Master = %s \nSlave  = %s\n",
				mode2str(iocmd.u.mode.mode[0]), 
				mode2str(iocmd.u.mode.mode[1]));
		}
	}
	else
	    	usage();
	exit(0);
}