Beispiel #1
0
int bfid_step( bf_code_t *dbf, int argc, char **argv ){
	char *bfcmds = "><+-.,[]#";
	char c;
	int i, j;
	if ( argc > 1 )
		i = atoi( argv[1] );
	else
		i = 1;

	//i %= dbf->codesize - dbf->ip + 1;
	c = '_';
	for ( j = 0; bfcmds[j]; j++ ){
		if ( dbf->code[ dbf->ip ] == bfcmds[j] ){
			c = dbf->code[ dbf->ip ];
			break;
		}
	}

	//printf( "stepping for %d\n", i );
	while( i-- ){
		//printf( "[%c] stepping...\n", c );
		bf_step( dbf );
	}

	char buf[32];
	sprintf( buf, "%u\0", dbf->ip );
	set_variable( "ip", buf );

	sprintf( buf, "%u\0", dbf->ptr );
	set_variable( "ptr", buf );

	return 0;
}
bool read_variables_from_fp(FILE *fp, inT64 end_offset, bool global_only) {
  char line[MAX_PATH];           // input line
  bool anyerr = false;          // true if any error
  bool foundit;                 // found variable
  inT16 length;                  // length of line
  char *valptr;                  // value field

  while ((end_offset < 0 || ftell(fp) < end_offset) &&
         fgets(line, MAX_PATH, fp)) {
    if (line[0] != '\n' && line[0] != '#') {
      length = strlen (line);
      if (line[length - 1] == '\n')
        line[length - 1] = '\0';  // cut newline
      for (valptr = line; *valptr && *valptr != ' ' && *valptr != '\t';
        valptr++);
      if (*valptr) {             // found blank
        *valptr = '\0';          // make name a string
        do
          valptr++;              // find end of blanks
        while (*valptr == ' ' || *valptr == '\t');
      }
      if (global_only && strstr(line, kGlobalVariablePrefix) == NULL) continue;
      foundit = set_variable(line, valptr);

      if (!foundit) {
        anyerr = TRUE;         // had an error
        tprintf("read_variables_file: variable not found: %s\n", line);
        exit(1);
      }
    }
  }
  return anyerr;
}
Beispiel #3
0
void opcode_store(void)
{
  TRACE_LOG("Opcode: STORE.\n");
  TRACE_LOG("Writing %x to variable %x.\n", op[1], op[0]);

  set_variable(op[0], op[1], true);
}
Beispiel #4
0
/*
 * set_var_value: Given the variable structure and the string representation
 * of the value, this sets the value in the most verbose and error checking
 * of manors.  It displays the results of the set and executes the function
 * defined in the var structure 
 */
void 	set_var_value (int svv_index, const char *value, int noisy)
{
	IrcVariable *var;

	var = (IrcVariable *)var_bucket->list[svv_index].stuff;
	set_variable(var_bucket->list[svv_index].name, var, value, noisy);
}
Beispiel #5
0
void init_variables(void)
{
  struct var_entry *p;

  for (p = &def_vars[0]; p < &def_vars[sizeof(def_vars) / sizeof(def_vars[0])]; p++)
    set_variable(p->var, p->val);
}
Beispiel #6
0
void opcode_restore_undo(void)
{
  int result;
  size_t dynamic_memory_size;
  struct undo_frame *frame_to_restore;

  TRACE_LOG("Opcode: RESTORE_UNDO.\n");

  if (undo_index > 0)
  {
    undo_index--;

    frame_to_restore = undo_frames[undo_index];

    dynamic_memory_size = (size_t)(
        active_z_story->dynamic_memory_end - z_mem + 1 );

    ensure_z_stack_size(frame_to_restore->z_stack_size);

    pc = frame_to_restore->pc;
    //current_z_stack_size = frame_to_restore->z_stack_size;
    //behind_z_stack = z_stack + current_z_stack_size;
    z_stack_index = z_stack + frame_to_restore->z_stack_size;
    stack_words_from_active_routine
      = frame_to_restore->stack_words_from_active_routine;
    number_of_locals_active
      = frame_to_restore->number_of_locals_active;
    number_of_locals_from_function_call
      = frame_to_restore->number_of_locals_from_function_call;
    local_variable_storage_index
      = z_stack_index
      - stack_words_from_active_routine
      - number_of_locals_active;

    memcpy(
        z_stack, // non-null when size > 0
        frame_to_restore->stack,
        frame_to_restore->z_stack_size * sizeof(uint16_t));
        //current_z_stack_size * sizeof(uint16_t));

    memcpy(
        z_mem,
        frame_to_restore->dynamic_memory,
        dynamic_memory_size);

    delete_undo_frame(frame_to_restore);

    write_interpreter_info_into_header();

    result = 2;
  }
  else
  {
    result = 0;
  }

  read_z_result_variable();
  set_variable(z_res_var, (uint16_t)result, false);
}
Beispiel #7
0
void opcode_pull(void)
{
  uint16_t value = 0;
  uint16_t spare_slots;
  uint8_t *user_stack;

  TRACE_LOG("Opcode: PULL.\n");

  if (ver == 6)
    (void)read_z_result_variable();

  if ( (ver != 6) || (number_of_operands < 1) )
  {
    if (
        (stack_words_from_active_routine == 0)
        &&
        (bool_equal(skip_active_routines_stack_check_warning, false))
       )
    {
      i18n_translate_and_exit(
          libfizmo_module_name,
          i18n_libfizmo_NOT_ENOUGH_STACK_WORDS_FROM_LOCAL_ROUTINE_ON_STACK, -1);
    }
    else
    {
      TRACE_LOG("Pulling to variable %x.\n", op[0]);
      value = z_stack_pull_word();
      stack_words_from_active_routine--;
    }
  }
  else
  {
    user_stack = z_mem + (uint16_t)op[0];
    spare_slots = load_word(user_stack);
    spare_slots++;
    value = load_word(user_stack + spare_slots);
    store_word(user_stack, spare_slots);
  }

  if (ver == 6)
    set_variable(z_res_var, value, true);
  else
    set_variable(op[0], value, true);

}
static void let_statement (void)
{
  int var;
  var = tokenizer_variable_num();
  accept(T_LETTER);
  accept(T_EQUAL);
  set_variable(var, expression());
  accept(T_EOL);
}
Beispiel #9
0
void opcode_inc(void)
{
  int16_t value;
  
  TRACE_LOG("Opcode: INC.\n");
  value = (int16_t)get_variable(op[0], false);
  TRACE_LOG("Incrementing variable %d from %d to %d.\n", op[0], value, value+1);

  set_variable(op[0], (uint16_t)(value + 1), false);
}
Beispiel #10
0
void opcode_load(void)
{
  TRACE_LOG("Opcode: LOAD.\n");

  read_z_result_variable();
  
  TRACE_LOG("Loading variable with code %d to variable with code %d.\n",
      op[0], z_res_var);

  set_variable(z_res_var, get_variable(op[0], true), false);
}
Beispiel #11
0
void opcode_loadw(void)
{
  uint16_t value;
  uint8_t *address = z_mem + (uint16_t)(op[0] + ((int16_t)op[1])*2);

  TRACE_LOG("Opcode: LOADW.\n");

  read_z_result_variable();

  if (address > active_z_story->static_memory_end)
  {
    TRACE_LOG("ERROR: Trying to loadw from %x which is above static memory.\n",
        address);
    set_variable(z_res_var, 0, false);
  }
  else
  {
    value = load_word(address);
    TRACE_LOG("Loading %x from %x var %x.\n", value, address, z_res_var);
    set_variable(z_res_var, value, false);
  }
}
Beispiel #12
0
int main()
{
	
	put_structure("h", 2, 3);	/* ?- X3 = h              */
	set_variable(2);			/*          (Z,           */
	set_variable(5);			/*             W),        */
	put_structure("f", 1, 4);	/*    X4 = f              */
	set_value(5);				/*          (W),          */
	put_structure("p", 3, 1);	/*    X1 = p              */
	set_value(2);				/*          (Z,           */
	set_value(3);				/*             X3,        */
	set_value(4);				/*                X4).    */

	print_register(1);			/* drukowanie X1          */

	dump_heap();
	
	fail = false;
	get_structure("p", 3, 1);	/* X1 = p                 */
	unify_variable(2);			/*       (X2,             */
	unify_variable(3);			/*           X3,          */
	unify_variable(4);			/*              Y),       */
	get_structure("f", 1, 2);	/* X2 = f                 */
	unify_variable(5);			/*       (X),             */
	get_structure("h", 2, 3);	/* X3 = h                 */
	unify_value(4);				/*       (Y,              */
	unify_variable(6);			/*          X6),          */
	get_structure("f", 1, 6);	/* X6 = f                 */
	unify_variable(7);			/*       (X7),            */
	get_structure("a", 0, 7);	/* X7 = a                 */

	printf("fail = %d\n", (int)fail);
	
	print_register(1);			/* drukowanie X1          */
	
	dump_heap();
	
	return 0;
}
Beispiel #13
0
/**
 * Parse a single line of the configuration file. Returns 0 on success or
 * anything else if an error occurred, it will be rare since most fatal errors
 * will quit the program with an error message anyways.
 */
