Esempio n. 1
0
void rtc_run(void)
{
  static hitimer_t last_time = -1;
  int rate;
  hitimer_t ticks_m, cur_time = GETusTIME(0);
  if (last_time == -1 || last_time > cur_time) {
    last_time = cur_time;
    return;
  }
  rate = rtc_get_rate(GET_CMOS(CMOS_STATUSA) & 0x0f);
  ticks_m = (cur_time - last_time) * rate;
  q_ticks_m += ticks_m;
  last_time = cur_time;
  if (debug_level('h') > 8)
    h_printf("RTC: A=%hhx B=%hhx C=%hhx rate=%i queued=%lli added=%lli\n",
	GET_CMOS(CMOS_STATUSA), GET_CMOS(CMOS_STATUSB), GET_CMOS(CMOS_STATUSC),
	rate, (long long)q_ticks_m, (long long)ticks_m);
  if (q_ticks_m >= 1000000) {
    Bit8u old_c = GET_CMOS(CMOS_STATUSC);
    SET_CMOS(CMOS_STATUSC, old_c | 0x40);
    if ((GET_CMOS(CMOS_STATUSB) & 0x40) && !(GET_CMOS(CMOS_STATUSC) & 0x80)) {
      SET_CMOS(CMOS_STATUSC, GET_CMOS(CMOS_STATUSC) | 0x80);
      if (debug_level('h') > 7)
        h_printf("RTC: periodic IRQ, queued=%lli, added=%lli\n",
	    (long long)q_ticks_m, (long long)ticks_m);
      pic_request(PIC_IRQ8);
    }
    if (!(old_c & 0x40))
      q_ticks_m -= 1000000;
  }
}
Esempio n. 2
0
static void dump_cd_sect (char *tb)
{
    unsigned char buf[128];
    int i,j;
    unsigned char *p,*q,c;

    q=tb;
    for (i=0; i<32 && debug_level('C')>5; i++) {		/* 32x64 */
      p=buf;
      for (j=0; j<64; j++) {
        c=*q++;
        *p++ = (isprint(c)? c:'.');
      }
      C_printf("%03x[%s]\n",i*64,buf);
    }
    q=tb;
    for (i=0; i<64 && debug_level('C')>8; i++) {		/* 64x32 */
      p=buf;
      for (j=0; j<4; j++) {
        p+=sprintf(p,":%02x%02x%02x%02x%02x%02x%02x%02x",q[0],q[1],q[2],
        	q[3],q[4],q[5],q[6],q[7]);
        q+=8;
      }
      C_printf("%03x%s\n",i*32,buf);
    }
}
Esempio n. 3
0
/*
 * Return address of the stub function is passed into eip
 */
static int m_munprotect(unsigned int addr, unsigned int len, unsigned char *eip)
{
	if (debug_level('e')>3) e_printf("\tM_MUNPROT %08x:%p [%08x]\n",
		addr,eip,*((int *)(eip-3)));
	/* verify that data, not code, has been hit */
	if (!e_querymark(addr, len))
	    return e_check_munprotect(addr, len);
	/* Oops.. we hit code, maybe the stub was set up before that
	 * code was parsed. Ok, undo the patch and clear that code */
	if (debug_level('e')>1)
	    e_printf("CODE %08x hit in DATA %p patch\n",addr,eip);
/*	if (UnCpatch((void *)(eip-3))) leavedos_main(0); */
	InvalidateNodePage(addr,len,eip,NULL);
	return e_check_munprotect(addr, len);
}
Esempio n. 4
0
static void printECB(ECB_t * ECB)
{
  int i;

  if(debug_level('n')) {
    n_printf("--DOS ECB (dump)--\n");
    dumpBytes((u_char *) ECB, 60);
    n_printf("--DOS ECB--\n");
    n_printf("Link             %04x:%04x\n", ECB->Link.segment, ECB->Link.offset);
    n_printf("ESR              %04x:%04x\n", ECB->ESRAddress.segment, ECB->ESRAddress.offset);
    n_printf("InUseFlag        %02x\n", ECB->InUseFlag);
    n_printf("CompletionCode   %02x\n", ECB->CompletionCode);
    n_printf("ECBSocket	     %04x\n", ntohs(ECB->ECBSocket));
    n_printf("ImmediateAddress %02X%02X%02X%02X%02X%02X\n",
      ECB->ImmediateAddress[0],
      ECB->ImmediateAddress[1],
      ECB->ImmediateAddress[2],
      ECB->ImmediateAddress[3],
      ECB->ImmediateAddress[4],
      ECB->ImmediateAddress[5]);
    n_printf("FragmentCount	 %d\n", ECB->FragmentCount);
    for (i = 0; i < ECB->FragmentCount; i++) {
      n_printf("Frag[%d].Length   %d\n", i, ECB->FragTable[i].Length);
      n_printf("Frag[%d].Address	 %p\n", i,
        FARt_PTR(ECB->FragTable[i].Address));
    }
  }
}
Esempio n. 5
0
static void report_pp_stats(Postprocessor *pp)
{
	size_t rule_cnt = 0;
	size_t unused_cnt = 0;
	pp_knowledge * kno;
	if (!debug_level(9)) return;

	printf("PP stats: local_rules_firing=%d\n", pp->n_local_rules_firing);
	kno = pp->knowledge;

	printf("\nPP stats: form_a_cycle_rules\n");
	rule_cnt += report_rule_use(kno->form_a_cycle_rules);

	printf("\nPP stats: contains_one_rules\n");
	rule_cnt += report_rule_use(kno->contains_one_rules);

	printf("\nPP stats: contains_none_rules\n");
	rule_cnt += report_rule_use(kno->contains_none_rules);

	printf("\nPP stats: bounded_rules\n");
	rule_cnt += report_rule_use(kno->bounded_rules);

	printf("\nPP stats: Rules that were not used:\n");
	unused_cnt += report_unused_rule(kno->form_a_cycle_rules);
	unused_cnt += report_unused_rule(kno->contains_one_rules);
	unused_cnt += report_unused_rule(kno->contains_none_rules);
	unused_cnt += report_unused_rule(kno->bounded_rules);

	printf("\nPP stats: %zd of %zd rules unused\n", unused_cnt, rule_cnt);
}
Esempio n. 6
0
static int GatherFragmentData(u_char *buffer, ECB_t * ECB)
{
  int i;
  int nextFragLen, totalDataCount;
  u_char *bufptr, *memptr;

  totalDataCount = 0;
  bufptr = buffer;
  for (i = 0; i < ECB->FragmentCount; i++) {
    nextFragLen = ECB->FragTable[i].Length;
    memptr = FARt_PTR(ECB->FragTable[i].Address);
    if (i == 0) {
      /* subtract off IPX header size from first fragment */
      nextFragLen -= 30;
      memptr += 30;
    }
    if (nextFragLen) {
      /* DANG_FIXTHIS - dumb use of hardcoded 1500 here */
      if (totalDataCount + nextFragLen > 1500) {
	return (-1);
      }
      memcpy(bufptr, memptr, nextFragLen);
      bufptr += nextFragLen;
      totalDataCount += nextFragLen;
    }
  }
  n_printf("IPX: gathered %d fragments for %d bytes of data\n",
	   ECB->FragmentCount, totalDataCount);
  if (debug_level('n')) {
    dumpBytes(buffer, totalDataCount);
  }
  return (totalDataCount);
}
Esempio n. 7
0
void pic_sched(int ilevel, int interval)
{
  char mesg[35];

 /* default for interval is 65536 (=54.9ms)
  * There's a problem with too small time intervals - an interrupt can
  * be continuously scheduled, without letting any time to process other
  * code.
  *
  * BIG WARNING - in non-periodic timer modes pit[0].cntr goes to -1
  *	at the end of the interval - was this the reason for the following
  *	[1u-15sec] range check?
  */
  if(interval > 0 && interval < 0x3fffffff) {
     if(pic_ltime[ilevel]==NEVER) {
	pic_itime[ilevel] = pic_itime[32] + interval;
     } else {
	pic_itime[ilevel] = pic_itime[ilevel] + interval;
     }
  }
  if (debug_level('r') > 2) {
    /* avoid going through sprintf for non-debugging */
    sprintf(mesg,", delay= %d.",interval);
    pic_print(2,"Scheduling lvl= ",ilevel,mesg);
    pic_print2(2,"pic_itime set to ",pic_itime[ilevel],"");
  }
}
Esempio n. 8
0
/*
 * Return address of the stub function is passed into eip
 */
