コード例 #1
0
ファイル: smbget.c プロジェクト: cmtsij/Vizio_XWR100_GPL
void print_progress(const char *name, time_t start, time_t now, off_t start_pos, off_t pos, off_t total)
{
	double avg = 0.0;
	long  eta = -1; 
	double prcnt = 0.0;
	char hpos[20], htotal[20], havg[20];
	char *status, *filename;
	int len;
	if(now - start)avg = 1.0 * (pos - start_pos) / (now - start);
	eta = (total - pos - start_pos) / avg;
	if(total)prcnt = 100.0 * pos / total;

	human_readable(pos, hpos, sizeof(hpos));
	human_readable(total, htotal, sizeof(htotal));
	human_readable(avg, havg, sizeof(havg));

	len = asprintf(&status, "%s of %s (%.2f%%) at %s/s ETA: %s", hpos, htotal, prcnt, havg, print_time(eta));
	
	if(columns) {
		int required = strlen(name), available = columns - len - strlen("[] ");
		if(required > available) asprintf(&filename, "...%s", name + required - available + 3);
		else filename = strndup(name, available);
	} else filename = strdup(name);

	fprintf(stderr, "\r[%s] %s", filename, status);

	free(filename); free(status);
}
コード例 #2
0
ファイル: ls.c プロジェクト: DanLipsitt/libguestfs
static void
output_int64_size (int64_t size)
{
  char buf[LONGEST_HUMAN_READABLE];
  int hopts = human_round_to_nearest|human_autoscale|human_base_1024|human_SI;
  int r;

  next_field ();

  if (!csv) {
    if (!human)
      r = printf ("%10" PRIi64, size);
    else
      r = printf ("%10s",
                  human_readable ((uintmax_t) size, buf, hopts, 1, 1));
  } else {
    /* CSV is the same as non-CSV but we don't need to right-align. */
    if (!human)
      r = printf ("%" PRIi64, size);
    else
      r = printf ("%s",
                  human_readable ((uintmax_t) size, buf, hopts, 1, 1));
  }

  if (r < 0) {
    perror ("printf");
    exit (EXIT_FAILURE);
  }
}
コード例 #3
0
ファイル: httpipe.c プロジェクト: N0NamedGuy/httpipe
/* Outputs a file described by the file pointer fp thru a socket connfd */
int send_file (int connfd, FILE* fp) {
    char* buf;
    size_t n;
    size_t total, cur_total;
    time_t last, cur;

    /* Get us a nice clean buffer */
    buf = malloc(g_buf_size);
    memset((void*)buf, 0, g_buf_size);


    /* Set up the statistic variables if we are being verbose */
    if (g_verbose) {
        last = time(NULL);
        cur_total = 0;
        total = 0;
        puts("");
    } else {
        /* Damn gcc complaining... */
        last = 0;
    }


    while ((n = fread(buf, 1, g_buf_size, fp)) > 0) {
        /* All the program revolves around this write */
        write(connfd, buf, n);
    
        /* Print statistics */
        if (g_verbose) {
            double elapsed;
            cur_total += n;

            cur = time(NULL);
            elapsed = difftime(cur, last); 
            if (elapsed > 1.0) {
                static char human_total[6];
                static char human_transfer[6];
                total += cur_total;

                /* Get the total transfered bytes and the current transfer
                 * speed in a human readable format */
                human_readable(total, human_total, 6);
                human_readable(cur_total / elapsed, human_transfer, 6);

                printverb("\033[F\033[JSent %s (%s per second)\n",
                        human_total,
                        human_transfer);

                /* Reset stuff */
                cur_total = 0;
                last = cur;
            }
        }
    }

    free(buf);
    return 0;
}
コード例 #4
0
ファイル: rss.c プロジェクト: firebitsbr/book-srcs
void main(void)
{
#if defined(__linux)
  struct sysinfo si;

  sysinfo(&si);   
  printf("System wide available memory: %s\n", human_readable(si.freeram));
#endif

  printf("RSS: %s\n"
         "Peak RSS: %s\n",
         human_readable(getCurrentRSS()), human_readable(getPeakRSS()));
}
コード例 #5
0
ファイル: main.c プロジェクト: dilawar/microdc2
static void
display_transfer_ended_msg(bool upload, DCUserConn *uc, bool success, const char *extras_fmt, ...)
{
    char timebuf[LONGEST_ELAPSED_TIME+1];
    char ratebuf[LONGEST_HUMAN_READABLE+1];
    char sizebuf[LONGEST_HUMAN_READABLE+1];
    char *str1;
    char *str2;
    time_t now;
    uint64_t len;
    va_list args;

    len = uc->transfer_pos - uc->transfer_start;

    if (uc->transfer_time == (time_t) -1) {
        str2 = xstrdup("");
    } else {
        time(&now);
        if (now == (time_t) -1) {
            warn(_("Cannot get current time - %s\n"), errstr);
            str2 = xstrdup("");
        } else {
            str2 = xasprintf(_(" in %s (%s/s)"),
                             elapsed_time_to_string(now - uc->transfer_time, timebuf),
                             human_readable(
                                 len/MAX(now - uc->transfer_time, 1), ratebuf,
                                 human_suppress_point_zero|human_autoscale|human_base_1024|human_SI|human_B,
                                 1, 1));
        }
    }

    va_start(args, extras_fmt);
    str1 = xvasprintf(extras_fmt, args);
    va_end(args);

    flag_putf(upload ? DC_DF_UPLOAD : DC_DF_DOWNLOAD,
              _("%s: %s of %s %s%s. %s %s%s.\n"),
              quotearg_n(0, uc->info->nick),
              upload ? _("Upload") : _("Download"),
              quote_n(1, base_name(uc->transfer_file)),
              success ? _("succeeded") : _("failed"),
              str1,
              human_readable(len, sizebuf, human_suppress_point_zero|human_autoscale|human_base_1024|human_SI|human_B, 1, 1),
              ngettext("transferred", "transferred", len),
              str2);

    free(str1);
    free(str2);
}
コード例 #6
0
 void check_for_csm () const
 {
     if (_csm.empty ())
     {
         human_readable (_csm);
     }
 }