int
process_config_line(wchar_t *line, int linenum)
{
	int len;
	wchar_t *keyword, *name, *value;

        /* Strip trailing whitespace */
	for (len = wcslen(line) - 1; len > 0; len--) {
		if (wcschr(WHITESPACE, line[len]) == NULL)
			break;
		line[len] = '\0';
	}

	/* Get the keyword. (Each line is supposed to begin with a keyword). */
	if ((keyword = strdelim(&line)) == NULL)
		return 0;

	/* Ignore leading whitespace. */
	if (*keyword == '\0')
		keyword = strdelim(&line);

	if (keyword == NULL || !*keyword || *keyword == '\n' || *keyword == '#')
		return 0;

	/* set varname value */
	if (wcscmp(keyword, L"set") == 0) {
		if ((name = strdelim(&line)) == NULL) {
			fatal("prwdrc: set without variable name on line %d.\n", linenum);
			return -1;
		}
		value = strdelim(&line);
		set_variable(name, value, linenum);

	/* alias short long */
	} else if (wcscmp(keyword, L"alias") == 0) {
		if ((name = strdelim(&line)) == NULL) {
			fatal("prwdrc: alias without name on line %d.\n", linenum);
			return -1;
		}
		value = strdelim(&line);
		add_alias(name, value, linenum);

	/* Unknown operation... God help us. */
	} else {
		fatal("prwdrc: unknown command on line %d.\n", linenum);
		return -1;
	}

	return 0;
}
Beispiel #14
0
void opcode_loadb(void)
{
  uint8_t *address = z_mem + (uint16_t)(op[0] + (int16_t)op[1]);

  TRACE_LOG("Opcode: LOADB.\n");

  read_z_result_variable();

  if (address > active_z_story->static_memory_end)
  {
    TRACE_LOG("Static memory end: %x.\n", active_z_story->static_memory_end);
    TRACE_LOG("Trying to loadb from %x which is above static memory.\n",
        address);
    set_variable(z_res_var, 0, false);
  }
  else
  {
    TRACE_LOG("Loading from %x to var %x.\n",
        *address,
        z_res_var);
    set_variable(z_res_var, *address, false);
  }
}
Beispiel #15
0
bool evaluate_assignment()
{
    object result;

    if(!evaluate_top())
    {
        clear_stack();
        return false;
    }

    if(set_variable(result.data.variable, optic_stack.back()) == OK) // set_variable uses mem_copy, we need to remember to free the top of the stack
    {
//        mem_free(optic_stack.back()); // make sure to free memory!
        optic_stack.pop_back();
        return true;
    }

    else
    {
        out() << "Unable to bind variable " << result.data.string << std::endl;
        clear_stack();
        return false;
    }
}
Beispiel #16
0
// main debugger loop
int bf_debugger( Emulator_t *em )
{
    Emulator_t *dem = em;

    char buf[256];
    int lret = 0;
    int broke;
    int i;

    bfid_brkp_t *temp;
    bfid_cmd_hook_t *hook;

    if ( !bfid_initialized )
        bfid_init( );

    dem->Debugging = 1;
    interrupted = 1;
    signal( SIGINT, (__sighandler_t)debug_signal );

    printf( "[>] Unnamed NES debugger v0.01\n" );
    while ( dem->Debugging ) {
        if ( interrupted ) {
            if ( lret )
                printf( "[%x] ", lret & 0xff );
            else
                printf( "[ ] " );

            printf( "> " );

            fgets( buf, 256, stdin );
            if ( strlen( buf ) < 2 )
                continue;

            if (( lret = bfid_execcmd( dem, buf )) < 0 ) {
                printf( "Unknown command.\n" );
                continue;
            }

            sprintf( buf, "%u\0", dem->Cpus[0].pCounter );
            set_variable( "ip", buf );

            sprintf( buf, "%u\0", dem->Cpus[0].sPointer );
            set_variable( "ptr", buf );

        } else {

            for ( i = 0; i < dem->cpuNo; i++ ) {
                CpuStep( &dem->Cpus[i] );

                // Check for breakpoints on the cpu
                for ( temp = brkp_list; temp; temp = temp->next ) {
                    broke = 0;
                    if ( temp->type == BRK_IP && temp->val == dem->Cpus[i].pCounter ) {
                        interrupted = broke = 1;

                    } else if ( temp->type == BRK_MEM && temp->val == dem->Cpus[i].sPointer ) {
                        interrupted = broke = 1;

                    } else if ( 	temp->type == BRK_INSTR &&
                                    //temp->val == dem->Cpus[i].memory[ dem->Cpus[i].pCounter ]){
                                    temp->val == ReadByte( dem->Cpus[i].memory, dem->Cpus[i].pCounter )) {

                        interrupted = broke = 1;
                    }

                    if ( broke ) {
                        sprintf( buf, "%u\0", dem->Cpus[i].pCounter );
                        set_variable( "ip", buf );

                        sprintf( buf, "%u\0", dem->Cpus[i].sPointer );
                        set_variable( "ptr", buf );

                        if ( 	get_variable( "quiet" ) &&
                                strcmp( get_variable( "quiet" ), "true" )) {
                            printf( "[ ] cpu%d: breakpoint %d\n", i, temp->i );
                        }

                        for ( hook = temp->hooks; hook; hook = hook->next ) {
                            if ( bfid_execcmd( dem, hook->cmd ) < 0 )
                                printf( "[ ] Unknown hook command: \"%s\"\n", hook->cmd );
                        }
                    }
                }
            }
        }
    }

    return 0;
}
Beispiel #17
0
/*----------------------------------------------------------------------
      Rename the current sent-mail folder to sent-mail for last month

   open up sent-mail and get date of very first message
   if date is last month rename and...
       if files from 3 months ago exist ask if they should be deleted and...
           if files from previous months and yes ask about them, too.   
  ----------------------------------------------------------------------*/
