Exemple #1
0
/* Match a header. Same as find_header but uses fnmatch. */
char *
match_header(struct mail *m, const char *patt, size_t *len, int value)
{
	char	*ptr, *last, *hdr;
	size_t	 hdrlen;

	line_init(m, &ptr, len);
	while (ptr != NULL) {
		if (ptr >= m->data + m->body)
			return (NULL);

		if ((last = memchr(ptr, ':', *len)) != NULL) {
			hdrlen = last - ptr;
			hdr = xmalloc(hdrlen + 1);
			strlcpy(hdr, ptr, hdrlen + 1);

			if (fnmatch(patt, hdr, FNM_CASEFOLD) == 0)
				break;

			xfree(hdr);
		}

		line_next(m, &ptr, len);
	}
	if (ptr == NULL)
		return (NULL);
	xfree(hdr);

	/* If the entire header is wanted, return it. */
	if (!value)
		return (ptr);

	/* Include the : in the length. */
	hdrlen++;

	/* Otherwise skip the header and following spaces. */
	ptr += hdrlen;
	*len -= hdrlen;
	while (*len > 0 && isspace((u_char) *ptr)) {
		ptr++;
		(*len)--;
	}

	/* And trim newlines. */
	while (*len > 0 && ptr[*len - 1] == '\n')
		(*len)--;

	if (len == 0)
		return (NULL);
	return (ptr);
}
Exemple #2
0
int sporth_line(sporth_stack *stack, void *ud)
{
    plumber_data *pd = ud;
    
    sporth_line_d *line;

    switch(pd->mode) {
        case PLUMBER_CREATE:

#ifdef DEBUG_MODE
            fprintf(stderr, "line: Creating\n");
#endif
            line = malloc(sizeof(sporth_line_d));
            plumber_add_module(pd, SPORTH_LINE, sizeof(sporth_line_d), line);
            break;
        case PLUMBER_INIT:

#ifdef DEBUG_MODE
            fprintf(stderr, "line: Initialising\n");
#endif

            if(sporth_check_args(stack, "fff") != SPORTH_OK) {
                fprintf(stderr,"Not enough arguments for line\n");
                stack->error++;
                return PLUMBER_NOTOK;
            }
            line = pd->last->ud;
            line->ib = sporth_stack_pop_float(stack);
            line->idur = sporth_stack_pop_float(stack);
            line->ia = sporth_stack_pop_float(stack);
            line_init(pd, line);
            sporth_stack_push_float(stack, 0);
            break;
        case PLUMBER_COMPUTE:
            line = pd->last->ud;
            sporth_stack_pop_float(stack);
            sporth_stack_pop_float(stack);
            sporth_stack_pop_float(stack);

            sporth_stack_push_float(stack, line_compute(line));
            break;
        case PLUMBER_DESTROY:
            line = pd->last->ud;
            free(line);
            break;
        default:
            fprintf(stderr, "line: Uknown mode!\n");
            break;
    }
    return PLUMBER_OK;
}
Exemple #3
0
int main( int argc, char** argv){
  int d = 0, quit = 1, commandNum, numRead;
  char *input, command;
  Line l = line_init(stdin);
  Ll ll = ll_init();

  gen_parse_args( argc, argv, &d);

  while( quit){
    printf("Command: ");
    line_read_line( l);
    input = get_line( l);
    sscanf(input, " %c%n", &command, &numRead);
    switch( command){
      case 'q': quit = 0; break;
      case 'i': if( gen_exists_num( input+numRead) ){
                sscanf(input+numRead, "%d", &commandNum);
                ll_insert( ll, commandNum , d);
              }
              else printf("Sorry, you didn't enter a number!\n");
              break;
      case 'd': if( gen_exists_num( input+numRead) ){
                sscanf( input+numRead, "%d", &commandNum);
                ll_delete( ll, commandNum, d);
              }
              else printf("Sorry, you didn't enter a number!\n");
              break;
      case 'c': if( gen_exists_num( input+numRead) ){
                  sscanf( input+numRead, "%d", &commandNum);
                  if( ll_contains( ll, commandNum, d) )
                    printf("LIST DOES CONTAIN %d\n", commandNum);
                  else printf("LIST DOES NOT CONATAIN %d\n", commandNum);
                }
                else printf("Sorry, you didn't enter a number!\n");
                break;
      case 'e': ll_empty( ll, d); break;
      case 'l': ll_print( ll, d); break;
      case 'r': ll_print_rev( ll, d); break;
      case '?': gen_print_help(); break;
      case 'h': gen_print_help(); break;
      case '\n': break;
      default: printf("Invalid Command\n");
    }
    free( input);    
  }

  ll_free( ll, d);
  line_free( l);
  return 0;
}
Exemple #4
0
//~~~~~~~~~~~~~~~~~MAIN~~~~~~~~~~~~~~~~~~~~~~~
int main(int argc, char* argv[]){
  int debug = 0, flag = 1, arg, numRead = 0;
  char command, *stream;
  Line line = line_init( stdin);
  gen_parse_args( argc, argv, &debug);
  Htable htable = ht_init( ht_mod_hash);

  while(flag){
    arg = -1;
    fprintf( stdout, "\ncommand: ");
    line_read_line( line);
    stream = get_line( line);
    sscanf( stream, " %c%n", &command, &numRead);
    switch( command){
      case 'q': flag = 0; break;
      case 'i': sscanf( stream+numRead, "%d", &arg);
                if( arg < 0) fprintf( stderr, "MUST BE >= 0\n");
                else ht_add( htable, arg, arg, debug);
                break;
      case 'd': sscanf( stream+numRead, "%d", &arg);
                if( arg < 0) fprintf( stderr, "MUST BE >= 0\n");
                else{
                  int pos = ht_mod_hash( htable, arg);
                  node_delete( &((htable->table)[pos]), arg, arg, debug); 
                }
                break;
      case 'c': sscanf( stream+numRead, "%d", &arg);
                if( arg < 0) fprintf( stderr, "MUST BE >= 0\n");
                else{
                  if( ht_exists( htable, arg, debug) )
                    fprintf( stdout, "The value, %d, exists!\n", arg);
                  else
                    fprintf( stdout, "The value, %d, does NOT exist\n", arg);
                }
                break;
      case 'e': ht_erase( htable); break;
      case 'r': sscanf( stream+numRead, "%d", &arg);
                if( arg >= 1) ht_resize( htable, arg, debug);
                else fprintf( stderr, "Error, size must be >= 1\n");
                break;
      case 'l': ht_list( htable); break;
      case '\n': break;
      default: fprintf( stdout, "Sorry, Invalid command\n"); break;
    }
    free(stream);
  }
  line_free( line);
  ht_free( htable);
  return 0;
}
Exemple #5
0
void ritual()
{
    myusbInit();

    myBT_Init();
    line_init();
    distance_init();
    sonic_init();
    motor_init();
    motor_left_duty(10);
    motor_right_duty(10);
    color_init();
    myCmdLineInit();

}
Exemple #6
0
void
trim_from(struct mail *m)
{
	char	*ptr;
	size_t	 len;

	if (m->data == NULL || m->body == 0 || m->size < 5)
		return;
	if (strncmp(m->data, "From ", 5) != 0)
		return;

	line_init(m, &ptr, &len);
	m->size -= len;
	m->off += len;
	m->data = m->base + m->off;
	m->body -= len;
}
set * set_init(){
    int i;
    set *cbset = (set *)malloc(sizeof(set));
    
    
    cbset->ways = (cache_block **)malloc( bassoc * sizeof(cache_block *));
    cbset->hk_nuka = (int *)malloc(bsassoc * sizeof(int));
            
    for( i = 0 ; i < bassoc ; i++ ){
        cbset->ways[i] = line_init();
    }
    
    for( i = 0 ; i < bsassoc ; i++ ){
        cbset->hk_nuka[i] = 0;
    }
    
    return cbset;
}
Exemple #8
0
/*
 * Find a header. If value is set, only the header value is returned, with EOL
 * stripped
 */