static void m_munprotect(unsigned int addr, unsigned int len, unsigned char *eip)
{
	if (debug_level('e')>3) e_printf("\tM_MUNPROT %08x:%p [%08x]\n",
		addr,eip,*((int *)(eip-3)));
	/* if only data in aliased low memory is hit, nothing to do */
	if (LINEAR2UNIX(addr) != MEM_BASE32(addr) && !e_querymark(addr, len))
		return;
	/* Always unprotect and clear all code in the pages
	 * for either DPMI data or code.
	 * Maybe the stub was set up before that code was parsed.
	 * Clear that code */
	if (debug_level('e')>1 && e_querymark(addr, len))
	    e_printf("CODE %08x hit in DATA %p patch\n",addr,eip);
/*	if (UnCpatch((void *)(eip-3))) leavedos_main(0); */
	InvalidateNodePage(addr,len,eip,NULL);
	e_resetpagemarks(addr,len);
	e_munprotect(addr,len);
}
Esempio n. 9
0
int main(int argc, char *argv[]) {
    int opt;
    int daemonize = FALSE;
    int verbose_level = 2;

    char *configfile = DEFAULT_CONFIG_FILE;

    while((opt = getopt(argc, argv, "c:bd:")) != -1) {
        switch(opt) {
        case 'c':
            configfile = optarg;
            break;
        case 'b':
            daemonize = TRUE;
            break;
        case 'd':
            verbose_level = atoi(optarg);
            break;
        default:
            usage(argv[0]);
            exit(EXIT_FAILURE);
            break;
        }
    }

    debug_level(verbose_level);
    DEBUG("Loading config from %s", configfile);

    if(cfg_load(configfile) == -1) {
        ERROR("Error loading config.  Aborting");
        return EXIT_FAILURE;
    }

    cfg_dump();

    DEBUG("Starting mqtt workers");

    mqtt_init();

    DEBUG("Starting receive thread");

    if(!nrf24_recv_init()) {
        ERROR("Error starting radio receiver.  Abort");
        exit(EXIT_FAILURE);
    }

    while(1) {
        sleep(1);
    }

    nrf24_recv_deinit();
    mqtt_deinit();

    return(EXIT_SUCCESS);
}
Esempio n. 10
0
CH263PayloadFormat::CH263PayloadFormat() :
    m_lRefCount(0),
    m_pCCF(0),
    m_state(NeedPSC),
    m_ulFrameSize(0),
    m_ulTimestamp(0),
    m_pDepackHlpr(0)
{
#ifdef DEBUG
    debug_level() |= D_H263;
#endif /* DEBUG */
}
Esempio n. 11
0
static void r_munprotect(unsigned int addr, unsigned int len, unsigned char *eip)
{
	if (EFLAGS & EFLAGS_DF) addr -= len;
	if (debug_level('e')>3)
	    dbug_printf("\tR_MUNPROT %08x:%08x %s\n",
		addr,addr+len,(EFLAGS&EFLAGS_DF?"back":"fwd"));
	if (LINEAR2UNIX(addr) != MEM_BASE32(addr) && !e_querymark(addr, len))
		return;
	InvalidateNodePage(addr,len,eip,NULL);
	e_resetpagemarks(addr,len);
	e_munprotect(addr,len);
}
Esempio n. 12
0
static int logging_ioctl(int fd, unsigned int cmd, void *arg)
{
    int rval;
    int err;
    if (debug_level('C')>5)
      C_printf("CDROM: ioctl %#x\n", cmd);
    rval = ioctl(fd, cmd, arg);
    err = errno;

    if (rval == -1) {
	C_printf("CDROM: err %s\n", strerror(errno));
	errno = err;
    }
    return rval;
}
Esempio n. 13
0
char *e_print_regs(void)
{
	static char buf[300];
	char *p = buf;
	char *q = eregbuf;

	while (*q) *p++ = *q++; *p=0;
	exprintl(rEAX,buf,(ERB_L1+ERB_LEFTM));
	exprintl(rEBX,buf,(ERB_L1+ERB_LEFTM)+13);
	exprintl(rECX,buf,(ERB_L1+ERB_LEFTM)+26);
	exprintl(rEDX,buf,(ERB_L1+ERB_LEFTM)+39);
	exprintl(rESI,buf,(ERB_L2+ERB_LEFTM));
	exprintl(rEDI,buf,(ERB_L2+ERB_LEFTM)+13);
	exprintl(rEBP,buf,(ERB_L2+ERB_LEFTM)+26);
	exprintl(rESP,buf,(ERB_L2+ERB_LEFTM)+39);
	if (TheCPU.eflags&EFLAGS_VM)
		exprintl(TheCPU.veflags,buf,(ERB_L3+ERB_LEFTM));
	else
		exprintl(get_vFLAGS(TheCPU.eflags),buf,(ERB_L3+ERB_LEFTM));
	exprintw(TheCPU.cs,buf,(ERB_L3+ERB_LEFTM)+13);
	exprintw(TheCPU.ds,buf,(ERB_L3+ERB_LEFTM)+26);
	exprintw(TheCPU.es,buf,(ERB_L3+ERB_LEFTM)+39);
	exprintw(TheCPU.fs,buf,(ERB_L4+ERB_LEFTM));
	exprintw(TheCPU.gs,buf,(ERB_L4+ERB_LEFTM)+13);
	exprintw(TheCPU.ss,buf,(ERB_L4+ERB_LEFTM)+26);
	exprintl(TheCPU.eflags,buf,(ERB_L4+ERB_LEFTM)+39);
	if (debug_level('e')>4) {
		int i;
		unsigned char *st = MEM_BASE32(LONG_SS+TheCPU.esp);
		if ((st >= mem_base && st < (unsigned char *)MEM_BASE32(0x110000)) ||
		    (st > (unsigned char *)config.dpmi_base &&
		     st <= (unsigned char *)config.dpmi_base +
		     config.dpmi * 1024)) {
			unsigned short *stk = (unsigned short *)st;
			for (i=(ERB_L5+ERB_LEFTM); i<(ERB_L6-2); i+=5) {
			   exprintw(*stk++,buf,i);
			}
		}
	}
	else
		buf[ERB_L5]=0;
	return buf;
}
Esempio n. 14
0
ConfigWatcher::ConfigWatcher(IHXRegistry* pRegistry)
    : m_lRefCount(0)
    , m_pRegistry(pRegistry)
    , m_pActiveRegistry(NULL)
    , m_pResponse(NULL)
    , m_pPropWatch(NULL) 
{

#ifdef _SCRVERBOSE
    debug_level() = 0xf;
#endif
    if (m_pRegistry)
    {
	m_pRegistry->AddRef();

	m_pRegistry->QueryInterface(IID_IHXActiveRegistry, 
		(void**)&m_pActiveRegistry);

    }
}
Esempio n. 15
0
Bit8u rtc_read(Bit8u reg)
{
  Bit8u ret = GET_CMOS(reg);

  switch (reg) {
  case CMOS_SEC:
  case CMOS_SECALRM:
  case CMOS_MIN:
  case CMOS_MINALRM:
  case CMOS_DOW:
  case CMOS_DOM:
  case CMOS_MONTH:
  case CMOS_YEAR:
  case CMOS_CENTURY:
    /* Note - the inline function BCD() in cmos.h will check bit 2 of
     * status reg B for proper output format */
    ret = BCD(ret);
    break;

  case CMOS_HOUR:		/* RTC hour...bit 1 of 0xb set=24 hour mode, clear 12 hour */
  case CMOS_HOURALRM:
    if (!(GET_CMOS(CMOS_STATUSB) & 2)) {	/* 12-hour mode */
      if (ret == 0)
	ret = 12;
      else if (ret > 12)
	ret -= 12;
    }
    ret = BCD(ret);
    break;

  case CMOS_STATUSC:
    if (debug_level('h') > 8)
      h_printf("RTC: Read C=%hhx\n", ret);
    SET_CMOS(CMOS_STATUSC, 0);
    pic_untrigger(PIC_IRQ8);
    rtc_run();
    break;
  }

  return ret;
}
Esempio n. 16
0
/**
 * Call this (a) after having called post_process_scan_linkage() on all
 * generated linkages, but (b) before calling post_process() on any
 * particular linkage. Here we mark all rules which we know (from having
 * accumulated a set of link names appearing in *any* linkage) that won't
 * ever be needed.
 */
static void prune_irrelevant_rules(Postprocessor *pp)
{
	pp_rule *rule;
	int coIDX, cnIDX, rcoIDX = 0, rcnIDX = 0;

	/* If we didn't scan any linkages, there's no pruning to be done. */
	if (pp_linkset_population(pp->set_of_links_of_sentence) == 0) return;

	for (coIDX = 0; ; coIDX++)
	{
		rule = &(pp->knowledge->contains_one_rules[coIDX]);
		if (rule->msg == NULL) break;
		if (pp_linkset_match_bw(pp->set_of_links_of_sentence, rule->selector))
		{
			/* Mark rule as being relevant to this sentence */
			pp->relevant_contains_one_rules[rcoIDX++] = coIDX;
			pp_linkset_add(pp->set_of_links_in_an_active_rule, rule->selector);
		}
	}
	pp->relevant_contains_one_rules[rcoIDX] = -1;  /* end sentinel */

	for (cnIDX = 0; ; cnIDX++)
	{
		rule = &(pp->knowledge->contains_none_rules[cnIDX]);
		if (rule->msg == NULL) break;
		if (pp_linkset_match_bw(pp->set_of_links_of_sentence, rule->selector))
		{
			pp->relevant_contains_none_rules[rcnIDX++] = cnIDX;
			pp_linkset_add(pp->set_of_links_in_an_active_rule, rule->selector);
		}
	}
	pp->relevant_contains_none_rules[rcnIDX] = -1;

	if (debug_level(5))
	{
		printf("PP: Saw %zd unique link names in all linkages.\n",
		       pp_linkset_population(pp->set_of_links_of_sentence));
		printf("PP: Using %i 'contains one' rules and %i 'contains none' rules\n",
		       rcoIDX, rcnIDX);
	}
}
Esempio n. 17
0
static void process_samples(long long now, int min_buf)
{
    int nframes, retry;
    double period, mf_time_cur;
    mf_time_cur = pcm_time_lock(pcm_stream);
    do {
	retry = 0;
	period = pcm_frame_period_us(flus_srate);
	nframes = (now - mf_time_cur) / period;
	if (nframes > FLUS_MAX_BUF) {
	    nframes = FLUS_MAX_BUF;
	    retry = 1;
	}
	if (nframes >= min_buf) {
	    mf_process_samples(nframes);
	    mf_time_cur = pcm_get_stream_time(pcm_stream);
	    if (debug_level('S') >= 5)
		S_printf("MIDI: processed %i samples with fluidsynth\n", nframes);
	}
    } while (retry);
    pcm_time_unlock(pcm_stream);
}
Esempio n. 18
0
static void printIPXHeader(IPXPacket_t * IPXHeader)
{
  if (debug_level('n')) {
    n_printf("--IPX Header (dump)--\n");
    dumpBytes((u_char *) IPXHeader, 30);
    n_printf("--IPX Header --\n");
    n_printf("Checksum         %04x\n", ntohs(IPXHeader->Checksum));
    n_printf("Length           %d\n", ntohs(IPXHeader->Length));
    n_printf("TransportControl %d\n", IPXHeader->TransportControl);
    n_printf("PacketType       %d\n", IPXHeader->PacketType);
    n_printf("Destination      %02X%02X%02X%02X:%02X%02X%02X%02X%02X%02X:%02X%02X\n",
      IPXHeader->Destination.Network[0],
      IPXHeader->Destination.Network[1],
      IPXHeader->Destination.Network[2],
      IPXHeader->Destination.Network[3],
      IPXHeader->Destination.Node[0],
      IPXHeader->Destination.Node[1],
      IPXHeader->Destination.Node[2],
      IPXHeader->Destination.Node[3],
      IPXHeader->Destination.Node[4],
      IPXHeader->Destination.Node[5],
      IPXHeader->Destination.Socket[0],
      IPXHeader->Destination.Socket[1]);
    n_printf("Source           %02X%02X%02X%02X:%02X%02X%02X%02X%02X%02X:%02X%02X\n",
      IPXHeader->Source.Network[0],
      IPXHeader->Source.Network[1],
      IPXHeader->Source.Network[2],
      IPXHeader->Source.Network[3],
      IPXHeader->Source.Node[0],
      IPXHeader->Source.Node[1],
      IPXHeader->Source.Node[2],
      IPXHeader->Source.Node[3],
      IPXHeader->Source.Node[4],
      IPXHeader->Source.Node[5],
      IPXHeader->Source.Socket[0],
      IPXHeader->Source.Socket[1]);
  }
}
Esempio n. 19
0
/* DANG_BEGIN_FUNCTION pic_request
 *
 * pic_request triggers an interrupt.  There is presently no way to
 * "un-trigger" an interrupt.  The interrupt will be initiated the
 * next time pic_run is called, unless masked or superceded by a
 * higher priority interrupt.  pic_request takes one argument, an
 * interrupt level, which specifies the interrupt to be triggered.
 * If that interrupt is already active, the request will be queued
 * until all active interrupts have been completed.  The queue is
 * only one request deep for each interrupt, so it is the responsibility
 * of the interrupt code to retrigger itself if more interrupts are
 * needed.
 *
 * DANG_END_FUNCTION
 */