int
expire_sent_mail(void)
{
    int		 cur_month, ok = 1;
    time_t	 now;
    char	 tmp[50], **p;
    struct tm	*tm_now;
    CONTEXT_S	*prune_cntxt;

    dprint((5, "==== expire_mail called ====\n"));

    if(!check_prune_time(&now, &tm_now))
      return 0;

    cur_month = (1900 + tm_now->tm_year) * 12 + tm_now->tm_mon;
    dprint((5, "Current month %d\n", cur_month));

    /*
     * locate the default save context...
     */
    if(!(prune_cntxt = default_save_context(ps_global->context_list)))
      prune_cntxt = ps_global->context_list;

    /*
     * Since fcc's and read-mail can be an IMAP mailbox, be sure to only
     * try expiring a list if it's an ambiguous name associated with some
     * collection...
     *
     * If sentmail set outside a context, then pruning is up to the
     * user...
     */
    if(prune_cntxt){
	if(ps_global->VAR_DEFAULT_FCC && *ps_global->VAR_DEFAULT_FCC
	   && context_isambig(ps_global->VAR_DEFAULT_FCC))
	  ok = prune_folders(prune_cntxt, ps_global->VAR_DEFAULT_FCC,
			     cur_month, " SENT",
			     ps_global->pruning_rule);

	if(ok && ps_global->VAR_READ_MESSAGE_FOLDER 
	   && *ps_global->VAR_READ_MESSAGE_FOLDER
	   && context_isambig(ps_global->VAR_READ_MESSAGE_FOLDER))
	  ok = prune_folders(prune_cntxt, ps_global->VAR_READ_MESSAGE_FOLDER,
			     cur_month, " READ",
			     ps_global->pruning_rule);
    }

    /*
     * Within the default prune context,
     * prune back the folders with the given name
     */
    if(ok && prune_cntxt && (p = ps_global->VAR_PRUNED_FOLDERS))
      for(; ok && *p; p++)
	if(**p && context_isambig(*p))
	  ok = prune_folders(prune_cntxt, *p, cur_month, "",
			     ps_global->pruning_rule);

    /*
     * Mark that we're done for this month...
     */
    if(ok){
	ps_global->last_expire_year = tm_now->tm_year;
	ps_global->last_expire_month = tm_now->tm_mon;
	snprintf(tmp, sizeof(tmp), "%d.%d", ps_global->last_expire_year,
		ps_global->last_expire_month + 1);
	set_variable(V_LAST_TIME_PRUNE_QUESTION, tmp, 1, 1, Main);
    }

    return(1);
}
Beispiel #18
0
void bfid_init( ){
	// initialize variables
	set_variable( "?", "0" );
	set_variable( "ip", "0" );
	set_variable( "ptr", "0" );

	// register all the functions
	register_bfid_func( "alias", "create an alias for a debugger command", 
			"alias [alias] [command]", bfid_alias );

	register_bfid_func( "break", "set program breakpoints", 
			"break [type] [value]", bfid_break );

	register_bfid_func( "clear", "remove program breakpoints", 
			"clear [value]", bfid_clear );

	register_bfid_func( "cont", "continue program execution in the debugger", 
			"cont", bfid_cont );

	register_bfid_func( "disas", "disassemble program instructions", 
			"disas [amount] | disas [start] [end] [(optional)filter string]", bfid_disas );

	register_bfid_func( "dump", "dump program memory", 
			"dump [amount] | dump [start] [end]", bfid_dump );

	register_bfid_func( "echo", "print text to screen", 
			"echo [text]", bfid_echo );

	register_bfid_func( "exec", "execute brainfuck code in program's context",
			"exec [code]", bfid_exec );

	register_bfid_func( "exit", "exit the debugger. Resumes execution if "
			"the debugger was started from the code.", "exit", bfid_exit );

	register_bfid_func( "help", "Get help for debugger commands", 
			"help [command]", bfid_help );

	register_bfid_func( "hook", "hook command onto breakpoint", 
			"hook [id] [code]", bfid_hook );

	register_bfid_func( "peek", "get values from memory", 
			"peek [type] [where]", bfid_peek );

	register_bfid_func( "poke", "place values in memory", 
			"poke [type] [where] [value]", bfid_poke );

	register_bfid_func( "script", "run a debugger script", 
			"script [filename]", bfid_script );

	register_bfid_func( "set", "set program variables", 
			"set [variable] [value]", bfid_set );

	register_bfid_func( "step", "step through code instructions", 
			"step [amount]", bfid_step );

	register_bfid_func( "trace", "trace program structures", 
			"trace [type]", bfid_trace );

	// and we're good
	bfid_initialized = 1;
}
Beispiel #19
0
// main debugger loop
int bf_debugger( bf_code_t *bf ){
	bf_code_t *dbf = bf;
	//bf_code_t *dbf = new( bf_code_t );
	//memcpy( dbf, bf, sizeof( bf_code_t ));
	char buf[256];
	int lret = 0;
	int broke;

	bfid_brkp_t *temp;
	bfid_cmd_hook_t *hook;

	if ( !bfid_initialized )
		bfid_init( );

	dbf->debugging = 1;
	interrupted = 1;
	signal( SIGINT, (__sighandler_t)debug_signal );

	printf( "[>] yabi debugger v0.99\n" );
	while ( dbf->debugging ){
		if ( interrupted ){
			if ( lret )
				printf( "[%d] ", lret );
			else 
				printf( "[ ] " );

			printf( "> " );

			fgets( buf, 256, stdin );
			if ( strlen( buf ) < 2 )
				continue;

			if (( lret = bfid_execcmd( dbf, buf )) < 0 )
				printf( "Unknown command.\n" );
		} else {
			if ( dbf->ip < dbf->codesize ){
				bf_step( dbf );

				for ( temp = brkp_list; temp; temp = temp->next ){
					broke = 0;
					if ( temp->type == BRK_IP && temp->val == dbf->ip ){
						interrupted = broke = 1;

					} else if ( temp->type == BRK_MEM && temp->val == dbf->ptr ){
						interrupted = broke = 1;

					} else if ( 	temp->type == BRK_INSTR && 
							temp->val == dbf->code[ dbf->ip ]){
						interrupted = broke = 1;
					}

					if ( broke ){
						sprintf( buf, "%u\0", dbf->ip );
						set_variable( "ip", buf );

						sprintf( buf, "%u\0", dbf->ptr );
						set_variable( "ptr", buf );
				
						for ( hook = temp->hooks; hook; hook = hook->next ){
							if ( bfid_execcmd( dbf, hook->cmd ) < 0 )
								printf( "[ ] Unknown hook command: \"%s\"\n", hook->cmd );
						}
					}
				}

			} else {
				printf( "Program terminated.\n" );
				interrupted = 1;
			}
		}
	}

	//free( dbf );
	return 0;
}
Beispiel #20
0
/*
 * Set initial variables at INIT stage
 */