char *
find_header(struct mail *m, const char *hdr, size_t *len, int value)
{
	char	*ptr;
	size_t	 hdrlen;

	hdrlen = strlen(hdr) + 1; /* include : */
	if (m->body < hdrlen || m->size < hdrlen)
		return (NULL);

	line_init(m, &ptr, len);
	while (ptr != NULL) {
		if (ptr >= m->data + m->body)
			return (NULL);
		if (*len >= hdrlen && ptr[hdrlen - 1] == ':') {
			if (strncasecmp(ptr, hdr, hdrlen - 1) == 0)
				break;
		}
		line_next(m, &ptr, len);
	}
	if (ptr == NULL)
		return (NULL);

	/* If the entire header is wanted, return it. */
	if (!value)
		return (ptr);

	/* Otherwise skip the header and following spaces. */
	ptr += hdrlen;
	*len -= hdrlen;
	while (*len > 0 && isspace((u_char) *ptr)) {
		ptr++;
		(*len)--;
	}

	/* And trim newlines. */
	while (*len > 0 && ptr[*len - 1] == '\n')
		(*len)--;

	if (len == 0)
		return (NULL);
	return (ptr);
}
Exemple #9
0
/**
 * Initialize the templ theme
 * @param hue [0..360] hue value from HSV color space to define the theme's base color
 * @param font pointer to a font (NULL to use the default)
 * @return pointer to the initialized theme
 */
lv_theme_t * lv_theme_templ_init(uint16_t hue, lv_font_t *font)
{
    if(font == NULL) font = LV_FONT_DEFAULT;

    _hue = hue;
    _font = font;

    /*For backward compatibility initialize all theme elements with a default style */
    uint16_t i;
    lv_style_t **style_p = (lv_style_t**) &theme;
    for(i = 0; i < sizeof(lv_theme_t) / sizeof(lv_style_t*); i++) {
        *style_p = &def;
        style_p++;
    }

    basic_init();
    cont_init();
    btn_init();
    label_init();
    img_init();
    line_init();
    led_init();
    bar_init();
    slider_init();
    sw_init();
    lmeter_init();
    gauge_init();
    chart_init();
    cb_init();
    btnm_init();
    kb_init();
    mbox_init();
    page_init();
    ta_init();
    list_init();
    ddlist_init();
    roller_init();
    tabview_init();
    win_init();

    return &theme;
}
Exemple #10
0
/* Count mail lines. */
void
count_lines(struct mail *m, u_int *total, u_int *body)
{
	size_t	 len;
	char	*ptr;
	int	 flag;

	flag = 0;
	*total = *body = 0;

	line_init(m, &ptr, &len);
	while (ptr != NULL) {
		if (flag)
			(*body)++;
		if (len == 1 && *ptr == '\n')
			flag = 1;
		(*total)++;
		line_next(m, &ptr, &len);
	}
}
Exemple #11
0
/*
 * Find offset of body. The body is the offset of the first octet after the
 * separator (\n\n), or zero.
 */
