Exemplo n.º 1
0
void do_flash(transport_t *trans, const char *pname, const char *fname)
{
    int64_t sz64;
    void *data;
    int64_t limit;

    sz64 = file_size(fname);
    limit = get_sparse_limit(trans, sz64);
    if (limit) {
        struct sparse_file **s = load_sparse_files(fname, limit);
        if (s == NULL) {
            die("cannot sparse load '%s'\n", fname);
        }
        while (*s) {
            sz64 = sparse_file_len(*s, true, false);
            fb_queue_flash_sparse(pname, *s++, sz64);
        }
    } else {
        unsigned int sz;
        data = load_file(fname, &sz);
        if (data == 0) die("cannot load '%s': %s\n", fname, strerror(errno));
        fb_queue_flash(pname, data, sz);
    }
}
Exemplo n.º 2
0
static char *load(const char *filename) {
    FILE *f;
    char *b;
    size_t s;
    size_t r;
    s = file_size (filename);
    b = malloc (s+1);
    if (!b) {
        perror ("malloc");
        exit (1);
    }
    f = fopen (filename, "r");
    if (f == NULL) {
        perror ("fopen");
        exit (1);
    }
    r = fread (b, s, 1, f);
    if (r != 1) {
        perror ("fread");
        exit (1);
    }
    b[s] = '\0';
    return b;
}
Exemplo n.º 3
0
Arquivo: _cat.c Projeto: ehershey/pd
int cmd_cat(string str) {
    string tmp;
    int max, a=0;

    if(!str) return notify_fail("Usage: <cat [file]>\n");
    str = resolv_path((string)this_player()->get_path(), str);
    seteuid(geteuid(previous_object()));
//    if(!(max = sizeof(lines=explode(read_file(str), "\n")))) 
//     return notify_fail("File not found.\n");
// if(!(tmp = read_file(str))) return notify_fail("File not found.\n");
  if ((max = file_size(str)) < 0) return notify_fail("File not found.\n");
     for (a = 0; a < max; a += 1025)
     {
        if( max - a < 1024 )
            tmp = read_bytes(str, a, max - a);
        else
            tmp = read_bytes(str, a, 1024);
        write(tmp);
     } 
    seteuid(getuid());
    IMSTAT_D->add_stat(this_player()->query_name(), "cat", time());

    return 1;
}
Exemplo n.º 4
0
 */