コード例 #7
0
ファイル: smbget.c プロジェクト: cmtsij/Vizio_XWR100_GPL
void clean_exit(void)
{
	char bs[100];
	human_readable(total_bytes, bs, sizeof(bs));
	if(!quiet)fprintf(stderr, "Downloaded %s in %lu seconds\n", bs, time(NULL) - total_start_time);
	exit(0);
}
コード例 #8
0
static void
write_row (const char *name, const char *type,
           const char *vfs_type, const char *vfs_label, int mbr_id,
           int64_t size, char **parents, const char *uuid)
{
  const char *strings[NR_COLUMNS];
  CLEANUP_FREE char *parents_str = NULL;
  size_t len = 0;
  char hum[LONGEST_HUMAN_READABLE];
  char num[256];
  char mbr_id_str[3];

  if ((columns & COLUMN_NAME))
    strings[len++] = name;
  if ((columns & COLUMN_TYPE))
    strings[len++] = type;
  if ((columns & COLUMN_VFS_TYPE))
    strings[len++] = vfs_type;
  if ((columns & COLUMN_VFS_LABEL))
    strings[len++] = vfs_label;
  if ((columns & COLUMN_MBR)) {
    if (mbr_id >= 0) {
      snprintf (mbr_id_str, sizeof mbr_id_str, "%02x", mbr_id);
      strings[len++] = mbr_id_str;
    } else
      strings[len++] = NULL;
  }
  if ((columns & COLUMN_SIZE)) {
    if (size >= 0) {
      if (human) {
        strings[len++] =
          human_readable ((uintmax_t) size, hum,
                          human_round_to_nearest|human_autoscale|
                          human_base_1024|human_SI,
                          1, 1);
      }
      else {
        snprintf (num, sizeof num, "%" PRIi64, size);
        strings[len++] = num;
      }
    }
    else
      strings[len++] = NULL;
  }
  if ((columns & COLUMN_PARENTS)) {
    /* Internally comma-separated field. */
    parents_str = guestfs___join_strings (",", parents);
    strings[len++] = parents_str;
  }
  if ((columns & COLUMN_UUID))
    strings[len++] = uuid;
  assert (len <= NR_COLUMNS);

  write_row_strings ((char **) strings, len);
}
コード例 #9
0
void setup_stream(f_state *s, f_info *i)
{
	char	buffer[MAX_STRING_LENGTH];
	u_int64_t	skip = (((u_int64_t) s->skip) * ((u_int64_t) s->block_size));
#ifdef DEBUG
	printf("s->skip=%d s->block_size=%d total=%llu\n",
		   s->skip,
		   s->block_size,
		   (((u_int64_t) s->skip) * ((u_int64_t) s->block_size)));
#endif
	i->bytes_read = 0;
	i->total_megs = i->total_bytes / ONE_MEGABYTE;

	if (i->total_bytes != 0)
		{
		audit_msg(s,
				  "Length: %s (%llu bytes)",
				  human_readable(i->total_bytes, buffer),
				  i->total_bytes);
		}
	else
		audit_msg(s, "Length: Unknown");

	if (s->skip != 0)
		{
		audit_msg(s, "Skipping: %s (%llu bytes)", human_readable(skip, buffer), skip);
		fseeko(i->handle, skip, SEEK_SET);
		if (i->total_bytes != 0)
			i->total_bytes -= skip;
		}

	audit_msg(s, " ");

#ifdef __WIN32
	i->last_read = 0;
	i->overflow_count = 0;
#endif

}
コード例 #10
0
ファイル: demo_number.c プロジェクト: sekharpariga/toybox
void demo_number_main(void)
{
  char **arg;

  for (arg = toys.optargs; *arg; arg++) {
    long long ll = atolx(*arg);

    if (toys.optflags) {
      human_readable(toybuf, ll, toys.optflags);
      xputs(toybuf);
    } else printf("%lld\n", ll);
  }
}
コード例 #11
0
ファイル: diskio.c プロジェクト: dilawar/suckless
/* dir indicates the direction:
 * -1: read
 *  0: read + write
 *  1: write
 */