int pic_request(int inum)
{
static char buf[81];
  int ret=PIC_REQ_NOP;

  if ((pic_irr|pic_isr)&(1<<inum))
    {
    if (pic_pirr&(1<<inum)){
     ret=PIC_REQ_LOST;
     pic_print(2,"Requested irq lvl ",    inum, " lost     ");
      }
    else {
     ret=PIC_REQ_PEND;
     pic_print(2,"Requested irq lvl ",    inum, " pending  ");
      }
    pic_pirr|=(1<<inum);
    if(pic_itime[inum] == pic_ltime[inum]) {
       pic_print(2,"pic_itime and pic_ltime for timer ",inum," matched!");
       pic_itime[inum] = pic_itime[32];
    }
    pic_ltime[inum] = pic_itime[inum];
  }
  else {
    pic_print(2,"Requested irq lvl ",    inum, " successfully");
    pic_irr|=(1<<inum);
    if(pic_itime[inum] == pic_ltime[inum]) pic_itime[inum] = pic_itime[32];
    pic_ltime[inum] = pic_itime[inum];
    ret=PIC_REQ_OK;
  }
  if (debug_level('r') >2) {
    /* avoid going through sprintf for non-debugging */
    sprintf(buf,", k%d",(int)pic_dpmi_count);
    pic_print(2,"Zeroing vm86, DPMI from ",pic_vm86_count,buf);
  }
  pic_vm86_count=pic_dpmi_count=0;
  return ret;
}
Esempio n. 20
0
static int m_mprotect(unsigned int addr, size_t len)
{
	if (debug_level('e')>3)
	    e_printf("\tM_MPROT   %08x\n",addr);
	return e_mprotect(addr, len);
}
Esempio n. 21
0
/* This function is borrowed from Wine (LGPL'ed)
   http://source.winehq.org/source/dlls/x11drv/keyboard.c
   with adjustments to match dosemu

   The idea is, if $_layout="auto", to match each keyboard map with
   the X keymap and choose the one that matches best.

   It is used when we can access display, not just for xdosemu,
   but also in xterms. Remote users using terminals will have
   to specify $_layout explicitly though.

   The console map is just another map in this scheme that may
   or may not be the best one.
*/
int X11_DetectLayout (void)
{
  Display *display;
  unsigned match, mismatch, seq, i, alternate;
  int score, keyc, key, pkey, ok = 0;
  KeySym keysym;
  unsigned max_seq[3] = {0, 0};
  int max_score[3] = {INT_MIN, INT_MIN};
  int ismatch = 0;
  int min_keycode, max_keycode;
  t_unicode ckey[2] = {0, 0};
  t_keysym lkey[2] = {0, 0};
  struct keytable_entry *kt;
  struct char_set_state X_charset;

  char *display_name = config.X_display ? config.X_display : getenv("DISPLAY");
  display = XOpenDisplay(display_name);
  if (display == NULL) return 1;

  XDisplayKeycodes(display, &min_keycode, &max_keycode);

#ifndef HAVE_XKB
  int keysyms_per_keycode;
  KeySym *key_mapping;

  /* get data for keycode from X server */
  key_mapping = XGetKeyboardMapping(display, min_keycode,
			    max_keycode + 1 - min_keycode,
			    &keysyms_per_keycode);
#endif

  init_charset_state(&X_charset, lookup_charset("X_keysym"));
  for (kt = keytable_list, alternate = 0; kt->name; ) {
    k_printf("Attempting to match against \"%s\"\n", kt->name);
    match = 0;
    mismatch = 0;
    score = 0;
    seq = 0;
    pkey = -1;
    for (keyc = min_keycode; keyc <= max_keycode; keyc++) {

      for (i = 0; i < 2; i++) {
#ifdef HAVE_XKB
	keysym = XkbKeycodeToKeysym(display, keyc, alternate, i);
#else
	keysym = X11_KeycodeToKeysym(key_mapping, keysyms_per_keycode,
			min_keycode, keyc, alternate, i);
#endif
	charset_to_unicode(&X_charset, &ckey[i],
                (const unsigned char *)&keysym, sizeof(keysym));
      }

      if (ckey[0] != U_VOID && (ckey[0] & 0xf000) != 0xe000) {
        /* search for a match in layout table */
        /* right now, we just find an absolute match for defined positions */
        /* (undefined positions are ignored, so if it's defined as "3#" in */
        /* the table, it's okay that the X server has "3#£", for example) */
        /* however, the score will be higher for longer matches */
        for (key = 0; key < kt->sizemap; key++) {
	  lkey[0] = keysym_to_unicode(kt->key_map[key]);
	  lkey[1] = keysym_to_unicode(kt->shift_map[key]);
          for (ok = 0, i = 0; (ok >= 0) && (i < 2); i++) {
            if (lkey[i] != U_VOID) {
	      if (lkey[i] == ckey[i])
		ok++;
	      else if (ckey[i] != U_VOID)
		ok = -1;
	    }
          }
	  if (debug_level('k') > 5)
	    k_printf("key: % 3d score % 2d for keycode % 3d, %04x %04x, "
		     "got %04x %04x\n",
		     key, ok, keyc, lkey[0], lkey[1], ckey[0], ckey[1]);
          if (ok > 0) {
            score += ok;
            break;
          }
        }
        /* count the matches and mismatches */
        if (ok > 0) {
          match++;
          /* and how much the keycode order matches */
          if (key > pkey) seq++;
          pkey = key;
        } else {
          /* print spaces instead of \0's */
          for (i = 0; i < ARRAY_SIZE(ckey); i++) if (!ckey[i]) ckey[i] = ' ';
          mismatch++;
          score -= 2;
        }
      }
    }
    k_printf("matches=%d, mismatches=%d, seq=%d, score=%d\n",
           match, mismatch, seq, score);
    if (score > max_score[alternate] ||
       (score == max_score[alternate] &&
	((seq > max_seq[alternate]) ||
	 (seq == max_seq[alternate] && kt->keyboard == KEYB_AUTO)))) {
      /* best match so far */
      if (alternate) {
	/* alternate keyboards are optional so a threshold is used */
	if (score > 20) config.altkeytable = kt;
      }
      else
	config.keytable = kt;
      max_score[alternate] = score;
      max_seq[alternate] = seq;
      ismatch = !mismatch;
    }
    alternate = !alternate;
    if (!alternate)
      kt++;
  }
  cleanup_charset_state(&X_charset);

#ifndef HAVE_XKB
  XFree(key_mapping);
#endif

  /* we're done, report results if necessary */
  if (!ismatch)
    k_printf("Using closest match (%s) for scan/virtual codes mapping.\n",
	   config.keytable->name);

  c_printf("CONF: detected layout is \"%s\"\n", config.keytable->name);
  if (config.altkeytable)
    c_printf("CONF: detected alternate layout: %s\n", config.altkeytable->name);
  XCloseDisplay(display);
  return 0;
}
Esempio n. 22
0
static bool afdict_init(Dictionary dict)
{
	Afdict_class * ac;
	Dictionary afdict = dict->affix_table;

	/* FIXME: read_entry() builds word lists in reverse order (can we
	 * just create the list top-down without breaking anything?). Unless
	 * it is fixed to preserve the order, reverse here the word list for
	 * each affix class. */
	for (ac = afdict->afdict_class;
		  ac < &afdict->afdict_class[ARRAY_SIZE(afdict_classname)]; ac++)
	{
		int i;
		int l = ac->length - 1;
		const char * t;

		for (i = 0;  i < l; i++, l--)
		{
			t = ac->string[i];
			ac->string[i] = ac->string[l];
			ac->string[l] = t;
		}
	}

	/* Create the affix lists */
	ac = AFCLASS(afdict, AFDICT_INFIXMARK);
	if ((1 < ac->length) || ((1 == ac->length) && (1 != strlen(ac->string[0]))))
	{
		prt_error("Error: afdict_init: Invalid value for class %s in file %s"
		          " (should have been one ASCII punctuation - ignored)\n",
		          afdict_classname[AFDICT_INFIXMARK], afdict->name);
		free((void *)ac->string);
		ac->length = 0;
		ac->mem_elems = 0;
		ac->string = NULL;
	}
	/* XXX For now there is a possibility to use predefined SUF and PRE lists.
	 * So if SUF or PRE are defined, don't extract any of them from the dict. */
	if (1 == ac->length)
	{
		if ((0 == AFCLASS(afdict, AFDICT_PRE)->length) &&
		    (0 == AFCLASS(afdict, AFDICT_SUF)->length))
		{
			char last_entry[MAX_WORD+1] = "";
			get_dict_affixes(dict, dict->root, ac->string[0][0], last_entry);
		}
	}
	else
	{
		/* No INFIX_MARK - create a dummy one that always mismatches */
		affix_list_add(afdict, &afdict->afdict_class[AFDICT_INFIXMARK], "");
	}

	if (debug_level(+D_AI))
	{
		size_t l;

		for (ac = afdict->afdict_class;
		     ac < &afdict->afdict_class[ARRAY_SIZE(afdict_classname)]; ac++)
		{
				if (0 == ac->length) continue;
				lgdebug(+0, "Class %s, %zd items:",
				        afdict_classname[ac-afdict->afdict_class], ac->length);
				for (l = 0; l < ac->length; l++)
					lgdebug(0, " '%s'", ac->string[l]);
				lgdebug(0, "\n");
		}
	}
#undef D_AI

	/* Store the SANEMORPHISM regex in the unused (up to now)
	 * regex_root element of the affix dictionary, and precompile it */
	assert(NULL == afdict->regex_root, "SM regex is already assigned");
	ac = AFCLASS(afdict, AFDICT_SANEMORPHISM);
	if (0 != ac->length)
	{
		int rc;

		Regex_node *sm_re = malloc(sizeof(*sm_re));
		dyn_str *rebuf = dyn_str_new();

		/* The regex used to be converted to: ^((original-regex)b)+$
		 * In the initial wordgraph version word boundaries are not supported,
		 * so instead it is converted to: ^(original-regex)+$ */
#ifdef WORD_BOUNDARIES
		dyn_strcat(rebuf, "^((");
#else
		dyn_strcat(rebuf, "^(");
#endif
		dyn_strcat(rebuf, ac->string[0]);
#ifdef WORD_BOUNDARIES
		dyn_strcat(rebuf, ")b)+$");
#else
		dyn_strcat(rebuf, ")+$");
#endif
		sm_re->pattern = strdup(rebuf->str);
		dyn_str_delete(rebuf);

		afdict->regex_root = sm_re;
		sm_re->name = strdup(afdict_classname[AFDICT_SANEMORPHISM]);
		sm_re->re = NULL;
		sm_re->next = NULL;
		sm_re->neg = false;
		rc = compile_regexs(afdict->regex_root, afdict);
		if (rc) {
			prt_error("Error: afdict_init: Failed to compile "
			          "regex '%s' in file %s, return code %d\n",
			          afdict_classname[AFDICT_SANEMORPHISM], afdict->name, rc);
			return false;
		}
		lgdebug(+5, "%s regex %s\n",
		        afdict_classname[AFDICT_SANEMORPHISM], sm_re->pattern);
	}

	/* sort the UNITS list */
	/* Longer unit names must get split off before shorter ones.
	 * This prevents single-letter splits from screwing things
	 * up. e.g. split 7gram before 7am before 7m
	 */
	ac = AFCLASS(afdict, AFDICT_UNITS);
	if (0 < ac->length)
	{
		qsort(ac->string, ac->length, sizeof(char *), cmplen);
	}

#ifdef AFDICT_ORDER_NOT_PRESERVED
	/* pre-sort the MPRE list */
	ac = AFCLASS(afdict, AFDICT_MPRE);
	if (0 < ac->length)
	{
		/* Longer subwords have priority over shorter ones,
		 * reverse-sort by length.
		 * XXX mprefix_split() for Hebrew depends on that. */
		qsort(ac->string, ac->length, sizeof(char *), revcmplen);
	}
#endif /* AFDICT_ORDER_NOT_PRESERVED */

	concat_class(afdict, AFDICT_QUOTES);
	concat_class(afdict, AFDICT_BULLETS);

	if (! anysplit_init(afdict)) return false;

	return true;
}
Esempio n. 23
0
Boolean handle_dosemu_keys(Boolean make, t_keysym key) 
{
	Boolean result = TRUE;
	switch(key) {

#ifdef X86_EMULATOR
	case KEY_DOSEMU_X86EMU_DEBUG:
		k_printf("KBD: Ctrl-Alt-PgUp\n");
		if (config.cpuemu) {
			if (debug_level('e') < 2) set_debug_level('e', 4);
			fflush(dbg_fd);
		}
		return 1;
#endif
	/* C-A-D is disabled */
	case KEY_DOSEMU_REBOOT:
		if (make) {
			k_printf("KBD: Ctrl-Alt-Del: rebooting dosemu\n");
			dos_ctrl_alt_del();
		}
		break;
	case KEY_DOSEMU_EXIT:
		if (make) {
			k_printf("KBD: Ctrl-Alt-PgDn: bye bye!\n");
			leavedos(0);
		}
		break;
		
	case KEY_DOSEMU_FREEZE:
		if (make) {
			if (!dosemu_frozen) {
				freeze_dosemu_manual();
			} else {
				unfreeze_dosemu();
			}
		}
		break;

	case KEY_DOSEMU_VT_1: 
	case KEY_DOSEMU_VT_2:
	case KEY_DOSEMU_VT_3:
	case KEY_DOSEMU_VT_4:
	case KEY_DOSEMU_VT_5:
	case KEY_DOSEMU_VT_6:
	case KEY_DOSEMU_VT_7:
	case KEY_DOSEMU_VT_8:
	case KEY_DOSEMU_VT_9:
	case KEY_DOSEMU_VT_10:
	case KEY_DOSEMU_VT_11:
	case KEY_DOSEMU_VT_12:
		if (make) {
			int vc_num;
			vc_num = (key - KEY_DOSEMU_VT_1) +1;
			result = switch_to_console(vc_num);
		}
		break;
			
	case KEY_MOUSE_UP:
	case KEY_MOUSE_DOWN:
	case KEY_MOUSE_LEFT:
	case KEY_MOUSE_RIGHT:
	case KEY_MOUSE_UP_AND_LEFT:
	case KEY_MOUSE_UP_AND_RIGHT:
	case KEY_MOUSE_DOWN_AND_LEFT:
	case KEY_MOUSE_DOWN_AND_RIGHT:
	case KEY_MOUSE_BUTTON_LEFT:
	case KEY_MOUSE_BUTTON_MIDDLE:
	case KEY_MOUSE_BUTTON_RIGHT:
		mouse_keyboard(make, key);        /* mouse emulation keys */
		break;

	case KEY_DOSEMU_HELP:
	case KEY_DOSEMU_REDRAW:
	case KEY_DOSEMU_SUSPEND:
	case KEY_DOSEMU_RESET:
	case KEY_DOSEMU_MONO:
	case KEY_DOSEMU_PAN_UP:
	case KEY_DOSEMU_PAN_DOWN:
	case KEY_DOSEMU_PAN_LEFT:
	case KEY_DOSEMU_PAN_RIGHT:
		if (Keyboard->handle_keys) {
			Keyboard->handle_keys(make, key);
		} else
		{
			result = FALSE;
		}
		break;

#if 0
	case KEY_MOUSE_GRAB:
		if (Keyboard == &Keyboard_X) {
			handle_X_keys(make, key);
		} else {
			result = FALSE;
		}
#endif

	default:
		result = FALSE;
		break;
	}
	return result;
}
Esempio n. 24
0
bool sane_linkage_morphism(Sentence sent, Linkage lkg, Parse_Options opts)
{
	Wordgraph_pathpos *wp_new = NULL;
	Wordgraph_pathpos *wp_old = NULL;
	Wordgraph_pathpos *wpp;
	Gword **next; /* next Wordgraph words of the current word */

	size_t i;
	Linkage_info * const lifo = &lkg->lifo;

	bool match_found = true; /* if all the words are null - it's still a match */
	Gword **lwg_path;

	Dictionary afdict = sent->dict->affix_table;       /* for SANEMORPHISM */
	char *const affix_types = alloca(sent->length*2 + 1);   /* affix types */

	affix_types[0] = '\0';

	/* Populate the path word queue, initializing the path to NULL. */
	for (next = sent->wordgraph->next; *next; next++)
	{
		wordgraph_path_append(&wp_new, /*path*/NULL, /*add_word*/NULL, *next);
	}
	assert(NULL != wp_new, "Path word queue is empty");

	for (i = 0; i < lkg->num_words; i++)
	{
		Disjunct *cdj;            /* chosen disjunct */

		lgdebug(D_SLM, "%p Word %zu: ", lkg, i);

		if (NULL == wp_new)
		{
			lgdebug(+D_SLM, "- No more words in the wordgraph\n");
			match_found = false;
			break;
		}

		if (wp_old != wp_new)
		{
			wordgraph_path_free(wp_old, true);
			wp_old = wp_new;
		}
		wp_new = NULL;
		//wordgraph_pathpos_print(wp_old);

		cdj = lkg->chosen_disjuncts[i];
		/* Handle null words */
		if (NULL == cdj)
		{
			lgdebug(D_SLM, "- Null word\n");
			/* A null word matches any word in the Wordgraph -
			 * so, unconditionally proceed in all paths in parallel. */
			match_found = false;
			for (wpp = wp_old; NULL != wpp->word; wpp++)
			{
				if (NULL == wpp->word->next)
					continue; /* This path encountered the Wordgraph end */

				/* The null words cannot be marked here because wpp->path consists
				 * of pointers to the Wordgraph words, and these words are common to
				 * all the linkages, with potentially different null words in each
				 * of them. However, the position of the null words can be inferred
				 * from the null words in the word array of the Linkage structure.
				 */
				for (next = wpp->word->next; NULL != *next; next++)
				{
					match_found = true;
					wordgraph_path_append(&wp_new, wpp->path, wpp->word, *next);
				}
			}
			continue;
		}

		if (!match_found)
		{
			const char *e = "Internal error: Too many words in the linkage\n";
			lgdebug(D_SLM, "- %s", e);
			prt_error("Error: %s.", e);
			break;
		}

		assert(MT_EMPTY != cdj->word[0]->morpheme_type); /* already discarded */

		if (debug_level(D_SLM)) print_with_subscript_dot(cdj->string);

		match_found = false;
		/* Proceed in all the paths in which the word is found. */
		for (wpp = wp_old; NULL != wpp->word; wpp++)
		{
			const Gword **wlp; /* disjunct word list */

			for (wlp = cdj->word; *wlp; wlp++)
			{
				if (*wlp == wpp->word)
				{
					match_found = true;
					for (next = wpp->word->next; NULL != *next; next++)
					{
						wordgraph_path_append(&wp_new, wpp->path, wpp->word, *next);
					}
					break;
				}
			}
		}

		if (!match_found)
		{
			/* FIXME? A message can be added here if there are too many words
			 * in the linkage (can happen only if there is an internal error). */
			lgdebug(D_SLM, "- No Wordgraph match\n");
			break;
		}
		lgdebug(D_SLM, "\n");
	}

	if (match_found)
	{
		match_found = false;
		/* Validate that there are no missing words in the linkage. It is so if
		 * the dummy termination word is found in the new pathpos queue. */
		if (NULL != wp_new)
		{
			for (wpp = wp_new; NULL != wpp->word; wpp++)
			{
				if (MT_INFRASTRUCTURE == wpp->word->morpheme_type) {
					match_found = true;
					/* Exit the loop with with wpp of the termination word. */
					break;
				}
			}
		}
		if (!match_found)
		    lgdebug(D_SLM, "%p Missing word(s) at the end of the linkage.\n", lkg);
	}

#define DEBUG_morpheme_type 0
	/* Check the morpheme type combination.
	 * If null_count > 0, the morpheme type combination may be invalid
	 * due to null subwords, so skip this check. */
	if (match_found && (0 == sent->null_count) &&
		(NULL != afdict) && (NULL != afdict->regex_root))
	{
		const Gword **w;
		char *affix_types_p = affix_types;

		/* Construct the affix_types string. */
#if DEBUG_morpheme_type
		print_lwg_path(wpp->path);
#endif
		i = 0;
		for (w = wpp->path; *w; w++)
		{
			i++;
			if (MT_EMPTY == (*w)->morpheme_type) continue; /* really a null word */

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch-enum"
			switch ((*w)->morpheme_type)
			{
#pragma GCC diagnostic pop
				default:
					/* What to do with the rest? */
				case MT_WORD:
					*affix_types_p = AFFIXTYPE_WORD;
					break;
				case MT_PREFIX:
					*affix_types_p = AFFIXTYPE_PREFIX;
					break;
				case MT_STEM:
					*affix_types_p = AFFIXTYPE_STEM;
					break;
				case MT_MIDDLE:
					*affix_types_p = AFFIXTYPE_MIDDLE;
					break;
				case MT_SUFFIX:
					*affix_types_p = AFFIXTYPE_SUFFIX;
					break;
			}

#if DEBUG_morpheme_type
			lgdebug(D_SLM, "Word %zu: %s affixtype=%c\n",
			     i, (*w)->subword,  *affix_types_p);
#endif

			affix_types_p++;
		}
		*affix_types_p = '\0';

#ifdef WORD_BOUNDARIES /* not yet implemented */
		{
			const Gword *uw;

			/* If w is an "end subword", return its unsplit word, else NULL. */
			uw = word_boundary(w); /* word_boundary() unimplemented */

			if (NULL != uw)
			{
				*affix_types_p++ = AFFIXTYPE_END;
				lgdebug(D_SLM, "%p End of Gword %s\n", lkg, uw->subword);
			}
		}
#endif

		/* Check if affix_types is valid according to SANEMORPHISM. */
		if (('\0' != affix_types[0]) &&
		    (NULL == match_regex(afdict->regex_root, affix_types)))
		{
			/* Morpheme type combination is invalid */
			match_found = false;
			/* Notify to stdout, so it will be shown along with the result.
			 * XXX We should have a better way to notify. */
			if (0 < opts->verbosity)
				printf("Warning: Invalid morpheme type combination '%s', "
				       "run with !bad and !verbosity=4 to debug\n", affix_types);
		}
	}

	if (match_found) lwg_path = (Gword **)wpp->path; /* OK to modify */
	wordgraph_path_free(wp_old, true);
	wordgraph_path_free(wp_new, !match_found);

	if (match_found)
	{
		if ('\0' != affix_types[0])
		{
			lgdebug(D_SLM, "%p Morpheme type combination '%s'\n", lkg, affix_types);
		}
		lgdebug(+D_SLM, "%p SUCCEEDED\n", lkg);
		lkg->wg_path = lwg_path;
		return true;
	}

	/* Oh no ... invalid morpheme combination! */
	sent->num_valid_linkages --;
	lifo->N_violations++;
	lifo->pp_violation_msg = "Invalid morphism construction.";
	lkg->wg_path = NULL;
	lifo->discarded = true;
	lgdebug(D_SLM, "%p FAILED\n", lkg);
	return false;
}
Esempio n. 25
0
void print_log(int level, const char *file, int line, int dm_errno_or_class,
	       const char *format, ...)
{
	va_list ap;
	char buf[1024], message[4096];
	int bufused, n;
	const char *trformat;		/* Translated format string */
	char *newbuf;
	int use_stderr = level & _LOG_STDERR;
	int log_once = level & _LOG_ONCE;
	int fatal_internal_error = 0;
	size_t msglen;
	const char *indent_spaces = "";
	FILE *stream;
	static int _abort_on_internal_errors_env_present = -1;
	static int _abort_on_internal_errors_env = 0;
	char *env_str;

	level &= ~(_LOG_STDERR|_LOG_ONCE);

	if (_abort_on_internal_errors_env_present < 0) {
		if ((env_str = getenv("DM_ABORT_ON_INTERNAL_ERRORS"))) {
			_abort_on_internal_errors_env_present = 1;
			/* Set when env DM_ABORT_ON_INTERNAL_ERRORS is not "0" */
			_abort_on_internal_errors_env = strcmp(env_str, "0");
		} else
			_abort_on_internal_errors_env_present = 0;
	}

	/* Use value from environment if present, otherwise use value from config. */
	if (((_abort_on_internal_errors_env_present && _abort_on_internal_errors_env) ||
	     (!_abort_on_internal_errors_env_present && _abort_on_internal_errors_config)) &&
	    !strncmp(format, INTERNAL_ERROR, sizeof(INTERNAL_ERROR) - 1)) {
		fatal_internal_error = 1;
		/* Internal errors triggering abort cannot be suppressed. */
		_log_suppress = 0;
		level = _LOG_FATAL;
	}

	if (level <= _LOG_ERR)
		init_error_message_produced(1);

	trformat = _(format);

	if (level < _LOG_DEBUG && dm_errno_or_class && !_lvm_errno)
		_lvm_errno = dm_errno_or_class;

	if (_lvm2_log_fn ||
	    (_store_errmsg && (level <= _LOG_ERR)) ||
	    log_once) {
		va_start(ap, format);
		n = vsnprintf(message, sizeof(message), trformat, ap);
		va_end(ap);

		/* When newer glibc returns >= sizeof(locn), we will just log what
                 * has fit into buffer, it's '\0' terminated string */
		if (n < 0) {
			fprintf(stderr, _("vsnprintf failed: skipping external "
					"logging function"));
			goto log_it;
		}
	}

/* FIXME Avoid pointless use of message buffer when it'll never be read! */
	if (_store_errmsg && (level <= _LOG_ERR) &&
	    _lvm_errmsg_len < MAX_ERRMSG_LEN) {
		msglen = strlen(message);
		if ((_lvm_errmsg_len + msglen + 1) >= _lvm_errmsg_size) {
			_lvm_errmsg_size = 2 * (_lvm_errmsg_len + msglen + 1);
			if ((newbuf = dm_realloc(_lvm_errmsg,
						 _lvm_errmsg_size)))
				_lvm_errmsg = newbuf;
			else
				_lvm_errmsg_size = _lvm_errmsg_len;
		}
		if (_lvm_errmsg &&
		    (_lvm_errmsg_len + msglen + 2) < _lvm_errmsg_size) {
			/* prepend '\n' and copy with '\0' but do not count in */
                        if (_lvm_errmsg_len)
				_lvm_errmsg[_lvm_errmsg_len++] = '\n';
			memcpy(_lvm_errmsg + _lvm_errmsg_len, message, msglen + 1);
			_lvm_errmsg_len += msglen;
		}
	}

	if (log_once) {
		if (!_duplicated)
			_duplicated = dm_hash_create(128);
		if (_duplicated) {
			if (dm_hash_lookup(_duplicated, message))
				level = _LOG_NOTICE;
			else
				(void) dm_hash_insert(_duplicated, message, (void*)1);
		}
	}

	if (_lvm2_log_fn) {
		_lvm2_log_fn(level, file, line, 0, message);
		if (fatal_internal_error)
			abort();
		return;
	}

      log_it:
	if ((verbose_level() >= level) && !_log_suppress) {
		if (verbose_level() > _LOG_DEBUG) {
			(void) dm_snprintf(buf, sizeof(buf), "#%s:%d ",
					   file, line);
		} else
			buf[0] = '\0';

		if (_indent)
			switch (level) {
			case _LOG_NOTICE: indent_spaces = "  "; break;
			case _LOG_INFO:   indent_spaces = "    "; break;
			case _LOG_DEBUG:  indent_spaces = "      "; break;
			default: /* nothing to do */;
			}

		va_start(ap, format);
		switch (level) {
		case _LOG_DEBUG:
			if (verbose_level() < _LOG_DEBUG)
				break;
			if (!debug_class_is_logged(dm_errno_or_class))
				break;
			if ((verbose_level() == level) &&
			    (strcmp("<backtrace>", format) == 0))
				break;
			/* fall through */
		default:
			/* Typically only log_warn goes to stdout */
			stream = (use_stderr || (level != _LOG_WARN)) ? stderr : stdout;
			if (stream == stderr)
				fflush(stdout);
			fprintf(stream, "%s%s%s%s", buf, log_command_name(),
				_msg_prefix, indent_spaces);
			vfprintf(stream, trformat, ap);
			fputc('\n', stream);
		}
		va_end(ap);
	}

	if ((level > debug_level()) ||
	    (level >= _LOG_DEBUG && !debug_class_is_logged(dm_errno_or_class))) {
		if (fatal_internal_error)
			abort();
		return;
	}

	if (_log_to_file && (_log_while_suspended || !critical_section())) {
		fprintf(_log_file, "%s:%d %s%s", file, line, log_command_name(),
			_msg_prefix);

		va_start(ap, format);
		vfprintf(_log_file, trformat, ap);
		va_end(ap);

		fputc('\n', _log_file);
		fflush(_log_file);
	}

	if (_syslog && (_log_while_suspended || !critical_section())) {
		va_start(ap, format);
		vsyslog(level, trformat, ap);
		va_end(ap);
	}

	if (fatal_internal_error)
		abort();

	/* FIXME This code is unfinished - pre-extend & condense. */
	if (!_already_logging && _log_direct && critical_section()) {
		_already_logging = 1;
		memset(&buf, ' ', sizeof(buf));
		bufused = 0;
		if ((n = dm_snprintf(buf, sizeof(buf),
				      "%s:%d %s%s", file, line, log_command_name(),
				      _msg_prefix)) == -1)
			goto done;

		bufused += n;		/* n does not include '\0' */

		va_start(ap, format);
		n = vsnprintf(buf + bufused, sizeof(buf) - bufused,
			      trformat, ap);
		va_end(ap);

		if (n < 0)
			goto done;

		bufused += n;
		if (n >= sizeof(buf))
			bufused = sizeof(buf) - 1;
	      done:
		buf[bufused] = '\n';
		buf[sizeof(buf) - 1] = '\n';
		/* FIXME real size bufused */
		dev_append(&_log_dev, sizeof(buf), buf);
		_already_logging = 0;
	}
}
Esempio n. 26
0
File: log.c Progetto: Rabsido/lvm2
void print_log(int level, const char *file, int line, int dm_errno,
	       const char *format, ...)
{
	va_list ap;
	char buf[1024], locn[4096];
	int bufused, n;
	const char *message;
	const char *trformat;		/* Translated format string */
	char *newbuf;
	int use_stderr = level & _LOG_STDERR;
	int log_once = level & _LOG_ONCE;
	int fatal_internal_error = 0;
	size_t msglen;

	level &= ~(_LOG_STDERR|_LOG_ONCE);

	if (_abort_on_internal_errors &&
	    !strncmp(format, INTERNAL_ERROR,
		     strlen(INTERNAL_ERROR))) {
		fatal_internal_error = 1;
		/* Internal errors triggering abort cannot be suppressed. */
		_log_suppress = 0;
		level = _LOG_FATAL;
	}

	if (_log_suppress == 2)
		return;

	if (level <= _LOG_ERR)
		init_error_message_produced(1);

	trformat = _(format);

	if (dm_errno && !_lvm_errno)
		_lvm_errno = dm_errno;

	if (_lvm2_log_fn ||
	    (_store_errmsg && (level <= _LOG_ERR)) ||
	    log_once) {
		va_start(ap, format);
		n = vsnprintf(locn, sizeof(locn) - 1, trformat, ap);
		va_end(ap);

		if (n < 0) {
			fprintf(stderr, _("vsnprintf failed: skipping external "
					"logging function"));
			goto log_it;
		}

		locn[sizeof(locn) - 1] = '\0';
		message = locn;
	}

/* FIXME Avoid pointless use of message buffer when it'll never be read! */
	if (_store_errmsg && (level <= _LOG_ERR) &&
	    _lvm_errmsg_len < MAX_ERRMSG_LEN) {
		msglen = strlen(message);
		if ((_lvm_errmsg_len + msglen + 1) >= _lvm_errmsg_size) {
			_lvm_errmsg_size = 2 * (_lvm_errmsg_len + msglen + 1);
			if ((newbuf = dm_realloc(_lvm_errmsg,
						 _lvm_errmsg_size)))
				_lvm_errmsg = newbuf;
			else
				_lvm_errmsg_size = _lvm_errmsg_len;
		}
		if (_lvm_errmsg &&
		    (_lvm_errmsg_len + msglen + 2) < _lvm_errmsg_size) {
			/* prepend '\n' and copy with '\0' but do not count in */
                        if (_lvm_errmsg_len)
				_lvm_errmsg[_lvm_errmsg_len++] = '\n';
			memcpy(_lvm_errmsg + _lvm_errmsg_len, message, msglen + 1);
			_lvm_errmsg_len += msglen;
		}
	}

	if (log_once) {
		if (!_duplicated)
			_duplicated = dm_hash_create(128);
		if (_duplicated) {
			if (dm_hash_lookup(_duplicated, message))
				level = _LOG_NOTICE;
			(void) dm_hash_insert(_duplicated, message, (void*)1);
		}
	}

	if (_lvm2_log_fn) {
		_lvm2_log_fn(level, file, line, 0, message);
		if (fatal_internal_error)
			abort();
		return;
	}

      log_it:
	if (!_log_suppress) {
		if (verbose_level() > _LOG_DEBUG)
			(void) dm_snprintf(locn, sizeof(locn), "#%s:%d ",
					   file, line);
		else
			locn[0] = '\0';

		va_start(ap, format);
		switch (level) {
		case _LOG_DEBUG:
			if (!strcmp("<backtrace>", format) &&
			    verbose_level() <= _LOG_DEBUG)
				break;
			if (verbose_level() >= _LOG_DEBUG) {
				fprintf(stderr, "%s%s%s", locn, log_command_name(),
					_msg_prefix);
				if (_indent)
					fprintf(stderr, "      ");
				vfprintf(stderr, trformat, ap);
				fputc('\n', stderr);
			}
			break;

		case _LOG_INFO:
			if (verbose_level() >= _LOG_INFO) {
				fprintf(stderr, "%s%s%s", locn, log_command_name(),
					_msg_prefix);
				if (_indent)
					fprintf(stderr, "    ");
				vfprintf(stderr, trformat, ap);
				fputc('\n', stderr);
			}
			break;
		case _LOG_NOTICE:
			if (verbose_level() >= _LOG_NOTICE) {
				fprintf(stderr, "%s%s%s", locn, log_command_name(),
					_msg_prefix);
				if (_indent)
					fprintf(stderr, "  ");
				vfprintf(stderr, trformat, ap);
				fputc('\n', stderr);
			}
			break;
		case _LOG_WARN:
			if (verbose_level() >= _LOG_WARN) {
				fprintf(use_stderr ? stderr : stdout, "%s%s",
					log_command_name(), _msg_prefix);
				vfprintf(use_stderr ? stderr : stdout, trformat, ap);
				fputc('\n', use_stderr ? stderr : stdout);
			}
			break;
		case _LOG_ERR:
			if (verbose_level() >= _LOG_ERR) {
				fprintf(stderr, "%s%s%s", locn, log_command_name(),
					_msg_prefix);
				vfprintf(stderr, trformat, ap);
				fputc('\n', stderr);
			}
			break;
		case _LOG_FATAL:
		default:
			if (verbose_level() >= _LOG_FATAL) {
				fprintf(stderr, "%s%s%s", locn, log_command_name(),
					_msg_prefix);
				vfprintf(stderr, trformat, ap);
				fputc('\n', stderr);
			}
			break;
		}
		va_end(ap);
	}

	if (level > debug_level())
		return;

	if (_log_to_file && (_log_while_suspended || !critical_section())) {
		fprintf(_log_file, "%s:%d %s%s", file, line, log_command_name(),
			_msg_prefix);

		va_start(ap, format);
		vfprintf(_log_file, trformat, ap);
		va_end(ap);

		fprintf(_log_file, "\n");
		fflush(_log_file);
	}

	if (_syslog && (_log_while_suspended || !critical_section())) {
		va_start(ap, format);
		vsyslog(level, trformat, ap);
		va_end(ap);
	}

	if (fatal_internal_error)
		abort();

	/* FIXME This code is unfinished - pre-extend & condense. */
	if (!_already_logging && _log_direct && critical_section()) {
		_already_logging = 1;
		memset(&buf, ' ', sizeof(buf));
		bufused = 0;
		if ((n = dm_snprintf(buf, sizeof(buf) - 1,
				      "%s:%d %s%s", file, line, log_command_name(),
				      _msg_prefix)) == -1)
			goto done;

		bufused += n;

		va_start(ap, format);
		n = vsnprintf(buf + bufused - 1, sizeof(buf) - bufused - 1,
			      trformat, ap);
		va_end(ap);
		bufused += n;

		buf[bufused - 1] = '\n';
	      done:
		buf[bufused] = '\n';
		buf[sizeof(buf) - 1] = '\n';
		/* FIXME real size bufused */
		dev_append(&_log_dev, sizeof(buf), buf);
		_already_logging = 0;
	}
}
Esempio n. 27
0
void
CoreProcessInitCallback::func(Process* proc)
{
    Config*         config   = NULL;
    DistributedLicenseRequester* license_requester = NULL;
    ServerRegistry* registry = NULL;
    int backlog = 0;
    int setegid_err = 0;
    int seteuid_err = 0;
    INT32 nUseRegistryForStats = 0;

    printf ("Starting %s %d.%d Core...\n", ServerVersion::ProductName(),
            ServerVersion::MajorVersion(), ServerVersion::MinorVersion());

    proc->pc = new CoreContainer(proc);
    proc->pc->process_type = PTCore;

    proc->pc->lbound_tcp_listenRTSPResponse = NULL;

    proc->pc->dispatchq = dispatch_queue;
    proc->pc->dispatchq->init(proc);

    MulticastAccessControl* mcast_ctrl = new MulticastAccessControl();

    /*
     * Must create the ErrorSinkHandler before accessing Config
     */

    proc->pc->error_sink_handler = new ErrorSinkHandler();

    progname = GetProgName(argv[0]);
    os_init();
    registry = new ServerRegistry(proc);
    proc->pc->registry = registry;
    registry->AddComp("Client", proc);
    registry->AddComp("Server", proc);

    // Add system composite to the registry
    registry->AddComp("system", proc);

    // Add startuplog info to the registry
    ServerBuffer* pBuf = new ServerBuffer((UCHAR*)g_szStartupLog, strlen(g_szStartupLog));
    if (g_szStartupLog)
        registry->AddStr("Server.StartupLogPath", pBuf, proc);

    config = new Config(proc, g_pszConfigFile, g_pszImportKey, registry);
    if (!config->valid())
    {
        ERRMSG(proc->pc->error_handler, "Invalid configuration.\n");
        terminate(1);
    }

    if (g_pszImportKey && g_pszImportKey[0])
    {
        terminate(1);
    }

    proc->pc->client_stats_manager = new ClientStatsManager;
    //proc->pc->client_stats_manager->AddRef();

    if (SUCCEEDED(registry->GetInt("config.ClientStats.UseRegistry",
                                            &nUseRegistryForStats,
                                            proc)))
    {
        proc->pc->client_stats_manager->SetUseRegistryForStats(nUseRegistryForStats ? TRUE : FALSE);
    }

    proc->pc->license_requester = new DistributedLicenseRequester;


    /*
     * Now that the proc->pc and the registry are established, it is safe to
     * initialize the IHXNetworkServicesContext
     */

    proc->pc->network_services->Init(proc->pc->server_context,
                                     proc->pc->engine,
                                     NULL);

    proc->pc->net_services->Init(proc->pc->server_context);
    // MulticastManager needs MulticastAddressPool!
    proc->pc->mcst_addr_pool    = new MulticastAddressPool();
    proc->pc->mcst_addr_pool->AddRef();

    /*
    *   CSapManager and MulticastManager both needs
    *   plugin hander which will be avilable in
    *   _main CoreTransferCallback::func
    */
    // will be Init'ed in _main CoreTransferCallback::func
    proc->pc->sap_mgr = new CSapManager();
    proc->pc->sap_mgr->AddRef();

    // addtional Init will be done in _main CoreTransferCallback::func
    proc->pc->multicast_mgr = new MulticastManager(proc->pc->server_context);

    /*
     */
    proc->pc->alt_server_proxy_cfg_mgr =
        new AltServerProxyConfigHandler(proc, registry);
    proc->pc->alt_server_proxy_cfg_mgr->AddRef();
    if (HXR_FAIL == proc->pc->alt_server_proxy_cfg_mgr->Init())
    {
        HX_RELEASE(proc->pc->alt_server_proxy_cfg_mgr);
    }

    /* setup QoS core */
    proc->pc->qos_prof_select = new QoSProfileSelector(proc);
    proc->pc->qos_prof_select->AddRef();
    proc->pc->qos_bus_ctl     = new QoSSignalBusController();
    proc->pc->qos_bus_ctl->AddRef();
    proc->pc->qos_sig_src     = new QoSSignalSource(proc, proc->pc->qos_bus_ctl);
    proc->pc->qos_sig_src->AddRef();

    /* setup capex profile cache */
    proc->pc->capex_static_cache = new StaticProfileCache();
    proc->pc->capex_static_cache->AddRef();
    proc->pc->capex_profile_cache = new HTTPProfileCache();
    proc->pc->capex_profile_cache->AddRef();

    Config_error* error_result = 0;

    backlog = config->GetInt(proc, "config.ListenBacklog");
    if (backlog < CONFIG_BACKLOG)
        backlog = CONFIG_BACKLOG;

#ifdef  DEBUG
    debug_level() = g_ulDebugFlags ? g_ulDebugFlags :
                  config->GetInt(proc, "config.Debug");
    debug_func_level() = g_ulDebugFuncFlags ? g_ulDebugFuncFlags :
                       config->GetInt(proc, "config.DebugFunc");
#endif

    ((CoreContainer*)proc->pc)->m_pListenResponseList = new CHXSimpleList;

    HXRegistry* hxreg = new HXRegistry(registry, proc);
    HX_RESULT res = HXR_OK;

    hxreg->AddRef();

    char**      pHTTPablePaths = NULL;
    char**      pHTTPpostablePaths = NULL;

    ::GetHTTPPaths(hxreg, (char*)"config.HTTPDeliverable", pHTTPablePaths);
    ::GetHTTPPaths(hxreg, (char*)"config.HTTPPostable", pHTTPpostablePaths);

    /*
     * Add key for broadcast plugins to register their connections
     */
    hxreg->AddComp("LiveConnections");
    hxreg->AddInt("LiveConnections.Index", 0);
    hxreg->AddInt("LiveConnections.Count", 0);

    proc->pc->named_lock_manager->CreateNamedLock("LiveConnectionsLock");

    INT32* pEncoders = new INT32;
    IHXBuffer* pIHXBuf = new ServerBuffer(TRUE);
    HX_ASSERT(pIHXBuf);

    *pEncoders = 0;
    pIHXBuf->SetSize(sizeof(void*));
    *((void**)pIHXBuf->GetBuffer()) = (void*)pEncoders;
    hxreg->AddBuf("EncoderConnections.Index", pIHXBuf);
    HX_RELEASE(pIHXBuf);

    /*
     * Add key for monitor plugins to register their connections
     */
    hxreg->AddComp("Monitors");
    hxreg->AddInt("Monitors.Count", 0);

    /*
     * Add key for splitters to register their connections
     */
    hxreg->AddComp("Splitters");
    hxreg->AddInt("Splitters.Index", 0);
    hxreg->AddInt("Splitters.Count", 0);

    mcast_ctrl->Init(proc);
    proc->pc->mcast_ctrl        = mcast_ctrl;

    IHXValues* pAddrList = NULL;
    IHXBuffer* pAddrBuf = NULL;
    const char* pAddrStr = NULL;
    BOOL bBindToLocalHost = FALSE;

    TimeZoneCheckCallback* tzcb = new TimeZoneCheckCallback(proc);
    tzcb->SetTimeZone();
    tzcb->ScheduleFirstCheckCallback();

    HX_RESULT pn_res = hxreg->GetPropListByName("config.IPBindings", pAddrList);
    if (pn_res != HXR_OK)
    {
        pn_res = hxreg->GetPropListByName("config.IPBinding", pAddrList);
    }

    INT32 sbind_id = hxreg->AddComp("server.ipbinding");
    HX_ASSERT(sbind_id);
    int num_props = 0;

    switch (pn_res)
    {
        case HXR_OK:
        {
            const char* addr_prop_name;
            UINT32      addr_prop_id;

            res = pAddrList->GetFirstPropertyULONG32(addr_prop_name,
                addr_prop_id);
            while(res == HXR_OK)
            {
                char str[64];

                if (HXR_OK == hxreg->GetStrById(addr_prop_id, pAddrBuf))
                {
                    const char* strAddr = (const char*)pAddrBuf->GetBuffer();
                    if (!strcmp(strAddr, "*"))
                    {
                        //XXXJJ "*" means any interfaces(including ipv4 and ipv6)
                        // will be handled in "default:".

                        //if we have "*", we shouldn't have other entries in the list.
                        HX_ASSERT(num_props == 0);
                        break;
                    }
                    else if (!strcmp(strAddr, "127.0.0.1") || !strcmp(strAddr, "0.0.0.0"))
                    {
                        bBindToLocalHost = TRUE;
                    }

                    ++num_props;
                    sprintf(str, "server.ipbinding.addr_%.2d", num_props);
                    hxreg->AddStr(str, pAddrBuf);

                    HX_RELEASE(pAddrBuf);
                }
                res = pAddrList->GetNextPropertyULONG32(addr_prop_name,
                                                        addr_prop_id);
            }
            pAddrList->Release();

            if (num_props)
                break;
        }

        // Three cases fall into here: no ipbinding list, empty list, or only "*"
        // in the list
        default:
        {
            ServerBuffer::FromCharArray("*", &pAddrBuf);
            hxreg->AddStr("server.ipbinding.addr_01", pAddrBuf);
            pAddrBuf->Release();

            bBindToLocalHost = TRUE;
            break;
        }
    };

    if(!g_pHeartBeatIP) 
    {
        // heartbeat ip not specified
        if(!bBindToLocalHost)
        {
            //localhost is not in the binding list, we need to manually add it
            // for heartbeat connection to succeed.
            char str[64];
            ++num_props;
            sprintf(str, "server.ipbinding.addr_%.2d", num_props);
            ServerBuffer::FromCharArray("127.0.0.1", &pAddrBuf);
            hxreg->AddStr(str, pAddrBuf);
            pAddrBuf->Release();
        }

    }
    
    _initializeListenRespObjects(proc, config, registry, backlog);

    hxreg->Release();

    // This used to set g_pCPUCount based on config.ProcessorCount but
    // setting StreamerCount is the way to do this now.
    *g_pCPUCount = g_bSkipCPUTest ? 1 : CPUDetect();

    //
    // This just gives the "Linux22Compat" code a platform-neutral
    // name for testing/debugging on other platforms.
    //
    UINT32 ulLessParallel = config->GetInt(proc, "config.LessParallel");
    if (ulLessParallel)
    {
        printf("Note: Configuration specified LessParallel mode.\n");
        *g_bLimitParallelism = TRUE;
    }


#ifdef _UNIX
    const char* pPIDPath;
    if ((pPIDPath = config->GetString(proc, "config.PidPath")))
    {
        FILE* f = fopen(pPIDPath, "w");
        if (f > 0)
        {
#if defined PTHREADS_SUPPORTED
            fprintf(f, "%d\n", getpid());
#else
            fprintf(f, "%d\n", proc->procid(PROC_RM_CONTROLLER));
#endif
            fclose(f);
        }
        else
        {
            ERRMSG(proc->pc->error_handler,
                   "Couldn't open PID File %s", pPIDPath);
        }
    }

    int gid = GetGIDFromConfig(proc, config);
    int uid = GetUIDFromConfig(proc, config);

    if (pPIDPath && gid >= 0 && uid >= 0)
    {
        if (chown(pPIDPath, uid, gid) < 0)
            perror("could not set the PIDPath's ownership\n");
    }
    if (gid >= 0)
    {
#ifdef _AIX
        if (setregid(-1, gid) < 0)
#elif defined _HPUX
         if (setresgid(-1, gid, gid) < 0)
#else
        if (setegid(gid) < 0)
#endif
        {
            setegid_err = errno;
            perror("setegid() failed(1)");
            *return_gid = (UINT32)-1;
        }
        else
            *return_gid = gid;
    }
    if (uid >= 0)
    {
#if defined _AIX || defined _HPUX
        if (setreuid(-1, uid) < 0)
#else
        if (seteuid(uid) < 0)
#endif
        {
            seteuid_err = errno;
            perror("seteuid() failed(1)");
            *return_uid = (UINT32)-1;
        }
        else
        {
            *return_uid = uid;
        }
    }
    fflush(0);
#endif

    proc->pc->config            = config;

    /*
     * Handle streamer_info creation and overriding of capacity defaults
     * from the config file.
     */
    UINT32 ul;
    proc->pc->streamer_info     = new StreamerInfo;
    if (HXR_OK == proc->pc->registry->GetInt("config.StreamerSessionCapacity",
        (INT32*)&ul, proc))
    {
        proc->pc->streamer_info->SetSessionCapacity(ul);
    }

    if (HXR_OK == proc->pc->registry->GetInt("config.MaxSockCapacity",
        (INT32*)&ul, proc))
    {
        SOCK_CAPACITY_VALUE = ul;
    }

    if ((HXR_OK == proc->pc->registry->GetInt("config.MaxDescCapacity",
        (INT32*)&ul, proc)) ||
        (HXR_OK == proc->pc->registry->GetInt("config.MaxDescriptorCapacity",
        (INT32*)&ul, proc)))
    {
        DESCRIPTOR_CAPACITY_VALUE = ul;
    }

    proc->pc->conn_id_table     = new CHXTSID(config->GetInt(proc, "config.Capacity"));
    proc->pc->resolver_info     = new ResolverInfo;
    proc->pc->rdispatch         = new ResolverDispatch(proc);
    proc->pc->scheduler         = new ServerScheduler(proc);
    proc->pc->server_prefs      = new ServerPreferences(proc);
    proc->pc->server_info       = new ServerInfo(proc);
    proc->pc->loadinfo          = new LoadInfo(proc);

    //XXXTDM: Where's all the AddRef() calls???
    proc->pc->net_services->AddRef();
    proc->pc->scheduler->AddRef();

    // Tell mem routines where to find a regularly-updated timestamp in shared memory

    SharedMemory::SetTimePtr(&proc->pc->engine->now);

#ifdef PAULM_LEAKCHECK
    if (g_bLeakCheck)
        new MemChecker(proc);
#endif /* PAULM_LEAKCHECK */

    proc->pc->misc_plugins      = new CHXMapPtrToPtr();
    proc->pc->allowance_plugins = new CHXMapPtrToPtr();
    proc->pc->server_fork       = new ServerFork(proc);
    proc->pc->global_server_control = new GlobalServerControl(proc);
    proc->pc->data_convert_con  = new DataConvertController;

#if defined _UNIX
    proc->pc->m_pResMUX         = new ResolverMUX(RESOLVER_CAPACITY_VALUE,
                                        MAX_RESOLVERS, proc->pc->server_fork,
                                        proc->pc->async_io, proc->pc->error_handler);
#endif

    proc->pc->HTTP_deliver_paths = new char**;
    if (pHTTPablePaths)
    {
        *proc->pc->HTTP_deliver_paths= pHTTPablePaths;
    }
    else
    {
        *proc->pc->HTTP_deliver_paths = NULL;
    }
    new HTTPDeliverablePrefController(proc, (char*)"config.HTTPDeliverable",
                                      proc->pc->HTTP_deliver_paths);

    proc->pc->HTTP_postable_paths = new char**;
    if (pHTTPpostablePaths)
    {
        *proc->pc->HTTP_postable_paths= pHTTPpostablePaths;
    }
    else
    {
        *proc->pc->HTTP_postable_paths = NULL;
    }
    new HTTPDeliverablePrefController(proc, (char*)"config.HTTPPostable",
                                      proc->pc->HTTP_postable_paths);

    proc->pc->cloaked_guid_dict = new CloakedGUIDDict();
    proc->pc->broadcast_manager = new BroadcastManager();
    proc->pc->load_listen_mgr = new LoadBalancedListenerManager(proc);

    /*
     * Setup the global mimetype dictionary.
     */
    proc->pc->mime_type_dict = new Dict();
    hxreg = new HXRegistry(proc->pc->registry, proc);
    hxreg->AddRef();
    IHXValues* pTypeList;

    if(HXR_OK == hxreg->GetPropListByName("config.MimeTypes", pTypeList))
    {
        HX_RESULT res;
        const char* mimeTypeRegname;
        UINT32 mime_id;
        res = pTypeList->GetFirstPropertyULONG32(mimeTypeRegname, mime_id);
        while(HXR_OK == res)
        {
            HXPropType mimetypetype = hxreg->GetTypeById(mime_id);
            if(mimetypetype != PT_COMPOSITE)
                res = HXR_FAIL;
            else
            {
                const char* mimeType = strrchr(mimeTypeRegname, '.');
                if(!mimeType)
                    mimeType = mimeTypeRegname;
                else
                    mimeType++;

                IHXValues* pExtList;
                if(HXR_OK == hxreg->GetPropListById(mime_id, pExtList))
                {
                    const char* ext;
                    UINT32 ext_id;
                    res = pExtList->GetFirstPropertyULONG32(ext, ext_id);
                    while(res == HXR_OK)
                    {
                        if(PT_STRING == hxreg->GetTypeById(ext_id) ||
                           PT_BUFFER == hxreg->GetTypeById(ext_id))
                        {
                            IHXBuffer* extBuffer;
                            if(HXR_OK == hxreg->GetStrById(ext_id,
                                                           extBuffer))
                            {
                                proc->pc->mime_type_dict->enter(
                                    (const char*)extBuffer->GetBuffer(),
                                    new_string(mimeType));
                                HX_RELEASE(extBuffer);
                            }
                        }
                        res = pExtList->GetNextPropertyULONG32(ext, ext_id);
                    }
                    HX_RELEASE(pExtList);
                }
                res = pTypeList->GetNextPropertyULONG32(mimeTypeRegname,
                    mime_id);
            }
        }
        HX_RELEASE(pTypeList);
    }
    HX_RELEASE(hxreg);

    proc->pc->rtspstats_manager = new RTSPEventsManager();
    proc->pc->sdpstats_manager = new SDPAggregateStats();
    proc->pc->sdpstats_manager->AddRef();

    // If a default mime type doesn't yet exist, add one so that
    // we will always send some mime type
    Dict_entry* ent = proc->pc->mime_type_dict->find("*");
    if(!ent)
    {
        proc->pc->mime_type_dict->enter("*", new_string("application/octet-stream"));
    }
    new MimeTypesPrefController(proc);

    ((CoreContainer *)proc->pc)->cdispatch = new ConnDispatch(proc);

    /*
     * AddRef() all objects handed out by ServerContext
     */

    proc->pc->server_prefs->AddRef();
    proc->pc->server_fork->AddRef();

    *core_proc = proc;
    *controller_waiting_on_core = 0; // Signal Controller to continue
    while (!(*controller_ready))
        microsleep(1); // Busy Wait for the Controller
    delete controller_ready;

    CoreTransferCallback* cb = new CoreTransferCallback;
    cb->core_proc           = proc;
#ifdef DEBUG
    cb->m_debug_level       = debug_level();
    cb->m_debug_func_level  = debug_func_level();
#endif

    int* volatile core_waiting_for_refresh;
    cb->core_waiting_for_refresh = new int;
    *cb->core_waiting_for_refresh = 1;
    core_waiting_for_refresh = cb->core_waiting_for_refresh;

#ifdef _WIN32
    MaybeNotifyServiceUp();
#endif

    proc->pc->dispatchq->send(proc, cb, PROC_RM_CONTROLLER);

    /*
     * Wait here for the controller to get the plugins loaded.
     */
    while (*core_waiting_for_refresh)
        microsleep(1);

    delete core_waiting_for_refresh;

    /*
     * NOTE: Both NT and mac have servers that run to completion in
     *       os_start()
     */
    os_start();

    fflush(0);

    // add the global var ptr into the registry, so that the mmap managers in
    // each process can then access and modify the var using atomic
    // operations. g_pMemoryMappedDataSize is used to report the amount of
    // mmapped data that is read via the local file system (smplfsys).
    registry->AddIntRef("server.MMappedDataSize",
	(INT32 *)g_pMemoryMappedDataSize, proc);

    proc->pc->engine->mainloop();

    // NEVER REACHED!
#if 0
    delete this;
#endif
    PANIC(("Internal Error cp/737\n"));
}
Esempio n. 28
0
int main( int argc, char *argv[] ) {
  IMAGE *img;
  IMAGE *find;
  int off_x, off_y, tolerance;
  int start_x, start_y;
  int total_match;
  IMAGE **matches;
  
  POINT pt, tmp_pt;

  int cnt, gotmatch, tmp_i, find_next, final_exit;
  int opt;

  off_x = off_y = 0;
  start_x = start_y = 0;
  tolerance = 0;
  final_exit = 1;
  
  while( ( opt = getopt( argc, argv, "hX:Y:x:d:y:t:" ) ) != EOF ) {
    switch( opt ) {
    case 'h':
      printf( "visgrep v" VERSION "\n"
	      "visual grep, greps for images in another image\n"
	      "Author: Steve Slaven - http://hoopajoo.net\n"
	      "\n"
	      "usage: %s [-h] [-x x_off] [-y y_off] [-X start x_off] [-Y start y_off]\n"
	      "          [-d debuglevel] [-t tolerance] image.png detect.pat match.pat ...\n"
	      "\n"
	      "  -h   This help\n"
	      "  -x   Set x offset for detection matching\n"
	      "  -y   Set y offset for detection matching\n"
	      "  -X   Start scanning at X\n"
	      "  -Y   Start scanning at Y\n"
	      "  -t   Set tolerance for 'fuzzy' matches, higher numbers are more tolerant\n"
	      "\n"
	      "All .pat files are created using png2pat or rgb2pat.  The image.png is\n"
	      "scanned for detect.pat starting from X,Y specified above.  When detect.pat\n"
	      "is found, then all the match.pat files are scanned at an offset of x,y as\n"
	      "specified above.  If a match is found, then visgrep prints the x,y and\n"
	      "index of the item.\n"
	      "\n"
	      "image.png must be an 8 bit deep RGB or RGBA png file."
	      "\n"
	      "For example, image.png is a screenshot and match1.pat .. to match5.pat are\n"
	      "images of letters a to e.  Each of these letters is enclosed in a blue box,\n"
	      "so detect.pat is an image of the upper left corner of the box.  This box is\n"
	      "not included in the match*.pat files, so they are actually offset 5 pixels\n"
	      "down and 4 pixels to the left.  You might run it like this then:\n"
	      "\n"
	      "  visgrep -x-4 -y5 image.png match_corner.pat match_a.pat match_b.bat ...\n"
	      "\n"
	      "Etc, with all matches listed.  Now suppose the screen showed 'ace' so\n"
	      "visgrep might output:\n"
	      "\n"
	      "10,10 0\n"
	      "50,10 2\n"
	      "90,10 4\n"
	      "\n"
	      "Showing that match_a.pat (index 0) is at 10,10 on the screen.  If no match\n"
	      "is found even though the detection image is found, the index will be -1.\n"
	      "\n"
	      "Exit status is 0 for successful match, 1 for no match, and 2 for error.\n"
	      , argv[ 0 ] );
      exit( 0 );
      break;
      
    case 'x':
      sscanf( optarg, "%d", &off_x );
      dmsg( 2, "X offset is %d\n", off_x );
      break;
      
    case 'y':
      sscanf( optarg, "%d", &off_y );
      dmsg( 2, "Y offset is %d\n", off_y );
      break;

    case 'X':
      sscanf( optarg, "%d", &start_x );
      dmsg( 2, "Start X offset is %d\n", start_x );
      break;
      
    case 'Y':
      sscanf( optarg, "%d", &start_y );
      dmsg( 2, "Start Y offset is %d\n", start_y );
      break;
      
    case 't':
      sscanf( optarg, "%d", &tolerance );
      dmsg( 2, "Tolerance is %d\n", tolerance );
      break;

    case 'd':
      sscanf( optarg, "%d", &tmp_i );
      dmsg( 2, "Debug set to %d\n", tmp_i );
      debug_level( tmp_i );
      break;
      
    case '?':
      fprintf( stderr, "Unknown option '%c'\n", optopt );
      break;
      
    default:
      fprintf( stderr, "Unhandled option '%c'\n", opt );
      break;
    }
  }

  if( argc - optind < 2 ) {
    fprintf( stderr, "Error, not enough args, try -h\n" );
    exit( 2 );
  }
  
  dmsg( 1, "Loading main PNG image '%s'\n", argv[ optind ] );
  img = img_load_from_png( argv[ optind ] );
  optind++;
  if( img == NULL ) {
    fprintf( stderr, "Error, unable to load png, try -h\n" );
    exit( 2 );
  }
  
  dmsg( 1, "Loading detection image '%s'\n", argv[ optind ] );
  find = img_load( argv[ optind ] );
  dmsg( 1, "Loaded %dx%d\n", find -> width, find -> height );
  optind++;
  
  total_match = argc - optind;
  dmsg( 1, "Now optind=%d : argc=%d : total_match=%d\n", optind, argc, total_match );

  matches = (IMAGE **)malloc( total_match * sizeof( IMAGE * ) );
  
  /* Load actual scoreboxes */
  dmsg( 1, "Loading match data....\n" );
  for( cnt = 0; cnt < total_match; cnt++ ) {
    dmsg( 1, " -- %s\n", argv[ optind ] );
    matches[ cnt ] = img_load( argv[ optind ] );
    if( ! matches[ cnt ] ) {
      printf( "Error loading '%s'\n", argv[ optind ] );
      exit( 2 );
    }
    optind++;
  }

  dmsg( 1, "Detecting offsets...\n" );
  pt.x = start_x;
  pt.y = start_y;
  find_next = 0;
  while( pt.x != -1 ) {
    pt = img_subimage_find( img, find, pt, tolerance, find_next );

    /* Not first time anymore */
    find_next = 1;
    
    if( pt.x != -1 ) {
      dmsg( 1, "  Found match at %d,%d\n", pt.x, pt.y );

      /* Try and identify what thing it is */
      gotmatch = 0;
      tmp_pt.x = pt.x + off_x;
      tmp_pt.y = pt.y + off_y;
      for( cnt = 0; cnt < total_match; cnt++ ) {
	if( matches[ cnt ] != NULL ) {
	  dmsg( 1, " Testing for %d  ", cnt );
	  dmsg( 1, " (%d,%d) ", tmp_pt.x, tmp_pt.y );
	  if( img_subimage_cmp( img, matches[ cnt ], tmp_pt, tolerance ) <= tolerance ) {
	    dmsg( 1, "  YES\n" );
	    
	    printf( "%d,%d %d\n", tmp_pt.x, tmp_pt.y, cnt );
	    gotmatch = 1;
	    final_exit = 0;

	    /* Fall out */
	    cnt = total_match;
	  }else{
	    dmsg( 1, "  NO\n" );
	  }
	}else{
	  dmsg( 1, " No image in slot %d\n", cnt );
	}
      }

      /* Notify of no match */
      if( ! gotmatch ) {
	dmsg( 1, " NO ITEMS MATCHED!\n" );
	printf( "%d,%d %d\n", tmp_pt.x, tmp_pt.y, -1 );
      }
    }
  }

  exit( final_exit );
}
Esempio n. 29
0
static int ScatterFragmentData(int size, unsigned char *buffer, ECB_t * ECB,
                               struct sockaddr_ipx *sipx)
{
  int i;
  int nextFragLen, dataLeftCount;
  u_char *bufptr, *memptr;
  IPXPacket_t *IPXHeader;