gorgonError gorgonLoadAnimation(gorgonAnimation *animation,char *filename)
{
	FILE	*file;
	long	size = file_size(filename);
	char	*data;
	int	erro;
	int	ofs=0;
	if(size>0)
	{
		file= fopen(filename,"rb");
		data= (char *)malloc(size);
		if(data!=NULL)
		{
			fread(&(data[0]),1,size, file);
			fclose(file);
			erro=gorgonLoadAnimation_fm(animation,data,&ofs);
			free(data);			
			if(erro!=GORGON_OK) return erro;
			return GORGON_OK;
		}
		return GORGON_MEMORY_ERROR;
	}
	return GORGON_FILE_NOT_FOUND;
Exemplo n.º 5
0
Arquivo: manual.c Projeto: xxx/cdlib
nomask int
find_source(string docfile, string argv)
{
    string          docs,
                    str,
                    src;
    int             line;

    if (file_size(docfile) < 0)
	return 0;

    docs = read_file(docfile);
    if (sscanf(docs, "%d:%s %s", line, src, str) == 3)
    {
	write("File: " + src + " Line: " + line + "\n\n");
	if (argv == "-s")
	{
	    this_player()->more(src, line);
	    return 1;
	}

	if (SECURITY->query_wiz_rank(this_interactive()->
	    query_real_name()) < WIZ_NORMAL)
	{
	    write("Only true wizards can use the -e option.\n");
	}
	else
	{
	    ed(src);
	}

	return 1;
    }

    return 0;
}
Exemplo n.º 6
0
int main(int argc, char *argv[])
{
        if(argc != 2) {
                fprintf(stderr, "One file, please\n");
                exit(1);
        }

        UM_state curr_state = create_UM();
        char *filename = argv[1];
        int filesize = file_size(filename);
        FILE *file = fopen(filename, "rb");

        if (file == NULL) {
                fprintf(stderr, "Can't open file\n");
                exit(1);
        }

        load(file, curr_state, filesize);
        execute(curr_state);
        clean_up(curr_state);
        fclose(file);

        return 0;
}
Exemplo n.º 7
0
bool copy_file(const std::string& source, const std::string& dest)
{
    if (!file_exists(source))
        return false;

    // if file is larger than 128 MB, show copy progress
    auto size = file_size(source);
    uint64_t max_size = 1024UL * 1024UL * 1024UL * 128UL;
    if (size > max_size)
    {
        printing::progress prog{"Copying file ", size};
        std::ifstream source_file{source, std::ios::binary};
        std::ofstream dest_file{dest, std::ios::binary};
        std::streamsize buf_size = 1024UL * 1024UL * 32UL; // 32 MB buffer
        uint64_t total_processed = 0;
        std::vector<char> buffer(static_cast<std::size_t>(buf_size));
        while (source_file)
        {
            source_file.read(buffer.data(), buf_size);
            auto processed = source_file.gcount();
            total_processed += static_cast<std::size_t>(processed);
            dest_file.write(buffer.data(), processed);
            prog(total_processed);
        }
        prog.end();
    }
    // otherwise, copy the file normally
    else
    {
        std::ifstream source_file{source, std::ios::binary};
        std::ofstream dest_file{dest, std::ios::binary};
        dest_file << source_file.rdbuf();
    }

    return true;
}
Exemplo n.º 8
0
file_cache::file::file(const std::string& name, bool read_from_disk) {
    path p(name);
    if (exists(p)) {
        if (is_regular_file(p)) {
            m_size = file_size(p);
            m_time = last_write_time(p);
            if (read_from_disk) {
                std::ifstream is(name, std::ifstream::binary);
                if (is) {
                    m_data.reserve(m_size);
                    std::copy(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(),
                              std::back_inserter(m_data));
                    m_good = true;
                } else {
                    log_err("can't open file " << name);
                }
            }
        } else {
            log_err(name << " is no file");
        }
    } else {
        log_err(name << " does not exists");
    }
}
Exemplo n.º 9
0
char *
loadLocalizableStrings(
    char *name
)
{
    char buf[256], *config;
    register int count, fd;
    
    sprintf(buf, LOCALIZABLE, name, Language);
    if ((fd = open(buf,0)) < 0) {
	sprintf(buf, LOCALIZABLE, name, "English");
	if ((fd = open(buf,0)) < 0)
	    return 0;
    }
    count = file_size(fd);
    config = malloc(count);
    count = read(fd, config, count);
    close(fd);
    if (count <= 0) {
	free(config);
	return 0;
    }
    return config;
}
Exemplo n.º 10
0
void init_string_hash (void) {
  string_storage = cmalloc(string_storage_length);
  string_storage_table =
    (size_t*)cmalloc(STRING_STORAGE_TABLE_LENGTH * sizeof(size_t));

#ifdef USAGE
  printf("Allocating %dM for string storage\n", meg(string_storage_length));
  printf("Allocating %dM for string hash table\n",
	 meg(STRING_STORAGE_TABLE_LENGTH * sizeof(size_t)));
#endif

  if ((string_storage_file = open64(index_file_name(STRING_STORAGE_FILE),
				    O_RDWR|O_CREAT, 0644)) == -1) {
    fprintf(stderr, "Couldn't open %s\n", 
	    index_file_name(STRING_STORAGE_FILE));
    merror("Opening the string storage file.");
  }

  if (file_size(string_storage_file) == 0) {
    write_from(string_storage_file, "@@@", 4);
    next_string = 4;
  } else 
    smart_populate_string_table_from_file(string_storage_file);
}
Exemplo n.º 11
0
mixed get_lines( string file_name )
{
  string file;

  file_name = evaluate_path( file_name );
  switch( file_size( file_name ) ) 
  {
    case -2: { write( file_name + " is a directory.\n" ); return 0; }
    case -1: { write( file_name + " is not a file.\n" ); return 0; }
  }
  if( !master()-> valid_read( file_name,
    previous_object(), "diff" ) )
  {
    write( file_name + " : Permission denied.\n" );
    return 0;
  }
  file = read_file( file_name );
  if( !file ) 
  {
    write( file_name + " is empty.\n" );
    return 0;
  }
  return explode( file, "\n" );
}
Exemplo n.º 12
0
int translate_define(string define, string includefile) {
  string tmpdir = "/adm/tmp/translate/";
  string file;

  // can't have | in filenames
  define = replace_string(define, "|", "+");
  // remove spaces too
  define = replace_string(define, " ", "");
  
  file = tmpdir+includefile+"."+define+".c";

  if (file_size(file) == -1) {
    seteuid(UID_ROOT);
    write_file(file,
      "#include <"+includefile+">\n"
      "int translate_this() {\n"
      "  return "+define+";\n"
      "}"
    );
    seteuid(geteuid(previous_object()));
  }

  return file->translate_this();
}
Exemplo n.º 13
0
static void
get_keys (void)
{
  int search = 0;
  int c, quit = 1;
  uint64_t size1 = 0;

  if (!logger->piping)
    size1 = file_size (conf.ifile);

  while (quit) {
    c = wgetch (stdscr);
    switch (c) {
    case 'q':  /* quit */
      if (!gscroll.expanded) {
        quit = 0;
        break;
      }
      collapse_current_module ();
      break;
    case KEY_F (1):
    case '?':
    case 'h':
      load_help_popup (main_win);
      render_screens ();
      break;
    case 49:   /* 1 */
      /* reset expanded module */
      set_module_to (&gscroll, VISITORS);
      break;
    case 50:   /* 2 */
      /* reset expanded module */
      set_module_to (&gscroll, REQUESTS);
      break;
    case 51:   /* 3 */
      /* reset expanded module */
      set_module_to (&gscroll, REQUESTS_STATIC);
      break;
    case 52:   /* 4 */
      /* reset expanded module */
      set_module_to (&gscroll, NOT_FOUND);
      break;
    case 53:   /* 5 */
      /* reset expanded module */
      set_module_to (&gscroll, HOSTS);
      break;
    case 54:   /* 6 */
      /* reset expanded module */
      set_module_to (&gscroll, OS);
      break;
    case 55:   /* 7 */
      /* reset expanded module */
      set_module_to (&gscroll, BROWSERS);
      break;
    case 56:   /* 8 */
      /* reset expanded module */
      set_module_to (&gscroll, VISIT_TIMES);
      break;
    case 57:   /* 9 */
      /* reset expanded module */
      set_module_to (&gscroll, REFERRERS);
      break;
    case 48:   /* 0 */
      /* reset expanded module */
      set_module_to (&gscroll, REFERRING_SITES);
      break;
    case 33:   /* shift + 1 */
      /* reset expanded module */
      set_module_to (&gscroll, KEYPHRASES);
      break;
    case 34:   /* Shift + 2 */
      /* reset expanded module */
#ifdef HAVE_LIBGEOIP
      set_module_to (&gscroll, GEO_LOCATION);
#else
      set_module_to (&gscroll, STATUS_CODES);
#endif
      break;
#ifdef HAVE_LIBGEOIP
    case 35:   /* Shift + 3 */
      /* reset expanded module */
      set_module_to (&gscroll, STATUS_CODES);
      break;
#endif
    case 9:    /* TAB */
      /* reset expanded module */
      collapse_current_module ();
      if (next_module () == 0)
        render_screens ();
      break;
    case 353:  /* Shift TAB */
      /* reset expanded module */
      collapse_current_module ();
      if (previous_module () == 0)
        render_screens ();
      break;
    case 'g':  /* g = top */
      scroll_to_first_line ();
      display_content (main_win, logger, dash, &gscroll);
      break;
    case 'G':  /* G = down */
      scroll_to_last_line ();
      display_content (main_win, logger, dash, &gscroll);
      break;
      /* expand dashboard module */
    case KEY_RIGHT:
    case 0x0a:
    case 0x0d:
    case 32:   /* ENTER */
    case 79:   /* o */
    case 111:  /* O */
    case KEY_ENTER:
      expand_current_module ();
      display_content (main_win, logger, dash, &gscroll);
      break;
    case KEY_DOWN:     /* scroll main dashboard */
      if ((gscroll.dash + real_size_y) < (unsigned) dash->total_alloc) {
        gscroll.dash++;
        display_content (main_win, logger, dash, &gscroll);
      }
      break;
    case KEY_MOUSE:    /* handles mouse events */
      expand_on_mouse_click ();
      break;
    case 106:  /* j - DOWN expanded module */
      scroll_down_expanded_module ();
      display_content (main_win, logger, dash, &gscroll);
      break;
      /* scroll up main_win */
    case KEY_UP:
      if (gscroll.dash > 0) {
        scroll_up_dashboard ();
        display_content (main_win, logger, dash, &gscroll);
      }
      break;
    case 2:    /* ^ b - page up */
    case 339:  /* ^ PG UP */
      page_up_module ();
      display_content (main_win, logger, dash, &gscroll);
      break;
    case 6:    /* ^ f - page down */
    case 338:  /* ^ PG DOWN */
      page_down_module ();
      display_content (main_win, logger, dash, &gscroll);
      break;
    case 107:  /* k - UP expanded module */
      scroll_up_expanded_module ();
      display_content (main_win, logger, dash, &gscroll);
      break;
    case 'n':
      search_next_match (search);
      break;
    case '/':
      render_search_dialog (search);
      break;
    case 99:   /* c */
      if (conf.no_color)
        break;
      load_schemes_win (main_win);
      free_dashboard (dash);
      allocate_data ();
      render_screens ();
      break;
    case 115:  /* s */
      render_sort_dialog ();
      break;
    case 269:
    case KEY_RESIZE:
      window_resize ();
      break;
    default:
      perform_tail_follow (&size1);
      break;
    }
  }
}
Exemplo n.º 14
0
//Compress a file
DWORD WINAPI compress_one_file(Params *pDataArray)
{    
    //Open struct and set variables
	char *infilename = new char [MAX_PATH];             //Get input file name
	strcpy_s(infilename, MAX_PATH, pDataArray -> para_infilename);
    char *outfilename = new char [MAX_PATH];             //Get output file name
	strcpy_s(outfilename, MAX_PATH, pDataArray -> para_outfilename);
    bool UseAppend = pDataArray -> para_UseAppend;      //G et whether to append or write
	LPRDATA rdPtr = pDataArray -> para_rdPtr;           //Get rdPtr
	delete pDataArray;                                  //Container is expendable 
	
	char * WriteType = "wb9";        //User is using write (overwriting)
	if (UseAppend) WriteType = "ab9"; //User is using append
					
	//Check input file size - no handles to close
    if (FileSizeCheck(infilename, rdPtr)) {Terminate();}

    //Open handles to both files
    FILE *infile = fopen(infilename, "rb");      //r = read, b = binary
    gzFile outfile = gzopen(outfilename, WriteType); //a = append (or w=write), b = binary, 9 = max compression
	
	//Check handles - HandleCheck() automatically closes handles if invalid
    if (HandleCheck(infile, outfile, rdPtr)) {Terminate();}

    //Declare variables
    unsigned long PreviousOutputSize = 0; //For calculation purposes
    signed int num_read = 0;
    unsigned long total_read = 0;
    ThreadSafe_Start();
    unsigned short tempinbuffersize = rdPtr -> inbuffersize;
    ThreadSafe_End();

	//If using Write, output size should not be included in the calculation later. Otherwise:
	if (UseAppend) PreviousOutputSize = file_size(outfilename); 

    //This makes sure that the buffer is the right size - if too large, set buffer smaller
    if ( file_size(infilename) < tempinbuffersize)
        tempinbuffersize = (unsigned short)file_size(infilename);
    
    //Then declare final variable, the buffer
    char *inbuffer = new char[tempinbuffersize];

    //Iteration through the files
    while ((num_read = fread(inbuffer, 1, tempinbuffersize, infile)) > 0)
    {
        total_read += num_read;
        gzwrite(outfile, inbuffer, num_read);
    }
               
    //Close thread
    fclose(infile);
    gzclose(outfile);
    delete[] inbuffer, infilename, outfilename;

	//Set variables afnter completion
    ThreadSafe_Start();
	unsigned long saveoutfilesize = file_size(outfilename);
	unsigned long saveinfilesize = file_size(infilename);
    rdPtr -> PercentageDifference = ((file_size(outfilename)-PreviousOutputSize)*(1.0/file_size(infilename)))*100.0;
    
	stringstream temp;
    temp <<"Buffer used: "
         << tempinbuffersize
         <<", total bytes read: "
         << file_size(infilename)
         <<", total bytes written: "
         << file_size(outfilename)-PreviousOutputSize
         <<", compression rate: "
         << rdPtr -> PercentageDifference
         <<"%.";
    rdPtr -> returnstring = temp.str();
    temp.flush();
    rdPtr -> LastOutput = outfilename;
    rdPtr -> rRd -> PushEvent(0); 
    ThreadSafe_End();
    return 0;
}
Exemplo n.º 15
0
static void
print_json_summary (FILE * fp, GLog * logger)
{
  long long t = 0LL;
  int total = 0;
  off_t log_size = 0;
  char now[DATE_TIME];

  generate_time ();
  strftime (now, DATE_TIME, "%Y-%m-%d %H:%M:%S", now_tm);

  fprintf (fp, "\t\"%s\": {\n", GENER_ID);

  /* generated date time */
  fprintf (fp, "\t\t\"%s\": \"%s\",\n", OVERALL_DATETIME, now);

  /* total requests */
  total = logger->process;
  fprintf (fp, "\t\t\"%s\": %d,\n", OVERALL_REQ, total);

  /* invalid requests */
  total = logger->invalid;
  fprintf (fp, "\t\t\"%s\": %d,\n", OVERALL_FAILED, total);

  /* generated time */
  t = (long long) end_proc - start_proc;
  fprintf (fp, "\t\t\"%s\": %llu,\n", OVERALL_GENTIME, t);

  /* visitors */
  total = get_ht_size_by_metric (VISITORS, MTRC_UNIQMAP);
  fprintf (fp, "\t\t\"%s\": %d,\n", OVERALL_VISITORS, total);

  /* files */
  total = get_ht_size_by_metric (REQUESTS, MTRC_DATAMAP);
  fprintf (fp, "\t\t\"%s\": %d,\n", OVERALL_FILES, total);

  /* excluded hits */
  total = logger->exclude_ip;
  fprintf (fp, "\t\t\"%s\": %d,\n", OVERALL_EXCL_HITS, total);

  /* referrers */
  total = get_ht_size_by_metric (REFERRERS, MTRC_DATAMAP);
  fprintf (fp, "\t\t\"%s\": %d,\n", OVERALL_REF, total);

  /* not found */
  total = get_ht_size_by_metric (NOT_FOUND, MTRC_DATAMAP);
  fprintf (fp, "\t\t\"%s\": %d,\n", OVERALL_NOTFOUND, total);

  /* static files */
  total = get_ht_size_by_metric (REQUESTS_STATIC, MTRC_DATAMAP);
  fprintf (fp, "\t\t\"%s\": %d,\n", OVERALL_STATIC, total);

  /* log size */
  if (!logger->piping)
    log_size = file_size (conf.ifile);
  fprintf (fp, "\t\t\"%s\": %jd,\n", OVERALL_LOGSIZE, (intmax_t) log_size);

  /* bandwidth */
  fprintf (fp, "\t\t\"%s\": %lld,\n", OVERALL_BANDWIDTH, logger->resp_size);

  /* log path */
  if (conf.ifile == NULL)
    conf.ifile = (char *) "STDIN";
  fprintf (fp, "\t\t\"%s\": \"", OVERALL_LOG);
  escape_json_output (fp, conf.ifile);
  fprintf (fp, "\"\n");

  fprintf (fp, "\t},\n");
}
Exemplo n.º 16
0
int gzipMmap(int do_comp,FILE *in,FILE *out){
	double Start = Time();
	int ifd,ofd;
	int iz,izm;
	unsigned long oz;
	Byte *ia,*iam;
	Byte *oa,*oam;
	int rcode;
	int ioff;
	int ooff;

	ifd = fileno(in);
	ofd = fileno(out);
	if( !file_isreg(ifd) || !file_isreg(ofd) ){
		syslog_ERROR("--- gzipMmap: not reg-file: %d %d\n",ifd,ofd);
		return -1;
	}

	ioff = lseek(ifd,0,1);
	ooff = lseek(ofd,0,1);
	izm = file_size(ifd);
	iz = izm - ioff;
	if( do_comp )
		oz = 1024+iz;
	else	oz = 1024+iz*20;

	iam = (Byte*)mmap(0,izm,PROT_READ,MAP_SHARED,ifd,0);
	if( iam == 0 ){
		syslog_ERROR("--- gzipMmap: can't open in mmap(%d)\n",ifd);
		return -1;
	}
	ia = iam + ioff;

	oa = (Byte*)mmap(0,oz,PROT_READ|PROT_WRITE,MAP_SHARED,ofd,ooff);
	if( oa == 0 ){
		syslog_ERROR("--- gzipMmap: can't open out mmap(%d)\n",ofd);
		munmap(iam,iz);
		return -1;
	}

	lseek(ofd,oz-1,1);
	write(ofd,"",1);
	if( do_comp ){
		/*
		Byte *op = oa;
		*op++ = 0x1F; *op++ = 0x8B; *op++ = 8;
		*op++ = 0; *op++ = 0; *op++ = 0; *op++ = 0;
		*op++ = 0; *op++ = 0; *op++ = 3;
		rcode = compress2(op,&oz,ia,iz,-1);
		if( rcode == 0 ){
			oz += (op - oa);
		}
		*/
		rcode = compress2(oa,&oz,ia,iz,-1);
	}else{
		rcode = uncompress(oa,&oz,ia,iz);
	}

	munmap(iam,izm);
	munmap(oa,oz);

	syslog_ERROR("(%.4f)g%szip/mmap(%d) %d -> %d\n",
		Time()-Start,do_comp?"":"un",rcode,iz,oz);

	if( rcode == 0 ){
		Ftruncate(out,ooff+oz,0);
		fseek(out,0,0);
		if( do_comp )
			return iz;
		else	return oz;
	}
	lseek(ifd,ioff,0);
	lseek(ofd,ooff,0);
	Ftruncate(out,0,1);
	return -1;
}
Exemplo n.º 17
0
void vm_process(VM *vm) {
  int a, b, opcode;
  opcode = vm->image[vm->ip];

  switch(opcode) {
    case VM_NOP:
         break;
    case VM_LIT:
         vm->sp++;
         vm->ip++;
         TOS = vm->image[vm->ip];
         break;
    case VM_DUP:
         vm->sp++;
         vm->data[vm->sp] = NOS;
         break;
    case VM_DROP:
         DROP
         break;
    case VM_SWAP:
         a = TOS;
         TOS = NOS;
         NOS = a;
         break;
    case VM_PUSH:
         vm->rsp++;
         TORS = TOS;
         DROP
         break;
    case VM_POP:
         vm->sp++;
         TOS = TORS;
         vm->rsp--;
         break;
    case VM_CALL:
         vm->ip++;
         vm->rsp++;
         TORS = vm->ip;
         vm->ip = vm->image[vm->ip] - 1;
         if (vm->ip < 0)
           vm->ip = IMAGE_SIZE;
         else {
           if (vm->image[vm->ip+1] == 0)
             vm->ip++;
           if (vm->image[vm->ip+1] == 0)
             vm->ip++;
         }
         break;
    case VM_JUMP:
         vm->ip++;
         vm->ip = vm->image[vm->ip] - 1;
         if (vm->ip < 0)
           vm->ip = IMAGE_SIZE;
         else {
           if (vm->image[vm->ip+1] == 0)
             vm->ip++;
           if (vm->image[vm->ip+1] == 0)
             vm->ip++;
         }
         break;
    case VM_RETURN:
         vm->ip = TORS;
         vm->rsp--;
         break;
    case VM_GT_JUMP:
         vm->ip++;
         if(NOS > TOS)
           vm->ip = vm->image[vm->ip] - 1;
         DROP DROP
         break;
    case VM_LT_JUMP:
         vm->ip++;
         if(NOS < TOS)
           vm->ip = vm->image[vm->ip] - 1;
         DROP DROP
         break;
    case VM_NE_JUMP:
         vm->ip++;
         if(TOS != NOS)
           vm->ip = vm->image[vm->ip] - 1;
         DROP DROP
         break;
    case VM_EQ_JUMP:
         vm->ip++;
         if(TOS == NOS)
           vm->ip = vm->image[vm->ip] - 1;
         DROP DROP
         break;
    case VM_FETCH:
         TOS = vm->image[TOS];
         break;
    case VM_STORE:
         vm->image[TOS] = NOS;
         DROP DROP
         break;
    case VM_ADD:
         NOS += TOS;
         DROP
         break;
    case VM_SUB:
         NOS -= TOS;
         DROP
         break;
    case VM_MUL:
         NOS *= TOS;
         DROP
         break;
    case VM_DIVMOD:
         a = TOS;
         b = NOS;
         TOS = b / a;
         NOS = b % a;
         break;
    case VM_AND:
         a = TOS;
         b = NOS;
         DROP
         TOS = a & b;
         break;
    case VM_OR:
         a = TOS;
         b = NOS;
         DROP
         TOS = a | b;
         break;
    case VM_XOR:
         a = TOS;
         b = NOS;
         DROP
         TOS = a ^ b;
         break;
    case VM_SHL:
         a = TOS;
         b = NOS;
         DROP
         TOS = b << a;
         break;
    case VM_SHR:
         a = TOS;
         b = NOS;
         DROP
         TOS = b >>= a;
         break;
    case VM_ZERO_EXIT:
         if (TOS == 0) {
           DROP
           vm->ip = TORS;
           vm->rsp--;
         }
         break;
    case VM_INC:
         TOS += 1;
         break;
    case VM_DEC:
         TOS -= 1;
         break;
    case VM_IN:
         a = TOS;
         TOS = vm->ports[a];
         vm->ports[a] = 0;
         break;
    case VM_OUT:
         vm->ports[0] = 0;
         vm->ports[TOS] = NOS;
         DROP DROP
         break;
    case VM_WAIT:
         if (vm->ports[0] == 1)
           break;

         /* Input */
         if (vm->ports[0] == 0 && vm->ports[1] == 1) {
           vm->ports[1] = dev_getch();
           vm->ports[0] = 1;
         }

         /* Output (character generator) */
         if (vm->ports[2] == 1) {
           dev_putch(TOS); DROP
           vm->ports[2] = 0;
           vm->ports[0] = 1;
         }

         if (vm->ports[4] != 0) {
           vm->ports[0] = 1;
           switch (vm->ports[4]) {
             case  1: vm_save_image(vm, vm->filename);
                      vm->ports[4] = 0;
                      break;
             case  2: file_add(vm);
                      vm->ports[4] = 0;
                      break;
             case -1: vm->ports[4] = file_handle(vm);
                      break;
             case -2: vm->ports[4] = file_readc(vm);
                      break;
             case -3: vm->ports[4] = file_writec(vm);
                      break;
             case -4: vm->ports[4] = file_closehandle(vm);
                      break;
             case -5: vm->ports[4] = file_getpos(vm);
                      break;
             case -6: vm->ports[4] = file_seek(vm);
                      break;
             case -7: vm->ports[4] = file_size(vm);
                      break;
             default: vm->ports[4] = 0;
           }
         }

         /* Capabilities */
         if (vm->ports[5] != 0) {
           vm->ports[0] = 1;
           switch(vm->ports[5]) {
             case -1:  vm->ports[5] = IMAGE_SIZE;
                       break;
             case -2:  vm->ports[5] = 0;
                       break;
             case -3:  vm->ports[5] = 0;
                       break;
             case -4:  vm->ports[5] = 0;
                       break;
             case -5:  vm->ports[5] = vm->sp;
                       break;
             case -6:  vm->ports[5] = vm->rsp;
                       break;
             case -7:  vm->ports[5] = 0;
                       break;
             case -8:  vm->ports[5] = time(NULL);
                       break;
             case -9:  vm->ports[5] = 0;
                       vm->ip = IMAGE_SIZE;
                       break;
             default:  vm->ports[5] = 0;
           }
         }

         if (vm->ports[8] != 0) {
           vm->ports[0] = 1;
           switch (vm->ports[8]) {
             case -1: rsocket(vm);
                      vm->ports[8] = 0;
                      break;
             case -2: rbind(vm);
                      vm->ports[8] = 0;
                      break;
             case -3: rlisten(vm);
                      vm->ports[8] = 0;
                      break;
             case -4: raccept(vm);
                      vm->ports[8] = 0;
                      break;
             case -5: rclose(vm);
                      vm->ports[8] = 0;
                      break;
             case -6: rsend(vm);
                      vm->ports[8] = 0;
                      break;
             case -7: rrecv(vm);
                      vm->ports[8] = 0;
                      break;
             case -8: rconnect(vm);
                      vm->ports[8] = 0;
                      break;
             default: vm->ports[8] = 0;
           }
           vm->ports[8] = 0;
         }
         break;
    default:
         vm->rsp++;
         TORS = vm->ip;
         vm->ip = vm->image[vm->ip] - 1;

         if (vm->ip < 0)
           vm->ip = IMAGE_SIZE;
         else {
           if (vm->image[vm->ip+1] == 0)
             vm->ip++;
           if (vm->image[vm->ip+1] == 0)
             vm->ip++;
         }
         break;
  }
  vm->ports[3] = 1;
}
Exemplo n.º 18
0
/**
 *  This directive will insert definitions from another file into
 *  the current collection.  If the file name is adorned with
 *  double quotes or angle brackets (as in a C program), then the
 *  include is ignored.
 */
char *
doDir_include(directive_enum_t id, char const * dir, char * scan_next)
{
    static char const * const apzSfx[] = { DIRECT_INC_DEF_SFX, NULL };
    scan_ctx_t * new_ctx;
    size_t     inc_sz;
    char       full_name[ AG_PATH_MAX + 1 ];
    (void)id;

    dir = SPN_WHITESPACE_CHARS(dir);
    /*
     *  Ignore C-style includes.  This allows "C" files to be processed
     *  for their "#define"s.
     */
    if ((*dir == '"') || (*dir == '<'))
        return scan_next;

    if (! SUCCESSFUL(
            find_file(dir, full_name, apzSfx, cctx->scx_fname))) {
        errno = ENOENT;
        fswarn("search for", cctx->scx_fname);
        return scan_next;
    }

    /*
     *  Make sure the specified file is a regular file and we can get
     *  the correct size for it.
     */
    inc_sz = file_size(full_name);
    if (inc_sz == 0)
        return scan_next;

    /*
     *  Get the space for the output data and for context overhead.
     *  This is an extra allocation and copy, but easier than rewriting
     *  'loadData()' for this special context.
     */
    {
        size_t sz = sizeof(scan_ctx_t) + 4 + inc_sz;
        new_ctx = (scan_ctx_t *)AGALOC(sz, "inc def head");

        memset(VOIDP(new_ctx), 0, sz);
        new_ctx->scx_line = 1;
    }

    /*
     *  Link it into the context stack
     */
    cctx->scx_scan     = scan_next;
    new_ctx->scx_next  = cctx;
    cctx               = new_ctx;
    AGDUPSTR(new_ctx->scx_fname, full_name, "def file");

    new_ctx->scx_scan  =
    new_ctx->scx_data  =
    scan_next          = (char *)(new_ctx + 1);

    /*
     *  Read all the data.  Usually in a single read, but loop
     *  in case multiple passes are required.
     */
    {
        FILE * fp = fopen(full_name, "r" FOPEN_TEXT_FLAG);
        char * pz = scan_next;

        if (fp == NULL)
            AG_CANT(DIRECT_INC_CANNOT_OPEN, full_name);

        if (dep_fp != NULL)
            add_source_file(full_name);

        do  {
            size_t rdct = fread(VOIDP(pz), (size_t)1, inc_sz, fp);

            if (rdct == 0)
                AG_CANT(DIRECT_INC_CANNOT_READ, full_name);

            pz += rdct;
            inc_sz -= rdct;
        } while (inc_sz > 0);

        fclose(fp);
        *pz = NUL;
    }

    return scan_next;
}
Exemplo n.º 19
0
Arquivo: csv.c Projeto: 0-T-0/goaccess
/* Output general statistics information. */
static void
print_csv_summary (FILE * fp, GLog * logger)
{
  long long t = 0LL;
  int i = 0, total = 0;
  off_t log_size = 0;
  char now[DATE_TIME];
  const char *fmt;

  generate_time ();
  strftime (now, DATE_TIME, "%Y-%m-%d %H:%M:%S", now_tm);

  /* generated date time */
  fmt = "\"%d\",,\"%s\",,,,,,,,\"%s\",\"%s\"\r\n";
  fprintf (fp, fmt, i++, GENER_ID, now, OVERALL_DATETIME);

  /* total requests */
  fmt = "\"%d\",,\"%s\",,,,,,,,\"%d\",\"%s\"\r\n";
  total = logger->processed;
  fprintf (fp, fmt, i++, GENER_ID, total, OVERALL_REQ);

  /* valid requests */
  fmt = "\"%d\",,\"%s\",,,,,,,,\"%d\",\"%s\"\r\n";
  total = logger->valid;
  fprintf (fp, fmt, i++, GENER_ID, total, OVERALL_VALID);

  /* invalid requests */
  total = logger->invalid;
  fprintf (fp, fmt, i++, GENER_ID, total, OVERALL_FAILED);

  /* generated time */
  fmt = "\"%d\",,\"%s\",,,,,,,,\"%llu\",\"%s\"\r\n";
  t = (long long) end_proc - start_proc;
  fprintf (fp, fmt, i++, GENER_ID, t, OVERALL_GENTIME);

  /* visitors */
  fmt = "\"%d\",,\"%s\",,,,,,,,\"%d\",\"%s\"\r\n";
  total = ht_get_size_uniqmap (VISITORS);
  fprintf (fp, fmt, i++, GENER_ID, total, OVERALL_VISITORS);

  /* files */
  total = ht_get_size_datamap (REQUESTS);
  fprintf (fp, fmt, i++, GENER_ID, total, OVERALL_FILES);

  /* excluded hits */
  total = logger->excluded_ip;
  fprintf (fp, fmt, i++, GENER_ID, total, OVERALL_EXCL_HITS);

  /* referrers */
  total = ht_get_size_datamap (REFERRERS);
  fprintf (fp, fmt, i++, GENER_ID, total, OVERALL_REF);

  /* not found */
  total = ht_get_size_datamap (NOT_FOUND);
  fprintf (fp, fmt, i++, GENER_ID, total, OVERALL_NOTFOUND);

  /* static files */
  total = ht_get_size_datamap (REQUESTS_STATIC);
  fprintf (fp, fmt, i++, GENER_ID, total, OVERALL_STATIC);

  /* log size */
  if (!logger->piping && conf.ifile)
    log_size = file_size (conf.ifile);
  fmt = "\"%d\",,\"%s\",,,,,,,,\"%jd\",\"%s\"\r\n";
  fprintf (fp, fmt, i++, GENER_ID, (intmax_t) log_size, OVERALL_LOGSIZE);

  /* bandwidth */
  fmt = "\"%d\",,\"%s\",,,,,,,,\"%lld\",\"%s\"\r\n";
  fprintf (fp, fmt, i++, GENER_ID, logger->resp_size, OVERALL_BANDWIDTH);

  /* log path */
  if (conf.ifile == NULL)
    conf.ifile = (char *) "STDIN";

  fmt = "\"%d\",,\"%s\",,,,,,,,\"%s\",\"%s\"\r\n";
  fprintf (fp, fmt, i++, GENER_ID, conf.ifile, OVERALL_LOG);
}
Exemplo n.º 20
0
/* render general statistics */
void
display_general (WINDOW * win, char *ifile, GLog * logger)
{
  char *bw, *size, *log_file;
  char *failed, *not_found, *process, *ref, *req;
  char *static_files, *now, *visitors, *exclude_ip;

  int x_field = 2, x_value = 0;
  size_t n, i, j, max_field = 0, max_value = 0, mod_val, y;

  typedef struct Field_
  {
    const char *field;
    char *value;                /* char due to log, bw, log_file */
    int color;
  } Field;

  Field fields[] = {
    {T_REQUESTS, NULL, COL_CYAN},
    {T_UNIQUE_VIS, NULL, COL_CYAN},
    {T_REFERRER, NULL, COL_CYAN},
    {T_LOG, NULL, COL_CYAN},
    {T_F_REQUESTS, NULL, COL_CYAN},
    {T_UNIQUE_FIL, NULL, COL_CYAN},
    {T_UNIQUE404, NULL, COL_CYAN},
    {T_BW, NULL, COL_CYAN},
    {T_GEN_TIME, NULL, COL_CYAN},
    {T_EXCLUDE_IP, NULL, COL_CYAN},
    {T_STATIC_FIL, NULL, COL_CYAN},
    {T_LOG_PATH, NULL, COL_YELLOW}
  };

  werase (win);
  draw_header (win, T_HEAD, " %s", 0, 0, getmaxx (stdscr), 1, 0);

  if (!logger->piping && ifile != NULL) {
    size = filesize_str (file_size (ifile));
    log_file = alloc_string (ifile);
  } else {
    size = alloc_string ("N/A");
    log_file = alloc_string ("STDIN");
  }
  bw = filesize_str ((float) logger->resp_size);

  /* *INDENT-OFF* */
  failed       = int_to_str (logger->invalid);
  not_found    = int_to_str (get_ht_size (ht_not_found_requests));
  process      = int_to_str (logger->process);
  ref          = int_to_str (get_ht_size (ht_referrers));
  req          = int_to_str (get_ht_size(ht_requests));
  static_files = int_to_str (get_ht_size(ht_requests_static));
  now          = int_to_str (((long long) end_proc - start_proc));
  visitors     = int_to_str (get_ht_size(ht_unique_visitors));
  exclude_ip    = int_to_str (logger->exclude_ip);

  fields[0].value = process;
  fields[1].value = visitors;
  fields[2].value = ref;
  fields[3].value = size;
  fields[4].value = failed;
  fields[5].value = req;
  fields[6].value = not_found;
  fields[7].value = bw;
  fields[8].value = now;
  fields[9].value = exclude_ip;
  fields[10].value = static_files;
  fields[11].value = log_file;

  n = ARRAY_SIZE (fields);

  /* *INDENT-ON* */
  for (i = 0, y = 2; i < n; i++) {
    mod_val = i % 4;
    if (i > 0 && mod_val == 0) {
      max_field = 0;
      max_value = 0;
      x_field = 2;
      x_value = 2;
      y++;
    }

    x_field += max_field;
    mvwprintw (win, y, x_field, "%s", fields[i].field);

    max_field = 0;
    for (j = 0; j < n; j++) {
      size_t len = strlen (fields[j].field);
      if (j % 4 == mod_val && len > max_field)
        max_field = len;
    }

    max_value = 0;
    for (j = 0; j < n; j++) {
      size_t len = strlen (fields[j].value);
      if (j % 4 == mod_val && len > max_value)
        max_value = len;
    }
    x_value = max_field + x_field + 1;
    max_field += max_value + 2;

    wattron (win, A_BOLD | COLOR_PAIR (fields[i].color));
    mvwprintw (win, y, x_value, "%s", fields[i].value);
    wattroff (win, A_BOLD | COLOR_PAIR (fields[i].color));
  }
  for (i = 0; i < n; i++) {
    free (fields[i].value);
  }
}
Exemplo n.º 21
0
int mountRAMDisk(const char * param)
{
	int fh = 0, ramDiskSize;
	int error = 0;

	// Get file handle for ramdisk file.
	fh = open(param, 0);
	if (fh != -1)
	{
		printf("\nreading ramdisk image: %s", param);

		ramDiskSize = file_size(fh);
		if (ramDiskSize > 0)
		{
			// Unmount previously mounted image if exists.
			umountRAMDisk();

			// Read new ramdisk image contents into PREBOOT_DATA area.
			if (read(fh, (char *)PREBOOT_DATA, ramDiskSize) != ramDiskSize) error = -1;
		}
		else error = -1;

		close(fh);
	}
	else error = -1;

	if (error == 0)
	{
		// Save filename in gRAMDiskFile to display information.
		strcpy(gRAMDiskFile, param);

		// Set gMI as well for the multiboot ramdisk driver hook.
		gMI = gRAMDiskMI = malloc(sizeof(multiboot_info));
		struct multiboot_module * ramdisk_module = malloc(sizeof(multiboot_module));

		// Fill in multiboot info and module structures.
		if (gRAMDiskMI != NULL && ramdisk_module != NULL)
		{
			gRAMDiskMI->mi_mods_count = 1;
			gRAMDiskMI->mi_mods_addr = (uint32_t)ramdisk_module;
			ramdisk_module->mm_mod_start = PREBOOT_DATA;
			ramdisk_module->mm_mod_end = PREBOOT_DATA + ramDiskSize;

			// Set ramdisk driver hooks.
			p_get_ramdisk_info = &multiboot_get_ramdisk_info;
			p_ramdiskReadBytes = &multibootRamdiskReadBytes;

			int partCount; // unused
			// Save bvr of the mounted image.
			gRAMDiskVolume = diskScanBootVolumes(0x100, &partCount);
			if(gRAMDiskVolume == NULL)
			{
				umountRAMDisk();
				printf("\nRamdisk contains no partitions.");
			}
			else
			{
				char dirSpec[128];

				// Reading ramdisk configuration.
				strcpy(dirSpec, RAMDISKCONFIG_FILENAME);

				if (loadConfigFile(dirSpec, &bootInfo->ramdiskConfig) == 0)
				{
					getBoolForKey("BTAlias", &gRAMDiskBTAliased, &bootInfo->ramdiskConfig);
				}
				else
				{
					printf("\nno ramdisk config...\n");
				}

				printf("\nmounting: done");
			}
		}
	}

	return error;
}
Exemplo n.º 22
0
static BOOLEAN
read_config_file(EFI_LOADED_IMAGE *image, CHAR16 **options,
		 UINT32 *options_size)
{
	struct file *file;
	EFI_STATUS err;
	CHAR16 path[4096];
	CHAR16 *u_buf, *q;
	char *a_buf, *p;
	UINT64 size;
	int i;

	err = get_path(image, path, sizeof(path));
	if (err != TRUE)
		return FALSE;

	err = file_open(image, path, &file);
	if (err != EFI_SUCCESS)
		return FALSE;

	err = file_size(file, &size);
	if (err != EFI_SUCCESS)
		goto fail;

	/*
	 * The config file contains ASCII characters, but the command
	 * line parser expects arguments to be UTF-16. Convert them
	 * once we've read them into 'a_buf'.
	 */

	/* Make sure we don't overflow the UINT32 */
	if (size > 0xffffffff || (size * 2) > 0xffffffff ) {
		Print(L"Config file size too large. Ignoring.\n");
		goto fail;
	}

	a_buf = malloc((UINTN)size);
	if (!a_buf) {
		Print(L"Failed to alloc buffer %d bytes\n", size);
		goto fail;
	}

	u_buf = malloc((UINTN)size * 2);
	if (!u_buf) {
		Print(L"Failed to alloc buffer %d bytes\n", size);
		free(a_buf);
		goto fail;
	}

	err = file_read(file, (UINTN *)&size, a_buf);
	if (err != EFI_SUCCESS)
		goto fail;

	Print(L"Using efilinux config file\n");

	/*
	 * Read one line. Stamp a NUL-byte into the buffer once we've
	 * read the end of the first line.
	 */
	for (p = a_buf, i = 0; *p && *p != '\n' && i < size; p++, i++)
		;
	if (*p == '\n')
		*p++ = '\0';

	if (i == size && *p) {
		Print(L"Error: missing newline at end of config file?\n");
		goto fail;
	}

	if ((p - a_buf) < size)
		Print(L"Warning: config file contains multiple lines?\n");

	p = a_buf;
	q = u_buf;
	for (i = 0; i < size; i++)
		*q++ = *p++;
	free(a_buf);

	*options = u_buf;
	*options_size = (UINT32)size * 2;

	file_close(file);
	return TRUE;
fail:
	file_close(file);
	return FALSE;
}
Exemplo n.º 23
0
    long long BSONTool::processFile( const boost::filesystem::path& root ) {
        std::string fileName = root.string();

        unsigned long long fileLength = file_size( root );

        if ( fileLength == 0 ) {
            toolInfoOutput() << "file " << fileName << " empty, skipping" << std::endl;
            return 0;
        }


        FILE* file = fopen( fileName.c_str() , "rb" );
        if ( ! file ) {
            toolError() << "error opening file: " << fileName << " " << errnoWithDescription()
                      << std::endl;
            return 0;
        }

#ifdef POSIX_FADV_SEQUENTIAL
        posix_fadvise(fileno(file), 0, fileLength, POSIX_FADV_SEQUENTIAL);
#endif

        if (logger::globalLogDomain()->shouldLog(logger::LogSeverity::Debug(1))) {
            toolInfoOutput() << "\t file size: " << fileLength << std::endl;
        }

        unsigned long long read = 0;
        unsigned long long num = 0;
        unsigned long long processed = 0;

        const int BUF_SIZE = BSONObjMaxUserSize + ( 1024 * 1024 );
        boost::scoped_array<char> buf_holder(new char[BUF_SIZE]);
        char * buf = buf_holder.get();

        ProgressMeter m(fileLength);
        if (!toolGlobalParams.quiet) {
            m.setUnits( "bytes" );
        }

        while ( read < fileLength ) {
            size_t amt = fread(buf, 1, 4, file);
            verify( amt == 4 );

            int size = ((int*)buf)[0];
            uassert( 10264 , str::stream() << "invalid object size: " << size , size < BUF_SIZE );

            amt = fread(buf+4, 1, size-4, file);
            verify( amt == (size_t)( size - 4 ) );

            BSONObj o( buf );
            if (bsonToolGlobalParams.objcheck) {
                const Status status = validateBSON(buf, size);
                if (!status.isOK()) {
                    toolError() << "INVALID OBJECT - going to try and print out " << std::endl;
                    toolError() << "size: " << size << std::endl;
                    toolError() << "error: " << status.reason() << std::endl;

                    StringBuilder sb;
                    try {
                        o.toString(sb); // using StringBuilder version to get as much as possible
                    } catch (...) {
                        toolError() << "object up to error: " << sb.str() << endl;
                        throw;
                    }
                    toolError() << "complete object: " << sb.str() << endl;

                    // NOTE: continuing with object even though we know it is invalid.
                }
            }

            if (!bsonToolGlobalParams.hasFilter || _matcher->matches(o)) {
                gotObject( o );
                processed++;
            }

            read += o.objsize();
            num++;

            if (!toolGlobalParams.quiet) {
                m.hit(o.objsize());
            }
        }

        fclose( file );

        uassert(10265, "counts don't match", read == fileLength);
        toolInfoOutput() << num << ((num == 1) ? " document" : " documents")
                         << " found" << std::endl;
        if (bsonToolGlobalParams.hasFilter) {
            toolInfoOutput() << processed
                             << ((processed == 1) ? " document" : " documents")
                             << " processed" << std::endl;
        }
        return processed;
    }
Exemplo n.º 24
0
int main(int argc, char **argv) 
{
  struct jpeg_decompress_struct dinfo;
  struct jpeg_compress_struct cinfo;
  struct my_error_mgr jcerr,jderr;
  JSAMPARRAY buf = NULL;
  jvirt_barray_ptr *coef_arrays = NULL;
  char marker_str[256];
  char tmpfilename[MAXPATHLEN],tmpdir[MAXPATHLEN];
  char newname[MAXPATHLEN], dest_path[MAXPATHLEN];
  volatile int i;
  int c,j, tmpfd, searchcount, searchdone;
  int opt_index = 0;
  long insize = 0, outsize = 0, lastsize = 0;
  int oldquality;
  double ratio;
  struct stat file_stat;
  jpeg_saved_marker_ptr cmarker; 
  unsigned char *outbuffer = NULL;
  size_t outbuffersize;
  char *outfname = NULL;
  FILE *infile = NULL, *outfile = NULL;
  int marker_in_count, marker_in_size;
  int compress_err_count = 0;
  int decompress_err_count = 0;
  long average_count = 0;
  double average_rate = 0.0, total_save = 0.0;


  if (rcsid)
  ; /* so compiler won't complain about "unused" rcsid string */

  umask(077);
  signal(SIGINT,own_signal_handler);
  signal(SIGTERM,own_signal_handler);

  /* initialize decompression object */
  dinfo.err = jpeg_std_error(&jderr.pub);
  jpeg_create_decompress(&dinfo);
  jderr.pub.error_exit=my_error_exit;
  jderr.pub.output_message=my_output_message;
  jderr.jump_set = 0;

  /* initialize compression object */
  cinfo.err = jpeg_std_error(&jcerr.pub);
  jpeg_create_compress(&cinfo);
  jcerr.pub.error_exit=my_error_exit;
  jcerr.pub.output_message=my_output_message;
  jcerr.jump_set = 0;


  if (argc<2) {
    if (!quiet_mode) fprintf(stderr,PROGRAMNAME ": file arguments missing\n"
			     "Try '" PROGRAMNAME " --help' for more information.\n");
    exit(1);
  }
 
  /* parse command line parameters */
  while(1) {
    opt_index=0;
    if ((c=getopt_long(argc,argv,"d:hm:nstqvfVpPoT:S:b",long_options,&opt_index))
	      == -1) 
      break;

    switch (c) {
    case 'm':
      {
        int tmpvar;

        if (sscanf(optarg,"%d",&tmpvar) == 1) {
	  quality=tmpvar;
	  if (quality < 0) quality=0;
	  if (quality > 100) quality=100;
	}
	else 
	  fatal("invalid argument for -m, --max");
      }
      break;
    case 'd':
      if (realpath(optarg,dest_path)==NULL || !is_directory(dest_path)) {
	fatal("invalid argument for option -d, --dest");
      }
      strncat(dest_path,DIR_SEPARATOR_S,sizeof(dest_path)-strlen(dest_path)-1);

      if (verbose_mode) 
	fprintf(stderr,"Destination directory: %s\n",dest_path);
      dest=1;
      break;
    case 'v':
      verbose_mode++;
      break;
    case 'h':
      print_usage();
      exit(0);
      break;
    case 'q':
      quiet_mode=1;
      break;
    case 't':
      totals_mode=1;
      break;
    case 'n':
      noaction=1;
      break;
    case 'f':
      force=1;
      break;
    case 'b':
      csv=1;
      quiet_mode=1;
      break;
    case '?':
      break;
    case 'V':
      print_version();
      exit(0);
      break;
    case 'o':
      overwrite_mode=1;
      break;
    case 'p':
      preserve_mode=1;
      break;
    case 'P':
      preserve_perms=1;
      break;
    case 's':
      save_exif=0;
      save_iptc=0;
      save_com=0;
      save_icc=0;
      save_xmp=0;
      break;
    case 'T':
      {
	int tmpvar;
	if (sscanf(optarg,"%d",&tmpvar) == 1) {
	  threshold=tmpvar;
	  if (threshold < 0) threshold=0;
	  if (threshold > 100) threshold=100;
	}
	else fatal("invalid argument for -T, --threshold");
      }
      break;
    case 'S':
      {
	unsigned int tmpvar;
	if (sscanf(optarg,"%u",&tmpvar) == 1) {
	  if (tmpvar > 0 && tmpvar < 100 && optarg[strlen(optarg)-1] == '%' ) {
	    target_size=-tmpvar;
	  } else {
	    target_size=tmpvar;
	  }
	  quality=100;
	}
	else fatal("invalid argument for -S, --size");
      }
      break;

    }
  }


  /* check for '-' option indicating input is from stdin... */
  i=1;
  while (argv[i]) {
    if (argv[i][0]=='-' && argv[i][1]==0) stdin_mode=1;
    i++;
  }

  if (stdin_mode) { stdout_mode=1; force=1; }
  if (stdout_mode) { logs_to_stdout=0; }

  if (all_normal && all_progressive)
    fatal("cannot specify both --all-normal and --all-progressive"); 

  if (verbose_mode) {
    if (quality>=0 && target_size==0) 
      fprintf(stderr,"Image quality limit set to: %d\n",quality);
    if (threshold>=0) 
      fprintf(stderr,"Compression threshold (%%) set to: %d\n",threshold);
    if (all_normal) 
      fprintf(stderr,"All output files will be non-progressive\n");
    if (all_progressive) 
      fprintf(stderr,"All output files will be progressive\n");
    if (target_size > 0) 
      fprintf(stderr,"Target size for output files set to: %u Kbytes.\n",
	      target_size);
    if (target_size < 0) 
      fprintf(stderr,"Target size for output files set to: %u%%\n",
	      -target_size);
  }


  /* loop to process the input files */
  i=1;  
  do {
    if (stdin_mode) {
      infile=stdin;
      set_filemode_binary(infile);
    } else {
      if (!argv[i][0]) continue;
      if (argv[i][0]=='-') continue;
      if (strlen(argv[i]) >= MAXPATHLEN) {
	warn("skipping too long filename: %s",argv[i]);
	continue;
      }

      if (!noaction) {
	/* generate tmp dir & new filename */
	if (dest) {
	  STRNCPY(tmpdir,dest_path,sizeof(tmpdir));
	  STRNCPY(newname,dest_path,sizeof(newname));
	  if (!splitname(argv[i],tmpfilename,sizeof(tmpfilename)))
	    fatal("splitname() failed for: %s",argv[i]);
	  strncat(newname,tmpfilename,sizeof(newname)-strlen(newname)-1);
	} else {
	  if (!splitdir(argv[i],tmpdir,sizeof(tmpdir))) 
	    fatal("splitdir() failed for: %s",argv[i]);
	  STRNCPY(newname,argv[i],sizeof(newname));
	}
      }
      
    retry_point:
      
      if (!is_file(argv[i],&file_stat)) {
	if (is_directory(argv[i])) 
	  warn("skipping directory: %s",argv[i]);
	else
	  warn("skipping special file: %s",argv[i]); 
	continue;
      }
      if ((infile=fopen(argv[i],"rb"))==NULL) {
	warn("cannot open file: %s", argv[i]);
	continue;
      }
    }

   if (setjmp(jderr.setjmp_buffer)) {
     /* error handler for decompress */
     jpeg_abort_decompress(&dinfo);
     fclose(infile);
     if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
     if (!quiet_mode || csv) 
       fprintf(LOG_FH,csv ? ",,,,,error\n" : " [ERROR]\n");
     decompress_err_count++;
     jderr.jump_set=0;
     continue;
   } else {
     jderr.jump_set=1;
   }

   if (!retry && (!quiet_mode || csv)) {
     fprintf(LOG_FH,csv ? "%s," : "%s ",(stdin_mode?"stdin":argv[i])); fflush(LOG_FH); 
   }

   /* prepare to decompress */
   global_error_counter=0;
   jpeg_save_markers(&dinfo, JPEG_COM, 0xffff);
   for (j=0;j<=15;j++) 
     jpeg_save_markers(&dinfo, JPEG_APP0+j, 0xffff);
   jpeg_stdio_src(&dinfo, infile);
   jpeg_read_header(&dinfo, TRUE); 

   /* check for Exif/IPTC/ICC/XMP markers */
   marker_str[0]=0;
   marker_in_count=0;
   marker_in_size=0;
   cmarker=dinfo.marker_list;

   while (cmarker) {
     marker_in_count++;
     marker_in_size+=cmarker->data_length;

     if (cmarker->marker == EXIF_JPEG_MARKER &&
	 !memcmp(cmarker->data,EXIF_IDENT_STRING,EXIF_IDENT_STRING_SIZE))
       strncat(marker_str,"Exif ",sizeof(marker_str)-strlen(marker_str)-1);

     if (cmarker->marker == IPTC_JPEG_MARKER)
       strncat(marker_str,"IPTC ",sizeof(marker_str)-strlen(marker_str)-1);

     if (cmarker->marker == ICC_JPEG_MARKER &&
	 !memcmp(cmarker->data,ICC_IDENT_STRING,ICC_IDENT_STRING_SIZE))
       strncat(marker_str,"ICC ",sizeof(marker_str)-strlen(marker_str)-1);

     if (cmarker->marker == XMP_JPEG_MARKER &&
	 !memcmp(cmarker->data,XMP_IDENT_STRING,XMP_IDENT_STRING_SIZE)) 
       strncat(marker_str,"XMP ",sizeof(marker_str)-strlen(marker_str)-1);

     cmarker=cmarker->next;
   }


   if (verbose_mode > 1) 
     fprintf(LOG_FH,"%d markers found in input file (total size %d bytes)\n",
	     marker_in_count,marker_in_size);
   if (!retry && (!quiet_mode || csv)) {
     fprintf(LOG_FH,csv ? "%dx%d,%dbit,%c," : "%dx%d %dbit %c ",(int)dinfo.image_width,
	     (int)dinfo.image_height,(int)dinfo.num_components*8,
	     (dinfo.progressive_mode?'P':'N'));

     if (!csv) {
       fprintf(LOG_FH,"%s",marker_str);
       if (dinfo.saw_Adobe_marker) fprintf(LOG_FH,"Adobe ");
       if (dinfo.saw_JFIF_marker) fprintf(LOG_FH,"JFIF ");
     }
     fflush(LOG_FH);
   }

   if ((insize=file_size(infile)) < 0)
     fatal("failed to stat() input file");

  /* decompress the file */
   if (quality>=0 && !retry) {
     jpeg_start_decompress(&dinfo);

     /* allocate line buffer to store the decompressed image */
     buf = malloc(sizeof(JSAMPROW)*dinfo.output_height);
     if (!buf) fatal("not enough memory");
     for (j=0;j<dinfo.output_height;j++) {
       buf[j]=malloc(sizeof(JSAMPLE)*dinfo.output_width*
		     dinfo.out_color_components);
       if (!buf[j]) fatal("not enough memory");
     }

     while (dinfo.output_scanline < dinfo.output_height) {
       jpeg_read_scanlines(&dinfo,&buf[dinfo.output_scanline],
			   dinfo.output_height-dinfo.output_scanline);
     }
   } else {
     coef_arrays = jpeg_read_coefficients(&dinfo);
   }

   if (!retry && !quiet_mode) {
     if (global_error_counter==0) fprintf(LOG_FH," [OK] ");
     else fprintf(LOG_FH," [WARNING] ");
     fflush(LOG_FH);
   }

     

   if (dest && !noaction) {
     if (file_exists(newname) && !overwrite_mode) {
       warn("target file already exists: %s\n",newname);
       jpeg_abort_decompress(&dinfo);
       fclose(infile);
       if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
       continue;
     }
   }


   if (setjmp(jcerr.setjmp_buffer)) {
     /* error handler for compress failures */
     
     jpeg_abort_compress(&cinfo);
     jpeg_abort_decompress(&dinfo);
     fclose(infile);
     if (!quiet_mode) fprintf(LOG_FH," [Compress ERROR]\n");
     if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
     compress_err_count++;
     jcerr.jump_set=0;
     continue;
   } else {
     jcerr.jump_set=1;
   }


   lastsize = 0;
   searchcount = 0;
   searchdone = 0;
   oldquality = 200;



  binary_search_loop:

   /* allocate memory buffer that should be large enough to store the output JPEG... */
   if (outbuffer) free(outbuffer);
   outbuffersize=insize + 32768;
   outbuffer=malloc(outbuffersize);
   if (!outbuffer) fatal("not enough memory");

   /* setup custom "destination manager" for libjpeg to write to our buffer */
   jpeg_memory_dest(&cinfo, &outbuffer, &outbuffersize, 65536);

   if (quality>=0 && !retry) {
     /* lossy "optimization" ... */

     cinfo.in_color_space=dinfo.out_color_space;
     cinfo.input_components=dinfo.output_components;
     cinfo.image_width=dinfo.image_width;
     cinfo.image_height=dinfo.image_height;
     jpeg_set_defaults(&cinfo); 
     jpeg_set_quality(&cinfo,quality,TRUE);
     if ( (dinfo.progressive_mode || all_progressive) && !all_normal )
       jpeg_simple_progression(&cinfo);
     cinfo.optimize_coding = TRUE;

     j=0;
     jpeg_start_compress(&cinfo,TRUE);
     
     /* write markers */
     write_markers(&dinfo,&cinfo);

     /* write image */
     while (cinfo.next_scanline < cinfo.image_height) {
       jpeg_write_scanlines(&cinfo,&buf[cinfo.next_scanline],
			    dinfo.output_height);
     }

   } else {
     /* lossless "optimization" ... */

     jpeg_copy_critical_parameters(&dinfo, &cinfo);
     if ( (dinfo.progressive_mode || all_progressive) && !all_normal )
       jpeg_simple_progression(&cinfo);
     cinfo.optimize_coding = TRUE;

     /* write image */
     jpeg_write_coefficients(&cinfo, coef_arrays);

     /* write markers */
     write_markers(&dinfo,&cinfo);

   }

   jpeg_finish_compress(&cinfo);
   outsize=outbuffersize;

   if (target_size != 0 && !retry) {
     /* perform (binary) search to try to reach target file size... */

     long osize = outsize/1024;
     long isize = insize/1024;
     long tsize = target_size;

     if (tsize < 0) { 
       tsize=((-target_size)*insize/100)/1024; 
       if (tsize < 1) tsize=1;
     }

     if (osize == tsize || searchdone || searchcount >= 8 || tsize > isize) {
       if (searchdone < 42 && lastsize > 0) {
	 if (abs(osize-tsize) > abs(lastsize-tsize)) {
	   if (verbose_mode) fprintf(LOG_FH,"(revert to %d)",oldquality);
	   searchdone=42;
	   quality=oldquality;
	   goto binary_search_loop;
	 }
       }
       if (verbose_mode) fprintf(LOG_FH," ");
       
     } else {
       int newquality;
       int dif = floor((abs(oldquality-quality)/2.0)+0.5);
       if (osize > tsize) {
	 newquality=quality-dif;
	 if (dif < 1) { newquality--; searchdone=1; }
	 if (newquality < 0) { newquality=0; searchdone=2; }
       } else {
	 newquality=quality+dif;
	 if (dif < 1) { newquality++; searchdone=3; }
	 if (newquality > 100) { newquality=100; searchdone=4; }
       }
       oldquality=quality;
       quality=newquality;

       if (verbose_mode) fprintf(LOG_FH,"(try %d)",quality);

       lastsize=osize;
       searchcount++;
       goto binary_search_loop;
     }
   } 

   if (buf) FREE_LINE_BUF(buf,dinfo.output_height);
   jpeg_finish_decompress(&dinfo);
   fclose(infile);


   if (quality>=0 && outsize>=insize && !retry && !stdin_mode) {
     if (verbose_mode) fprintf(LOG_FH,"(retry w/lossless) ");
     retry=1;
     goto retry_point; 
   }

   retry=0;
   ratio=(insize-outsize)*100.0/insize;
   if (!quiet_mode || csv)
     fprintf(LOG_FH,csv ? "%ld,%ld,%0.2f," : "%ld --> %ld bytes (%0.2f%%), ",insize,outsize,ratio);
   average_count++;
   average_rate+=(ratio<0 ? 0.0 : ratio);

   if ((outsize < insize && ratio >= threshold) || force) {
        total_save+=(insize-outsize)/1024.0;
	if (!quiet_mode || csv) fprintf(LOG_FH,csv ? "optimized\n" : "optimized.\n");
        if (noaction) continue;

	if (stdout_mode) {
	  outfname=NULL;
	  set_filemode_binary(stdout);
	  if (fwrite(outbuffer,outbuffersize,1,stdout) != 1)
	    fatal("write failed to stdout");
	} else {
	  if (preserve_perms && !dest) {
	    /* make backup of the original file */
	    snprintf(tmpfilename,sizeof(tmpfilename),"%s.jpegoptim.bak",newname);
	    if (verbose_mode > 1 && !quiet_mode) 
	      fprintf(LOG_FH,"creating backup of original image as: %s\n",tmpfilename);
	    if (file_exists(tmpfilename))
	      fatal("backup file already exists: %s",tmpfilename);
	    if (copy_file(newname,tmpfilename))
	      fatal("failed to create backup of original file");
	    if ((outfile=fopen(newname,"wb"))==NULL)
	      fatal("error opening output file: %s", newname);
	    outfname=newname;
	  } else {
#ifdef HAVE_MKSTEMPS
	    /* rely on mkstemps() to create us temporary file safely... */  
	    snprintf(tmpfilename,sizeof(tmpfilename),
		     "%sjpegoptim-%d-%d.XXXXXX.tmp", tmpdir, (int)getuid(), (int)getpid());
	    if ((tmpfd = mkstemps(tmpfilename,4)) < 0) 
	      fatal("error creating temp file: mkstemps() failed");
	    if ((outfile=fdopen(tmpfd,"wb"))==NULL) 
#else
	      /* if platform is missing mkstemps(), try to create at least somewhat "safe" temp file... */  
	      snprintf(tmpfilename,sizeof(tmpfilename),
		       "%sjpegoptim-%d-%d.%d.tmp", tmpdir, (int)getuid(), (int)getpid(),time(NULL));
	    tmpfd=0;
	    if ((outfile=fopen(tmpfilename,"wb"))==NULL) 
#endif
	      fatal("error opening temporary file: %s",tmpfilename);
	    outfname=tmpfilename;
	  }

	  if (verbose_mode > 1 && !quiet_mode) 
	    fprintf(LOG_FH,"writing %lu bytes to file: %s\n",
		    (long unsigned int)outbuffersize, outfname);
	  if (fwrite(outbuffer,outbuffersize,1,outfile) != 1)
	    fatal("write failed to file: %s", outfname);
	  fclose(outfile);
	}

	if (outfname) {
	  
	  if (preserve_mode) {
	    /* preserve file modification time */
	    struct utimbuf time_save;
	    time_save.actime=file_stat.st_atime;
	    time_save.modtime=file_stat.st_mtime;
	    if (utime(outfname,&time_save) != 0) 
	      warn("failed to reset output file time/date");
	  }

	  if (preserve_perms && !dest) {
	    /* original file was already replaced, remove backup... */
	    if (delete_file(tmpfilename))
	      warn("failed to remove backup file: %s",tmpfilename);
	  } else {
	    /* make temp file to be the original file... */

	    /* preserve file mode */
	    if (chmod(outfname,(file_stat.st_mode & 0777)) != 0) 
	      warn("failed to set output file mode"); 

	    /* preserve file group (and owner if run by root) */
	    if (chown(outfname,
		      (geteuid()==0 ? file_stat.st_uid : -1),
		      file_stat.st_gid) != 0)
	      warn("failed to reset output file group/owner");

	    if (verbose_mode > 1 && !quiet_mode) 
	      fprintf(LOG_FH,"renaming: %s to %s\n",outfname,newname);
	    if (rename_file(outfname,newname)) fatal("cannot rename temp file");
	  }
	}
   } else {
     if (!quiet_mode || csv) fprintf(LOG_FH,csv ? "skipped\n" : "skipped.\n");
   }
   

  } while (++i<argc && !stdin_mode);


  if (totals_mode && !quiet_mode)
    fprintf(LOG_FH,"Average ""compression"" (%ld files): %0.2f%% (%0.0fk)\n",
	    average_count, average_rate/average_count, total_save);
  jpeg_destroy_decompress(&dinfo);
  jpeg_destroy_compress(&cinfo);

  return (decompress_err_count > 0 || compress_err_count > 0 ? 1 : 0);;
}
Exemplo n.º 25
0
// Notify OS X that a ramdisk has been setup. XNU with attach this to /dev/md0
void md0Ramdisk()
{
	RAMDiskParam ramdiskPtr;
	char filename[512];
	const char* override_filename = 0;
	int fh = -1;
	int len;
	
	if(getValueForKey(kMD0Image, &override_filename, &len,  
				   &bootInfo->bootConfig))
	{
		// Use user specified md0 file
		sprintf(filename, "%s", override_filename);
		fh = open(filename, 0);
		
		if(fh < 0)
		{
			sprintf(filename, "rd(0,0)/Extra/%s", override_filename);
			fh = open(filename, 0);

			if(fh < 0)
			{
				sprintf(filename, "/Extra/%s", override_filename);
				fh = open(filename, 0);
			}
		}		
	}

	if(fh < 0)
	{
		sprintf(filename, "rd(0,0)/Extra/Postboot.img");
		fh = open(filename, 0);

		if(fh < 0)
		{
			sprintf(filename, "/Extra/Postboot.img");	// Check /Extra if not in rd(0,0)
			fh = open(filename, 0);
		}
	}		

	if (fh >= 0)
	{
		verbose("Enabling ramdisk %s\n", filename);

		ramdiskPtr.size  = file_size(fh);
		ramdiskPtr.base = AllocateKernelMemory(ramdiskPtr.size);

		if(ramdiskPtr.size && ramdiskPtr.base)
		{
			// Read new ramdisk image contents in kernel memory.
			if (read(fh, (char*) ramdiskPtr.base, ramdiskPtr.size) == ramdiskPtr.size)
			{
				AllocateMemoryRange("RAMDisk", ramdiskPtr.base, ramdiskPtr.size, kBootDriverTypeInvalid);
				Node* node = DT__FindNode("/chosen/memory-map", false);
				if(node != NULL)
				{
					DT__AddProperty(node, "RAMDisk", sizeof(RAMDiskParam),  (void*)&ramdiskPtr);		
				}
				else
				{
					verbose("Unable to notify Mac OS X of the ramdisk %s.\n", filename);
				}
			}
			else
			{
				verbose("Unable to read md0 image %s.\n", filename);
			}			
		}
		else
		{
			verbose("md0 image %s is empty.\n", filename);
		}

		close(fh);

	}
}
Exemplo n.º 26
0
int main(object me, string msg)
{
        string *lines;
        string arg,file="/log/notice";
        if( !msg || msg=="" ){
        if (file_size(file)<0) {
        	write("现在没有设定任何连线通知\n");
        	write("--------------------------------------------\n\n");
        	return help(me);}
        arg=read_file(file);
        write("你现在所设定的连线通知是:\n");
        write("--------------------------------------------\n\n");
        if (strlen(arg)>8190)
           me->start_more(arg);
        else
           write(arg);
        return 1;
        }
      if(msg=="-rm")
      {
          rm("/log/login/notice");
          write("通知已被清除!\n");
          return 1;
       }
        lines = explode(msg, "\n");
        for(int i=0; i<sizeof(lines); i++)
                lines[i] = "    " + lines[i];
        msg = implode(lines, "\n") + "\n";
        arg = replace_string(msg, "$BLK$", BLK);
        msg = replace_string(msg, "$RED$", RED);
        msg = replace_string(msg, "$GRN$", GRN);
        msg = replace_string(msg, "$YEL$", YEL);
        msg = replace_string(msg, "$BLU$", BLU);
        msg = replace_string(msg, "$MAG$", MAG);
        msg = replace_string(msg, "$CYN$", CYN);
        msg = replace_string(msg, "$WHT$", WHT);
        msg = replace_string(msg, "$HIR$", HIR);
        msg = replace_string(msg, "$HIG$", HIG);
        msg = replace_string(msg, "$HIY$", HIY);
        msg = replace_string(msg, "$HIB$", HIB);
        msg = replace_string(msg, "$HIM$", HIM);
        msg = replace_string(msg, "$HIC$", HIC);
        msg = replace_string(msg, "$HIW$", HIW);
        msg = replace_string(msg, "$NOR$", NOR);
        msg = replace_string(msg, "$BLINK$", BLINK);
        msg = replace_string(msg, "$BGRN$", BGRN);
        msg = replace_string(msg, "$BCYN$", BCYN);
        msg = replace_string(msg, "$BYEL$", BYEL);
        msg = replace_string(msg, "$BBLU$", BBLU);
        msg = replace_string(msg, "$BMAG$", BMAG);
        msg = replace_string(msg, "$BGRN$", BRED);
        msg = replace_string(msg, "$HBGRN$", HBGRN);
        msg = replace_string(msg, "$HBRED$", HBRED);
        msg = replace_string(msg, "$HBYEL$", HBYEL);
        msg = replace_string(msg, "$HBBLU$", HBBLU);
        msg = replace_string(msg, "$HBMAG$", HBMAG);
        msg = replace_string(msg, "$HBCYN$", HBCYN);
        msg = replace_string(msg, "$HBWHT$", HBWHT);
        write_file(file, msg,1);
        write("连线通知加入完毕。\n");
        return 1;
}
Exemplo n.º 27
0
int do_convert(string arg)
{
	string from, to;
	int amount, bv1, bv2;
	object from_ob, to_ob;
	object me;
	
	if (query_temp("busy"))
		return notify_fail("哟,抱歉啊,我这儿正忙着呢……您请稍候。\n");

	me = this_player();

	if (!arg || sscanf(arg, "%d %s to %s", amount, from, to) != 3)
	{
		return notify_fail("命令格式:convert|duihuan <数量> <货币单位> to <新货币单位>\n");
	}

	from_ob = present(from + "_money", me);
	to_ob = present(to + "_money", me);

	if (!to_ob && file_size("/clone/money/" + to + ".c") < 0)
	{
		return notify_fail("你想兑换成什么?\n");
	}
	if (!from_ob)
	{
		return notify_fail("你身上没有带这种钱。\n");
	}
	if (amount < 1)
	{
		return notify_fail("你想白赚啊?\n");
	}
	if ((int)from_ob->query_amount() < amount)
	{
		return notify_fail("你带的" + from_ob->query("name") + "不够。\n");
	}
	
	bv1 = from_ob->query("base_value");
	if (!bv1)
	{
		return notify_fail("这样东西不值钱。\n");
	}

	bv2 = to_ob ? to_ob->query("base_value") : call_other("/clone/money/" + to, "query", "base_value" );
	
	if (bv1 < bv2)
		amount -= amount % (bv2 / bv1);	

	if (amount == 0)
	{
		return notify_fail("这些" + from_ob->query("name") + "不够换。\n");
	}

	// allowed to convert now
	set_temp("busy", 1);	

	from_ob->add_amount(-amount);

	if (!to_ob) {
		to_ob = new("/clone/money/" + to);
		to_ob->set_amount(amount * bv1 * 9 / (bv2 * 10));
		to_ob->move(me);
	}
Exemplo n.º 28
0
/*
** Start a listening socket and process incoming HTTP requests on
** that socket.
*/
void win32_http_server(
  int mnPort, int mxPort,   /* Range of allowed TCP port numbers */
  const char *zBrowser,     /* Command to launch browser.  (Or NULL) */
  const char *zStopper,     /* Stop server when this file is exists (Or NULL) */
  const char *zNotFound,    /* The --notfound option, or NULL */
  int flags                 /* One or more HTTP_SERVER_ flags */
){
  WSADATA wd;
  SOCKET s = INVALID_SOCKET;
  SOCKADDR_IN addr;
  int idCnt = 0;
  int iPort = mnPort;
  Blob options;
  WCHAR zTmpPath[MAX_PATH];

  if( zStopper ) file_delete(zStopper);
  blob_zero(&options);
  if( zNotFound ){
    blob_appendf(&options, " --notfound %s", zNotFound);
  }
  if( g.useLocalauth ){
    blob_appendf(&options, " --localauth");
  }
  if( WSAStartup(MAKEWORD(1,1), &wd) ){
    fossil_fatal("unable to initialize winsock");
  }
  while( iPort<=mxPort ){
    s = socket(AF_INET, SOCK_STREAM, 0);
    if( s==INVALID_SOCKET ){
      fossil_fatal("unable to create a socket");
    }
    addr.sin_family = AF_INET;
    addr.sin_port = htons(iPort);
    if( flags & HTTP_SERVER_LOCALHOST ){
      addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    }else{
      addr.sin_addr.s_addr = htonl(INADDR_ANY);
    }
    if( bind(s, (struct sockaddr*)&addr, sizeof(addr))==SOCKET_ERROR ){
      closesocket(s);
      iPort++;
      continue;
    }
    if( listen(s, SOMAXCONN)==SOCKET_ERROR ){
      closesocket(s);
      iPort++;
      continue;
    }
    break;
  }
  if( iPort>mxPort ){
    if( mnPort==mxPort ){
      fossil_fatal("unable to open listening socket on ports %d", mnPort);
    }else{
      fossil_fatal("unable to open listening socket on any"
                   " port in the range %d..%d", mnPort, mxPort);
    }
  }
  if( !GetTempPathW(MAX_PATH, zTmpPath) ){
    fossil_fatal("unable to get path to the temporary directory.");
  }
  zTempPrefix = mprintf("%sfossil_server_P%d_", fossil_unicode_to_utf8(zTmpPath), iPort);
  fossil_print("Listening for HTTP requests on TCP port %d\n", iPort);
  if( zBrowser ){
    zBrowser = mprintf(zBrowser, iPort);
    fossil_print("Launch webbrowser: %s\n", zBrowser);
    fossil_system(zBrowser);
  }
  fossil_print("Type Ctrl-C to stop the HTTP server\n");
  /* Set the service status to running and pass the listener socket to the
  ** service handling procedures. */
  win32_http_service_running(s);
  for(;;){
    SOCKET client;
    SOCKADDR_IN client_addr;
    HttpRequest *p;
    int len = sizeof(client_addr);
    int wsaError;

    client = accept(s, (struct sockaddr*)&client_addr, &len);
    if( client==INVALID_SOCKET ){
      /* If the service control handler has closed the listener socket,
      ** cleanup and return, otherwise report a fatal error. */
      wsaError =  WSAGetLastError();
      if( (wsaError==WSAEINTR) || (wsaError==WSAENOTSOCK) ){
        WSACleanup();
        return;
      }else{
        closesocket(s);
        WSACleanup();
        fossil_fatal("error from accept()");
      }
    }else if( zStopper && file_size(zStopper)>=0 ){
      break;
    }
    p = fossil_malloc( sizeof(*p) );
    p->id = ++idCnt;
    p->s = client;
    p->addr = client_addr;
    p->zOptions = blob_str(&options);
    _beginthread(win32_process_one_http_request, 0, (void*)p);
  }
  closesocket(s);
  WSACleanup();
}
Exemplo n.º 29
0
int CHHashFileSaltedSSHA::OpenHashFile(char *filename){
    FILE *hashfile;
    long int estimated_hash_number;
    char buffer[1024];
    unsigned char hexbuffer[1024];
    long int i;
    int decoded_length; // For the length of the base64 decoded output



    // Estimate number of hashes - this *WILL* be high.
    estimated_hash_number = (file_size(filename) / this->hashLength) + 10; // Add some slack.

    hashfile = fopen(filename, "r");
    if (!hashfile) {
      printf("Cannot open hash file %s.  Exiting.\n", filename);
      exit(1);
    }

    // Allocate new memory.  Return 0 on failure, not an exception.
    this->HashList = new (std::nothrow) SaltedHash32*[estimated_hash_number];
    if (this->HashList == 0) {
        printf("Cannot allocate memory for hash list!\n");
        exit(1);
    }

    for (i = 0; i < estimated_hash_number; i++) {
        this->HashList[i] = new (std::nothrow) SaltedHash32;
        if (this->HashList[i] == 0) {
            printf("Cannot allocate memory for hash list!\n");
            exit(1);
        }
        memset(this->HashList[i], 0, sizeof(SaltedHash32));
    }
    this->TotalHashes = 0;
    this->TotalHashesFound = 0;



    while (!feof(hashfile)) {
        memset(buffer, 0, 1024);
      // If fgets returns NULL, there's been an error or eof.  Continue.
      if (!fgets(buffer, 1024, hashfile)) {
        continue;
      }

      // Get rid of any newlines
      chomp(buffer);

      // Check for the {SSHA} prefix: If not found, continue
      if ((buffer[0] != '{') || (buffer[1] != 'S') || (buffer[2] != 'S')
              || (buffer[3] != 'H') || (buffer[4] != 'A') || (buffer[5] != '}')) {
          continue;
      }

      // If this is not a full line, continue (usually a trailing crlf)
      // 28 is the length of the base64
      // Adding the additional characters for "{SHA}"
      if (strlen(buffer) < (28 + 6)) {
        continue;
      }
      memset(hexbuffer, 0, 1024);
      // Decode the base64 magic
      decoded_length = UnBase64(hexbuffer, (unsigned char *)&buffer[6], strlen(buffer) - 6);

      // Set the hash data for SHA1 - 20 bytes
      for (i = 0; i < 20; i++) {
          this->HashList[this->TotalHashes]->hash[i] = hexbuffer[i];
      }
      // Set the salt - anything after the 20 bytes of SHA1
      for (i = 20; i < decoded_length; i++) {
          this->HashList[this->TotalHashes]->salt[i - 20] = hexbuffer[i];
      }
      this->HashList[this->TotalHashes]->saltLength = decoded_length - 20;

      this->TotalHashes++;
    }
    this->TotalHashesFound = 0;
    this->TotalHashesRemaining = this->TotalHashes;
    this->SortHashList();
    return 1;
}
Exemplo n.º 30
0
string search_help(string str) {
  if (file_size(NROFF_DIR+str+".o") > 0)
    return NROFF_DIR+str;
  if (this_player()->query_creator() && file_size(CNROFF_DIR+str+".o") > 0)
    return CNROFF_DIR+str;
} /* search_help() */