static void print_diskio_dir(struct text_object *obj, int dir, char *p, int p_max_size)
{
	struct diskio_stat *diskio = obj->data.opaque;
	double val;

	if (!diskio)
		return;

	if (dir < 0)
		val = diskio->current_read;
	else if (dir == 0)
		val = diskio->current;
	else
		val = diskio->current_write;

	/* TODO: move this correction from kB to kB/s elsewhere
	 * (or get rid of it??) */
	human_readable((val / update_interval) * 1024LL, p, p_max_size);
}
コード例 #12
0
ファイル: dir.c プロジェクト: nmcv/foremost
/*We have found a file so write to disk*/
int write_to_disk(f_state *s, s_spec *needle, u_int64_t len, unsigned char *buf, u_int64_t t_offset)
{

	char		fn[MAX_STRING_LENGTH];
	FILE		*f;
	FILE		*test;
	long		byteswritten = 0;
	char		temp[32];
	u_int64_t	block = ((t_offset) / s->block_size);
	int			i = 1;

	//Name files based on their block offset
	needle->written = TRUE;

	if (get_mode(s, mode_write_audit))
		{
		if (needle->comment == NULL)
			strcpy(needle->comment, " ");

		audit_msg(s,
				  "%d:\t%10llu.%s \t %10s \t %10llu \t %s", // http://sourceforge.net/p/foremost/bugs/2/
				  s->fileswritten,
				  block,
				  needle->suffix,
				  human_readable(len, temp),
				  t_offset,
				  needle->comment);
		s->fileswritten++;
		needle->found++;
		return TRUE;
		}

	snprintf(fn,
			 MAX_STRING_LENGTH,
			 "%s/%s/%0*llu.%s",
			 s->output_directory,
			 needle->suffix,
			 8,
			 block,
			 needle->suffix);

	test = fopen(fn, "r");
	while (test)	/*Test the files to make sure we have unique file names, some headers could be within the same block*/
		{
		memset(fn, 0, MAX_STRING_LENGTH - 1);
		snprintf(fn,
				 MAX_STRING_LENGTH - 1,
				 "%s/%s/%0*llu_%d.%s",
				 s->output_directory,
				 needle->suffix,
				 8,
				 block,
				 i,
				 needle->suffix);
		i++;
		fclose(test);
		test = fopen(fn, "r");
		}

	if (!(f = fopen(fn, "w")))
		{
		printf("fn = %s  failed\n", fn);
		fatal_error(s, "Can't open file for writing \n");
		}

	if ((byteswritten = fwrite(buf, sizeof(char), len, f)) != len)
		{
		fprintf(stderr, "fn=%s bytes=%lu\n", fn, byteswritten);
		fatal_error(s, "Error writing file\n");
		}

	if (fclose(f))
		{
		fatal_error(s, "Error closing file\n");
		}

	if (needle->comment == NULL)
		strcpy(needle->comment, " ");
	
	if (i == 1) {
      audit_msg(s,"%d:\t%08llu.%s \t %10s \t %10llu \t %s",
         s->fileswritten,
         block,
         needle->suffix,
         human_readable(len, temp),
         t_offset,
         needle->comment);
         } else {
      audit_msg(s,"%d:\t%08llu_%d.%s \t %10s \t %10llu \t %s",
         s->fileswritten,
         block,
         i - 1,
         needle->suffix, 
         human_readable(len, temp),
         t_offset,
         needle->comment);
         }

/*
	audit_msg(s,"%d:\t%10llu.%s \t %10s \t %10llu \t %s",
			  s->fileswritten,
			  block,
			  needle->suffix,
			  human_readable(len, temp),
			  t_offset,
			  needle->comment);

*/
	s->fileswritten++;
	needle->found++;
	return TRUE;
}
コード例 #13
0
ファイル: client.cpp プロジェクト: vasiletoncu/TemePC-2015
int digest_user_comand(char *msg) 
{
	cmd_t cmd = extract_command(msg);
	char buf[sizeof(info_clients)];

	/* Eventuale argumente ale comenzilor */
	char arg1[NAME_LEN];
	char arg2[NAME_LEN];
	memset(arg1, '\0', NAME_LEN);
	memset(arg2, '\0', NAME_LEN);

	if(cmd == infoclients) {
		int x = send(sockfd, msg, strlen(msg), 0);
		memset(buf, '\0', sizeof(info_clients));

		x = recv(sockfd, buf, sizeof(info_clients), 0);

		struct info_clients *X = (struct info_clients *)buf;
		log_file << client_name << "> infoclients\n";
		for(int i = 0; i < X->nr; ++i) {
			log_file  << X->clients[i].name << " " << X->clients[i].IP << " " << X->clients[i].port << "\n";
			std::cout << X->clients[i].name << " " << X->clients[i].IP << " " << X->clients[i].port << "\n";
			if( !client_exists(X->clients[i].name) ) {
				struct known_client new_client;
				memset(new_client.basic_info.name, '\0', NAME_LEN);
				sprintf(new_client.basic_info.name, "%s", X->clients[i].name);

				memset(new_client.basic_info.IP, '\0', NAME_LEN);
				sprintf(new_client.basic_info.IP, "%s", X->clients[i].IP);

				new_client.basic_info.port = X->clients[i].port;
				new_client.nr_of_shared_files = 0;

				known_clients.push_back(new_client);
			}
		}
		memset(buf, '\0', sizeof(info_clients));
		std::cout << "\n";	
	}

	if(cmd == share) {
		extract_arguments(arg1, arg2, msg);
		log_file << client_name << "> " << msg << "\n";

		FILE *f = fopen(arg1, "r");
		if( f == NULL ) {
			std::cout << ABSENT_FILE << " : Fisier inexistent\n";
			log_file  << ABSENT_FILE << " : Fisier inexistent\n";
			return 1;
		}
		fclose(f);

		if(nr_of_shared_files >= 32) {
			std::cout << "At depasit numarul maxim de fisiere ce pot fi partajate\n";
			return 0;
		}

		/* Punem in arg 2 dimensiunea fisierului */
		struct stat info;
		lstat(arg1, &info);
		memset(arg2, '\0', NAME_LEN);
		human_readable((double)info.st_size, arg2);

		bool is_new_file = true;

		for(int i = 0; i < nr_of_shared_files; ++i) {
			if( strcmp(arg1, shared[i].name) == 0 ) {
				memset(shared[i].size, '\0', NAME_LEN);
				sprintf(shared[i].size, "%s", arg2);
				is_new_file = false;
				break;
			}
		}

		if( is_new_file ) {
			memset(shared[nr_of_shared_files].name, '\0', NAME_LEN);
			memset(shared[nr_of_shared_files].size, '\0', NAME_LEN);

			sprintf(shared[nr_of_shared_files].name, "%s", arg1);
			sprintf(shared[nr_of_shared_files].size, "%s", arg2);
			nr_of_shared_files++;
		}
		
		memset(msg, '\0', BUFLEN);		
		strcat(msg, "share ");
		strcat(msg, arg1);
		strcat(msg, " ");
		strcat(msg, arg2);
		int x = send(sockfd, msg, BUFLEN, 0);
		
		memset(arg2, '\0', NAME_LEN);
		recv(sockfd, arg2, NAME_LEN, 0);

		std::cout << arg2 << "\n\n";		
		log_file  << arg2 << "\n";
	}

	if( cmd == unshare_file ) {
		extract_arguments(arg1, arg2, msg);
		
		std::cout << client_name << "> unshare " << arg1 << "\n";
		log_file  << client_name << "> unshare " << arg1 << "\n";

		int id = -1;
		for(int i = 0; i < nr_of_shared_files; ++i) {
			if( strcmp(shared[i].name, arg1) == 0 ) {
				id = i;
				break;
			}
		}
		
		if( id == -1 ) {
			std::cout << "-5 : Fisier inexistent\n";
			log_file  << "-5 : Fisier inexistent\n";
			return 0;
		}

		for(int i = id + 1; i < nr_of_shared_files; ++i) {
			/* shared[i - 1] <- shared[i] */
			memset(shared[i - 1].name, '\0', NAME_LEN);
			sprintf(shared[i - 1].name, "%s", shared[i].name);
			memset(shared[i - 1].size, '\0', NAME_LEN);
			sprintf(shared[i - 1].size, "%s", shared[i].size);
		}

		nr_of_shared_files--;

		send(sockfd, msg, strlen(msg), 0);

		log_file  << "Succes\n";
		std::cout << "Succes\n\n";
		
	}

	if( cmd == getshare ) {
		extract_arguments(arg1, arg2, msg);
		
		std::cout << client_name << "> " << msg << "\n";
		log_file  << client_name << "> " << msg << "\n";

		send(sockfd, msg, strlen(msg), 0);

		memset(buf, '\0', NAME_LEN);
		recv(sockfd, buf, NAME_LEN, 0);

		int status;
		sscanf(buf, "%d", &status);

		if(status == ABSENT_CLIENT) {
			std::cout << ABSENT_CLIENT << " : Client inexistent\n";
			log_file  << ABSENT_CLIENT << " : Client inexistent\n";
			return 1;
		}

		memset(buf, '\0', NAME_LEN);
		recv(sockfd, buf, NAME_LEN, 0);

		
		int nr;
		sscanf(buf, "%d", &nr);

		int id = -1;
		for(int i = 0; i < known_clients.size(); ++i) {
			if( strcmp(known_clients[i].basic_info.name, arg1) == 0) id = i;
		}

		if( id != -1) known_clients[id].nr_of_shared_files = nr;

		log_file << nr << "\n";		

		char buf1[sizeof(struct client) * MAX_FILES];
		memset(buf1, '\0', sizeof(struct client) * MAX_FILES);

		recv(sockfd, buf1, sizeof(struct client) * MAX_FILES, 0);
		
		struct client *X = (struct client *)buf1;

		for(int i = 0; i < nr; ++i) {
			std::cout << X->shared[i].name << " " << X->shared[i].size << "\n"; 
			log_file  << X->shared[i].name << " " << X->shared[i].size << "\n";
			if( id != -1 ) {
				memset(known_clients[id].shared[i].name, '\0', NAME_LEN);
				sprintf(known_clients[id].shared[i].name, "%s", X->shared[i].name);

				memset(known_clients[id].shared[i].size, '\0', NAME_LEN);
				sprintf(known_clients[id].shared[i].size, "%s", X->shared[i].size);
			}
		}

	}

	if(cmd == history) {
		
		std::cout << client_name << "> history \n"; 
		log_file  << client_name << "> history \n"; 
		if( age == 0 ) return 0;
		std::cout << age << "\n"; 
		log_file  << age << "\n"; 
		for(int i = 0; i < age; i++) {
			std::cout << H[i] << "\n";
			log_file  << H[i] << "\n";
		}
	}

	if(cmd == NOP) {
		;
	}	
}
コード例 #14
0
ファイル: time_qutil_qsort.c プロジェクト: Agobin/chapel
int main(int argc, char *argv[])
{
    aligned_t *ui_array, *ui_array2;
    double *d_array, *d_array2;
    size_t len = 1000000;
    qtimer_t timer = qtimer_create();
    double cumulative_time_qutil = 0.0;
    double cumulative_time_libc = 0.0;
    int using_doubles = 0;
    unsigned long iterations = 10;

    qthread_initialize();

    CHECK_VERBOSE();
    printf("%i threads\n", (int)qthread_num_workers());
    NUMARG(len, "TEST_LEN");
    NUMARG(iterations, "TEST_ITERATIONS");
    NUMARG(using_doubles, "TEST_USING_DOUBLES");
    printf("using %s\n", using_doubles ? "doubles" : "aligned_ts");

    if (using_doubles) {
        d_array = calloc(len, sizeof(double));
	printf("array is %s\n", human_readable(len * sizeof(double)));
        assert(d_array);
        // madvise(d_array,len*sizeof(double), MADV_SEQUENTIAL);
        for (unsigned int i = 0; i < len; i++) {
            d_array[i] = ((double)random()) / ((double)RAND_MAX) + random();
        }
        d_array2 = calloc(len, sizeof(double));
        assert(d_array2);
        // madvise(d_array2,len*sizeof(double), MADV_RANDOM);
        iprintf("double array generated...\n");
        for (unsigned int i = 0; i < iterations; i++) {
            memcpy(d_array2, d_array, len * sizeof(double));
            qtimer_start(timer);
            qutil_qsort(d_array2, len);
            qtimer_stop(timer);
            cumulative_time_qutil += qtimer_secs(timer);
            iprintf("\t%u: sorting %lu doubles with qutil took: %f seconds\n",
                    i, (unsigned long)len, qtimer_secs(timer));
        }
        cumulative_time_qutil /= (double)iterations;
        printf("sorting %lu doubles with qutil took: %f seconds (avg)\n",
               (unsigned long)len, cumulative_time_qutil);
        for (unsigned int i = 0; i < iterations; i++) {
            memcpy(d_array2, d_array, len * sizeof(double));
            qtimer_start(timer);
            qsort(d_array2, len, sizeof(double), dcmp);
            qtimer_stop(timer);
            cumulative_time_libc += qtimer_secs(timer);
            iprintf("\t%u: sorting %lu doubles with libc took: %f seconds\n",
                    i, (unsigned long)len, qtimer_secs(timer));
        }
	cumulative_time_libc /= (double)iterations;
        printf("sorting %lu doubles with libc took: %f seconds\n",
               (unsigned long)len, cumulative_time_libc);
        free(d_array);
        free(d_array2);
    } else {
        ui_array = calloc(len, sizeof(aligned_t));
	printf("array is %s\n", human_readable(len * sizeof(aligned_t)));
        for (unsigned int i = 0; i < len; i++) {
            ui_array[i] = random();
        }
        ui_array2 = calloc(len, sizeof(aligned_t));
        iprintf("ui_array generated...\n");
        for (int i = 0; i < iterations; i++) {
            memcpy(ui_array2, ui_array, len * sizeof(aligned_t));
            qtimer_start(timer);
            qutil_aligned_qsort(ui_array2, len);
            qtimer_stop(timer);
            cumulative_time_qutil += qtimer_secs(timer);
        }
	cumulative_time_qutil /= (double)iterations;
        printf("sorting %lu aligned_ts with qutil took: %f seconds\n",
               (unsigned long)len, cumulative_time_qutil);
        for (int i = 0; i < iterations; i++) {
            memcpy(ui_array2, ui_array, len * sizeof(aligned_t));
            qtimer_start(timer);
            qsort(ui_array2, len, sizeof(double), acmp);
            qtimer_stop(timer);
            cumulative_time_libc += qtimer_secs(timer);
        }
	cumulative_time_libc /= (double)iterations;
        printf("sorting %lu aligned_ts with libc took: %f seconds (avg)\n",
               (unsigned long)len, cumulative_time_libc);
        free(ui_array);
        free(ui_array2);
    }
    if (cumulative_time_qutil < cumulative_time_libc) {
	printf("qutil with %lu threads provides a %0.2fx speedup.\n", (unsigned long)qthread_num_shepherds(), cumulative_time_libc/cumulative_time_qutil);
    } else {
	printf("qutil with %lu threads provides a %0.2fx slowdown.\n", (unsigned long)qthread_num_shepherds(), cumulative_time_libc/cumulative_time_qutil);
    }

    qtimer_destroy(timer);

    return 0;
}
コード例 #15
0
ファイル: du.c プロジェクト: redwinner/unxutils
static long
count_entry (char *ent, int top, dev_t last_dev)
{
  long size;

  if (((top && opt_dereference_arguments)
       ? stat (ent, &stat_buf)
       : (*xstat) (ent, &stat_buf)) < 0)
    {
      error (0, errno, "%s", path->text);
      exit_status = 1;
      return 0;
    }

  if (!opt_count_all
      && stat_buf.st_nlink > 1
      && hash_insert (stat_buf.st_ino, stat_buf.st_dev))
    return 0;			/* Have counted this already.  */

  if (output_size == size_bytes)
    size = stat_buf.st_size;
  else
    size = ST_NBLOCKS (stat_buf);

  tot_size += size;

  if (S_ISDIR (stat_buf.st_mode))
    {
      unsigned pathlen;
      dev_t dir_dev;
      char *name_space;
      char *namep;
      struct saved_cwd cwd;
      int through_symlink;
      struct stat e_buf;

      dir_dev = stat_buf.st_dev;

      if (opt_one_file_system && !top && last_dev != dir_dev)
	return 0;		/* Don't enter a new file system.  */

#ifndef S_ISDIR
# define S_ISDIR(s) 0
#endif
      /* If we're dereferencing symlinks and we're about to chdir through
	 a symlink, remember the current directory so we can return to it
	 later.  In other cases, chdir ("..") works fine.  */
      through_symlink = (xstat == stat
			 && lstat (ent, &e_buf) == 0
			 && S_ISLNK (e_buf.st_mode));
      if (through_symlink)
	if (save_cwd (&cwd))
	  exit (1);

      if (chdir (ent) < 0)
	{
	  error (0, errno, _("cannot change to directory %s"), path->text);
	  exit_status = 1;
	  return 0;
	}

      errno = 0;
      name_space = savedir (".", stat_buf.st_size);
      if (name_space == NULL)
	{
	  if (errno)
	    {
	      error (0, errno, "%s", path->text);
	      if (through_symlink)
		{
		  if (restore_cwd (&cwd, "..", path->text))
		    exit (1);
		  free_cwd (&cwd);
		}
	      else if (chdir ("..") < 0)
		  error (1, errno, _("cannot change to `..' from directory %s"),
			 path->text);
	      exit_status = 1;
	      return 0;
	    }
	  else
	    error (1, 0, _("virtual memory exhausted"));
	}

      /* Remember the current path.  */

      str_concatc (path, "/");
      pathlen = path->length;

      namep = name_space;
      while (*namep != 0)
	{
	  str_concatc (path, namep);

	  size += count_entry (namep, 0, dir_dev);

	  str_trunc (path, pathlen);
	  namep += strlen (namep) + 1;
	}
      free (name_space);
      if (through_symlink)
	{
	  restore_cwd (&cwd, "..", path->text);
	  free_cwd (&cwd);
	}
      else if (chdir ("..") < 0)
        error (1, errno,
	       _("cannot change to `..' from directory %s"), path->text);

      str_trunc (path, pathlen - 1); /* Remove the "/" we added.  */
      if (!opt_summarize_only || top)
	{
	  if (opt_human_readable)
	    {
	      char buf[LONGEST_HUMAN_READABLE + 1];
	      printf("%s\t%s\n",
		     human_readable (size, buf, LONGEST_HUMAN_READABLE + 1),
		     path->length > 0 ? path->text : "/");
	    }
	  else
	    {
	      printf ("%ld\t%s\n", (output_size == size_bytes
				    ? size
				    : convert_blocks (size, output_size)),
		      path->length > 0 ? path->text : "/");
	    }
	  fflush (stdout);
	}
      return opt_separate_dirs ? 0 : size;
    }
  else if (opt_all || top)
    {
      /* FIXME: make this an option.  */
      int print_only_dir_size = 0;
      if (!print_only_dir_size)
	{
	  if (opt_human_readable)
	    {
	      char buf[LONGEST_HUMAN_READABLE + 1];
	      printf("%s\t%s\n",
		     human_readable (size, buf, LONGEST_HUMAN_READABLE + 1),
		     path->length > 0 ? path->text : "/");
	    }
	  else
	    {
	      printf ("%ld\t%s\n", output_size == size_bytes ? size
		      : convert_blocks (size, output_size),
		      path->text);
	    }
	  fflush (stdout);
	}
    }

  return size;
}
コード例 #16
0
ファイル: du.c プロジェクト: redwinner/unxutils
static void
du_files (char **files)
{
  struct saved_cwd cwd;
  ino_t initial_ino;		/* Initial directory's inode. */
  dev_t initial_dev;		/* Initial directory's device. */
  int i;			/* Index in FILES. */

  if (save_cwd (&cwd))
    exit (1);

  /* Remember the inode and device number of the current directory.  */
  if (stat (".", &stat_buf))
    error (1, errno, _("current directory"));
  initial_ino = stat_buf.st_ino;
  initial_dev = stat_buf.st_dev;

  for (i = 0; files[i]; i++)
    {
      char *arg;
      int s;

      arg = files[i];

      /* Delete final slash in the argument, unless the slash is alone.  */
      s = strlen (arg) - 1;
      if (s != 0)
	{
	  if (arg[s] == '\\')
	    arg[s] = 0;

	  str_copyc (path, arg);
	}
      else if (arg[0] == '\\')
	str_trunc (path, 0);	/* Null path for root directory.  */
      else
	str_copyc (path, arg);

      if (!opt_combined_arguments)
	hash_reset ();

      count_entry (arg, 1, 0);

      /* chdir if `count_entry' has changed the working directory.  */
      if (stat (".", &stat_buf))
	error (1, errno, ".");
      if (stat_buf.st_ino != initial_ino || stat_buf.st_dev != initial_dev)
	{
	  if (restore_cwd (&cwd, _("starting directory"), NULL))
	    exit (1);
	}
    }

  if (opt_combined_arguments)
    {
      if (opt_human_readable)
	{
	  char buf[LONGEST_HUMAN_READABLE + 1];
	  printf("%s\ttotal\n", human_readable (tot_size, buf,
						LONGEST_HUMAN_READABLE + 1));
	}
      else
	{
	  printf (_("%ld\ttotal\n"), output_size == size_bytes ? tot_size
		  : convert_blocks (tot_size, output_size == size_kilobytes));
	}
      fflush (stdout);
    }

  free_cwd (&cwd);
}
コード例 #17
0
ファイル: print.c プロジェクト: hnw/iOS-FindCmd
static void
do_fprintf (struct format_val *dest,
            struct segment *segment,
            const char *pathname,
            const struct stat *stat_buf)
{
  char hbuf[LONGEST_HUMAN_READABLE + 1];
  const char *cp;

  switch (segment->segkind)
    {
    case KIND_PLAIN:    /* Plain text string (no % conversion). */
      /* trusted */
      checked_fwrite(segment->text, 1, segment->text_len, dest);
      break;

    case KIND_STOP:             /* Terminate argument and flush output. */
      /* trusted */
      checked_fwrite (segment->text, 1, segment->text_len, dest);
      checked_fflush (dest);
      break;

    case KIND_FORMAT:
      switch (segment->format_char[0])
        {
        case 'a':               /* atime in `ctime' format. */
          /* UNTRUSTED, probably unexploitable */
          checked_fprintf (dest, segment->text, ctime_format (get_stat_atime (stat_buf)));
          break;
        case 'b':               /* size in 512-byte blocks */
          /* UNTRUSTED, probably unexploitable */
          checked_fprintf (dest, segment->text,
                           human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
                                           hbuf, human_ceiling,
                                           ST_NBLOCKSIZE, 512));
          break;
        case 'c':               /* ctime in `ctime' format */
          /* UNTRUSTED, probably unexploitable */
          checked_fprintf (dest, segment->text, ctime_format (get_stat_ctime (stat_buf)));
          break;
        case 'd':               /* depth in search tree */
          /* UNTRUSTED, probably unexploitable */
          checked_fprintf (dest, segment->text, state.curdepth);
          break;
        case 'D':               /* Device on which file exists (stat.st_dev) */
          /* trusted */
          checked_fprintf (dest, segment->text,
                           human_readable ((uintmax_t) stat_buf->st_dev, hbuf,
                                           human_ceiling, 1, 1));
          break;
        case 'f':               /* base name of path */
          /* sanitised */
          {
            char *base = base_name (pathname);
            checked_print_quoted (dest, segment->text, base);
            free (base);
          }
          break;
        case 'F':               /* file system type */
          /* trusted */
          checked_print_quoted (dest, segment->text, filesystem_type (stat_buf, pathname));
          break;
        case 'g':               /* group name */
          /* trusted */
          /* (well, the actual group is selected by the user but
           * its name was selected by the system administrator)
           */
          {
            struct group *g;

            g = getgrgid (stat_buf->st_gid);
            if (g)
              {
                segment->text[segment->text_len] = 's';
                checked_fprintf (dest, segment->text, g->gr_name);
                break;
              }
            else
              {
                /* Do nothing. */
                /*FALLTHROUGH*/
              }
          }
          /*FALLTHROUGH*/ /*...sometimes, so 'G' case.*/

        case 'G':               /* GID number */
          /* UNTRUSTED, probably unexploitable */
          checked_fprintf (dest, segment->text,
                           human_readable ((uintmax_t) stat_buf->st_gid, hbuf,
                                           human_ceiling, 1, 1));
          break;
        case 'h':               /* leading directories part of path */
          /* sanitised */
          {
            cp = strrchr (pathname, '/');
            if (cp == NULL)     /* No leading directories. */
              {
                /* If there is no slash in the pathname, we still
                 * print the string because it contains characters
                 * other than just '%s'.  The %h expands to ".".
                 */
                checked_print_quoted (dest, segment->text, ".");
              }
            else
              {
                char *s = strdup (pathname);
                s[cp - pathname] = 0;
                checked_print_quoted (dest, segment->text, s);
                free (s);
              }
          }
          break;

        case 'H':               /* ARGV element file was found under */
          /* trusted */
          {
            char *s = xmalloc (state.starting_path_length+1);
            memcpy (s, pathname, state.starting_path_length);
            s[state.starting_path_length] = 0;
            checked_fprintf (dest, segment->text, s);
            free (s);
          }
          break;

        case 'i':               /* inode number */
          /* UNTRUSTED, but not exploitable I think */
          /* POSIX does not guarantee that ino_t is unsigned or even
           * integral (except as an XSI extension), but we'll work on
           * fixing that if we ever get a report of a system where
           * ino_t is indeed a signed integral type or a non-integral
           * arithmetic type. */
          checked_fprintf (dest, segment->text,
                           human_readable ((uintmax_t) stat_buf->st_ino, hbuf,
                                           human_ceiling,
                                           1, 1));
          break;
        case 'k':               /* size in 1K blocks */
          /* UNTRUSTED, but not exploitable I think */
          checked_fprintf (dest, segment->text,
                           human_readable ((uintmax_t) ST_NBLOCKS (*stat_buf),
                                           hbuf, human_ceiling,
                                           ST_NBLOCKSIZE, 1024));
          break;
        case 'l':               /* object of symlink */
          /* sanitised */
#ifdef S_ISLNK
          {
            char *linkname = 0;

            if (S_ISLNK (stat_buf->st_mode))
              {
                linkname = areadlinkat (state.cwd_dir_fd, state.rel_pathname);
                if (linkname == NULL)
                  {
                    nonfatal_target_file_error (errno, pathname);
                    state.exit_status = 1;
                  }
              }
            if (linkname)
              {
                checked_print_quoted (dest, segment->text, linkname);
              }
            else
              {
                /* We still need to honour the field width etc., so this is
                 * not a no-op.
                 */
                checked_print_quoted (dest, segment->text, "");
              }
            free (linkname);
          }
#endif                          /* S_ISLNK */
          break;

        case 'M':               /* mode as 10 chars (eg., "-rwxr-x--x" */
          /* UNTRUSTED, probably unexploitable */
          {
            char modestring[16] ;
            filemodestring (stat_buf, modestring);
            modestring[10] = '\0';
            checked_fprintf (dest, segment->text, modestring);
          }
          break;

        case 'm':               /* mode as octal number (perms only) */
          /* UNTRUSTED, probably unexploitable */
          {
            /* Output the mode portably using the traditional numbers,
               even if the host unwisely uses some other numbering
               scheme.  But help the compiler in the common case where
               the host uses the traditional numbering scheme.  */
            mode_t m = stat_buf->st_mode;
            bool traditional_numbering_scheme =
              (S_ISUID == 04000 && S_ISGID == 02000 && S_ISVTX == 01000
               && S_IRUSR == 00400 && S_IWUSR == 00200 && S_IXUSR == 00100
               && S_IRGRP == 00040 && S_IWGRP == 00020 && S_IXGRP == 00010
               && S_IROTH == 00004 && S_IWOTH == 00002 && S_IXOTH == 00001);
            checked_fprintf (dest, segment->text,
                     (traditional_numbering_scheme
                      ? m & MODE_ALL
                      : ((m & S_ISUID ? 04000 : 0)
                         | (m & S_ISGID ? 02000 : 0)
                         | (m & S_ISVTX ? 01000 : 0)
                         | (m & S_IRUSR ? 00400 : 0)
                         | (m & S_IWUSR ? 00200 : 0)
                         | (m & S_IXUSR ? 00100 : 0)
                         | (m & S_IRGRP ? 00040 : 0)
                         | (m & S_IWGRP ? 00020 : 0)
                         | (m & S_IXGRP ? 00010 : 0)
                         | (m & S_IROTH ? 00004 : 0)
                         | (m & S_IWOTH ? 00002 : 0)
                         | (m & S_IXOTH ? 00001 : 0))));
          }
          break;

        case 'n':               /* number of links */
          /* UNTRUSTED, probably unexploitable */
          checked_fprintf (dest, segment->text,
                   human_readable ((uintmax_t) stat_buf->st_nlink,
                                   hbuf,
                                   human_ceiling,
                                   1, 1));
          break;

        case 'p':               /* pathname */
          /* sanitised */
          checked_print_quoted (dest, segment->text, pathname);
          break;

        case 'P':               /* pathname with ARGV element stripped */
          /* sanitised */
          if (state.curdepth > 0)
            {
              cp = pathname + state.starting_path_length;
              if (*cp == '/')
                /* Move past the slash between the ARGV element
                   and the rest of the pathname.  But if the ARGV element
                   ends in a slash, we didn't add another, so we've
                   already skipped past it.  */
                cp++;
            }
          else
            {
              cp = "";
            }
          checked_print_quoted (dest, segment->text, cp);
          break;

        case 's':               /* size in bytes */
          /* UNTRUSTED, probably unexploitable */
          checked_fprintf (dest, segment->text,
                   human_readable ((uintmax_t) stat_buf->st_size,
                                   hbuf, human_ceiling, 1, 1));
          break;

        case 'S':               /* sparseness */
          /* UNTRUSTED, probably unexploitable */
          checked_fprintf (dest, segment->text, file_sparseness (stat_buf));
          break;

        case 't':               /* mtime in `ctime' format */
          /* UNTRUSTED, probably unexploitable */
          checked_fprintf (dest, segment->text,
                           ctime_format (get_stat_mtime (stat_buf)));
          break;

        case 'u':               /* user name */
          /* trusted */
          /* (well, the actual user is selected by the user on systems
           * where chown is not restricted, but the user name was
           * selected by the system administrator)
           */
          {
            struct passwd *p;

            p = getpwuid (stat_buf->st_uid);
            if (p)
              {
                segment->text[segment->text_len] = 's';
                checked_fprintf (dest, segment->text, p->pw_name);
                break;
              }
            /* else fallthru */
          }
          /* FALLTHROUGH*/ /* .. to case U */

        case 'U':               /* UID number */
          /* UNTRUSTED, probably unexploitable */
          checked_fprintf (dest, segment->text,
                           human_readable ((uintmax_t) stat_buf->st_uid, hbuf,
                                           human_ceiling, 1, 1));
          break;

          /* %Y: type of file system entry like `ls -l`:
           *     (d,-,l,s,p,b,c,n) n=nonexistent (symlink)
           */
        case 'Y':               /* in case of symlink */
          /* trusted */
          {
#ifdef S_ISLNK
            if (S_ISLNK (stat_buf->st_mode))
              {
                struct stat sbuf;
                /* If we would normally follow links, do not do so.
                 * If we would normally not follow links, do so.
                 */
                if ((following_links () ? optionp_stat : optionl_stat)
                    (state.rel_pathname, &sbuf) != 0)
                  {
                    if ( errno == ENOENT )
                      {
                        checked_fprintf (dest, segment->text, "N");
                        break;
                      }
                    else if ( errno == ELOOP )
                      {
                        checked_fprintf (dest, segment->text, "L");
                        break;
                      }
                    else
                      {
                        checked_fprintf (dest, segment->text, "?");
                        error (0, errno, "%s",
                               safely_quote_err_filename (0, pathname));
                        /* exit_status = 1;
                           return ; */
                        break;
                      }
                  }
                checked_fprintf (dest, segment->text,
                                 mode_to_filetype (sbuf.st_mode & S_IFMT));
              }
#endif /* S_ISLNK */
            else
              {
                checked_fprintf (dest, segment->text,
                                 mode_to_filetype (stat_buf->st_mode & S_IFMT));
              }
          }
          break;

        case 'y':
          /* trusted */
          {
            checked_fprintf (dest, segment->text,
                             mode_to_filetype (stat_buf->st_mode & S_IFMT));
          }
          break;

        case 'Z':               /* SELinux security context */
          {
            security_context_t scontext;
            int rv = (*options.x_getfilecon) (state.cwd_dir_fd, state.rel_pathname,
                                              &scontext);
            if (rv < 0)
              {
                /* If getfilecon fails, there will in the general case
                   still be some text to print.   We just make %Z expand
                   to an empty string. */
                checked_fprintf (dest, segment->text, "");

                error (0, errno, _("getfilecon failed: %s"),
                    safely_quote_err_filename (0, pathname));
                state.exit_status = 1;
              }
            else
              {
                checked_fprintf (dest, segment->text, scontext);
                freecon (scontext);
              }
          }
          break;

        case 0:
        case '%':
          checked_fprintf (dest, segment->text);
          break;
        }
      /* end of KIND_FORMAT case */
      break;
    }
}
コード例 #18
0
ファイル: print.c プロジェクト: hnw/iOS-FindCmd
/* Return a static string formatting the time WHEN according to the
 * strftime format character KIND.
 *
 * This function contains a number of assertions.  These look like
 * runtime checks of the results of computations, which would be a
 * problem since external events should not be tested for with
 * "assert" (instead you should use "if").  However, they are not
 * really runtime checks.  The assertions actually exist to verify
 * that the various buffers are correctly sized.
 */