void set_preset_variables(int argc)
{
char *ttemp;

    if (argc)
    { /* Started from Shell */
	if (args[ARG_APPNAME])
	{
	    set_variable("@app-name", (STRPTR)args[ARG_APPNAME], 0);
	}
	else
	{
	    set_variable("@app-name", "DemoApp", 0);
	}

	if (args[ARG_LANGUAGE])
	{
	    set_variable("@language", (char *)args[ARG_LANGUAGE], 0);
	}
	else
	{
	    set_variable("@language", "english", 0);
	}
    }
    else
    { /* Started from Workbench */
	ttemp = ArgString(tooltypes, "APPNAME", NULL);
	if (ttemp)
	{
	    set_variable("@app-name", ttemp, 0);
	}
	else
	{
	    set_variable("@app-name", "DemoApp", 0);
	}
	set_variable("@language", ArgString(tooltypes, "LANGUAGE", "english"), 0);
    }

    set_variable("@abort-button", ABORT_BUTTON, 0);
    set_variable("@default-dest", DEFAULT_DEST, 0);
    set_variable("@installer-version", NULL, (INSTALLER_VERSION << 16) + INSTALLER_REVISION);
    set_variable("@user-level", NULL, preferences.defusrlevel);
    set_variable("@pretend",    NULL, preferences.pretend);

    /* Set help texts */
    set_variable("@askchoice-help",  ASKCHOICE_HELP,  0);
    set_variable("@asknumber-help",  ASKNUMBER_HELP,  0);
    set_variable("@askoptions-help", ASKOPTIONS_HELP, 0);
    set_variable("@askstring-help",  ASKSTRING_HELP,  0);

    /* Set other variables to (NULL|0) */
    set_variable("@askdir-help",    NULL, 0);
    set_variable("@askdisk-help",   NULL, 0);
    set_variable("@askfile-help",   NULL, 0);
    set_variable("@copyfiles-help", NULL, 0);
    set_variable("@copylib-help",   NULL, 0);
    set_variable("@each-name",      NULL, 0);
    set_variable("@each-type",      NULL, 0);
    set_variable("@error-msg",      NULL, 0);
    set_variable("@execute-dir",    NULL, 0);
    set_variable("@icon",           NULL, 0);
    set_variable("@ioerr",          NULL, 0);
    set_variable("@makedir-help",   NULL, 0);
    set_variable("@special-msg",    NULL, 0);
    set_variable("@startup-help",   NULL, 0);
}
Beispiel #21
0
int main(int argc, char *argv[]) {
/* main
 * The main LEAP program - This performs the display of the
 * title, and processes the command line. Clean termination
 * also should occur here. Everywhere else termination is
 * "unclean", and should return an error status. Define
 * error status' in the dtypes.h file
 */
#ifdef FULL_DEBUG
	/* Test vars */
	char source[50],result[50],*sptr;
#endif
	boolean tdebug=FALSE,ttiming=FALSE,ttimelog=FALSE,tlong=FALSE;
	boolean tquiet=FALSE,ttrace=FALSE,tpad=FALSE,tpjoin=FALSE;
	time_t tp;
	char *s;
	char *argptr;

	/********************************
	 * Startup - Firstly set up the
         * signal handlers
	 ********************************/

	/* Signal Interrupt from the keyboard - the daemon should handle it */
	signal(SIGINT,&signal_handler); 

	/* MSDOS/Windows does not know SIGQUIT/SIGHUP, whereas
	 * these are important in Unix
	 */
#ifndef __MSDOS__

	/* Signal Quit from the keyboard - Ignore it */
	signal(SIGQUIT,SIG_IGN);

	/* Signal Hang up - Handle it */
	signal(SIGHUP,&signal_handler);

#else

#endif

	define_handle(&default_handler,&errorHandler);
	raise_message(EVENT, "%s","Event Handler initialised.");

	define_handle(&default_quiethandler,&messageHandler);
	raise_message(EVENT,"%s","Message Handler initialised.");

	/* Signal Terminate - Handle it */
	signal(SIGTERM,&signal_handler);


	/* Perform some configuration... */
	build_base_dir(LEAP_DEFAULT_DIR);
	
	/* Set the random seed to the time in secs since 01.01.1970
	 * should be random enough!
	 */
	srand(time(NULL));

	s=getenv(LEAP_ENV_DIR);

	strcpy(dbtoopen,"");
	strcpy(activityfile,"");
	strcpy(tempdir,"");
	ACTIVITY_FILE=NULL;

	if (s!=NULL) {
		leap_fprintf(stdout,"Using environment variable %s for path (%s).\n",LEAP_ENV_DIR,s);
		build_base_dir(s);
	}

	/* Process the command line
		Stop if we run out of arguments
		or we get an argument without a dash */

	/* NB. This is based on O'Reilly & Associates "Practical
	  C Programming", by Steve Oualline, 2nd Ed. (pg 178) */

	while ((argc > 1) && (argv[1][0] == '-')) {
		/* 
		 * argv[1][1] is the actual option character
		 */
		if ((argv[1][0]==ARGUMENT_PREFIX) && (argv[1][1]==ARGUMENT_PREFIX)) {
			argptr=&argv[1][2];
		} else {
			argptr=&argv[1][1];
		}
		switch (*argptr) {
		case 'a':
		case 'A':
			if ((strcmp(argptr,"activity-file")==0)||(strcmp(argptr,"activity")==0)||(strlen(argptr)==1)) {
				if (specify(activityfile,argv[2],FILE_PATH_SIZE)){
					argv++;
					argc--;
				} else {
					leap_fprintf(stderr,"No file specified. Using %s\n",LEAP_ACTIVITY_FILE);
					strncpy(activityfile,LEAP_ACTIVITY_FILE,FILE_PATH_SIZE);
				}
				ACTIVITY_FILE=fopen(activityfile,"a");
				if (ACTIVITY_FILE==NULL) {
					leap_fprintf(stderr,"Unable to open activity file for appending.\n");
				} else {
					tp=time(NULL);
					fprintf(ACTIVITY_FILE,"###\n# Activity file STARTED at: %s###\n",ctime(&tp));
					leap_printf("Activity file: %s\n",activityfile);
				}
			}
			break;
			
		case 'b':
		case 'B':
			if (specify(dbtoopen,argv[2],DATABASE_NAME_SIZE)){
				argv++;
				argc--;
			} else {
				raise_message(MESSAGE,"No database specified on command line. %s will be used.",DEFAULT_DB);
			}
			break;

		case 'd':
		case 'D':
			if ((strcmp(argptr,"dir")==0)||(strcmp(argptr,"directory")==0)||(strlen(argptr)==1)) {
				if (argv[2]) {
					build_base_dir(argv[2]);
	
					/* Increment the counts... */
					argv++;
					argc--;
				} else {
					leap_fprintf(stderr,"ERROR: No directory specified after directory flag.\n");
					exit(1);
				}
			} else if (strcmp(argptr,"database")==0) {
				if (specify(dbtoopen,argv[2],DATABASE_NAME_SIZE)){
					argv++;
					argc--;
				}
			} else if (strcmp(argptr,"debug")==0) {
				/* The user wants debug information */
				leap_printf("Debug messages enabled\n");
				tdebug=TRUE;
			}
			break;

		case 'e':
		case 'E':
			if (strlen(argptr)==1) {
				/* The user wants debug information */
				leap_printf("Debug messages enabled\n");
				tdebug=TRUE;
			} else if ((strcmp(argptr,"events")==0)||(strcmp(argptr,"event")==0)) {
				/* User wants event reports */
				define_handle(&default_quiethandler,&eventHandler);
				raise_message(EVENT,"%s","Event Handler initialised.");
			}
			break;
		case 'h':
		case '?':
		case 'H':
			if ((strcmp(argptr,"help")==0)||(strlen(argptr)==1)) {
				/* The user wants some help... */
				print_help();

				/* Exit without an error */
				exit(0);
	
				/* Lint-ified - The break is not reached */
				/* break; */
			}
		case 'i':
		case 'I':
			/* The user wants timing information */
			leap_printf("Timing information enabled\n");
			ttiming=TRUE;
			break;

		case 'l':
		case 'L':
			if ((strcmp(argptr,"time-logging")==0)||(strlen(argptr)==1)) {
				/* Do not fetch the system time in log file */
				leap_printf("Time logging disabled\n");
				ttimelog=FALSE;
			} else if ((strcmp(argptr,"long-commands")==0)||(strcmp(argptr,"long")==0)){
				leap_printf("Long commands enabled\n");
				tlong=TRUE;
			}
			break;
		case 'n':
		case 'N':
			/* Display warranty information */
			do_warranty();
			exit(0);
				
			/* Lint-ified - The break is not reached */
			/* break; */
		case 'o':
		case 'O':
			leap_printf("Long commands enabled\n");
			tlong=TRUE;
			break;
		case 'p':
		case 'P':
			if ((strcmp(argptr,"padding")==0)||(strlen(argptr)==1)) {
				leap_printf("Relation Name Padding enabled\n");
				tpad=TRUE;
			} else if ((strcmp(argptr,"product-join")==0)||(strcmp(argptr,"pjoin")==0)) {
				leap_printf("Product performed in no-condition join\n");
				tpjoin=TRUE;
			} 
			break;
		case 'q':
		case 'Q':
			if ((strcmp(argptr,"quiet")==0)||(strlen(argptr)==1)) {
				tquiet=TRUE;
				BEEP=' ';

				/* Shutdown the message handler */
				define_handle(NULL,&messageHandler);
			}
			break;
		case 'r':
		case 'R':
			if ((strcmp(argptr,"regression")==0)||(strlen(argptr)==1)) {
				/*  What!? This is to disable outputting
 		 		 * items that might cause regression tests
				 * to fail for no good reason, ie. 
				 * temporary relation names which are random,
				 * and will differ between runs.
			     */
				status_regression=TRUE;
				leap_printf("Regression test mode on\n");
			}
			break;
		case 's':
		case 'S':
			if ((strcmp(argptr,"status")==0)||(strlen(argptr)==1)) {
				/* The user wants status messages to be
			   	displayed */
				leap_printf("Status messages enabled\n");
				status=TRUE;
			}
			break;
		case 't':
		case 'T':
			if ((strcmp(argptr,"time")==0)||(strcmp(argptr,"timing")==0)) {
				/* The user wants timing information */
				leap_printf("Timing information enabled\n");
				ttiming=TRUE;
			} else if ((strlen(argptr)==1)||(strcmp(argptr,"trace")==0)||(strcmp(argptr,"tracing")==0)) {
				/* The user wants tracing information */
				leap_printf("Tracing information enabled\n");
				ttrace=TRUE;
			}
			break;
		case 'v':
		case 'V':
			if ((strcmp(argptr,"version")==0)||(strlen(argptr)==1))  {
				/* Print BRIEF version information */
				print_header(TRUE);
				exit(0);
			}
			break;
		case 'w':
		case 'W':
			if ((strcmp(argptr,"warranty")==0)||(strlen(argptr)==1)) {
				do_warranty();
				exit(0);
			}
			break;
		case 'x':
		case 'X':
			if (argv[2]) {
				strncpy(tempdir,argv[2],FILE_PATH_SIZE);
				/* Increment the counts... */
				argv++;
				argc--;
			} else {
				leap_fprintf(stderr,"ERROR: No directory specified after temporary directory flag.\n");
				exit(1);
			}
			break;

			
		default:
			raise_error(ERROR_COMMAND_LINE,NONFATAL,argptr);
		}

		/* Move the argument list up one and the count down one */
		argv++;
		argc--;
	}
	raise_message(EVENT,"%s","Command line processed.");

	/* First things first, report (verbosely) what we are. */
	if ((status_regression!=TRUE) && (tquiet!=TRUE))
		print_header(FALSE);
	
	if ( (status) && (tquiet!=TRUE) ) {
		sprintf(temp_80_chars,"LEAP Base directory set to: %s",LEAP_BASE_DIR);
		leap_printf(temp_80_chars);
	}

	/* Call any initialisation routines... */
	util_init();

	/* This has to be done after the path is read, so that
     * the variable config file is located.
     */
	if (init_variables()!=RETURN_SUCCESS) {
		raise_message(MESSAGE,"Directory specified [%s] not valid. Trying [%s]",LEAP_BASE_DIR,LEAP_TRY_DIR);
		build_base_dir(LEAP_TRY_DIR);
		if (init_variables()!=RETURN_SUCCESS) {
			raise_message(MESSAGE,"[%s] is also not valid - Problems are likely",LEAP_TRY_DIR);
		} else {
			raise_message(MESSAGE,"Variables are now set.");
		}
	}
		

	if (tdebug==TRUE) set_variable(STATUS_DEBUG,STATUS_SETTING_ON);
	if (ttiming==TRUE) set_variable(STATUS_TIMING,STATUS_SETTING_ON);
	if (ttimelog==TRUE) set_variable(STATUS_TIMELOG,STATUS_SETTING_ON);
	if (tlong==FALSE) set_variable(STATUS_LONGLINE,STATUS_SETTING_OFF);
	if (tquiet==TRUE) set_variable(STATUS_QUIET,STATUS_SETTING_ON);
	if (ttrace==TRUE) set_variable(STATUS_TRACE,STATUS_SETTING_ON);
	if (tpad==TRUE) set_variable(STATUS_PADDING,STATUS_SETTING_ON);
	if (tpjoin==TRUE) set_variable(STATUS_PRODUCTJOIN,STATUS_SETTING_ON);

	/* Display some information */
	if (status_quiet!=TRUE) {
		raise_message(MESSAGE,"LEAP is starting...");
	}
	
#ifdef DEBUG
	status_debug=TRUE;
	leap_fprintf(stderr,"DEBUG: LEAP debug mode forced on\n");
#endif

	/* Do the main leap operation */
	(void) do_daemon();
	
	print_shutdown();

	/* Close the various files opened earlier */
	util_close();

	if (status_quiet!=TRUE) {
			/* Inform the user of a clean termination */
			raise_message(MESSAGE,"LEAP Terminated successfully!");
	}

	/* Return success. Elsewhere, non-zero should be returned */
	return(0);
}
Beispiel #22
0
void	do_stack_set (int type, char *args)
{
	VarStack *item;
	char *varname = NULL;
	char *(*dummy) (void) = NULL;
	IrcVariable *var;

	if (set_stack == NULL && (type == STACK_POP || type == STACK_LIST))
	{
		say("Set stack is empty!");
		return;
	}

	if (STACK_PUSH == type)
	{
		varname = next_arg(args, &args);
		if (!varname)
		{
			say("Must specify a variable name to stack");
			return;
		}
		upper(varname);

		item = (VarStack *)new_malloc(sizeof(VarStack));
		item->varname = malloc_strdup(varname);
		item->value = make_string_var(varname);

		item->next = set_stack;
		set_stack = item;
		return;
	}

	else if (STACK_POP == type)
	{
	    VarStack *prev = NULL;
	    int	owd = window_display;

	    varname = next_arg(args, &args);
	    if (!varname)
	    {
		say("Must specify a variable name to stack");
		return;
	    }
	    upper(varname);

	    for (item = set_stack; item; prev = item, item = item->next)
	    {
		/* If this is not it, go to the next one */
		if (my_stricmp(varname, item->varname))
			continue;

		/* remove it from the list */
		if (prev == NULL)
			set_stack = item->next;
		else
			prev->next = item->next;

		window_display = 0; 
		get_var_alias(item->varname, &dummy, &var);
		set_variable(item->varname, var, item->value, 1);
		window_display = owd; 

		new_free(&item->varname);
		new_free(&item->value);
		new_free(&item);
		return;
	    }

	    say("%s is not on the Set stack!", varname);
	    return;
	}

	else if (STACK_LIST == type)
	{
	    VarStack *prev = NULL;

	    for (item = set_stack; item; prev = item, item = item->next)
		say("Variable [%s] = %s", item->varname, item->value ? item->value : "<EMPTY>");

	    return;
	}

	else
		say("Unknown STACK type ??");
}
Beispiel #23
0
void Logger::set_next_line() {
	QMutexLocker locker(&mutex);
	virgin_line = true;
	if (line_message.startsWith(PROGRESS_ON)) progress_on = true;
	if (line_message.startsWith(PROGRESS_OFF)) progress_on = false;
	if (line_message.startsWith(PROGRESS_HEADER)) {
		if (progress_on) {
			if (line_message.startsWith(PROGRESS_MINIMUM)) {
				int v = line_message.right(line_message.length() - line_message.lastIndexOf(":") - 2).toInt();
				process_start.start();
				emit setProgressMinimum(v);
			}
			if (line_message.startsWith(PROGRESS_MAXIMUM)) {
				int v = line_message.right(line_message.length() - line_message.lastIndexOf(":") - 2).toInt();
				emit setProgressMaximum(v);
			}
			if (line_message.startsWith(PROGRESS_VALUE)) {
				int v = line_message.right(line_message.length() - line_message.lastIndexOf(":") - 2).toInt();
				emit setProgressValue(v);
			}
			if (line_message == PROGRESS_DONE) {
				emit setProgressMinimum(0);
				emit setProgressMaximum(1);
				emit resetProgress();
				emit setProgressStatus("Done.",1000);
				setTextColor(Qt::lightGray);
				append(line_time.toString("hh:mm:ss")+": ");
				moveCursor(QTextCursor::End);
				setTextColor(Qt::black);
				float sec = (float)process_start.elapsed()/1000;
				int min = sec / 60;
				QString start_string = last_progress_status;
				if (start_string == "") start_string = "Processing time";
				if (min>0) {
					sec = sec - min*60;
					insertPlainText(tr("%1: %2 min %3 s").arg(start_string).arg(min).arg(sec));
				} else insertPlainText(tr("%1: %2 s").arg(start_string).arg(sec));
				emit set_variable(Application_variable(tr("%1").arg(last_progress_status), QString::number((float)process_start.elapsed()/1000)));
				repaint();

			}
			if (line_message.startsWith(PROGRESS_STATUS)) {
				process_start.start();
				last_progress_status = line_message.right(line_message.length() - line_message.lastIndexOf(":") - 2);
				emit setProgressStatus(last_progress_status,0);
			}
		}
	} else {
		setTextColor(Qt::lightGray);
		append(line_time.toString("hh:mm:ss")+": ");
		moveCursor(QTextCursor::End);
		if (line_message.startsWith(LOG_ERROR)) {
			setTextColor(QColor(168,0,0));
			line_message = line_message.right((int)(line_message.size() - std::string(LOG_ERROR).size()));
			line_message = tr("%1 %2").arg("ERROR: ").arg(line_message);
		} else if (line_message.startsWith(LOG_WARNING)) {
			setTextColor(Qt::blue);
			line_message = line_message.right((int)(line_message.size() - std::string(LOG_WARNING).size()));
			line_message = tr("%1 %2").arg("WARNING: ").arg(line_message);
		} else if (line_message.startsWith(LOG_GREEN)) {
			setTextColor(QColor(0,168,0));
			line_message = line_message.right((int)(line_message.size() - std::string(LOG_GREEN).size()));
		} else if (line_message.startsWith(LOG_BLUE)) {
			setTextColor(Qt::blue);
			line_message = line_message.right((int)(line_message.size() - std::string(LOG_BLUE).size()));
		} else if (line_message.startsWith(LOG_RED)) {
			setTextColor(Qt::red);
			line_message = line_message.right((int)(line_message.size() - std::string(LOG_RED).size()));
		} else	setTextColor(Qt::black);
		insertPlainText(line_message);
//		repaint();
	}
	//#ifdef Q_WS_WIN
	//QEventLoop el(this);
	//el.processEvents(QEventLoop::ExcludeUserInputEvents | QEventLoop::ExcludeSocketNotifiers );	
	//#endif //Q_WS_WIN
	line_message.clear();
}
Beispiel #24
0
char *
rd_metadata_name(void)
{
    char        *p, *q, *metafile;
    char         path[MAXPATH], pinerc_dir[MAXPATH];
    struct variable *vars = ps_global->vars;

    dprint((9, "rd_metadata_name\n"));

    pinerc_dir[0] = '\0';
    if(ps_global->pinerc){
	char *prcn = ps_global->pinerc;
	char *lc;

	if((lc = last_cmpnt(prcn)) != NULL){
	    int to_copy;

	    to_copy = (lc - prcn > 1) ? (lc - prcn - 1) : 1;
	    strncpy(pinerc_dir, prcn, MIN(to_copy, sizeof(pinerc_dir)-1));
	    pinerc_dir[MIN(to_copy, sizeof(pinerc_dir)-1)] = '\0';
	}
	else{
	    pinerc_dir[0] = '.';
	    pinerc_dir[1] = '\0';
	}
    }

    /*
     * If there is no metadata file specified in the pinerc, create a filename.
     */
    if(!(VAR_REMOTE_ABOOK_METADATA && VAR_REMOTE_ABOOK_METADATA[0])){
	if(pinerc_dir[0] && (p = tempfile_in_same_dir(ps_global->pinerc,
						      meta_prefix, NULL))){
	    /* fill in the pinerc variable */
	    q = p + strlen(pinerc_dir) + 1;
	    set_variable(V_REMOTE_ABOOK_METADATA, q, 1, 0, Main);
	    dprint((2, "creating name for metadata file: %s\n",
		   q ? q : "?"));

	    /* something's broken, return NULL rab */
	    if(!VAR_REMOTE_ABOOK_METADATA || !VAR_REMOTE_ABOOK_METADATA[0]){
		our_unlink(p);
		fs_give((void **)&p);
		return(NULL);
	    }

	    fs_give((void **)&p);
	}
	else{
	    q_status_message(SM_ORDER, 3, 5,
		"can't create metadata file in pinerc directory, continuing");
	    return(NULL);
	}
    }

    build_path(path, pinerc_dir ? pinerc_dir : NULL,
	       VAR_REMOTE_ABOOK_METADATA, sizeof(path));
    metafile = path;

    /*
     * If the metadata file doesn't exist, create it.
     */
    if(can_access(metafile, ACCESS_EXISTS) != 0){
	int fd;

	if((fd = our_open(metafile, O_CREAT|O_EXCL|O_WRONLY|O_BINARY, 0600)) < 0){

	    set_variable(V_REMOTE_ABOOK_METADATA, NULL, 1, 0, Main);

	    q_status_message2(SM_ORDER, 3, 5,
		       "can't create cache file %.200s, continuing (%.200s)",
		       metafile, error_description(errno));

	    dprint((2, "can't create metafile %s: %s\n",
		       metafile ? metafile : "?", error_description(errno)));

	    return(NULL);
	}

	dprint((2, "created metadata file: %s\n",
	       metafile ? metafile : "?"));

	(void)close(fd);
    }

    return(cpystr(metafile));;
}
Beispiel #25
0
void do_daemon() {
/* do_leap
 * Main LEAP daemon routine - Contains socket handler
 */
	char buffer[MAXIMUM_INPUT_STRING+1];
	char loginname[MAXIMUM_INPUT_STRING+1];
	char password[MAXIMUM_INPUT_STRING+1];
	char maincommand[MAXIMUM_INPUT_STRING+1];
	char tprompt[MAXIMUM_INPUT_STRING+1];
	char *result,*tresult,*plogin,*ppass;
	relation result_relation;
	int res,startscript=0;
	int serverSocket=0, on=0, port=0, status=0, childPid=0;
	struct hostent *hostPtr=NULL;
	char hostname[80]="";
	struct sockaddr_in serverName={0},clientName={0};
	struct linger linger={0};
	struct utsname sysinfo;
	int clientLength;
	tuple ctuple;

	clientLength=sizeof(clientName);

	tempdb=LEAPAPI_db_create(NULL,TEMPDB_NAME);
	res=relations_ddopen(tempdb);
	if (res!=RETURN_SUCCESS) {
		raise_error(ERROR_OPEN_DATABASE,FATAL,TEMPDB_NAME);		
	}

	/* Open the master database */
	master_db=LEAPAPI_db_create(NULL,MASTER_DB_NAME);
	res=relations_ddopen(master_db);
	if (res!=RETURN_SUCCESS) {
		raise_error(ERROR_OPEN_DATABASE,FATAL,MASTER_DB_NAME);		
	}

	if (strlen(dbtoopen)==0) {
		/* Open up the default user database */
		current_db=LEAPAPI_db_create(NULL,DEFAULT_DB);
	} else {
		current_db=LEAPAPI_db_create(NULL,dbtoopen);
	}

	res=relations_ddopen(current_db);
	if (res!=RETURN_SUCCESS) {
		raise_error(ERROR_OPEN_DATABASE,FATAL,database_name(current_db));		
	}
	
	set_variable(VAR_CURRENTDB,database_name(current_db));

	/* Check to see if the logins relation exists */
	result_relation=relation_find(master_db,LEAP_DD_LOGINS);	

	if (result_relation==NULL) {
		raise_error(ERROR_CANNOT_FIND_REL,NONFATAL,LEAP_DD_LOGINS);
		raise_message(MESSAGE,"Building %s",LEAP_DD_LOGINS);

        /* Build the leaplogins relation */
        sprintf(buffer,"(SUID,INTEGER,3),(NAME,string,25),(PASSWORD,string,25),(DEFAULTDB,string,25)");
        relation_insert(master_db,create_user_relation(master_db,buffer,LEAP_DD_LOGINS,FALSE,TRUE));

        vprocess_query(master_db,"add (%s) (%d,%s,%s,%s)",LEAP_DD_LOGINS,LEAP_SUID_DBA,LEAP_LOGIN_DBA,LEAP_PASS_DBA,MASTER_DB_NAME);
	} else {
		raise_message(MESSAGE,"Found %s!",LEAP_DD_LOGINS);
	}


	if (status_quiet!=TRUE) {
		raise_message(MESSAGE,"%s","Startup sequence initiated.");
	}

	terminate=FALSE;
	terminatenow=FALSE;

	if (status_quiet) {
			strcpy(current_prompt,"");
			set_prompt("");
	} else {
			strcpy(current_prompt,DEFAULT_PROMPT);
			set_prompt(DEFAULT_PROMPT);
	}

	if (configuration!=TRUE) {
		raise_message(MESSAGE,"Sourcing %s%s in %s",LEAP_STARTUP,LEAP_SOURCE_EXT,database_name(master_db));
		sprintf(buffer,"%s%s%s%s",database_dir(master_db),LEAP_SOURCE_DIR,LEAP_STARTUP,LEAP_SOURCE_EXT);
		assign_input_stream(buffer);
	} else {
		sprintf(buffer,"%s",configurationfile);
		assign_input_stream(buffer);
	}


	serverSocket=socket(PF_INET,SOCK_STREAM,0);

	if (serverSocket==-1) {
		raise_error(ERROR_SOCKETINIT,FATAL,"socket()");
	}

	on=1;

	status=setsockopt(serverSocket,SOL_SOCKET,SO_REUSEADDR,(const char *) &on,sizeof(on));

	if (status==-1) {
		raise_error(ERROR_SOCKETINIT,FATAL,"setsockopt(...,SO_REUSEADDR,...)");
	}
	
	linger.l_onoff=1;
	linger.l_linger=30;
	status=setsockopt(serverSocket,SOL_SOCKET,SO_LINGER,(const char *) &linger,sizeof(linger));
	if (status==-1) {
		raise_error(ERROR_SOCKETINIT,FATAL,"setsockopt(...,SO_LINGER,...)");
	}
		
	status=uname(&sysinfo);
	if (status==-1) {
		raise_error(ERROR_SOCKETINIT,FATAL,"uname");
	} else {
		strncpy(hostname,sysinfo.nodename,sizeof(hostname));
	}
		
	status=gethostname(hostname,sizeof(hostname));
	hostPtr=gethostbyname(hostname);

	if (hostPtr==NULL) {
		raise_error(ERROR_SOCKETINIT,FATAL,"gethostbyname");
	} 
	
	(void) memset(&serverName,0,sizeof(serverName));
	(void) memcpy(&serverName.sin_addr,hostPtr->h_addr,hostPtr->h_length);
	
	serverName.sin_family=AF_INET;
	serverName.sin_port=htons(LEAPD_PORT);
	status=bind(serverSocket,(struct sockaddr *) &serverName,sizeof(serverName));

	if (status<0) {
		raise_error(ERROR_SOCKETINIT,FATAL,"bind() - port %u - errno %u",LEAPD_PORT,errno);
	} else {
		raise_message(MESSAGE,"Daemon starting on machine %s, port %u",hostname,LEAPD_PORT);
	}

	status=listen(serverSocket,LEAPD_BACK_LOG);
	if (status==-1) {
		raise_error(ERROR_SOCKETINIT,FATAL,"listen()");
	}


	while (!terminatenow) {
			slaveSocket=accept(serverSocket,(struct sockaddr *) &clientName,&clientLength);

			if (slaveSocket==-1) {
				raise_error(ERROR_SOCKETINIT,FATAL,"accept()");
			}
				
			raise_message(MESSAGE,"Connection received from [%s]",inet_ntoa(clientName.sin_addr));

			raise_message(MESSAGE,"Authenication expected");

			strcpy(buffer,"Please authenticate yourself: ");
			write(slaveSocket,buffer,strlen(buffer));

			read(slaveSocket,loginname,MAXIMUM_INPUT_STRING);
			plogin=strtok(loginname,"\r\n");
			raise_message(MESSAGE,"Login [%s] connecting...",plogin);

			if (strcmp(plogin,"guest")==0) {
				strcpy(buffer,"Enter your e-mail address: ");
				write(slaveSocket,buffer,strlen(buffer));
			} else {
				strcpy(buffer,"Password: "******"project (select (%s) (%s='%s')) (%s)",LEAP_DD_LOGINS,LEAP_DDA_LOGINS_NAME,plogin,LEAP_DDA_LOGINS_PASSWORD);
			result_relation=process_query(master_db,buffer);

			status=read(slaveSocket,password,MAXIMUM_INPUT_STRING);
			ppass=strtok(password,"\r\n");

			if ((ppass!=NULL) && (status==2)) {
				*ppass='******';
			}

			ctuple=tuple_readfirst(result_relation,TUPLE_BUILD,NULL);
			if (ctuple!=NULL) {
				tuple_to_string(ctuple,buffer);
				raise_message(MESSAGE,"Password expected [%s]",buffer);
				raise_message(MESSAGE,"Password received [%s]",ppass);
			} else {
				if (strcmp(plogin,"guest")==0) {
					raise_message(MESSAGE,"Guest ID [%s]",ppass);
				} else {
					raise_message(MESSAGE,"No login [%s] exists!",plogin);
				}
			}
	
			if (((strcmp(plogin,"guest")==0))||(strcmp(buffer,ppass)==0)) {
					raise_message(MESSAGE,"Login [%s] validated!",plogin); 
					/* Enable daemon on - this will send io to client */
					status_daemon=TRUE;
				
					strcpy(buffer,"version");
					result_relation=process_query(current_db,buffer);

					/* Ok, socket is initialised! */
					while (!terminate) {

						write(slaveSocket,DEFAULT_PROMPT,sizeof(DEFAULT_PROMPT));
						status=read(slaveSocket,buffer,MAXIMUM_INPUT_STRING);
						/* Null terminate reqd....*/
						
						result=strtok(buffer,"\r\n");
						
						status_daemon=FALSE;
						raise_message(MESSAGE,"received: %s",result);
						status_daemon=TRUE;

						result_relation=process_query(current_db,result);

					}
					/* Disable daemon */
					status_daemon=FALSE;
			} else {
				raise_message(MESSAGE,"Invalid password for login [%s]",plogin);
			}

			/* Reset terminate - one client has disconnected */
			terminate=FALSE;

			raise_message(MESSAGE,"Connection closed");
			close(slaveSocket);
	}

	if (!status_quiet) { raise_message(MESSAGE,"Closing [%s] database.",database_name(current_db)); }
	
	relations_dispose_all(current_db);

	LEAPAPI_db_destroy(&current_db);

	raise_event(EVENT,"[current_db] closed.");

	if (!status_quiet) { raise_message(MESSAGE,"Closing [%s] database.",database_name(master_db)); }

	relations_dispose_all(master_db);
	
	LEAPAPI_db_destroy(&master_db);

	raise_event(EVENT,"[master_db] closed.");

	if (!status_quiet) { raise_message(MESSAGE,"Closing [%s] database.",database_name(tempdb)); }

	relations_dispose_all(tempdb);
	
	LEAPAPI_db_destroy(&tempdb);

	raise_event(EVENT,"[tempdb] closed.");
}
inline bool set_variable(const string& Name, const string& Value) {
    return set_variable(Name.data(), Value.data());
}
Beispiel #27
0
void opcode_save_undo(void)
{
  size_t dynamic_memory_size;
  struct undo_frame *new_undo_frame;
  int result;
  size_t nof_stack_bytes_in_use;

  TRACE_LOG("Opcode: SAVE_UNDO.\n");

  if (max_undo_steps <= 0)
  {
    result = 0;
  }
  else
  {
    if ( (undo_frames == NULL) && (set_max_undo_steps(max_undo_steps) != 0) )
    {
      result = 0;
    }
    else
    {
      if ((new_undo_frame = create_new_undo_frame()) == NULL)
      {
        result = 0;
      }
      else
      {
        dynamic_memory_size = (size_t)(
            active_z_story->dynamic_memory_end - z_mem + 1 );

        if ( (new_undo_frame->dynamic_memory = malloc(dynamic_memory_size))
            == NULL)
        {
          delete_undo_frame(new_undo_frame);
          result = 0;
        }
        else
        {
          nof_stack_bytes_in_use = (z_stack_index - z_stack) * sizeof(uint16_t);

          if ((new_undo_frame->stack
                = (uint16_t*)malloc(nof_stack_bytes_in_use)) == NULL)
          {
            delete_undo_frame(new_undo_frame);
            result = 0;
          }
          else
          {
            if (undo_index == max_undo_steps)
            {
              delete_undo_frame(undo_frames[0]);

              memmove(
                  undo_frames,
                  undo_frames + 1,
                  sizeof(struct undo_frame*) * (max_undo_steps - 1));

              undo_index--;
            }

            memcpy(
                new_undo_frame->stack,
                z_stack, // non-null when size > 0
                nof_stack_bytes_in_use);

            memcpy(
                new_undo_frame->dynamic_memory,
                z_mem,
                dynamic_memory_size);

            // new_undo_frame->pc is not allocated, no free required.
            new_undo_frame->pc = pc;

            new_undo_frame->z_stack_size = z_stack_index - z_stack;
            new_undo_frame->stack_words_from_active_routine
              = stack_words_from_active_routine;
            new_undo_frame->number_of_locals_active
              = number_of_locals_active;
            new_undo_frame->number_of_locals_from_function_call
              = number_of_locals_from_function_call;

            undo_frames[undo_index++] = new_undo_frame;

            result = 1;
          }
        }
      }
    }
  }

  read_z_result_variable();
  set_variable(z_res_var, (uint16_t)result, false);
}
void dynamic_context::add_variable(ulong varid, store::Item_t& value)
{
  declare_variable(varid, false);
  set_variable(varid, NULL, QueryLoc::null, value);
}
Beispiel #29
0
static HANDLE run_simple_command_nowait(simple_command_t* sc, HANDLE _in, HANDLE _out)
{
	BOOL success = TRUE;
	HANDLE  in  = _in, 
			out = _out, 
			err = INVALID_HANDLE_VALUE;
	HANDLE proc;
	DWORD open_mode;

	char* command = word_to_string(sc->verb, FALSE);

	if (!strcmp(command, "cd")) {
		BOOL rc = TRUE;
		if (sc->params != NULL) {
			char* path = word_to_string(sc->params, FALSE);
			rc = change_directory(path);
			free(path);
		}
		if (rc)
			return SPECIAL_COMMAND_HANDLE;
		return  INVALID_HANDLE_VALUE;
	}


	if (strchr(command, '=')) {
		set_variable(command);
		return SPECIAL_COMMAND_HANDLE;
	}

	if (sc->params != NULL) {
		char* params = word_to_string(sc->params, TRUE);
		append(&command, params);
		free(params);
	}
	
	if (sc->in != NULL) {
		SECURITY_ATTRIBUTES sa;
		char* file_name = word_to_string(sc->in, FALSE);

		ZeroMemory(&sa, sizeof(sa));
		sa.bInheritHandle = TRUE;

		in = CreateFile(file_name, GENERIC_READ, FILE_SHARE_READ, &sa, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (in == INVALID_HANDLE_VALUE) {
			fprintf(stderr, "ERROR opening input");
			success = FALSE;
		}
		free(file_name);
	}

	if (sc->out != NULL) {
		SECURITY_ATTRIBUTES sa;
		char* file_name = word_to_string(sc->out, FALSE);

		ZeroMemory(&sa, sizeof(sa));
		sa.bInheritHandle = TRUE;
		if (sc->io_flags == IO_OUT_APPEND)
			open_mode = OPEN_ALWAYS;
		else
			open_mode = CREATE_ALWAYS;

		out = CreateFile(file_name, GENERIC_WRITE, FILE_SHARE_WRITE, &sa, open_mode, FILE_ATTRIBUTE_NORMAL, NULL);
		if (open_mode == OPEN_ALWAYS)
			seek_end_file(out);
		if (out == INVALID_HANDLE_VALUE) {
			fprintf(stderr, "ERROR opening output");
			success = FALSE;
		}
		free(file_name);
	}

	if (sc->err != NULL) {
		SECURITY_ATTRIBUTES sa;
		char* file_name;
		if (sc->io_flags == IO_ERR_APPEND)
			open_mode = OPEN_ALWAYS;
		else
			open_mode = CREATE_ALWAYS;

		if (sc->err == sc->out) {
			err = out;//DUPLICATEHANDLE?
		} else {

			file_name  = word_to_string(sc->err, FALSE);
			ZeroMemory(&sa, sizeof(sa));
			sa.bInheritHandle = TRUE;

			err = CreateFile(file_name, GENERIC_WRITE, FILE_SHARE_WRITE, &sa, open_mode, FILE_ATTRIBUTE_NORMAL, NULL);
			if (open_mode == OPEN_ALWAYS)
				seek_end_file(err);
			if (err == INVALID_HANDLE_VALUE) {
				fprintf(stderr, "ERROR opening Error");
				success = FALSE;
			}
			free(file_name);
		}
	}

	if (success)
		proc = WinCreateProcess(command, in, out, err);

	CloseHandle(in);
	CloseHandle(out);
	CloseHandle(err);
	free(command);

	if (!success)
		return INVALID_HANDLE_VALUE;
	return proc;
}
Beispiel #30
0
void opcode_set_font(void)
{
  z_font new_z_font;

  // If the requested font is available, then it is chosen for the
  // current window, and the store value is the font ID of the previous
  // font (which is always positive). If the font is unavailable,
  // nothing will happen and the store value is 0.

  // Please note: I consider the "normal" -- code 1 -- and the courier,
  // fixed font -- code 4 -- to be always available. For simple interfaces,
  // these are probably the same. The availability of the character graphics
  // and picture font are read from interface definition.

  TRACE_LOG("Opcode: SET_FONT\n");
  read_z_result_variable();
  new_z_font = (int16_t)op[0];

  // REVISIT: Implement warning.
  if (
      ( (new_z_font < 0) || (new_z_font > 4) )
      ||
      (
       (new_z_font == Z_FONT_PICTURE)
       &&
       (active_interface->is_picture_font_availiable() != true)
      )
      ||
      (
       (new_z_font == Z_FONT_CHARACTER_GRAPHICS)
       &&
       (active_interface->is_character_graphics_font_availiable() != true)
      )
     )
  {
    set_variable(z_res_var, 0, false);
    return;
  }

  /*
  // REVISIT: Is it correct to not double-set fonts?
  if (new_z_font != current_font)
  {
    if (active_window_number == 0)
    {
#ifndef DISABLE_OUTPUT_HISTORY
      store_metadata_in_history(
          outputhistory[0],
          HISTORY_METADATA_TYPE_FONT,
          new_z_font);
#endif // DISABLE_OUTPUT_HISTORY
    }

    else if (active_window_number == 1)
    {
#ifndef DISABLE_BLOCKBUFFER
      if (ver >= 5)
      {
        set_blockbuf_font(upper_window_buffer, new_z_font);
      }
#endif // DISABLE_BLOCKBUFFER
    }

    active_interface->set_font(new_z_font);
    set_variable(z_res_var, (uint16_t)current_font, false);
    current_font = new_z_font;
    TRACE_LOG("New font is: %d\n", current_font);
  }
  else
  {
    set_variable(z_res_var, (uint16_t)current_font, false);
  }
  */

  current_font = new_z_font;
  set_variable(z_res_var, (uint16_t)current_font, false);
}