Beispiel #1
0
normalizer_t* normalizer_init() {

	normalizer_t* normalizer = malloc(sizeof(normalizer_t));
	if(!normalizer) {
		error(1, errno, "error allocating normalizer");
	}

	normalizer->vdfnsn_regex = malloc(sizeof(regex_t));
	if(!normalizer->vdfnsn_regex) {
		error(1, errno, "error allocating vodafone sn regex");
	}

	if(regcomp(normalizer->vdfnsn_regex, "/SN([0-9]+)[ ]*", REG_EXTENDED)!=0) {
		assert(false);
	}

	normalizer->language_regex = malloc(sizeof(regex_t));
	if(!normalizer->language_regex) {
		error(1, errno, "error allocating language regex");
	}

	if(regcomp(normalizer->language_regex, "([a-zA-Z]{2}-[a-zA-Z]{2})", REG_EXTENDED)!=0) {
		assert(false);
	}

	normalizer->handlers = linkedlist_init(&ref_eq);
	linkedlist_add(normalizer->handlers, &normalize_yeswap);
	linkedlist_add(normalizer->handlers, &normalize_babelfish);
	linkedlist_add(normalizer->handlers, &normalize_uplink);
	linkedlist_add(normalizer->handlers, &normalize_vodafonesn);
	linkedlist_add(normalizer->handlers, &normalize_language);

	return normalizer;
}
Beispiel #2
0
int
symcopy(struct sym *from, struct sym *to, struct allocator *al)
{
	iter_t iter;
	void *key, *data;

	to->flags = from->flags & 0xFFFF;
	to->idl_type = dupstr(from->idl_type, al);
	to->ndr_type = dupstr(from->ndr_type, al);
	to->interface = from->interface;

	hashmap_iterate(&from->attrs, &iter);
	while ((key = hashmap_next(&from->attrs, &iter))) {
		if ((data = hashmap_get(&from->attrs, key)) == NULL ||
				hashmap_put(&to->attrs, key, data) == -1) {
			AMSG("");
			return -1;
		}
	}
	linkedlist_iterate(&from->mems, &iter);
	while ((data = linkedlist_next(&from->mems, &iter))) {
		if (linkedlist_add(&to->mems, data) == -1) {
			AMSG("");
			return -1;
		}
	}

	to->name = dupstr(from->name, al);
	to->value = dupstr(from->value, al);
	to->ptr = from->ptr;
	to->align = from->align;

	return 0;
}
Beispiel #3
0
BOOLEAN KnOSWriteQueue(KnQueue_t queue, void* msg, U16BIT msg_size, U16BIT timeout)
{
	S_;
#ifdef _SW_Q_
	knQueue_t* que = (knQueue_t*) queue;
	void* data_p = KnMalloc(msg_size);
	KnMemcpy(data_p, msg, msg_size);
	KnOSMutexLock(que->lock);
	linkedlist_add(que->queue, data_p);
	KnOSMutexUnlock(que->lock);
	KnOSSemaphoreSignal(que->event);
	return TRUE;
#else
	knQueue_t* que = (knQueue_t*) queue;
	Q_;
	KnOSMutexLock(que->lock);
	Q_;
	int ret = msgsnd(que->fd, msg, msg_size, 0 | MSG_NOERROR);
	Q_;
	if(ret == -1)
	{
		Q_;
		KnOSMutexUnlock(que->lock);
		return FALSE;
	}
	KnOSMutexUnlock(que->lock);
	KnOSSemaphoreSignal(que->event);
	return TRUE;
#endif
}
Beispiel #4
0
int xwifi_wpa_parser_interfaces_result(linkedlist list, const char* result)
{
	S_;
	const char *ptr = result;

	KASSERT(list);
	KASSERT(result);

	linkedlist_clear(list, free);

	stringtokenizer tokenizer = stringtokenizer_new((const char**) &ptr);
	int ret;
	int i;
	char dst[512];
	char delim;
	for(i=0; (ret = stringtokenizer_next_token2(tokenizer, "\t\n ", 2, dst, &delim)) != -1 ; i++) {
		if(delim == '\t') {
			Q_;
		}
		else if(delim == '\n') {
			M_("<%d> : %s", i, dst);
			char* alias = strdup(dst);
			linkedlist_add(list, alias);
		}
	}
	return 0;
}
Beispiel #5
0
int
PoolExercise(int verbose, struct cfg *cfg, char *args[])
{
    void *data;
    int rate, i;
    struct linkedlist *l;
    struct pool *p;
    cfg = NULL;
    args[0] = NULL;

    if ((p = pool_new(EXERCISE_SM_COUNT,
                      (new_fn)allocator_alloc,
                      allocator_free,
                      NULL,
                      NULL, BUFFER_SIZE_SM, 0, NULL)) == NULL ||
            (l = linkedlist_new(0, NULL)) == NULL) {
        PMNO(errno);
        return 1;
    }

    rate = EXERCISE_R0;
    for (i = 0; i < EXERCISE_SM_COUNT; i++) {
        if (i == EXERCISE_SM_P1) {
            rate = EXERCISE_R1;
        } else if (i == EXERCISE_SM_P2) {
            rate = EXERCISE_R2;
        } else if (i == EXERCISE_SM_P3) {
            rate = EXERCISE_R3;
        }

        if (rand() % 10 < rate) {
            if (pool_size(p) == EXERCISE_SM_COUNT && pool_unused(p) == 0) {
                continue;
            } else if ((data = pool_get(p)) == NULL) {
                AMSG("");
                return -1;
            } else if (linkedlist_add(l, data) == -1) {
                AMSG("%04d %p s=%d,u=%d\n", i, data, pool_size(p), pool_unused(p));
                return -1;
            }
            tcase_printf(verbose, "%04d get %p s=%d,u=%d\n", i, data, pool_size(p), pool_unused(p));
        } else if ((data = linkedlist_remove(l, 0))) {
            if (data == NULL || pool_release(p, data) == -1) {
                AMSG("%04d %p s=%d,u=%d\n", i, data, pool_size(p), pool_unused(p));
                return -1;
            }
            tcase_printf(verbose, "%04d rel %p s=%d,u=%d\n", i, data, pool_size(p), pool_unused(p));
        } else {
            tcase_printf(verbose, "%04d nothing to release\n", i);
        }
    }

    linkedlist_del(l, NULL, NULL);
    pool_del(p);

    return 0;
}
Beispiel #6
0
int
AdtInit(int verbose, struct cfg *cfg, char *args[])
{
	char buf[0xFFFF];
	struct allocator *suba;
	struct stack s;
	struct linkedlist l;
	struct varray va;

	if ((suba = suba_init(buf, 0xFFFF, 1, 0)) == NULL ||
			stack_init(&s, 0, suba) == -1 ||
			linkedlist_init(&l, 0, suba) == -1 ||
			varray_init(&va, sizeof(int), suba) == -1) {
		AMSG("");
		return -1;
	}

	linkedlist_add(&l, "two");
	stack_push(&s, "two");
	linkedlist_add(&l, "three");
	stack_push(&s, "one");
	varray_get(&va, 444);
	stack_push(&s, "three");
	varray_get(&va, 4);
	varray_get(&va, 44);
	linkedlist_add(&l, "one");

	if (varray_deinit(&va) != 0 ||
			linkedlist_deinit(&l, NULL, NULL) != 0 ||
			stack_deinit(&s, NULL, NULL) != 0) {
		AMSG("");
		return -1;
	}

	tcase_printf(verbose, "done ");

	cfg = NULL;
	args[0] = NULL;
    return 0;
}
Beispiel #7
0
void kmem_init() {

    /* initialize free lists:  */
    /* ----------------------- */
    uint32_t i;
    for (i = 0; i < 32; i++)
        linkedlist_init(&freelist[i]);
    linkedlist_init(&usedlist);

    arch_vmpage_map(NULL, KERNEL_MEMORY_BASE, 0);
    linkedlist_add(&freelist[U], (linknode *)((uint32_t) KERNEL_MEMORY_BASE));

    kmem_initialized = 1;

}
Beispiel #8
0
JNIEXPORT jboolean JNICALL Java_gov_nasa_jpf_symbolic_dp_NativeInterface_isSatisfiable
  (JNIEnv *env, jclass cls, jstring constraintString )
{
  constraint = (char*) (*env)->GetStringUTFChars(env,constraintString, NULL);
  if( constraint == NULL ){
    throwRuntimeException( "out of memory?" );
  }

  //printf( "query: %s\n", constraint);
  //fflush(stdout);
  if (constraint[0] == '\0')
    return TRUE;

  vc_push(vc);
  marker = 0;
  int constraintCount = 1;
  char c;
  int i = 0;
  do{
    c = constraint[i++];
    if (c == ',')
      constraintCount++;
  }while(c != '\0');

  Expr* constraintArray = (Expr*) malloc(sizeof(Expr)*constraintCount);
  i = 0;
  char token[2]; // it must be just a comma and '\0'
  do{
    constraintArray[i++] = parse();
  }while(readToken(token));

  Expr andExpr = vc_andExprN(vc, constraintArray, constraintCount);
  linkedlist_add(&exprPool, andExpr);
  
  jboolean result = check(vc, andExpr);

  //fflush(stdout);

  //clean up
  (*env)->ReleaseStringUTFChars(env,constraintString, constraint);
  free(constraintArray);
  freeStuff();
  vc_pop(vc);

  return result;
}
Beispiel #9
0
jboolean check(VC vc, Expr e)
{
  //printf("Query: \n");
  Expr notExpr = vc_notExpr(vc, e);
  linkedlist_add(&exprPool, notExpr);
  //vc_printExpr(vc,notExpr);
  //fflush(stdout);
  check_error("Error occured during query");
  switch (vc_query(vc, notExpr)) {
    case 0:
      //printf("Invalid\n\n");
      break;
    case 1:
      //printf("Valid\n\n");
      return FALSE;
  }
  return TRUE;
}
Beispiel #10
0
void *kmalloc(uint32_t size) {
    /* local vars */
    linknode *ptr;
    uint32_t base, i;

    /* Get free hole: */
    base = get_hole(log2(nextpow2(size)));

    /* Allocate physical pages: */
    for (i = base & 0xFFFFF000; i < base+size; i+=PAGE_SIZE)
        arch_vmpage_map(NULL, i, 0);

    /* Store info about this allocated space... */
    ptr = (linknode *) get_hole(log2(16));
    arch_vmpage_map(NULL, (uint32_t) ptr, 0);
    linkedlist_add(&usedlist, ptr);
    ptr->datum[0] = base;
    ptr->datum[1] = size;
    return (void *) base;
}
Beispiel #11
0
uint32_t get_hole(uint32_t i) {
    if (i > U) return NULL;
    if (i < L) i = L;
    if (freelist[i].count) {
        linknode *ptr = freelist[i] .first;
        /* Remove first element from the free list. */
        linkedlist_remove(&freelist[i], ptr, NULL);
        if (i > 11) arch_vmpage_unmap(NULL, ptr);
        return (uint32_t) ptr;
    } else {
        uint32_t ret = get_hole(i+1);
        if (ret == NULL)
            return ret;
        /* Split ret to two (2^i) chunks, one is free, the other returned. */
        arch_vmpage_map(NULL, ret + pow2(i), 0);
        linkedlist_add(&freelist[i], (linknode *) (ret + pow2(i)));
        /* printk("ret: %x %dBytes\n", ret, pow2(i)); */
        return ret;
    }
}
Beispiel #12
0
void lazyworker_invokeLater(lazyworker lazy)
{
    if(lazy == NULL)
    {
        fprintf(stderr, "NULL\n");
        return;
    }
    _lazyworker_t* worker = (_lazyworker_t*) lazy;
    pthread_mutex_lock(&worker->mutex);

    _unit* u = (_unit*) malloc(sizeof(_unit));
    gettimeofday(&u->t, NULL);
    linkedlist_add(worker->sth_todo, u);
    int size;
    size = linkedlist_size(worker->sth_todo);
    if(size > 1)
    {
        _unit* unit = (_unit*)linkedlist_remove_at(worker->sth_todo, 0);
        free(unit);
    }
    pthread_cond_broadcast(&worker->cond);
    pthread_mutex_unlock(&worker->mutex);
    return;
}
Beispiel #13
0
int
symexpand(struct idl *idl, struct sym *sym)
{
	char *key;
	struct sym *mem;
	iter_t iter;

	if (IS_EXPANDED(sym)) {
		return 0;
	}
	sym->flags |= FLAGS_EXPANDED;
	sym->orig = sym;

	if (IS_INTERFACE(sym)) {
		const char *pd = hashmap_get(&sym->attrs, "pointer_default");
		idl->ptr_default = PTR_TYPE_UNIQUE;
		if (pd) {
			if (strcmp(pd, "ptr") == 0) {
				idl->ptr_default = PTR_TYPE_PTR;
			} else if (strcmp(pd, "ref") == 0) {
				idl->ptr_default = PTR_TYPE_REF;
			}
		}
	} else if (IS_ENUM(sym)) {
		char buf[16];
		int val = 0;

		linkedlist_iterate(&sym->mems, &iter);
		while ((mem = linkedlist_next(&sym->mems, &iter))) {
			mem->flags = FLAGS_CONST | FLAGS_PRIMATIVE;
			if (mem->value) {
				val = strtoul(mem->value, NULL, 0);
			}
			sprintf(buf, "%d", val++);
			mem->value = dupstr(buf, idl->al);
		}
	} else if (sym->ptr) {
		if (hashmap_get(&sym->attrs, "unique")) {
			sym->ptr_type = PTR_TYPE_UNIQUE;
		} else if (hashmap_get(&sym->attrs, "ptr")) {
			sym->ptr_type = PTR_TYPE_PTR;
		} else if (hashmap_get(&sym->attrs, "ref")) {
			sym->ptr_type = PTR_TYPE_REF;
		} else if (IS_PARAMETER(sym) || IS_OPERATION(sym)) {
			sym->ptr_type = PTR_TYPE_REF;
		} else {
			sym->ptr_type = idl->ptr_default;
		}
	}

	/* If the symbol is typedef'd add it to the table using the
	 * typedef'd name too
	 */
	if (IS_TYPEDEFD(sym) && sym->name) {
		if (IS_ENUM(sym) && (mem = hashmap_get(idl->syms, sym->idl_type))) {
			mem->noemit = 1; /* supress redundant enum */
		}
		key = sym->name;
	} else {
		key = sym->idl_type;
	}
	if (hashmap_get(idl->syms, key) == NULL) {
		if (hashmap_put(idl->syms, key, sym) == -1) {
			AMSG("");
		}
	}

	/* If the symbol has members it is already expanded
	 */
	if (linkedlist_size(&sym->mems) == 0) {
		struct sym *s = symlook(idl, sym->idl_type);
		if (s) {
			sym->interface = s->interface;
			linkedlist_iterate(&s->mems, &iter);
			while ((mem = linkedlist_next(&s->mems, &iter))) {
				struct sym *cpy = symnew(idl->al);
				symcopy(mem, cpy, idl->al);
				linkedlist_add(&sym->mems, cpy);
			}
		} else {
			AMSG("");
			return -1;
		}
	}

	sym->id = idl->symid++;

	/* Perform expansion recursively on all symbols
	 */
	linkedlist_iterate(&sym->mems, &iter);
	while ((mem = linkedlist_next(&sym->mems, &iter))) {
		symexpand(idl, mem);
		mem->parent = sym;
	}

	return 0;
}
Beispiel #14
0
Expr parse()
{
  char token[15];
  Expr expr = NULL, leftExpr, rightExpr, eqExpr;

  readToken(token);

  switch(token[0]){
  case '+':
    leftExpr = parse();
    rightExpr = parse();
    expr = vc_plusExpr(vc, leftExpr, rightExpr);
    break;
  case '-':
    if(token[1] == '\0'){
      leftExpr = parse();
      rightExpr = parse();
      expr = vc_minusExpr(vc, leftExpr, rightExpr);
    }
    else{
      // assert token[1] is a digit
      expr = parseNumber(token);
    }
    break;
  case '*':
    leftExpr = parse();
    rightExpr = parse();
    expr = vc_multExpr(vc, leftExpr, rightExpr);
    break;
  case '<':
    if (token[1] == '='){
      leftExpr = parse();
      rightExpr = parse();
      expr = vc_leExpr(vc, leftExpr, rightExpr);
    }
    else{
      leftExpr = parse();
      rightExpr = parse();
      expr = vc_ltExpr(vc, leftExpr, rightExpr);
    }
    break;
  case '>':
    if (token[1] == '='){
      leftExpr = parse();
      rightExpr = parse();
      expr = vc_geExpr(vc, leftExpr, rightExpr);
    }
    else{
      leftExpr = parse();
      rightExpr = parse();
      expr = vc_gtExpr(vc, leftExpr, rightExpr);
    }
    break;
  case '=':
    leftExpr = parse();
    rightExpr = parse();
    expr = vc_eqExpr(vc, leftExpr, rightExpr);
    break;
  case '!':
    // assert token[1] == '=';
    leftExpr = parse();
    rightExpr = parse();
    eqExpr = vc_eqExpr(vc, leftExpr, rightExpr);
    linkedlist_add(&exprPool, eqExpr);
    expr = vc_notExpr(vc, eqExpr);
    break;
  case '0':
  case '1':
  case '2':
  case '3':
  case '4':
  case '5':
  case '6':
  case '7':
  case '8':
  case '9':
    expr = parseNumber(token);
    break;
  case 'x':
    expr = hashmap_get(&vars, token);
    if (expr == NULL){
      expr = vc_varExpr(vc, token, intType);
      char* token_copy = (char*) malloc(sizeof(char)*(strlen(token)+1));
      strcpy(token_copy, token);
      hashmap_put(&vars, token_copy, expr);
      linkedlist_add(&exprPool, expr);
    }
    return expr;
  case 'r':
    expr = hashmap_get(&vars, token);
    if (expr == NULL){
      expr = vc_varExpr(vc, token, realType);
      char* token_copy = (char*) malloc(sizeof(char)*(strlen(token)+1));
      strcpy(token_copy, token);
      hashmap_put(&vars, token_copy, expr);
      linkedlist_add(&exprPool, expr);
    }
    return expr;
  default:
    printf( "%s", token);
    throwRuntimeException( "unexpected type of token" );
  }

  linkedlist_add(&exprPool, expr);
  return expr;
}
Beispiel #15
0
int main(int argc, char** argv)
{
  if(argc < 2)
    throwRuntimeException( "must specify the file name that contains the query" );

  printf( "argc: %d\n", argc);

  printf("%s\n",argv[1]);


  // initialize stuff
  hashmap_init(&vars, 0, hash_str, cmp_str, NULL, NULL);
  linkedlist_init(&exprPool, 0, NULL);
  
  //flags = vc_createFlags();
  //vc_setStringFlag(flags, "dump-log", "test1.cvc");
  //vc = vc_createValidityChecker(flags);
  vc = vc_createValidityChecker(NULL);
  intType = vc_intType(vc);
  realType = vc_realType(vc);

  constraint = (char*) malloc(sizeof(char)*10000);

  int k = 0;
  FILE* fpt = fopen(argv[1],"r");

  while(1){
    char c = fgetc(fpt);
    if (c == EOF) break;
    constraint[k++]=c;
  }
  constraint[k]='\0';


  if (constraint[0] == '\0')
    return TRUE;

  vc_push(vc);
  marker = 0;
  int constraintCount = 1;
  char c;
  int i = 0;
  do{
    c = constraint[i++];
    if (c == ',')
      constraintCount++;
  }while(c != '\0');
  
  Expr* constraintArray = (Expr*) malloc(sizeof(Expr)*constraintCount);
  i = 0;
  char token[2]; // it must be just a comma and '\0'
  do{
    constraintArray[i++] = parse();
  }while(readToken(token));

  Expr andExpr = vc_andExprN(vc, constraintArray, constraintCount);
  linkedlist_add(&exprPool, andExpr);

  jboolean result = check(vc, andExpr);

  //clean up
  free(constraintArray);
  freeStuff();
  vc_pop(vc);

  if(result)
    printf("satisfiable");
  else
    printf("unsatisfiable");

  return EXIT_SUCCESS;
}
Beispiel #16
0
uint32_t mmap(uint32_t base, uint32_t size, uint32_t type,
              uint32_t flags, uint32_t fd, uint64_t off) {

    int32_t pages;
    uint32_t addr;
    umem_t *umem = &(curproc->umem); /* current process umem image. */

    /*printk("mmap called: %x, size: %x\n", base, size);*/

    /* make sure fd is valid if a file is to be used */
    if (type & MMAP_TYPE_FILE) {
        if (fd < 0 || fd >= FD_MAX || curproc->file[fd] == NULL)
            return 0;
    }

    if (!base) {
        /* allocate space */
        base = umem->heap_end - size;
    }

    size += base & (~PAGE_BASE_MASK);     /* rectify "size". */
    base = base & PAGE_BASE_MASK;
    pages = (size+PAGE_SIZE-1)/PAGE_SIZE; /* pages to be allocated. */
    size = pages*PAGE_SIZE;               /* actual size. */

    /*printk("           - %x, size: %x\n", base, size); */

    /* make sure the system is initialized. */
    if (curproc == NULL)
        return 0; /* system is not initialized. */

    /* check whether the given range is valid or not. */
    for (addr = base; addr < base + size; addr+=PAGE_SIZE) {
        if (addr<USER_MEMORY_BASE || addr>=KERNEL_MEMORY_BASE) {
            return 0; /* invalid */
        }
    }

    /* update heap end: */
    if (base < umem->heap_end)
        umem->heap_end = base;

    /* now allocate. */
    for (addr = base; addr < base + size; addr+=PAGE_SIZE) {
        arch_vmpage_map(umem, (int32_t) addr, 1 /* user mode */);
        /* mapping a file? */
        if (type & MMAP_TYPE_FILE) {
            /* read file information */
            file_t *file = curproc->file[fd];
            inode_t *inode = file->inode;
            file_mem_t *region = inode->sma.first;

            /* shared? */
            if (flags & MMAP_FLAGS_SHARED) {
                /* search for the wanted region */
                while (region != NULL) {
                    if (region->pos == off) {
                        /* found */
                        region->ref++;
                        break;
                    }
                    region = region->next;
                }

                /* region found or not? */
                if (!region) {
                    /* region not found, create it */
                    region = kmalloc(sizeof(file_mem_t));
                    if (!region)
                        return 0;
                    if (file_reopen(file, &(region->file)))
                        return 0;
                    region->pos = off;
                    region->paddr = 0;
                    region->ref = 1;

                    /* add to the inode */
                    linkedlist_add(&(inode->sma), region);
                }
            } else {
                /* not shared, allocate a new one */
                region = kmalloc(sizeof(file_mem_t));
                if (!region)
                    return 0;
                if (file_reopen(file, &(region->file)))
                    return 0;
                region->pos = off;
                region->paddr = 0;
                region->ref = 1;
            }
            /* attach the virtual page to the mapping */
            arch_vmpage_attach_file(umem, (int32_t) addr, region);
            /* update offset */
            off += PAGE_SIZE;
        }
    }

    /* return the base address. */
    return base;
}
Beispiel #17
0
int main(int argc, char **argv) {
  int       exit_code=0;

  CERBFIG*  cer_config=NULL;

  // linked list to store the messages in
  struct linkedlist* messages=NULL;

  CXMLROOT* xml_root=NULL;
  CFILE*    file=NULL;
  CFSYS*    cfsys=NULL;

  // log struct
  CLOG_INFO* log=NULL;

#ifdef MEMWATCH
  EF_ALIGNMENT=1;
  EF_PROTECT_BELOW=1;
  EF_PROTECT_FREE=1;
#endif

// memory checking
// mtrace();

// ##########################################################################
// ############=- CHECK CMD LINE PARAMETERS -=###############################
// ##########################################################################

  // start the logging so we can log!
  if( !(argc==4) ) {
    fprintf(stderr, "\nUsage:\n%.80s xml_config_file log_level log.txt \n\n", argv[0]);
  }

// ##########################################################################
// ############=- Run Test Suite -=##########################################
// ##########################################################################
#ifndef NOTEST
  if(1==argc) {
    CuString *output = CuStringNew();
    CuSuite* suite = CuSuiteNew();

    printf("Running Test Suite\n");

    CuSuiteAddSuite(suite, CuGetSuite());
    CuSuiteAddSuite(suite, CuStringGetSuite());
    CuSuiteAddSuite(suite, TestSuite__cstring());
    CuSuiteAddSuite(suite, TestSuite__cfile());
    CuSuiteAddSuite(suite, TestSuite__cxml());
//    CuSuiteAddSuite(suite, TestSuite__cmime());

    CuSuiteRun(suite);
    CuSuiteSummary(suite, output);
    CuSuiteDetails(suite, output);
    printf("%s\n", output->buffer);

    CuStringFree(output);
    CuSuiteFree(suite);

    return EX_USAGE;
  }
#endif

  log = clog_open(argv[3], clog_getlevel(argv[2]), NULL, 0);

  // if we couldn't log to the file, let's log to stderr!
  if(NULL!=log && NULL==log->s_logfile) {
    clog_setcallback(log, clog_stderr);
    clog_setcallbacklevel(log, clog_getlevel(argv[2]));
    clog(log, CERROR, "Could not log to file, logging to stderr!");
  }

  clog(log, CMARK, "Cerberus v. 2.x build %s Starting", BUILDNUMBER);

  clog(log, CDEBUG, "CMDLINE: Command line: %.80s %.80s %.80s", argv[0], argv[1], argv[2]);

  clog(log, CDEBUG, "CMDLINE: Command line arguments check passed");

  clog(log, CMARK, "Cerberus Starting...");

// ##########################################################################
// ############=- LOAD XML CONFIG FILE -=####################################
// ##########################################################################

  // parse the XML now
  clog(log, CDEBUG, "XML: Starting XML config file parsing");

  clog(log, CDEBUG, "XML: Creating XML DOM Variable");
  xml_root = cxml_root_new(log);
  clog(log, CDEBUG, "XML: XML DOM Variable Created");

  // make a new cer filesystem obj
  cfsys = cfile_init(0);
  
  cer_config = malloc(sizeof(CERBFIG));
  memset(cer_config, 0, sizeof(CERBFIG));

  cer_config->cfsys = cfsys;
  
  exit_code = cer_load_config(log, &xml_root, argv[1], &cer_config);

  // ##########################################################################
  // ################=- READ IN FILES -=#######################################
  // ##########################################################################

  if(0==exit_code) {
    CPOP3* pop3 = NULL;
    char *filename = NULL;

    messages = linkedlist_new(0);
    // if there is something in the list, process via pop3
    if(NULL!=cer_config->poplist) {

      exit_code = cer_curl_init(log, &cer_config, cer_config->curl_location);

      clog(log, CMARK, "Parser is in POP3 mode.");


      while(NULL!=(pop3=linkedlist_remove_last(cer_config->poplist))) {
        if(0==exit_code) {
          if(NULL!=pop3->user && NULL!=pop3->pass) {
            if(0==cpop3_connect(log, pop3)){
              if(0==cpop3_user(log, pop3, pop3->user)) {
                if(0==cpop3_pass(log, pop3, pop3->pass)) {
                  int x=0;
                  int y=0;
                  x = cpop3_stat(log, pop3);
                  while(y<x && y<cer_config->pop3_max) {
                    if(NULL!=(filename = cpop3_retr(log, pop3, cer_config->tmp_cerbmail->string))) {
                      int pid = 0;
                      linkedlist_add(messages, filename);

                      pid = cer_fork();
                      if(-1==pid) {
                        clog(log, CDEBUG, "FORK: Could not fork, running straight through");
                        // if we couldn't fork run the parser and risk killing entire process
                        exit_code = cer_parse_files(log, &cer_config, xml_root, &messages);

                        if(pop3->dele) {
                          if(1==cer_config->pop3_max_delete) {
                            cpop3_dele(log, pop3);
                          }
                          else if(0==exit_code) {
                            cpop3_dele(log, pop3);
                          }
                        }
                      }
                      else if(0==pid) {
                        clog(log, CDEBUG, "FORK: Forked, running file parser");
                        exit_code = cer_parse_files(log, &cer_config, xml_root, &messages);

                        if(pop3->dele) {
                          if(1==cer_config->pop3_max_delete) {
                            cpop3_dele(log, pop3);
                          }
                          else if(0==exit_code) {
                            cpop3_dele(log, pop3);
                          }
                        }
                        // didn't send quit, just close the fork'd connection
                        cpop3_disconnect(log, pop3);
                        cpop3_free(log, &pop3);

                        // remove the emails from the list that we've processed
                        linkedlist_iterate(messages);
                        while(NULL!=(filename=linkedlist_remove_last(messages))) {
                          free(filename);
                          filename = NULL;
                        }
                        linkedlist_del(cer_config->poplist, free);
                        linkedlist_del(messages, free);
                        goto CLEANUP;
                      }
                      else {
                        // must be the parent process
                        // clean up any forked children that are sitting around
                        clog(log, CDEBUG, "FORK: Forked, am parent waiting for child process");
                        while(0<(pid=cer_wait4(0, NULL, 0, NULL))) {
                          clog(log, CDEBUG, "WAIT: cleaned up after child %d!", pid);
                        };
                      }
                      // remove the emails from the list that we've processed
                      linkedlist_iterate(messages);
                      while(NULL!=(filename=linkedlist_remove_last(messages))) {
                        free(filename);
                        filename = NULL;
                      }
                    }
                    ++y;
                  }
                }
              }
              cpop3_quit(log, pop3);
              cpop3_disconnect(log, pop3);
            }
          }
          else {
            clog(log, CERROR, "POP3: User or Password was NULL, skipping");
          }

        }
        cpop3_free(log, &pop3);
      }

      linkedlist_del(cer_config->poplist, free);
    }
    // otherwise it's stdin
    else {
      clog(log, CMARK, "Parser is in PIPE mode, waiting for input");
      file = cer_save_input(log, cfsys, cer_config->tmp_cerbmail->string);
      if(NULL!=file) {
        filename = strdup(file->filename);
        linkedlist_add(messages, filename);
        cfile_close(&file);
        cfile_free(&file);
  
        exit_code = cer_curl_init(log, &cer_config, cer_config->curl_location);
  
        if(0==exit_code) {
          exit_code = cer_parse_files(log, &cer_config, xml_root, &messages);
        }
      }
    }

    // free the linked list
    linkedlist_del(messages, free);
  }

  // this is above cleanup to keep the forks from clobbering each other
  cfile_cleanup(&cfsys);
  
CLEANUP:

  if(NULL!=dl_curl_easy_cleanup) {
    // clean up the info in cURL
    dl_curl_easy_cleanup(cer_config->curl);
  }
  if(NULL!=dl_curl_global_cleanup) {
    // close down curl
    dl_curl_global_cleanup();
  }

#ifndef WIN32
  if(NULL!=dl_curl) {
     dlclose(dl_curl);
     dl_curl=NULL;
  }
#endif

  dl_curl = NULL;
  dl_curl_formadd=NULL;
  dl_curl_formfree=NULL;
  dl_curl_global_init=NULL;
  dl_curl_easy_init=NULL;
  dl_curl_easy_setopt=NULL;
  dl_curl_easy_perform=NULL;
  dl_curl_easy_cleanup=NULL;
  dl_curl_global_cleanup=NULL;

  // free the xml data
  cxml_root_free(log, &xml_root);
  if(NULL!=cer_config->xsp) cstring_free(&cer_config->xsp);

  cstring_free(&cer_config->curl_location);

  cstring_free(&cer_config->tmp_cerbmail);
  cstring_free(&cer_config->tmp_cerbmime);

  // free the optional SSL data
  cstring_free(&cer_config->curl_cainfo);
  cstring_free(&cer_config->curl_capath);
  cer_config->curl_verifyhostpeer = 0;

  clog(log, CMARK, "Shutting Down");

  // close the log file
  clog_close(log);
  
  free(cer_config);
  cer_config=NULL;

  return exit_code;
}
Beispiel #18
0
int xwifi_wpa_parser_scan_result(linkedlist list, const char* result)
{
	S_;
//	M_("%s", result);
	const char *ptr = result;

	KASSERT(list);
	KASSERT(result);

	linkedlist_clear(list, free);

	// 1. skip head line : bssid / frequency / signal level / flags / ssid
	stringtokenizer tokenizer = stringtokenizer_new((const char**) &ptr);

	int ret;
	int i;
	char dst[512];
	char delim;
	XWifiScanInfo* scan_info = NULL;

	for(i=0; (ret = stringtokenizer_next_token2(tokenizer, "\t\n ", 2, dst, &delim)) != -1 ; i++) {

		if(delim == '\t') {
			KASSERT(scan_info);
//			M_("<%d> : %s", i, dst);

			KASSERT(i <= 5);
			switch(i) {
			case 1:  {// bssid
				sscanf(dst, "%02x:%02x:%02x:%02x:%02x:%02x",
						(unsigned int *) &scan_info->AP.BSSID[0],
						(unsigned int *) &scan_info->AP.BSSID[1],
						(unsigned int *) &scan_info->AP.BSSID[2],
						(unsigned int *) &scan_info->AP.BSSID[3],
						(unsigned int *) &scan_info->AP.BSSID[4],
						(unsigned int *) &scan_info->AP.BSSID[5]);
				break;
			}
			case 2: { // frequency (e.g.  2412)
				break;
			}
			case 3:  { // signal level (e.g. -87)
				break;
			}
			case 4: { // flags (e.g. [WEP][ESS])
				break;
			}
			default: {
				break;
			}
			}
		}
		else if(delim == '\n') {
//			M_("<%d> : %s", i, dst);
			if(i == 5) {
				strcpy((char*)scan_info->AP.SSID, (const char*)dst);
			}

			// We create node here.
			if(scan_info) {
				// here to the list.
				linkedlist_add(list, scan_info);
				scan_info = NULL;
			}
			scan_info = (XWifiScanInfo*) malloc(sizeof(*scan_info));
			memset(scan_info, 0, sizeof(*scan_info));
			i = 0;
		}
		else {
			W_("Unknown delim: %c", delim);
		}
		memset(dst, 0, sizeof(dst));
	}

	stringtokenizer_delete(tokenizer);
	return 0;
}