static char *
format_date (struct timespec ts, int kind)
{
  /* In theory, we use an extra 10 characters for 9 digits of
   * nanoseconds and 1 for the decimal point.  However, the real
   * world is more complex than that.
   *
   * For example, some systems return junk in the tv_nsec part of
   * st_birthtime.  An example of this is the NetBSD-4.0-RELENG kernel
   * (at Sat Mar 24 18:46:46 2007) running a NetBSD-3.1-RELEASE
   * runtime and examining files on an msdos filesytem.  So for that
   * reason we set NS_BUF_LEN to 32, which is simply "long enough" as
   * opposed to "exactly the right size".  Note that the behaviour of
   * NetBSD appears to be a result of the use of uninitialized data,
   * as it's not 100% reproducible (more like 25%).
   */
  enum {
    NS_BUF_LEN = 32,
    DATE_LEN_PERCENT_APLUS=21   /* length of result of %A+ (it's longer than %c)*/
  };
  static char buf[128u+10u + MAX(DATE_LEN_PERCENT_APLUS,
                            MAX (LONGEST_HUMAN_READABLE + 2, NS_BUF_LEN+64+200))];
  char ns_buf[NS_BUF_LEN]; /* -.9999999990 (- sign can happen!)*/
  int  charsprinted, need_ns_suffix;
  struct tm *tm;
  char fmt[6];

  /* human_readable() assumes we pass a buffer which is at least as
   * long as LONGEST_HUMAN_READABLE.  We use an assertion here to
   * ensure that no nasty unsigned overflow happened in our calculation
   * of the size of buf.  Do the assertion here rather than in the
   * code for %@ so that we find the problem quickly if it exists.  If
   * you want to submit a patch to move this into the if statement, go
   * ahead, I'll apply it.  But include performance timings
   * demonstrating that the performance difference is actually
   * measurable.
   */
  verify (sizeof (buf) >= LONGEST_HUMAN_READABLE);

  charsprinted = 0;
  need_ns_suffix = 0;

  /* Format the main part of the time. */
  if (kind == '+')
    {
      strcpy (fmt, "%F+%T");
      need_ns_suffix = 1;
    }
  else
    {
      fmt[0] = '%';
      fmt[1] = kind;
      fmt[2] = '\0';

      /* %a, %c, and %t are handled in ctime_format() */
      switch (kind)
        {
        case 'S':
        case 'T':
        case 'X':
        case '@':
          need_ns_suffix = 1;
          break;
        default:
          need_ns_suffix = 0;
          break;
        }
    }

  if (need_ns_suffix)
    {
      /* Format the nanoseconds part.  Leave a trailing zero to
       * discourage people from writing scripts which extract the
       * fractional part of the timestamp by using column offsets.
       * The reason for discouraging this is that in the future, the
       * granularity may not be nanoseconds.
       */
      charsprinted = snprintf (ns_buf, NS_BUF_LEN, ".%09ld0", (long int)ts.tv_nsec);
      assert (charsprinted < NS_BUF_LEN);
    }
  else
    {
      charsprinted = 0;
      ns_buf[0] = 0;
    }

  if (kind != '@')
    {
      tm = localtime (&ts.tv_sec);
      if (tm)
        {
          char *s = do_time_format (fmt, tm, ns_buf, charsprinted);
          if (s)
            return s;
        }
    }

  /* If we get to here, either the format was %@, or we have fallen back to it
   * because strftime failed.
   */
  if (1)
    {
      uintmax_t w = ts.tv_sec;
      size_t used, len, remaining;

      /* XXX: note that we are negating an unsigned type which is the
       * widest possible unsigned type.
       */
      char *p = human_readable (ts.tv_sec < 0 ? -w : w, buf + 1,
                                human_ceiling, 1, 1);
      assert (p > buf);
      assert (p < (buf + (sizeof buf)));
      if (ts.tv_sec < 0)
        *--p = '-'; /* XXX: Ugh, relying on internal details of human_readable(). */

      /* Add the nanoseconds part.  Because we cannot enforce a
       * particlar implementation of human_readable, we cannot assume
       * any particular value for (p-buf).  So we need to be careful
       * that there is enough space remaining in the buffer.
       */
      if (need_ns_suffix)
        {
          len = strlen (p);
          used = (p-buf) + len; /* Offset into buf of current end */
          assert (sizeof buf > used); /* Ensure we can perform subtraction safely. */
          remaining = sizeof buf - used - 1u; /* allow space for NUL */

          if (strlen (ns_buf) >= remaining)
            {
              error (0, 0,
                     "charsprinted=%ld but remaining=%lu: ns_buf=%s",
                     (long)charsprinted, (unsigned long)remaining, ns_buf);
            }
          assert (strlen (ns_buf) < remaining);
          strcat (p, ns_buf);
        }
      return p;
    }
}