size_t
find_body(struct mail *m)
{
	size_t	 len;
	char	*ptr;

	line_init(m, &ptr, &len);
	while (ptr != NULL) {
		if (len == 1 && *ptr == '\n') {
			line_next(m, &ptr, &len);
			/* If no next line, body is end of mail. */
			if (ptr == NULL)
				return (m->size);
			/* Otherwise, body is start of line after separator. */
			return (ptr - m->data);
		}
		line_next(m, &ptr, &len);
	}
	return (0);
}
double line_get_distance_to_point(line_t *line, double x, double y)
{

  double a1;
  double a2;

  line_t hipotenus;

  double distance;
  double angleDiffrence;
  point_t point;

  point_init(&point,x,y);

  line_init(&hipotenus,&line->sp,&point);

  a1 = line->angle;
  a2 = hipotenus.angle;

  if(a1 < 0)
      a1 = M_PI + a1;
  if(a2 < 0)
      a2 = M_PI + a2;

  angleDiffrence = line->angle - hipotenus.angle;

  if(angleDiffrence < 0)
      angleDiffrence = -angleDiffrence;

  /*if(angleDiffrence > M_PI / 2)
      distance = 1000;
  else*/

  distance = sin(angleDiffrence)*hipotenus.length;

  return distance;

}
int nlrf_split_line(plinel_t *ll, double treshold)
{
    double dist;
    double maxdist;
    point_t p,sp,ep;
    if(ll == NULL)
        return 0;



    pointl_t *point = ll->first;

    pointl_t *uzakNokta = NULL;

    plinel_t *tpl;

    plinel_t *next;
    plinel_t *pre;

    maxdist = 0;

    ll->point_cnt = 0;
    while(point != NULL)
    {
        dist = line_get_distance_to_point(&ll->line,point->x, point->y);

        if(dist > maxdist &&  point != ll->first &&  point != ll->last)
        {
            maxdist = dist;
            uzakNokta = point;
        }
        point = point->next;

        ll->point_cnt++;
    }

    if(maxdist >= treshold && uzakNokta != NULL)
    {
        tpl = lrf_create_plinel();

        if(tpl == NULL)
             return 0;



        tpl->first = uzakNokta;
        ll->last  = uzakNokta->pre;

        ll->last->next = NULL;

        tpl->first->pre = NULL;
        tpl->last = ll->last;
        tpl->last->next = NULL;


        point_init(&sp, tpl->first->x, tpl->first->y);
        point_init(&ep, tpl->last->x, tpl->last->y);
        line_init(&tpl->line,&sp,&ep);


        point_init(&sp, ll->first->x, ll->first->y);
        point_init(&ep, ll->last->x, ll->last->y);
        line_init(&ll->line,&sp,&ep);


        next = ll->next;
        pre  = ll;

        if(pre != NULL)
        {
          pre->next = tpl;
        }
        tpl->pre = pre;
        if(next != NULL)
        {
            next->pre = tpl;
        }
        tpl->next = next;

        return 1;
    }
    else
        return 0;
}
int nlrf_add_point(line_map_t *lm,double angle,double x, double y, double dist, double relDist)
{
   point_t sp,ep;

   double distance;

   plinel_t *tpl;
   pointl_t *point;


   if(lm == NULL)
       return 0;

   tpl = lm->last;

   if(tpl != NULL && tpl->last != NULL)
   {
      distance = point_get_distance(tpl->last->x, tpl->last->y, x, y);

      if(distance < relDist)
      {
          point = lrf_create_point_list(angle,x,y,dist);

          if(point == NULL)
             return 0;

          point->pre = tpl->last;
          tpl->last->next = point;
          tpl->last = point;


          point_init(&sp, tpl->first->x, tpl->first->y);
          point_init(&ep, tpl->last->x, tpl->last->y);

          line_init(&tpl->line,&sp,&ep);
          tpl->point_cnt++;

          return 1;
      }

   }

   tpl = lrf_create_plinel();

   if(tpl == NULL)
     return 0;

   point = lrf_create_point_list(angle,x,y,dist);

   if(point == NULL)
   {
      free(tpl);
      return 0;
   }

   tpl->first = point;
   tpl->last  = point;
   tpl->point_cnt++;


   if(lm->first == NULL)
   {
     lm->first = tpl;
     lm->lineCount = 0;
   }
   if(lm->last != NULL)
     lm->last->next = tpl;

   tpl->pre = lm->last;
   lm->last = tpl;

   point_init(&sp, tpl->first->x, tpl->first->y);
   point_init(&ep, tpl->last->x, tpl->last->y);

   line_init(&tpl->line,&sp,&ep);

   tpl->point_cnt = 1;

   lm->lineCount++;

   return 1;
}
Exemple #15
0
int
deliver_mbox_deliver(struct deliver_ctx *dctx, struct actitem *ti)
{
    struct account			*a = dctx->account;
    struct mail			*m = dctx->mail;
    struct deliver_mbox_data	*data = ti->data;
    char				*path, *ptr, *lptr, *from = NULL;
    const char			*msg;
    size_t				 len, llen;
    int				 fd, saved_errno;
    FILE				*f;
    gzFile				 gzf;
    long long			 used;
    sigset_t			 set, oset;
    struct stat			 sb;

    f = gzf = NULL;
    fd = -1;

    path = replacepath(&data->path, m->tags, m, &m->rml, dctx->udata->home);
    if (path == NULL || *path == '\0') {
        log_warnx("%s: empty path", a->name);
        goto error;
    }
    if (data->compress) {
        len = strlen(path);
        if (len < 3 || strcmp(path + len - 3, ".gz") != 0) {
            path = xrealloc(path, 1, len + 4);
            strlcat(path, ".gz", len + 4);
        }
    }
    log_debug2("%s: saving to mbox %s", a->name, path);

    /* Save the mbox path. */
    add_tag(&m->tags, "mbox_file", "%s", path);

    /* Check permissions and ownership. */
    if (stat(path, &sb) != 0) {
        if (conf.no_create || errno != ENOENT)
            goto error_log;

        log_debug2("%s: creating %s", a->name, xdirname(path));
        if (xmkpath(xdirname(path), -1, conf.file_group, DIRMODE) != 0)
            goto error_log;
    } else {
        if ((msg = checkmode(&sb, UMASK(FILEMODE))) != NULL)
            log_warnx("%s: %s: %s", a->name, path, msg);
        if ((msg = checkowner(&sb, -1)) != NULL)
            log_warnx("%s: %s: %s", a->name, path, msg);
        if ((msg = checkgroup(&sb, conf.file_group)) != NULL)
            log_warnx("%s: %s: %s", a->name, path, msg);
    }

    /* Create or open the mbox. */
    used = 0;
    do {
        if (conf.no_create)
            fd = openlock(path, O_WRONLY|O_APPEND, conf.lock_types);
        else {
            fd = createlock(path, O_WRONLY|O_APPEND,
                            -1, conf.file_group, FILEMODE, conf.lock_types);
        }
        if (fd == -1 && errno == EEXIST)
            fd = openlock(path, O_WRONLY|O_APPEND, conf.lock_types);
        if (fd == -1) {
            if (errno == EAGAIN) {
                if (locksleep(a->name, path, &used) != 0)
                    goto error;
                continue;
            }
            goto error_log;
        }
    } while (fd < 0);

    /* Open gzFile or FILE * for writing. */
    if (data->compress) {
        if ((gzf = gzdopen(fd, "a")) == NULL) {
            errno = ENOMEM;
            goto error_log;
        }
    } else {
        if ((f = fdopen(fd, "a")) == NULL)
            goto error_log;
    }

    /*
     * mboxes are a pain: if we are interrupted after this we risk
     * having written a partial mail. So, block SIGTERM until we're
     * done.
     */
    sigemptyset(&set);
    sigaddset(&set, SIGTERM);
    if (sigprocmask(SIG_BLOCK, &set, &oset) < 0)
        fatal("sigprocmask failed");

    /* Write the from line. */
    from = make_from(m, dctx->udata->name);
    if (deliver_mbox_write(f, gzf, from, strlen(from)) < 0) {
        xfree(from);
        goto error_unblock;
    }
    if (deliver_mbox_write(f, gzf, "\n", 1) < 0) {
        xfree(from);
        goto error_unblock;
    }
    log_debug3("%s: using from line: %s", a->name, from);
    xfree(from);

    /* Write the mail, escaping from lines. */
    line_init(m, &ptr, &len);
    while (ptr != NULL) {
        if (ptr != m->data) {
            /* Skip leading >s. */
            lptr = ptr;
            llen = len;
            while (*lptr == '>' && llen > 0) {
                lptr++;
                llen--;
            }

            if (llen >= 5 && strncmp(lptr, "From ", 5) == 0) {
                log_debug2("%s: quoting from line: %.*s",
                           a->name, (int) len - 1, ptr);
                if (deliver_mbox_write(f, gzf, ">", 1) < 0)
                    goto error_unblock;
            }
        }

        if (deliver_mbox_write(f, gzf, ptr, len) < 0)
            goto error_unblock;

        line_next(m, &ptr, &len);
    }

    /* Append newlines. */
    if (m->data[m->size - 1] == '\n') {
        if (deliver_mbox_write(f, gzf, "\n", 1) < 0)
            goto error_unblock;
    } else {
        if (deliver_mbox_write(f, gzf, "\n\n", 2) < 0)
            goto error_unblock;
    }

    /* Flush buffers and sync. */
    if (gzf == NULL) {
        if (fflush(f) != 0)
            goto error_unblock;
    } else {
        if (gzflush(gzf, Z_FINISH) != Z_OK) {
            errno = EIO;
            goto error_unblock;
        }
    }
    if (fsync(fd) != 0)
        goto error_unblock;

    if (sigprocmask(SIG_SETMASK, &oset, NULL) < 0)
        fatal("sigprocmask failed");

    if (gzf != NULL)
        gzclose(gzf);
    if (f != NULL)
        fclose(f);
    closelock(fd, path, conf.lock_types);

    xfree(path);
    return (DELIVER_SUCCESS);

error_unblock:
    saved_errno = errno;
    if (sigprocmask(SIG_SETMASK, &oset, NULL) < 0)
        fatal("sigprocmask failed");
    errno = saved_errno;

error_log:
    log_warn("%s: %s", a->name, path);

error:
    if (gzf != NULL)
        gzclose(gzf);
    if (f != NULL)
        fclose(f);
    if (fd != -1)
        closelock(fd, path, conf.lock_types);

    if (path != NULL)
        xfree(path);
    return (DELIVER_FAILURE);
}
Exemple #16
0
int
deliver_imap_deliver(struct deliver_ctx *dctx, struct actitem *ti)
{
	struct account			*a = dctx->account;
	struct mail			*m = dctx->mail;
	struct deliver_imap_data	*data = ti->data;
	struct io			*io;
	struct fetch_ctx		 fctx;
	struct fetch_imap_data		 fdata;
	char				*cause, *folder, *ptr, *line;
	size_t				 len, maillen;
	u_int				 total, body;

	/* Connect to the IMAP server. */
	io = connectproxy(&data->server,
	    conf.verify_certs, conf.proxy, IO_CRLF, conf.timeout, &cause);
	if (io == NULL) {
		log_warnx("%s: %s", a->name, cause);
		xfree(cause);
		return (DELIVER_FAILURE);
	}
	if (conf.debug > 3 && !conf.syslog)
		io->dup_fd = STDOUT_FILENO;

	/* Work out the folder name. */
	folder = replacestr(&data->folder, m->tags, m, &m->rml);
	if (folder == NULL || *folder == '\0') {
		log_warnx("%s: empty folder", a->name);
		goto error;
	}

	/* Fake up the fetch context for the fetch code. */
	memset(&fdata, 0, sizeof fdata);
	fdata.user = data->user;
	fdata.pass = data->pass;
	fdata.nocrammd5 = data->nocrammd5;
	fdata.nologin = data->nologin;
	memcpy(&fdata.server, &data->server, sizeof fdata.server);
	fdata.io = io;
	fdata.only = FETCH_ONLY_ALL;
	a->data = &fdata;
	fetch_imap_state_init(a, &fctx);
	fctx.state = imap_state_connected;
	fctx.llen = IO_LINESIZE;
	fctx.lbuf = xmalloc(fctx.llen);

	/* Use the fetch code until the select1 state is reached. */
	if (deliver_imap_pollto(imap_state_select1, a, io, &fctx) != 0)
		goto error;

retry:
	/* Send an append command. */
	if (imap_putln(a, "%u APPEND {%zu}", ++fdata.tag, strlen(folder)) != 0)
		goto error;
	switch (deliver_imap_waitappend(a, &fctx, io, &line)) {
	case IMAP_TAG_ERROR:
		if (line != NULL)
			imap_invalid(a, line);
		goto error;
	case IMAP_TAG_CONTINUE:
		break;
	default:
		if (imap_no(line) && strstr(line, "[TRYCREATE]") != NULL)
			goto try_create;
		imap_invalid(a, line);
		goto error;
	}

	/*
	 * Send the mail size, not forgetting lines are CRLF terminated. The
	 * Google IMAP server is written strangely, so send the size as if
	 * every CRLF was a CR if the server has XYZZY.
	 */
	count_lines(m, &total, &body);
	maillen = m->size + total - 1;
	if (fdata.capa & IMAP_CAPA_XYZZY) {
		log_debug2("%s: adjusting size: actual %zu", a->name, maillen);
		maillen = m->size;
	}
	if (fdata.capa & IMAP_CAPA_NOSPACE) {
		if (imap_putln(a, "%s{%zu}", folder, maillen) != 0)
			goto error;
	} else {
		if (imap_putln(a, "%s {%zu}", folder, maillen) != 0)
			goto error;
	}
	switch (deliver_imap_waitappend(a, &fctx, io, &line)) {
	case IMAP_TAG_ERROR:
		if (line != NULL)
			imap_invalid(a, line);
		goto error;
	case IMAP_TAG_CONTINUE:
		break;
	default:
		if (imap_no(line) && strstr(line, "[TRYCREATE]") != NULL)
			goto try_create;
		imap_invalid(a, line);
		goto error;
	}

	/* Send the mail data. */
	line_init(m, &ptr, &len);
	while (ptr != NULL) {
		if (len > 1)
			io_write(io, ptr, len - 1);
		io_writeline(io, NULL);

		/* Update if necessary. */
		if (io_update(io, conf.timeout, &cause) != 1) {
			log_warnx("%s: %s", a->name, cause);
			xfree(cause);
			goto error;
		}

		line_next(m, &ptr, &len);
	}

	/* Wait for an okay from the server. */
	switch (deliver_imap_waitappend(a, &fctx, io, &line)) {
	case IMAP_TAG_ERROR:
	case IMAP_TAG_CONTINUE:
		if (line != NULL)
			imap_invalid(a, line);
		goto error;
	default:
		if (imap_okay(line))
			break;
		if (strstr(line, "[TRYCREATE]") != NULL)
			goto try_create;
		imap_invalid(a, line);
		goto error;
	}

	xfree(fctx.lbuf);
	xfree(folder);

	if (imap_putln(a, "%u LOGOUT", ++fdata.tag) != 0)
		goto error;
	if (deliver_imap_waitokay(a, &fctx, io, &line) != 0)
		goto error;

	fdata.disconnect(a);
	return (DELIVER_SUCCESS);

try_create:	/* XXX function? */
	/* Try to create the folder. */
	if (imap_putln(a, "%u CREATE {%zu}", ++fdata.tag, strlen(folder)) != 0)
		goto error;
	if (deliver_imap_waitcontinue(a, &fctx, io, &line) != 0)
		goto error;
	if (imap_putln(a, "%s", folder) != 0)
		goto error;
	if (deliver_imap_waitokay(a, &fctx, io, &line) != 0)
		goto error;
	goto retry;

error:
	io_writeline(io, "QUIT");
	io_flush(io, conf.timeout, NULL);

	xfree(fctx.lbuf);
	if (folder != NULL)
		xfree(folder);

	fdata.disconnect(a);
	return (DELIVER_FAILURE);
}
Exemple #17
0
int
deliver_smtp_deliver(struct deliver_ctx *dctx, struct actitem *ti)
{
	struct account			*a = dctx->account;
	struct mail			*m = dctx->mail;
	struct deliver_smtp_data	*data = ti->data;
	int				 done, code;
	struct io			*io;
	char				*cause, *to, *from, *line, *ptr, *lbuf;
	enum deliver_smtp_state		 state;
	size_t				 len, llen;

	io = connectproxy(&data->server,
	    conf.verify_certs, conf.proxy, IO_CRLF, conf.timeout, &cause);
	if (io == NULL) {
		log_warnx("%s: %s", a->name, cause);
		xfree(cause);
		return (DELIVER_FAILURE);
	}
	if (conf.debug > 3 && !conf.syslog)
		io->dup_fd = STDOUT_FILENO;

	llen = IO_LINESIZE;
	lbuf = xmalloc(llen);

	if (conf.host_fqdn != NULL)
		xasprintf(&ptr, "%s@%s", dctx->udata->name, conf.host_fqdn);
	else
		xasprintf(&ptr, "%s@%s", dctx->udata->name, conf.host_name);
	if (data->to.str == NULL)
		to = xstrdup(ptr);
	else {
		to = replacestr(&data->to, m->tags, m, &m->rml);
		if (to == NULL || *to == '\0') {
			xasprintf(&cause, "%s: empty to", a->name);
			from = NULL;
			goto error;
		}
	}
	if (data->from.str == NULL)
		from = xstrdup(ptr);
	else {
		from = replacestr(&data->from, m->tags, m, &m->rml);
		if (from == NULL || *from == '\0') {
			xasprintf(&cause, "%s: empty from", a->name);
			goto error;
		}
	}
	xfree(ptr);

	state = SMTP_CONNECTING;
	line = NULL;
	done = 0;
	do {
		switch (io_pollline2(io,
		    &line, &lbuf, &llen, conf.timeout, &cause)) {
		case 0:
			cause = xstrdup("connection unexpectedly closed");
			goto error;
		case -1:
			goto error;
		}
		code = deliver_smtp_code(line);

		cause = NULL;
		switch (state) {
		case SMTP_CONNECTING:
			if (code != 220)
				goto error;
			state = SMTP_HELO;
			if (conf.host_fqdn != NULL)
				io_writeline(io, "HELO %s", conf.host_fqdn);
			else
				io_writeline(io, "HELO %s", conf.host_name);
			break;
		case SMTP_HELO:
			if (code != 250)
				goto error;
			state = SMTP_FROM;
			io_writeline(io, "MAIL FROM:<%s>", from);
			break;
		case SMTP_FROM:
			if (code != 250)
				goto error;
			state = SMTP_TO;
			io_writeline(io, "RCPT TO:<%s>", to);
			break;
		case SMTP_TO:
			if (code != 250)
				goto error;
			state = SMTP_DATA;
			io_writeline(io, "DATA");
			break;
		case SMTP_DATA:
			if (code != 354)
				goto error;
			line_init(m, &ptr, &len);
			while (ptr != NULL) {
				if (len > 1) {
					if (*ptr == '.')
						io_write(io, ".", 1);
					io_write(io, ptr, len - 1);
				}
				io_writeline(io, NULL);

				/* Update if necessary. */
				if (io_update(io, conf.timeout, &cause) != 1)
					goto error;

				line_next(m, &ptr, &len);
			}
			state = SMTP_DONE;
			io_writeline(io, ".");
			io_flush(io, conf.timeout, NULL);
			break;
		case SMTP_DONE:
			if (code != 250)
				goto error;
			state = SMTP_QUIT;
			io_writeline(io, "QUIT");
			break;
		case SMTP_QUIT:
			/*
			 * Exchange sometimes refuses to accept QUIT as a valid
			 * command, but since we got a 250 the mail has been
			 * accepted. So, allow 500 here too.
			 */
			if (code != 500 && code != 221)
				goto error;
			done = 1;
			break;
		}
	} while (!done);

	xfree(lbuf);
	xfree(from);
	xfree(to);

	io_close(io);
	io_free(io);

	return (DELIVER_SUCCESS);

error:
	if (cause != NULL) {
		log_warnx("%s: %s", a->name, cause);
		xfree(cause);
	} else
		log_warnx("%s: unexpected response: %s", a->name, line);

	io_writeline(io, "QUIT");
	io_flush(io, conf.timeout, NULL);

	xfree(lbuf);
	if (from != NULL)
		xfree(from);
	if (to != NULL)
		xfree(to);

	io_close(io);
	io_free(io);

	return (DELIVER_FAILURE);
}
Exemple #18
0
/**
 * @brief Loop event.
 * @param ui user interface.
 */