  n_printf("received data bytes:\n");
  if (debug_level('n')) {
    dumpBytes(buffer, size);
  }
  dataLeftCount = size;
  bufptr = buffer;
  if (ECB->FragmentCount < 1 || ECB->FragTable[0].Length < 30) {
    /* posted listen has a fragment error */
    n_printf("IPX: listen packet fragment error\n");
    return (size);
  }
  i = 0;
  while (i < ECB->FragmentCount && dataLeftCount) {
    nextFragLen = ECB->FragTable[i].Length;
    memptr = FARt_PTR(ECB->FragTable[i].Address);
    n_printf("IPX: filling fragment %d at %p, max_length %d with %d bytes left\n",
	     i, FARt_PTR(ECB->FragTable[i].Address), nextFragLen,
	     dataLeftCount);
    if (i == 0) {
      /* subtract off IPX header size from first fragment */
      nextFragLen -= 30;
      /* also, fill out IPX header */
      /* use data from sipx to fill out source address */
      IPXHeader = (IPXPacket_t *) memptr;
      IPXHeader->Checksum = 0xFFFF;
      IPXHeader->Length = htons(size + 30); /* in network order */
      /* DANG_FIXTHIS - use real values to fill out IPX header here */
      IPXHeader->TransportControl = 1;
      IPXHeader->PacketType = 0;
      memcpy((u_char *) & IPXHeader->Destination, MyAddress, 10);
      memcpy(&IPXHeader->Destination.Socket, &ECB->ECBSocket, 2);
      memcpy(IPXHeader->Source.Network, (char *) &sipx->sipx_network, 4);
      memcpy(IPXHeader->Source.Node, sipx->sipx_node, 6);
      memcpy(IPXHeader->Source.Socket, &sipx->sipx_port, 2);
      /* DANG_FIXTHIS - kludge for bug in linux IPX stack */
      /* IPX stack returns data count including IPX header */
      /*			dataLeftCount -= 30; */
      memptr += 30;
      printIPXHeader(IPXHeader);
    }
    if (nextFragLen > dataLeftCount) {
      nextFragLen = dataLeftCount;
    }
    if (nextFragLen) {
      memcpy(memptr, bufptr, nextFragLen);
      bufptr += nextFragLen;
      dataLeftCount -= nextFragLen;
    }
    i++;
  }
  n_printf("IPX: scattered %d fragments, %d bytes left over.\n",
	   i, dataLeftCount);
  return (dataLeftCount);
}
Esempio n. 30
0
int s_munprotect(unsigned int addr, size_t len)
{
	if (debug_level('e')>3) e_printf("\tS_MUNPROT %08x\n",addr);
	return e_check_munprotect(addr, len);
}