void ui_loop_edax(UI *ui)
{
	char *cmd = NULL, *param = NULL;
	Play *play = ui->play;
	char book_file[FILENAME_MAX];
	unsigned long long histogram[129][65];
	int repeat = options.repeat;

	histogram_init(histogram);

	// loop forever
	for (;;) {
		errno = 0;

		if (options.verbosity) {
			putchar('\n');
			play_print(play, stdout);
			if (play_is_game_over(play)) printf("\n*** Game Over ***\n");
			putchar('\n');
		}

		if (log_is_open(edax_log)) {
			putc('\n', edax_log->f);
			play_print(play, edax_log->f);
			if (play_is_game_over(play)) fputs("\n*** Game Over ***\n", edax_log->f);
			putc('\n', edax_log->f);
		}

		// edax turn ? (automatic play mode)
		if (!ui_event_exist(ui) && !play_is_game_over(play) && (ui->mode == !play->player || ui->mode == 2)) {
			putchar('\n');
			play_go(play, true);
			printf("\nEdax plays "); move_print(play_get_last_move(play)->x, 0, stdout); putchar('\n');
			if (ui->mode != 2) play_ponder(play);

		// proceed by reading a command
		} else {

			/* automatic rules after a game over*/
			if (play_is_game_over(play)) {
				if (options.auto_store) play_store(play);
				if (options.auto_swap && ui->mode < 2) ui->mode = !ui->mode;
				if (options.repeat && repeat > 1) {
					--repeat;
					play_new(play);
					continue;
				}
				if (options.auto_quit) {
					return;
				}
				if (options.auto_start) {
					play_new(play);
					continue;
				}
			}

			putchar('>'); fflush(stdout);
			ui_event_wait(ui, &cmd, &param);
			log_print(edax_log, "cmd=\"%s\" ; param=\"%s\"\n", cmd, param);
			putchar('\n');

			if (cmd == NULL) {
				warn("unexpected null command?\n");
				continue;
			}

			// skip empty lines or commented lines
			if (*cmd == '\0' || *cmd == '#') {
			
			// help
			} else if (strcmp(cmd, "help") == 0 || strcmp(cmd, "?") == 0) {
				if (*param == '\0' || strcmp(param, "options") == 0) help_options();
				if (*param == '\0' || strcmp(param, "commands") == 0) help_commands();
				if (*param == '\0' || strcmp(param, "book") == 0) help_book();
				if (*param == '\0' || strcmp(param, "base") == 0) help_base();
				if (*param == '\0' || strcmp(param, "test") == 0) help_test(); 

			// new game from standard position
			} else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "init") == 0) {
				board_init(play->initial_board);
				play_new(play);

			// new game from personnalized position
			} else if ((strcmp(cmd, "n") == 0 || strcmp(cmd, "new") == 0) && *param == '\0') {
				play_new(play);

			// open a saved game
			} else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "open") == 0 || strcmp(cmd, "load") == 0) {
				play_load(play, param);

			// save a game
			} else if (strcmp(cmd, "s") == 0 || strcmp(cmd, "save") == 0) {
				play_save(play, param);

			// quit
			} else if (strcmp(cmd, "quit") == 0 || strcmp(cmd, "q") == 0 || strcmp(cmd, "exit") == 0) {
				free(cmd); free(param);
				return;

			} else if (!options.auto_quit && (strcmp(cmd, "eof") == 0 && (ui->mode != 2 || play_is_game_over(play)))){
				free(cmd); free(param);
				return;

			// undo last move
			} else if (strcmp(cmd, "u") == 0 || strcmp(cmd, "undo") == 0) {
				play_undo(play);
				if (ui->mode == 0 || ui->mode == 1) play_undo(play);

			// redo last move
			} else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "redo") == 0) {
				play_redo(play);
				if (ui->mode == 0 || ui->mode == 1) play_undo(play);

			// mode
			} else if (strcmp(cmd, "m") == 0 || strcmp(cmd, "mode") == 0) {
				ui->mode = string_to_int(param, 3);

			// analyze a game
			} else if (strcmp(cmd, "a") == 0 || strcmp(cmd, "analyze") == 0 || strcmp(cmd, "analyse") == 0) {
				play_analyze(play, string_to_int(param, play->n_game));

			// set a new initial position
			} else if (strcmp(cmd, "setboard") == 0) {
				play_set_board(play, param);

			// vertical mirror
			} else if (strcmp(cmd, "vmirror") == 0) {
				play_symetry(play, 2);

			// horizontal mirror
			} else if (strcmp(cmd, "hmirror") == 0) {
				play_symetry(play, 1);

			// rotate
			} else if (strcmp(cmd, "rotate") == 0) {
				int angle = string_to_int(param, 90) % 360;
				if (angle < 0) angle += 360;
				switch (angle) {
				case 90: 
					play_symetry(play, 5);
					break; 
				case 180:
					play_symetry(play, 3);
					break; 
				case 270:
					play_symetry(play, 6);
					break; 
				default:
					warn("Rotate angle should be 90°, 180° or 270°");
					break;
				}

			// direct symetry...
			} else if (strcmp(cmd, "symetry") == 0) {
				int sym = string_to_int(param, 1);
				if (sym < 0 || sym >= 16) warn("symetry parameter should be a number between 0 and 15\n");
				else {
					if (sym & 8) play->player ^= 1;
					play_symetry(play, sym & 7);
				}

			// play a serie of moves
			} else if (strcmp(cmd, "play") == 0) {
				string_to_lowercase(param);
				play_game(play, param);

			// force edax to play an opening
			} else if (strcmp(cmd, "force") == 0) {
				string_to_lowercase(param);
				play_force_init(play, param);

			// solve a set of problems
			} else if (strcmp(cmd, "solve") == 0) {
				char problem_file[FILENAME_MAX + 1], *hard_file;
				hard_file = parse_word(param, problem_file, FILENAME_MAX);
				parse_word(hard_file, hard_file, FILENAME_MAX);
				obf_test(play->search, problem_file, hard_file);
				search_set_observer(play->search, edax_observer);

			// convert a set of problems in a .script file to a .obf file
			} else if (strcmp(cmd, "script-to-obf") == 0) {
				char script_file[FILENAME_MAX + 1], *obf_file;
				obf_file = parse_word(param, script_file, FILENAME_MAX);
				parse_word(obf_file, obf_file, FILENAME_MAX);
				script_to_obf(play->search, script_file, obf_file);
				search_set_observer(play->search, edax_observer);

			} else if (strcmp(cmd, "select-hard") == 0) {
				char full_file[FILENAME_MAX + 1], *hard_file;
				hard_file = parse_word(param, full_file, FILENAME_MAX);
				parse_word(hard_file, hard_file, FILENAME_MAX);
				obf_filter(full_file, hard_file);

			// game/position enumeration
			} else if (strcmp(cmd, "count") == 0) {
				char count_cmd[16], *count_param;
				int depth = 10, size = 8;

				count_param = parse_word(param, count_cmd, 15);
				count_param = parse_int(count_param, &depth); BOUND(depth, 1, 90, "max-ply");
				if (count_param) parse_int(count_param, &size); BOUND(size, 6, 8, "board-size");

				if (strcmp(count_cmd, "games") == 0) { // game enumeration
					quick_count_games(play->board, depth, size);
				} else if (strcmp(count_cmd, "positions") == 0) { // position enumeration
					count_positions(play->board, depth, size);
				} else if (strcmp(count_cmd, "shapes") == 0) { // shape enumeration
					count_shapes(play->board, depth, size);
				} else {
					warn("Unknown count command: \"%s %s\"\n", cmd, param);
				}

			} else if (strcmp(cmd, "perft") == 0) {
				int depth = 14;
				depth = string_to_int(param, 10); BOUND(depth, 1, 90, "max-ply");
				count_games(play->board, depth);
			
			// game/position enumeration
			} else if (strcmp(cmd, "estimate") == 0) {
				int n = 1000;
				n = string_to_int(param, 10); BOUND(n, 1, 2000000000, "max-trials");

				estimate_games(play->board, n);
	
			// seek highest mobility
			} else if (strcmp(cmd, "mobility") == 0) {
				int t = 3600; // 1 hour
				t = string_to_int(param, 10); BOUND(t, 1, 3600*24*365*10, "max time");

				seek_highest_mobility(play->board, t);

			// seek a position
			} else if (strcmp(cmd, "seek") == 0) {
				Board target;
				Line solution;
				
				board_set(&target, param);
				line_init(&solution, play->player);
				
				if (seek_position(&target, play->board, &solution)) {
					printf("Solution found:\n");
					line_print(&solution, 200, " ", stdout);
					putchar('\n');
				}
			
			// bench (a serie of low level tests).
			} else if (strcmp(cmd, "bench") == 0) {
				bench();

			// wtest test the engine against wthor theoretical scores
			} else if (strcmp(cmd, "wtest") == 0) {
				wthor_test(param, play->search);

			// make wthor games played by "Edax (Delorme)" as "Etudes" tournament.
			} else if (strcmp(cmd, "edaxify") == 0) {
				wthor_edaxify(param);

			// wtest test the engine against wthor theoretical scores
			} else if (strcmp(cmd, "weval") == 0) {
				wthor_eval(param, play->search, histogram);
				histogram_print(histogram);
				histogram_stats(histogram);
				histogram_to_ppm("weval.ppm", histogram);

			// go think!
			} else if (strcmp(cmd, "go") == 0) {
				if (play_is_game_over(play)) printf("\n*** Game Over ***\n");
				else {
					play_go(play, true);
					printf("\nEdax plays "); move_print(play_get_last_move(play)->x, 0, stdout); putchar('\n');
				}

			// hint for [n] moves
			} else if (strcmp(cmd, "hint") == 0) {
				int n = string_to_int(param, 1); BOUND(n, 1, 60, "n_moves");
				play_hint(play, n);

			// stop thinking
			} else if (strcmp(cmd, "stop") == 0) {
				ui->mode = 3;

			// user move
			} else if (play_user_move(play, cmd)) {
				printf("\nYou play "); move_print(play_get_last_move(play)->x, 0, stdout); putchar('\n');

			// debug pv
			} else if (strcmp(cmd, "debug-pv") == 0) {
				Move move[1];
				if (parse_move(param, play->board, move) != param) {
					search_set_board(play->search, play->board, play->player);
					pv_debug(play->search, move, stdout);
				}
			} else if (strcmp(cmd, "options") == 0) {
					options_dump(stdout);
#ifdef __unix__
			} else if (strcmp(cmd, "resources") == 0) {
				struct rusage u;
				long long t;
	 			getrusage(RUSAGE_SELF, &u);
				t = 1000 * u.ru_utime.tv_sec + u.ru_utime.tv_usec / 1000;
				printf("user cpu time: "); time_print(t, false, stdout); printf("\n");	
				t = 1000 * u.ru_stime.tv_sec + u.ru_stime.tv_usec / 1000;
				printf("system cpu time: "); time_print(t, false, stdout); printf("\n");	
				printf("max resident memory: %ld\n", u.ru_maxrss); 
				printf("page fault without I/O: %ld\n", u.ru_minflt); 
				printf("page fault with I/O: %ld\n", u.ru_majflt); 
				printf("number of input: %ld\n", u.ru_inblock); 
				printf("number of output: %ld\n", u.ru_oublock); 
				printf("number of voluntary context switch: %ld\n", u.ru_nvcsw); 
				printf("number of unvoluntary context switch: %ld\n\n", u.ru_nivcsw); 
#endif		
			// opening name
			} else if (strcmp(cmd, "opening") == 0) {
				const char *name;
				name = play_show_opening_name(play, opening_get_english_name);
				if (name == NULL) name = "?";
				puts(name);  

			// opening name in french
			} else if (strcmp(cmd, "ouverture") == 0) {
				const char *name;
				name = play_show_opening_name(play, opening_get_french_name);
				if (name == NULL) name = "?";
				puts(name); 

			// opening book commands
			} else if (strcmp(cmd, "book") == 0 || strcmp(cmd, "b") == 0) {
				char book_cmd[FILENAME_MAX + 1], *book_param;
				int val_1, val_2;
				Book *book = play->book;

				book->search = play->search;
				book->search->options.verbosity = book->options.verbosity;
				book_param = parse_word(param, book_cmd, FILENAME_MAX);
				// store the last played game
				if (strcmp(book_cmd, "store") == 0) {
					play_store(play);

				// turn book usage on
				} else if (strcmp(book_cmd, "on") == 0) { // learn
					options.book_allowed = true;

				// turn book usage off
				} else if (strcmp(book_cmd, "off") == 0) { // learn
					options.book_allowed = false;

				// set book randomness
				} else if (strcmp(book_cmd, "randomness") == 0) { // learn
					val_1 = 0; book_param = parse_int(book_param, &val_1);
					options.book_randomness = val_1;

				// set book depth (until which to learn)
				} else if (strcmp(book_cmd, "depth") == 0) { // learn
					val_1 = 36; book_param = parse_int(book_param, &val_1);
					book->options.n_empties = 61 - val_1;

				// create a new empty book
				} else if (strcmp(book_cmd, "new") == 0) {
					val_1 = 21; book_param = parse_int(book_param, &val_1);
					val_2 = 36;	book_param = parse_int(book_param, &val_2);
					book_free(book) ;
					book_new(book, val_1, 61 - val_2);

				// load an opening book (binary format) from the disc
				} else if (strcmp(book_cmd, "load") == 0 || strcmp(book_cmd, "open") == 0) {
					book_free(book) ;
					parse_word(book_param, book_file, FILENAME_MAX);
					book_load(book, book_file);

				// save an opening book (binary format) to the disc
				} else if (strcmp(book_cmd, "save") == 0) {
					parse_word(book_param, book_file, FILENAME_MAX);
					book_save(book, book_file);

				// import an opening book (text format)
				} else if (strcmp(book_cmd, "import") == 0) {
					book_free(book);
					parse_word(book_param, book_file, FILENAME_MAX);
					book_import(book, book_file);
					book_link(book);
					book_fix(book);
					book_negamax(book);
					book_sort(book);

				// export an opening book (text format)
				} else if (strcmp(book_cmd, "export") == 0) {
					parse_word(book_param, book_file, FILENAME_MAX);
					book_export(book, book_file);

				// merge an opening book to the current one
				} else if (strcmp(book_cmd, "merge") == 0) {
					Book src[1];
					parse_word(book_param, book_file, FILENAME_MAX);
					src->search = play->search;
					book_load(src, book_file);
					book_merge(book, src);
					book_free(src);
					warn("Book needs to be fixed before usage\n");

				// fix an opening book
				} else if (strcmp(book_cmd, "fix") == 0) {
					book_fix(book); // do nothing (or edax is buggy)
					book_link(book); // links nodes
					book_negamax(book); // negamax nodes
					book_sort(book); // sort moves

				// negamax an opening book
				} else if (strcmp(book_cmd, "negamax") == 0) {
					book_negamax(book); // negamax nodes
					book_sort(book); // sort moves

				// check and correct solved positions of the book
				} else if (strcmp(book_cmd, "correct") == 0) {
					book_correct_solved(book); // do nothing (or edax is buggy)
					book_fix(book); // do nothing (or edax is buggy)
					book_link(book); // links nodes
					book_negamax(book); // negamax nodes
					book_sort(book); // sort moves

				// prune an opening book
				} else if (strcmp(book_cmd, "prune") == 0) {
					book_prune(book); // remove unreachable lines.
					book_fix(book); // do nothing (or edax is buggy)
					book_link(book); // links nodes
					book_negamax(book); // negamax nodes
					book_sort(book); // sort moves

				// show the current position as stored in the book
				} else if (strcmp(book_cmd, "show") == 0) {
					book_show(book, play->board);

				// show book general information
				} else if (strcmp(book_cmd, "info") == 0) {
					book_info(book);

				// show book general information
				} else if (strcmp(book_cmd, "stats") == 0) {
					book_stats(book);


				// set book verbosity
				} else if (strcmp(book_cmd, "verbose") == 0) {
					parse_int(book_param, &book->options.verbosity);
					book->search->options.verbosity = book->options.verbosity;

				// analyze a game from the opening book point of view
				} else if (strcmp(book_cmd, "a") == 0 || strcmp(book_cmd, "analyze") == 0 || strcmp(book_cmd, "analyse") == 0) {
					val_1 = string_to_int(book_param, play->n_game); BOUND(val_1, 1, play->n_game, "depth");
					play_book_analyze(play, val_1);

				// add positions from a game database
				} else if (strcmp(book_cmd, "add") == 0) {
					Base base[1];
					parse_word(book_param, book_file, FILENAME_MAX);
					base_init(base);
					base_load(base, book_file);
					book_add_base(book, base);
					base_free(base);

				// check positions from a game database
				} else if (strcmp(book_cmd, "check") == 0) {
					Base base[1];
					parse_word(book_param, book_file, FILENAME_MAX);
					base_init(base);
					base_load(base, book_file);
					book_check_base(book, base);
					base_free(base);

				// extract positions
				} else if (strcmp(book_cmd, "problem") == 0) {
					val_1 = 24; book_param = parse_int(book_param, &val_1); BOUND(val_1, 0, 60, "number of empties");
					val_2 = 10; book_param = parse_int(book_param, &val_2); BOUND(val_2, 1, 1000000, "number of positions");
					book_extract_positions(book, val_1, val_2);
					
				// extract pv to a game database
				} else if (strcmp(book_cmd, "extract") == 0) {
					Base base[1];
					parse_word(book_param, book_file, FILENAME_MAX);
					base_init(base);
					book_extract_skeleton(book, base);
					base_save(base, book_file);
					base_free(base);

				// add position using the "deviate algorithm"
				} else if (strcmp(book_cmd, "deviate") == 0) {
					val_1 = 2; book_param = parse_int(book_param, &val_1); BOUND(val_1, -129, 129, "relative error");
					val_2 = 4; book_param = parse_int(book_param, &val_2); BOUND(val_2, 0, 65, "absolute error");
					book_deviate(book, play->board, val_1, val_2);

				// add position using the "enhance algorithm"
				} else if (strcmp(book_cmd, "enhance") == 0) {
					val_1 = 2; book_param = parse_int(book_param, &val_1); BOUND(val_1, 0, 129, "midgame error");
					val_2 = 4; book_param = parse_int(book_param, &val_2); BOUND(val_2, 0, 129, "endcut error");
					book_enhance(book, play->board, val_1, val_2);

				// add position by filling hole in the book
				} else if (strcmp(book_cmd, "fill") == 0) {
					val_1 = 1; book_param = parse_int(book_param, &val_1); BOUND(val_1, 1, 61, "fill depth");
					book_fill(book, val_1);

				// add positions by expanding positions with no-link
				} else if (strcmp(book_cmd, "play") == 0) {
					book_play(book);

				// add positions by expanding positions with no-link
				} else if (strcmp(book_cmd, "deepen") == 0) {
					book_deepen(book);

				// add book positions to the hash table
				} else if (strcmp(book_cmd, "feed-hash") == 0) {
					book_feed_hash(book, play->board, play->search);

				// wrong command ?
				} else {
					warn("Unknown book command: \"%s %s\"\n", cmd, param);
				}
				book->options.verbosity = book->search->options.verbosity;
				book->search->options.verbosity = options.verbosity;

			/* base TODO: add more actions... */
			} else if (strcmp(cmd, "base") == 0) {
				char base_file[FILENAME_MAX + 1];
				char base_cmd[512], *base_param;
				Base base[1];

				base_init(base);
				base_param = parse_word(param, base_cmd, 511);
				base_param = parse_word(base_param, base_file, FILENAME_MAX);

				// extract problem from a game base
				if (strcmp(base_cmd, "problem") == 0) {
					char problem_file[FILENAME_MAX + 1];
					int n_empties = 24;
					base_param = parse_int(base_param, &n_empties);
					base_param = parse_word(base_param, problem_file, FILENAME_MAX);

					base_load(base, base_file);
					base_to_problem(base, n_empties, problem_file);

				// extract FEN 
				} else if (strcmp(base_cmd, "tofen") == 0) {
					char problem_file[FILENAME_MAX + 1];
					int n_empties = 24;
					base_param = parse_int(base_param, &n_empties);
					base_param = parse_word(base_param, problem_file, FILENAME_MAX);

					base_load(base, base_file);
					base_to_FEN(base, n_empties, problem_file);
	
				// correct erroneous games
				} else if (strcmp(base_cmd, "correct") == 0) {
					int n_empties = 24;
					base_param = parse_int(base_param, &n_empties);

					base_load(base, base_file);
					base_analyze(base, play->search, n_empties, true);
					remove(base_file);
					base_save(base, base_file);

				// check erroneous games
				} else if (strcmp(base_cmd, "check") == 0) {
					int n_empties = 24;
					base_param = parse_int(base_param, &n_empties);

					base_load(base, base_file);
					base_analyze(base, play->search, n_empties, false);

				// terminate unfinished base
				} else if (strcmp(base_cmd, "complete") == 0) {
					base_load(base, base_file);
					base_complete(base, play->search);
					remove(base_file);
					base_save(base, base_file);

				// convert a base to another format
				} else if (strcmp(base_cmd, "convert") == 0) {
					base_load(base, base_file);
					base_param = parse_word(base_param, base_file, FILENAME_MAX);
					base_save(base, base_file);

				// make a base unique by removing identical games
				} else if (strcmp(base_cmd, "unique") == 0) {
					base_load(base, base_file);
					base_param = parse_word(base_param, base_file, FILENAME_MAX);
					base_unique(base);
					base_save(base, base_file);

				// compare two game bases
				} else if (strcmp(base_cmd, "compare") == 0) {
					char base_file_2[FILENAME_MAX + 1];
					base_param = parse_word(base_param, base_file_2, FILENAME_MAX);
					base_compare(base_file, base_file_2);

				} else {
					warn("Unknown base command: \"%s %s\"\n", cmd, param);
				}

				base_free(base);

			/* edax options */
			} else if (options_read(cmd, param)) {
				options_bound();
				// parallel search changes:
				if (search_count_tasks(play->search) != options.n_task) {
					play_stop_pondering(play);
					search_set_task_number(play->search, options.n_task);
				}

			/* switch to another protocol */
			} else if (strcmp(cmd, "nboard") == 0 && strcmp(param, "1") == 0) {
				free(cmd); free(param);
				play_stop_pondering(play);
				ui->free(ui);
				ui_switch(ui, "nboard");
				ui->init(ui);
				ui->loop(ui);
				return;

			} else if (strcmp(cmd, "xboard") == 0) {
				free(cmd); free(param);
				play_stop_pondering(play);
				ui->free(ui);
				ui_switch(ui, "xboard");
				ui->init(ui);
				ui->loop(ui);
				return;

			} else if (strcmp(cmd, "engine-protocol") == 0 && strcmp(param, "init") == 0) {
				free(cmd); free(param);
				play_stop_pondering(play);
				ui->free(ui);
				ui_switch(ui, "cassio");
				engine_loop();
				return;

			} else if (strcmp(cmd, "protocol_version") == 0) {
				free(cmd); free(param);
				play_stop_pondering(play);
				ui->free(ui);
				ui_switch(ui, "gtp");
				ui->init(ui);
				puts("= 2\n"); fflush(stdout);
				ui->loop(ui);
				return;

#ifdef TUNE_EDAX
			/* edax tuning */
			} else if (strcmp(cmd, "tune") == 0) {
				char problem[FILENAME_MAX];
				char *w_name;
				play_stop_pondering(play);
				w_name = parse_word(param, problem, FILENAME_MAX);
				tune_move_evaluate(play->search, problem, parse_skip_spaces(w_name));
				search_set_observer(play->search, edax_observer);
#endif
			/* illegal cmd/move */
			} else {
				warn("Unknown command/Illegal move: \"%s %s\"\n", cmd, param);
			}
		}
	}
}
Exemple #19
0
struct attach *
attach_build(struct mail *m)
{
	struct attach	*atr = NULL, *at;
	char		*hdr, *ptr, *b = NULL, *type;
	size_t		 len, bl;
	int		 last;
	u_int		 n;

	hdr = find_header(m, "content-type", &len, 0);
	if (hdr == NULL)
		return (NULL);

	type = attach_type(m, hdr, "boundary", &b);
	if (type == NULL || b == NULL) {
		if (type != NULL)
			xfree(type);
		goto error;
	}
	if (strncasecmp(type, "multipart/", 10) != 0) {
		xfree(type);
		goto error;
	}
	bl = strlen(b);

	atr = xmalloc(sizeof *atr);
	memset(atr, 0, sizeof *atr);
	TAILQ_INIT(&atr->children);
	atr->type = type;

	/* Find the first boundary. */
	line_init(m, &ptr, &len);
	while (ptr != NULL) {
		if (ptr[0] == '-' && ptr[1] == '-') {
			if (len - 3 == bl && strncmp(ptr + 2, b, bl) == 0)
				break;
		}
		line_next(m, &ptr, &len);
	}
	if (ptr == NULL)
		goto error;

	/* Now iterate over the rest. */
	last = 0;
	n = 0;
	while (ptr != NULL && !last) {
		if (ptr[0] == '-' && ptr[1] == '-') {
			if (len - 5 == bl && strncmp(ptr + 2, b, bl) == 0)
				break;
		}

		at = attach_get(m, &ptr, &len, b, &last);
		if (at == NULL)
			goto error;
		at->idx = n++;
		at->parent = atr;
		TAILQ_INSERT_TAIL(&atr->children, at, entry);
	}
	if (ptr == NULL)
		goto error;

	xfree(b);
	return (atr);

error:
	if (atr != NULL)
		attach_free(atr);

	if (b != NULL)
		xfree(b);
	return (NULL);
}
Exemple #20
0
parse()
	{int i,j,found,current, someread;
	char c;

	hash_init();
	routinit();
	line_init();

	someread = 0;			/* indicates haven't read part of a routine */

	empseek(0);
	endbuf = getline(&endline, &endchar, &endcom, & comchar);
	if (progress && endbuf != -1) fprintf(stderr,"parsing\n");
	while(endbuf != -1)			/* getline returns -1 when no more input */
		{
		someread = 1;
		if (progress > 0)
			{
			for (i = begline; i <= endline; i++)
				if (!(i % progress)) fprintf(stderr,"parsing line %d\n",i);
			}
		current = 0;
		for (i = 0; i < endbuf; i++)
			{

			c = buffer[i];
			if(c != '~') 
				{
				found = 0;
				if ( (current < 0 || current >= snum) && current != ABORT)
					{
					strerr("in parsing:","","");
					fprintf(stderr,"line %d of file, parser in invalid state", begline,current);
					fprintf(stderr,"treating it as straight line code\n");
					current = ABORT;
					}
				else
					for (j = match[current];  j < match[current + 1]; j++)
						{
						if ((symclass[j] == 0 && c == symbol[j]) ||
						    (symclass[j] != 0 && classmatch(c,symclass[j]) ))
							{found = 1;  break;
							}
						}
				if (!found)
					{
					error("in syntax:","","");
					fprintf(stderr,"between lines %d and %d of file\n",begline, endline);
					if (debug)
					fprintf(stderr,"symbol '%c' does not match entries for state %d\n",c,current);
					fprintf(stderr,"treating it as straight line code\n");
					current = ABORT;
					}
				else if (!action[j])  
					current = newstate[j];
				else
					{
					current = act(action[j],c,i);
					if (current == nulls)  current = newstate[j];
					}
				if (current == ABORT)  break;
				if (current == endrt)
					{
					return(1);
					}
				}
			}
		line_init();
		endbuf = getline(&endline, &endchar, &endcom,&comchar);
		}
	if (someread) return(1);
	else return(0);
	}
void native_nibobee_linedetector_init(void) {
  line_init();
}