コード例 #1
0
ファイル: ffserver.c プロジェクト: mobdim/ffmpeg-streaming
/* parse HTTP request and prepare header */
static int http_parse_request(HTTPContext *c)
{
    char *q, msg[1024];
    const char *mime_type, *p;
	HTTPContext *ctx;
	int ret = 0, is_first = 0;
	const char *first_tag = "First-Request=0";
	RequestData rd = {{0}};

    p = c->buffer;
	while(get_line(msg, sizeof(msg), &p) > 0){
		ret = handle_line(c, msg, sizeof(msg), &rd);
		if(ret < 0)return ret;
	}
	is_first = !av_stristr(rd.cookie, first_tag);
	
	if(c->post && c->content_length 
		&& !av_match_ext(c->url, "m3u8")
		&& !av_match_ext(c->url, "ts")
		&& !av_match_ext(c->url, "flv")){
		c->post = 0;
		c->content_length = read_request_content(c, rd.content, sizeof(rd.content));
	}
	#if defined(PLUGIN_DVB)
	if(!c->post && !strcmp(c->url, "digitalDvb/allServiceType/getClientInfo")){
		uint32_t *ptr = (uint32_t*)rd.content, *ptr_end = (uint32_t*)(rd.content+sizeof(rd.content)-8);
		for(ctx = first_http_ctx; ctx; ctx = ctx->next) 
			if(!ctx->post && av_match_ext(ctx->url, "flv") )
			{/*todo: record hls*/
				if(ptr < ptr_end){
					int chid = -1;
					sscanf(ctx->url, "%d", &chid);
		
					*ptr++ = inet_addr(inet_ntoa(ctx->from_addr.sin_addr));
					*ptr++ = chid;

					printf("ip %s id %u %s\t", inet_ntoa(ctx->from_addr.sin_addr), chid, ctx->url);
				}
			}
	}
	#endif

    //http_log("New conn: %s:%u %d %s cookie:%s\n", inet_ntoa(c->from_addr.sin_addr), ntohs(c->from_addr.sin_port), c->post, c->url, rd.cookie);

	/*handle m3u8/ts request solely*/
	if(av_match_ext(c->url, "m3u8") 
			|| av_match_ext(c->url, "ts")){
		c->keep_alive = 0; 
		ret = hls_parse_request(c, c->url, is_first);
		if(ret < 0)goto send_error;
		else if(ret == 1){
			long chid = atoi(c->url);
			if(!(0 <= chid && chid <= 10000)){
				sprintf(msg, "bad request: %s-->%ld", c->url, chid);
				http_log("%s\n", msg);
				goto send_error;
			}
			#if defined(PLUGIN_DVB)
			ff_ctl_send_string(1, c->url, rd.content);
			#endif
			http_log("wait get %s\n", c->url);
		}
		if(c->state == HTTPSTATE_SEND_HEADER)
			goto send_header;
		return 0; /*end here*/
	}

	#if defined(PLUGIN_DVB)
	ret = plugin_dvb(c, &rd);
	if(ret < 0){
		goto send_error;
	}else if(ret > 0){
		return 0;
	}
	#endif

    /*handle feed request*/
    if (c->post) {
		ctx = find_feed(c->url);
		if(ctx && ctx != c){
			sprintf(msg, "file %s has been feeded", c->url);
			http_log("%s\n", msg);
			goto send_error;
		}
        c->http_error = 0;
        c->state = HTTPSTATE_RECEIVE_DATA;
        return 0; /*end here*/
	}else{
		if(prepare_local_file(c) > 0){
			c->http_error = 200;
			c->state = HTTPSTATE_SEND_HEADER;
			return 0; /*no need feed, send local files directly.*/
		}
		
		ctx = find_feed(c->url);
		if(!ctx){
			c->keep_alive = 0; 
			sprintf(msg, "wait to get %s", c->url);
			http_log("%s\n", msg);
			#if defined(PLUGIN_DVB)
			ff_ctl_send(2, c->url, strlen(c->url)+1, rd.content, sizeof(rd.content)); 
			#endif
		}else{
			ctx->sff_ref_cnt++;
		}
		c->feed_ctx = ctx; 
	}

send_header:
    /* prepare HTTP header */
    c->buffer[0] = 0;
    av_strlcatf(c->buffer, c->buffer_size, "HTTP/1.1 200 OK\r\n");
	mime_type =  get_mine_type(c->url);
    av_strlcatf(c->buffer, c->buffer_size, "Pragma: no-cache\r\n");
    av_strlcatf(c->buffer, c->buffer_size, "Content-Type: %s\r\n", mime_type);
	av_strlcatf(c->buffer, c->buffer_size, "Connection: %s\r\n", (c->keep_alive ? "keep-alive" : "close"));
	av_strlcatf(c->buffer, c->buffer_size, "Set-Cookie: %s; Path=/; Domain=%s\r\n", first_tag, rd.domain);
    av_strlcatf(c->buffer, c->buffer_size, "\r\n");

    q = c->buffer + strlen(c->buffer);

    /* prepare output buffer */
    c->http_error = 0;
    c->buffer_ptr = c->buffer;
    c->buffer_end = q;
    c->state = HTTPSTATE_SEND_HEADER;

	#if 0
	if(S == c->hls_idx){
		HLS *s = &s_hls[c->hls_idx];
		char *ext = strrchr(c->url, '.');
		if(!(2 == s->flag && s->data && s->csize > 0)){/*not exist yet, fake one*/
			c->http_error = 200;
			c->buffer_end += sprintf(c->buffer_end, 
				"#EXTM3U\n"
				"#EXT-X-VERSION:3\n"
				"#EXT-X-TARGETDURATION:2\n"
				"#EXT-X-MEDIA-SEQUENCE:0\n"
				"#EXTINF:1.283989,\n"
				"%.*s0.ts\n", ext - c->url, c->url);
		}
	}
	#endif
    return 0;
 send_error:
	c->keep_alive = 0;
    c->http_error = 404;
    q = c->buffer;
    htmlstrip(msg);
    snprintf(q, c->buffer_size,
                  "HTTP/1.1 404 Not Found\r\n"
                  "Content-type: text/html\r\n"
                  "\r\n"
                  "<html>\n"
                  "<head><title>404 Not Found</title></head>\n"
                  "<body>%s</body>\n"
                  "</html>\n", msg);
    q += strlen(q);
    /* prepare output buffer */
    c->buffer_ptr = c->buffer;
    c->buffer_end = q;
    c->state = HTTPSTATE_SEND_HEADER;
    return 0;
}
コード例 #2
0
ファイル: nconf.gui.c プロジェクト: AlexShiLucky/linux
int dialog_inputbox(WINDOW *main_window,
		const char *title, const char *prompt,
		const char *init, char **resultp, int *result_len)
{
	int prompt_lines = 0;
	int prompt_width = 0;
	WINDOW *win;
	WINDOW *prompt_win;
	WINDOW *form_win;
	PANEL *panel;
	int i, x, y, lines, columns, win_lines, win_cols;
	int res = -1;
	int cursor_position = strlen(init);
	int cursor_form_win;
	char *result = *resultp;

	getmaxyx(stdscr, lines, columns);

	if (strlen(init)+1 > *result_len) {
		*result_len = strlen(init)+1;
		*resultp = result = xrealloc(result, *result_len);
	}

	/* find the widest line of msg: */
	prompt_lines = get_line_no(prompt);
	for (i = 0; i < prompt_lines; i++) {
		const char *line = get_line(prompt, i);
		int len = get_line_length(line);
		prompt_width = max(prompt_width, len);
	}

	if (title)
		prompt_width = max(prompt_width, strlen(title));

	win_lines = min(prompt_lines+6, lines-2);
	win_cols = min(prompt_width+7, columns-2);
	prompt_lines = max(win_lines-6, 0);
	prompt_width = max(win_cols-7, 0);

	/* place dialog in middle of screen */
	y = (lines-win_lines)/2;
	x = (columns-win_cols)/2;

	strncpy(result, init, *result_len);

	/* create the windows */
	win = newwin(win_lines, win_cols, y, x);
	prompt_win = derwin(win, prompt_lines+1, prompt_width, 2, 2);
	form_win = derwin(win, 1, prompt_width, prompt_lines+3, 2);
	keypad(form_win, TRUE);

	(void) wattrset(form_win, attributes[INPUT_FIELD]);

	(void) wattrset(win, attributes[INPUT_BOX]);
	box(win, 0, 0);
	(void) wattrset(win, attributes[INPUT_HEADING]);
	if (title)
		mvwprintw(win, 0, 3, "%s", title);

	/* print message */
	(void) wattrset(prompt_win, attributes[INPUT_TEXT]);
	fill_window(prompt_win, prompt);

	mvwprintw(form_win, 0, 0, "%*s", prompt_width, " ");
	cursor_form_win = min(cursor_position, prompt_width-1);
	mvwprintw(form_win, 0, 0, "%s",
		  result + cursor_position-cursor_form_win);

	/* create panels */
	panel = new_panel(win);

	/* show the cursor */
	curs_set(1);

	touchwin(win);
	refresh_all_windows(main_window);
	while ((res = wgetch(form_win))) {
		int len = strlen(result);
		switch (res) {
		case 10: /* ENTER */
		case 27: /* ESCAPE */
		case KEY_F(F_HELP):
		case KEY_F(F_EXIT):
		case KEY_F(F_BACK):
			break;
		case 127:
		case KEY_BACKSPACE:
			if (cursor_position > 0) {
				memmove(&result[cursor_position-1],
						&result[cursor_position],
						len-cursor_position+1);
				cursor_position--;
				cursor_form_win--;
				len--;
			}
			break;
		case KEY_DC:
			if (cursor_position >= 0 && cursor_position < len) {
				memmove(&result[cursor_position],
						&result[cursor_position+1],
						len-cursor_position+1);
				len--;
			}
			break;
		case KEY_UP:
		case KEY_RIGHT:
			if (cursor_position < len) {
				cursor_position++;
				cursor_form_win++;
			}
			break;
		case KEY_DOWN:
		case KEY_LEFT:
			if (cursor_position > 0) {
				cursor_position--;
				cursor_form_win--;
			}
			break;
		case KEY_HOME:
			cursor_position = 0;
			cursor_form_win = 0;
			break;
		case KEY_END:
			cursor_position = len;
			cursor_form_win = min(cursor_position, prompt_width-1);
			break;
		default:
			if ((isgraph(res) || isspace(res))) {
				/* one for new char, one for '\0' */
				if (len+2 > *result_len) {
					*result_len = len+2;
					*resultp = result = realloc(result,
								*result_len);
				}
				/* insert the char at the proper position */
				memmove(&result[cursor_position+1],
						&result[cursor_position],
						len-cursor_position+1);
				result[cursor_position] = res;
				cursor_position++;
				cursor_form_win++;
				len++;
			} else {
				mvprintw(0, 0, "unknown key: %d\n", res);
			}
			break;
		}
		if (cursor_form_win < 0)
			cursor_form_win = 0;
		else if (cursor_form_win > prompt_width-1)
			cursor_form_win = prompt_width-1;

		wmove(form_win, 0, 0);
		wclrtoeol(form_win);
		mvwprintw(form_win, 0, 0, "%*s", prompt_width, " ");
		mvwprintw(form_win, 0, 0, "%s",
			result + cursor_position-cursor_form_win);
		wmove(form_win, 0, cursor_form_win);
		touchwin(win);
		refresh_all_windows(main_window);

		if (res == 10) {
			res = 0;
			break;
		} else if (res == 27 || res == KEY_F(F_BACK) ||
				res == KEY_F(F_EXIT)) {
			res = KEY_EXIT;
			break;
		} else if (res == KEY_F(F_HELP)) {
			res = 1;
			break;
		}
	}

	/* hide the cursor */
	curs_set(0);
	del_panel(panel);
	delwin(prompt_win);
	delwin(form_win);
	delwin(win);
	return res;
}
コード例 #3
0
ファイル: get_param.c プロジェクト: visintainer/Epi
int get_data(char file[], char sep){
  int i;
  double maxZ;
  int out_get_line=2;
  char * line;
  char * string_who;
  char * string_value;
  FILE *fp;
  maxZ=0;
  string_who = (char *)calloc(100,sizeof(char));
  string_value = (char *)calloc(100,sizeof(char));
  if(!(fp = fopen(file,"r"))){
    printf("merda! in get data\n");
    return 1;
  }
  while(out_get_line>=2){
    out_get_line=get_line(&line,fp);
    if(out_get_line<3){
      switch(out_get_line){
      case 2:
	fprintf(stderr,"read_param: line of file %s does not end in newline\n",file);
	break;
      case 1:
	fprintf(stderr,"read_param: file %s contains an empty line\n",file);
	return 1;
	break;
      case 0:
	fclose(fp);
	return 0;
	break;
      case -1:
	fprintf(stderr,"read_param: get_line error on file %s\n",
		file);
	return 1;
      default:
	fprintf(stderr,"read_param: unrecognized exit status of get_line on file %s\n",file);
	return 1;
	break;
      }
    }
    sscanf(line,"%s", string_who);
    line = (char *)strchr(line, sep);
    line++;
    if(strcmp(string_who,"SI")==0){
      for (i = 0; i < NI; i++){
    	sscanf(line,"%s", string_value);
    	SI[i] = atoi(string_value);
    	line = (char *)strchr(line, sep);
      	line++;
      }
    }
    if(strcmp(string_who,"Z")==0){
      for (i = 0; i < NI; i++){
    	sscanf(line,"%s", string_value);
    	Z[i] = atof(string_value);
    	line = (char *)strchr(line, sep);
      	line++;
	if(Z[i]>maxZ)
	  maxZ=Z[i];
      }
    }
    if(strcmp(string_who,"AS")==0){
      for (i = 0; i < N; i++){
    	sscanf(line,"%s", string_value);
    	AS[i] = atoi(string_value);
    	line = (char *)strchr(line, sep);
      	line++;
      }
    }
    if(strcmp(string_who,"ILIdaybyday")==0){
      for (i = 0; i <= (lastPROXY); i++){
	if (i >= firstILI){
	  sscanf(line,"%s", string_value);
	  ILI[i] = atof(string_value);
	  line = (char *)strchr(line, sep);
	  line++;
	}
      }
    }
  }
  return 0;
}
コード例 #4
0
ファイル: tinyhttp.c プロジェクト: ywang2014/ProgramLearning
void accept_request(int client)  
{  
    char buf[1024];  
    int numchars;  
    char method[255];  
    char url[255];  
    char path[512];  
    size_t i, j;  
    struct stat st;  
    int cgi = 0;      /* becomes true if server decides this is a CGI program */  
    char *query_string = NULL;  
  
    /*得到请求的第一行*/  
    numchars = get_line(client, buf, sizeof(buf));  
    i = 0; j = 0;  
    /*把客户端的请求方法存到 method 数组*/  
    while (!ISspace(buf[j]) && (i < sizeof(method) - 1))  
    {  
        method[i] = buf[j];  
        i++; j++;  
    }  
    method[i] = '\0';  
  
    /*如果既不是 GET 又不是 POST 则无法处理 */  
    if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))  
    {  
        unimplemented(client);  
        return;  
    }  
  
    /* POST 的时候开启 cgi */  
    if (strcasecmp(method, "POST") == 0)  
        cgi = 1;  
  
    /*读取 url 地址*/  
    i = 0;  
    while (ISspace(buf[j]) && (j < sizeof(buf)))  
        j++;  
    while (!ISspace(buf[j]) && (i < sizeof(url) - 1) && (j < sizeof(buf)))  
    {  
        /*存下 url */  
        url[i] = buf[j];  
        i++; j++;  
    }  
    url[i] = '\0';  
  
    /*处理 GET 方法*/  
    if (strcasecmp(method, "GET") == 0)  
    {  
        /* 待处理请求为 url */  
        query_string = url;  
        while ((*query_string != '?') && (*query_string != '\0'))  
            query_string++;  
        /* GET 方法特点,? 后面为参数*/  
        if (*query_string == '?')  
        {  
            /*开启 cgi */  
            cgi = 1;  
            *query_string = '\0';  
            query_string++;  
        }  
    }  
  
    /*格式化 url 到 path 数组,html 文件都在 htdocs 中*/  
    sprintf(path, "htdocs%s", url);  
    /*默认情况为 index.html */  
    if (path[strlen(path) - 1] == '/')  
        strcat(path, "index.html");  
    /*根据路径找到对应文件 */  
    if (stat(path, &st) == -1) {  
        /*把所有 headers 的信息都丢弃*/  
        while ((numchars > 0) && strcmp("\n", buf))  /* read & discard headers */  
            numchars = get_line(client, buf, sizeof(buf));  
        /*回应客户端找不到*/  
        not_found(client);  
    }  
    else  
    {  
        /*如果是个目录,则默认使用该目录下 index.html 文件*/  
        if ((st.st_mode & S_IFMT) == S_IFDIR)  
            strcat(path, "/index.html");  
      if ((st.st_mode & S_IXUSR) || (st.st_mode & S_IXGRP) || (st.st_mode & S_IXOTH)    )  
          cgi = 1;  
      /*不是 cgi,直接把服务器文件返回,否则执行 cgi */  
      if (!cgi)  
          serve_file(client, path);  
      else  
          execute_cgi(client, path, method, query_string);  
    }  
  
    /*断开与客户端的连接(HTTP 特点:无连接)*/  
    close(client);  
}  
コード例 #5
0
ファイル: splice.c プロジェクト: StefanKarpinski/trace_tools
int main(int argc, char **argv) {
  parse_opts(argc,argv);
  if (optind == argc-1) argc++;
  int i = optind;

  char *packets_file = argv[i++];
  FILE *file = fopen(packets_file,"r+");
  if (!file)
    die("fopen(\"%s\",\"r\"): %s\n",packets_file,errstr);
  struct stat fs;
  fstat(fileno(file),&fs);
  u_int32_t n = fs.st_size / sizeof(packet_record);

  packet_record *packets = mmap(
    0,
    fs.st_size,
    PROT_READ | PROT_WRITE,
    MAP_SHARED,
    fileno(file),
    0
  );
  long long p = 0;

  while (i < argc) {
    FILE *values = open_arg(argv[i++]);
    char *line, *buffer = NULL;
    size_t length;
    if (sizes) {
      while (line = get_line(values,&buffer,&length)) {
        for (;;) {
          line += strcspn(line,"+-0123456789\n");
          if (*line == '\n' || *line == '\0') break;
          long z = strtol(line,&line,10);
          if (!z || z & 0xffff0000)
            die("Invalid packet size: %f\n",z);

          if (p >= n) goto too_many_values;
          packets[p++].size = htons((u_int16_t) z);
        }
      }
    }
    if (intervals) {
      long long flow = -1;
      long long time_usec;
      while (line = get_line(values,&buffer,&length)) {
        for (;;) {
          if (flow != packets[p].flow) {
            u_int32_t sec  = ntohl(packets[p].sec);
            u_int32_t usec = ntohl(packets[p].usec);
            time_usec = sec*1000000L + usec;
            flow = packets[p].flow;
            p++;
          }

          line += strcspn(line,"+-0123456789.\n");
          if (*line == '\n' || *line == '\0') break;
          double v = strtod(line,&line);
          time_usec += llround(v*1e6);
          u_int32_t sec  = (u_int32_t) (time_usec / 1000000L);
          u_int32_t usec = (u_int32_t) (time_usec % 1000000L);

          if (p >= n) goto too_many_values;
          packets[p].sec  = htonl(sec);
          packets[p].usec = htonl(usec);
          p++;
        }
      }
    }
    fclose(values);
    wait(NULL);
  }
  if (p < n)
    die("Too few splice values.\n");

  munmap(packets,fs.st_size);
  fclose(file);
  return 0;

too_many_values:
  die("Too many splice values.\n");
}
コード例 #6
0
ファイル: xref.c プロジェクト: EdwardGHub/Scripts
/* scan the file and build a list of line numbers where particular levels are */
void
parse(FILE *a)
{
    static char line[MAX_LINE_LEN+1];
    char *c;
    int lineno = 0;
    int lastline = 0;

    /* insert a special level 0 listitem
     * this one is the starting point for the table of contents in the html
     * version and the Top-Node of the info version.
     *
     * Added this to support multiple level 1 items.     --SB
     */
    listitems = 1;
    head = (list = (struct LIST *) xmalloc(sizeof(struct LIST)));
    list->prev = NULL;
    list->line = 0;
    list->level = 0;
    list->string = (char *) xmalloc(1);
    list->string[0] = NUL;
    list->next = NULL;

    while (get_line(line, sizeof(line), a)) {
	lineno++;
	if (isdigit((int)line[0])) {	/* start of new section */
	    listitems++;

	    if (list == NULL) {	/* impossible with the new level 0 item */
		head = (list = (struct LIST *) xmalloc(sizeof(struct LIST)));
		list->prev = NULL;
	    } else {
		list->next = (struct LIST *) xmalloc(sizeof(struct LIST));
		list->next->prev = list;
		list = list->next;
		list->next = NULL;
	    }

	    list->line = lastline = lineno;
	    list->level = line[0] - '0';
	    list->string = (char *) xmalloc(strlen(line) + 1);
	    c = strtok(&(line[1]), "\n");
	    strcpy(list->string, c);
	    list->next = NULL;
	    if (list->level > maxlevel)
		maxlevel = list->level;
	}
	if (line[0] == '?') {	/* keywords */
	    if (keylist == NULL) {
		keyhead = (keylist = (struct LIST *) xmalloc(sizeof(struct LIST)));
		keylist->prev = NULL;
	    } else {
		keylist->next = (struct LIST *) xmalloc(sizeof(struct LIST));
		keylist->next->prev = keylist;
		keylist = keylist->next;
	    }

	    keylist->line = lastline;
	    keylist->level = list->level;
	    c = strtok(&(line[1]), "\n");
	    if (c == NULL || *c == '\0')
		c = list->string;
	    keylist->string = (char *) malloc(strlen(c) + 1);
	    strcpy(keylist->string, c);
	    keylist->next = NULL;
	}
    }
    rewind(a);
}
コード例 #7
0
static void
abortpr(int dis)
{
	FILE *fp;
	struct stat stbuf;
	int pid, fd;

	if (cgetstr(bp, "sd", &SD) == -1)
		SD = _PATH_DEFSPOOL;
	if (cgetstr(bp, "lo", &LO) == -1)
		LO = DEFLOCK;
	(void)snprintf(line, sizeof(line), "%s/%s", SD, LO);
	printf("%s:\n", printer);

	PRIV_START;
	/*
	 * Turn on the owner execute bit of the lock file to disable printing.
	 */
	if (dis) {
		if (stat(line, &stbuf) >= 0) {
			stbuf.st_mode |= S_IXUSR;
			if (chmod(line, stbuf.st_mode & 0777) < 0)
				printf("\tcannot disable printing\n");
			else {
				upstat("printing disabled\n");
				printf("\tprinting disabled\n");
			}
		} else if (errno == ENOENT) {
			if ((fd = safe_open(line, O_WRONLY|O_CREAT|O_NOFOLLOW,
			    0760)) < 0)
				printf("\tcannot create lock file\n");
			else {
				(void)fchown(fd, DEFUID, -1);
				(void)close(fd);
				upstat("printing disabled\n");
				printf("\tprinting disabled\n");
				printf("\tno daemon to abort\n");
			}
			goto out;
		} else {
			printf("\tcannot stat lock file\n");
			goto out;
		}
	}
	/*
	 * Kill the current daemon to stop printing now.
	 */
	fd = safe_open(line, O_RDONLY|O_NOFOLLOW, 0);
	if (fd < 0 || (fp = fdopen(fd, "r")) == NULL) {
		if (fd >= 0)
			close(fd);
		printf("\tcannot open lock file\n");
		goto out;
	}
	if (!get_line(fp) || flock(fileno(fp), LOCK_SH|LOCK_NB) == 0) {
		(void)fclose(fp);	/* unlocks as well */
		printf("\tno daemon to abort\n");
		goto out;
	}
	(void)fclose(fp);
	if (kill(pid = atoi(line), SIGTERM) < 0) {
		if (errno == ESRCH)
			printf("\tno daemon to abort\n");
		else
			printf("\tWarning: daemon (pid %d) not killed\n", pid);
	} else
		printf("\tdaemon (pid %d) killed\n", pid);
out:
	PRIV_END;
}
コード例 #8
0
ファイル: snoop_icmp.c プロジェクト: AlainODea/illumos-gate
/*ARGSUSED*/
void
interpret_icmp(int flags, struct icmp *icmp, int iplen, int ilen)
{
	char *pt, *pc, *px;
	char *line;
	char buff[67627];	/* Router adv. can have 256 routers ....   */
				/* Each router has a name 256 char long .. */
	char extbuff[MAXHOSTNAMELEN + 1];
	struct udphdr *orig_uhdr;
	int num_rtr_addrs = 0;
	extern char *prot_nest_prefix;

	if (ilen < ICMP_MINLEN)
		return;		/* incomplete header */

	pt = "Unknown";
	pc = "";
	px = "";

	switch (icmp->icmp_type) {
	case ICMP_ECHOREPLY:
		pt = "Echo reply";
		(void) sprintf(buff, "ID: %d Sequence number: %d",
		    ntohs(icmp->icmp_id), ntohs(icmp->icmp_seq));
		pc = buff;
		break;
	case ICMP_UNREACH:
		pt = "Destination unreachable";
		switch (icmp->icmp_code) {
		case ICMP_UNREACH_NET:
			if (ilen >= ICMP_ADVLENMIN) {
				(void) sprintf(buff, "Net %s unreachable",
				    addrtoname(AF_INET,
				    &icmp->icmp_ip.ip_dst));
				pc = buff;
			} else {
				pc = "Bad net";
			}
			break;
		case ICMP_UNREACH_HOST:
			if (ilen >= ICMP_ADVLENMIN) {
				(void) sprintf(buff, "Host %s unreachable",
				    addrtoname(AF_INET,
				    &icmp->icmp_ip.ip_dst));
				pc = buff;
			} else {
				pc = "Bad host";
			}
			break;
		case ICMP_UNREACH_PROTOCOL:
			if (ilen >= ICMP_ADVLENMIN) {
				(void) sprintf(buff, "Bad protocol %d",
				    icmp->icmp_ip.ip_p);
				pc = buff;
			} else {
				pc = "Bad protocol";
			}
			break;
		case ICMP_UNREACH_PORT:
			if (ilen >= ICMP_ADVLENMIN) {
				orig_uhdr = (struct udphdr *)((uchar_t *)icmp +
				    ICMP_MINLEN + icmp->icmp_ip.ip_hl * 4);
				switch (icmp->icmp_ip.ip_p) {
				case IPPROTO_TCP:
					(void) sprintf(buff, "TCP port %d"
					    " unreachable",
					    ntohs(orig_uhdr->uh_dport));
					pc = buff;
					break;
				case IPPROTO_UDP:
					(void) sprintf(buff, "UDP port %d"
					    " unreachable",
					    ntohs(orig_uhdr->uh_dport));
					pc = buff;
					break;
				default:
					pc = "Port unreachable";
					break;
				}
			} else {
				pc = "Bad port";
			}
			break;
		case ICMP_UNREACH_NEEDFRAG:
			if (ntohs(icmp->icmp_nextmtu) != 0) {
				(void) sprintf(buff, "Needed to fragment:"
				    " next hop MTU = %d",
				    ntohs(icmp->icmp_nextmtu));
				pc = buff;
			} else {
				pc = "Needed to fragment";
			}
			break;
		case ICMP_UNREACH_SRCFAIL:
			pc = "Source route failed";
			break;
		case ICMP_UNREACH_NET_UNKNOWN:
			pc = "Unknown network";
			break;
		case ICMP_UNREACH_HOST_UNKNOWN:
			pc = "Unknown host";
			break;
		case ICMP_UNREACH_ISOLATED:
			pc = "Source host isolated";
			break;
		case ICMP_UNREACH_NET_PROHIB:
			pc = "Net administratively prohibited";
			break;
		case ICMP_UNREACH_HOST_PROHIB:
			pc = "Host administratively prohibited";
			break;
		case ICMP_UNREACH_TOSNET:
			pc = "Net unreachable for this TOS";
			break;
		case ICMP_UNREACH_TOSHOST:
			pc = "Host unreachable for this TOS";
			break;
		case ICMP_UNREACH_FILTER_PROHIB:
			pc = "Communication administratively prohibited";
			break;
		case ICMP_UNREACH_HOST_PRECEDENCE:
			pc = "Host precedence violation";
			break;
		case ICMP_UNREACH_PRECEDENCE_CUTOFF:
			pc = "Precedence cutoff in effect";
			break;
		default:
			break;
		}
		break;
	case ICMP_SOURCEQUENCH:
		pt = "Packet lost, slow down";
		break;
	case ICMP_REDIRECT:
		pt = "Redirect";
		switch (icmp->icmp_code) {
		case ICMP_REDIRECT_NET:
			pc = "for network";
			break;
		case ICMP_REDIRECT_HOST:
			pc = "for host";
			break;
		case ICMP_REDIRECT_TOSNET:
			pc = "for tos and net";
			break;
		case ICMP_REDIRECT_TOSHOST:
			pc = "for tos and host";
			break;
		default:
			break;
		}
		(void) sprintf(buff, "%s %s to %s",
			pc, addrtoname(AF_INET, &icmp->icmp_ip.ip_dst),
			addrtoname(AF_INET, &icmp->icmp_gwaddr));
		pc = buff;
		break;
	case ICMP_ECHO:
		pt = "Echo request";
		(void) sprintf(buff, "ID: %d Sequence number: %d",
		    ntohs(icmp->icmp_id), ntohs(icmp->icmp_seq));
		pc = buff;
		break;
	case ICMP_ROUTERADVERT:

#define	icmp_num_addrs	icmp_hun.ih_rtradv.irt_num_addrs
#define	icmp_wpa	icmp_hun.ih_rtradv.irt_wpa
#define	icmp_lifetime	icmp_hun.ih_rtradv.irt_lifetime

		pt = "Router advertisement";
		(void) sprintf(buff, "Lifetime %ds [%d]:",
		    ntohs(icmp->icmp_lifetime), icmp->icmp_num_addrs);
		if (icmp->icmp_wpa == 2) {
			struct icmp_ra_addr *ra;
			char ra_buf[MAXHOSTNAMELEN + 32];
			char ra_ext_buf[50];
			struct in_addr sin;
			int icmp_ra_len;
			int i;

			/* Cannot trust anything from the network... */
			num_rtr_addrs = MIN((ilen - ICMP_MINLEN) / 8,
			    icmp->icmp_num_addrs);

			ra = (struct icmp_ra_addr *)icmp->icmp_data;
			for (i = 0; i < num_rtr_addrs; i++) {
				sin.s_addr = ra->addr;
				(void) snprintf(ra_buf, sizeof (ra_buf),
				    " {%s %u}",
				    addrtoname(AF_INET, &sin),
				    ntohl(ra->preference));
				if (strlcat(buff, ra_buf, sizeof (buff)) >=
					sizeof (buff)) {
					buff[sizeof (buff) -
					    strlen("<Too Long>)")] = '\0';
					(void) strlcat(buff, "<Too Long>",
						sizeof (buff));
					break;
				}
				ra++;
			}

			icmp_ra_len = ICMP_MINLEN + num_rtr_addrs *
			    sizeof (struct icmp_ra_addr);
			if (ilen > icmp_ra_len) {
				int curr_len = ilen - icmp_ra_len;
				int ocurr_len;
				exthdr_t *exthdr = (exthdr_t *)ra;

				extbuff[0] = '\0';

				while (curr_len > 0) {
				    /* Append Mobile-IP description */
				    (void) snprintf(ra_ext_buf,
					sizeof (ra_ext_buf), ", %s",
					get_mip_adv_desc(exthdr->type));
				    (void) strlcat(extbuff, ra_ext_buf,
					sizeof (extbuff));

				    /* Special case for padding */
				    if (exthdr->type ==
					ICMP_ADV_MSG_PADDING_EXT) {

					curr_len--;
					exthdr = (exthdr_t *)
						((char *)exthdr + 1);
					continue;
				    }

				    /* else normal extension */
				    ocurr_len = curr_len;
				    curr_len -= sizeof (*exthdr) +
							exthdr->length;
				    /* detect bad length */
				    if (ocurr_len < curr_len)
						break;
				    exthdr = (exthdr_t *)
						((char *)exthdr +
						sizeof (*exthdr) +
						exthdr->length);
				}
				px = extbuff;
			}
			pc = buff;
		}
		break;
	case ICMP_ROUTERSOLICIT:
		pt = "Router solicitation";
		break;
	case ICMP_TIMXCEED:
		pt = "Time exceeded";
		switch (icmp->icmp_code) {
		case ICMP_TIMXCEED_INTRANS:
			pc = "in transit";
			break;
		case ICMP_TIMXCEED_REASS:
			pc = "in reassembly";
			break;
		default:
			break;
		}
		break;
	case ICMP_PARAMPROB:
		pt = "IP parameter problem";
		switch (icmp->icmp_code) {
		case ICMP_PARAMPROB_OPTABSENT:
			pc = "Required option missing";
			break;
		case ICMP_PARAMPROB_BADLENGTH:
			pc = "Bad length";
			break;
		case 0: /* Should this be the default? */
			(void) sprintf(buff, "Problem at octet %d\n",
			    icmp->icmp_pptr);
			pc = buff;
		default:
			break;
		}
		break;
	case ICMP_TSTAMP:
		pt = "Timestamp request";
		break;
	case ICMP_TSTAMPREPLY:
		pt = "Timestamp reply";
		break;
	case ICMP_IREQ:
		pt = "Information request";
		break;
	case ICMP_IREQREPLY:
		pt = "Information reply";
		break;
	case ICMP_MASKREQ:
		pt = "Address mask request";
		break;
	case ICMP_MASKREPLY:
		pt = "Address mask reply";
		(void) sprintf(buff, "Mask = 0x%x", ntohl(icmp->icmp_mask));
		pc = buff;
		break;
	default:
		break;
	}

	if (flags & F_SUM) {
		line = get_sum_line();
		if (*pc) {
			if (*px) {
				(void) sprintf(line, "ICMP %s (%s)%s",
				    pt, pc, px);
			} else {
				(void) sprintf(line, "ICMP %s (%s)", pt, pc);
			}
		} else {
			(void) sprintf(line, "ICMP %s", pt);
		}
	}

	if (flags & F_DTAIL) {
		show_header("ICMP:  ", "ICMP Header", ilen);
		show_space();
		(void) sprintf(get_line(0, 0), "Type = %d (%s)",
		    icmp->icmp_type, pt);
		if (*pc) {
			(void) sprintf(get_line(0, 0), "Code = %d (%s)",
			    icmp->icmp_code, pc);
		} else {
			(void) sprintf(get_line(0, 0), "Code = %d",
			    icmp->icmp_code);
		}
		(void) sprintf(get_line(0, 0), "Checksum = %x",
		    ntohs(icmp->icmp_cksum));

		if (icmp->icmp_type == ICMP_UNREACH ||
		    icmp->icmp_type == ICMP_REDIRECT) {
			if (ilen > 28) {
				show_space();
				(void) sprintf(get_line(0, 0),
				    "[ subject header follows ]");
				show_space();
				prot_nest_prefix = "ICMP:";
				(void) interpret_ip(flags,
				    (struct ip *)icmp->icmp_data, 28);
				prot_nest_prefix = "";
			}
		} else if (icmp->icmp_type == ICMP_PARAMPROB) {
			if (ilen > 28) {
				show_space();
				(void) sprintf(get_line(0, 0),
				    "[ subject header follows ]");
				show_space();
				prot_nest_prefix = "ICMP:";
				(void) interpret_ip(flags,
				    (struct ip *)icmp->icmp_data, 28);
				prot_nest_prefix = "";
			}
		} else if (icmp->icmp_type == ICMP_ROUTERADVERT) {
			if (icmp->icmp_wpa == 2) {
				int icmp_ra_len;

				show_space();
				icmp_ra_len = ICMP_MINLEN +
				    num_rtr_addrs *
					sizeof (struct icmp_ra_addr);
				prot_nest_prefix = "";
				if (ilen > icmp_ra_len) {
					interpret_icmp_mip_ext(
					    (uchar_t *)icmp + icmp_ra_len,
					    ilen - icmp_ra_len);
				}
			}
		}
		show_space();
	}
}
コード例 #9
0
ファイル: macro.c プロジェクト: DmitrySkiba/itoa-toolchain
int
buffer_and_nest (const char *from, const char *to, sb *ptr,
		 int (*get_line) (sb *))
{
  int from_len;
  int to_len = strlen (to);
  int depth = 1;
  int line_start = ptr->len;

  int more = get_line (ptr);

  if (to_len == 4 && strcasecmp(to, "ENDR") == 0)
    {
      from = NULL;
      from_len = 0;
    }
  else
    from_len = strlen (from);

  while (more)
    {
      /* Try to find the first pseudo op on the line.  */
      int i = line_start;

      /* With normal syntax we can suck what we want till we get
	 to the dot.  With the alternate, labels have to start in
	 the first column, since we can't tell what's a label and
	 what's a pseudoop.  */

      if (! LABELS_WITHOUT_COLONS)
	{
	  /* Skip leading whitespace.  */
	  while (i < ptr->len && ISWHITE (ptr->ptr[i]))
	    i++;
	}

      for (;;)
	{
	  /* Skip over a label, if any.  */
	  if (i >= ptr->len || ! is_name_beginner (ptr->ptr[i]))
	    break;
	  i++;
	  while (i < ptr->len && is_part_of_name (ptr->ptr[i]))
	    i++;
	  if (i < ptr->len && is_name_ender (ptr->ptr[i]))
	    i++;
	  if (LABELS_WITHOUT_COLONS)
	    break;
	  /* Skip whitespace.  */
	  while (i < ptr->len && ISWHITE (ptr->ptr[i]))
	    i++;
	  /* Check for the colon.  */
	  if (i >= ptr->len || ptr->ptr[i] != ':')
	    {
	      i = line_start;
	      break;
	    }
	  i++;
	  line_start = i;
	}

      /* Skip trailing whitespace.  */
      while (i < ptr->len && ISWHITE (ptr->ptr[i]))
	i++;

      if (i < ptr->len && (ptr->ptr[i] == '.'
			   || NO_PSEUDO_DOT
			   || macro_mri))
	{
	  if (! flag_m68k_mri && ptr->ptr[i] == '.')
	    i++;
	  if (from == NULL
	     && strncasecmp (ptr->ptr + i, "IRPC", from_len = 4) != 0
	     && strncasecmp (ptr->ptr + i, "IRP", from_len = 3) != 0
	     && strncasecmp (ptr->ptr + i, "IREPC", from_len = 5) != 0
	     && strncasecmp (ptr->ptr + i, "IREP", from_len = 4) != 0
	     && strncasecmp (ptr->ptr + i, "REPT", from_len = 4) != 0
	     && strncasecmp (ptr->ptr + i, "REP", from_len = 3) != 0)
	    from_len = 0;
	  if ((from != NULL
	       ? strncasecmp (ptr->ptr + i, from, from_len) == 0
	       : from_len > 0)
	      && (ptr->len == (i + from_len)
		  || ! (is_part_of_name (ptr->ptr[i + from_len])
			|| is_name_ender (ptr->ptr[i + from_len]))))
	    depth++;
	  if (strncasecmp (ptr->ptr + i, to, to_len) == 0
	      && (ptr->len == (i + to_len)
		  || ! (is_part_of_name (ptr->ptr[i + to_len])
			|| is_name_ender (ptr->ptr[i + to_len]))))
	    {
	      depth--;
	      if (depth == 0)
		{
		  /* Reset the string to not include the ending rune.  */
		  ptr->len = line_start;
		  break;
		}
	    }
	}

      /* Add the original end-of-line char to the end and keep running.  */
      sb_add_char (ptr, more);
      line_start = ptr->len;
      more = get_line (ptr);
    }

  /* Return 1 on success, 0 on unexpected EOF.  */
  return depth == 0;
}
コード例 #10
0
ファイル: tie.c プロジェクト: luigiScarso/mflua
int main P2C(int,argc,string*,argv)
#line 1238 "../../../texk/web2c/tiedir/tie.w"
{{/*12:*/
#line 408 "../../../texk/web2c/tiedir/tie.w"

int i;


/*:12*/
#line 1238 "../../../texk/web2c/tiedir/tie.w"

/*10:*/
#line 296 "../../../texk/web2c/tiedir/tie.w"

xchr[32]= ' ';
xchr[33]= '!';
xchr[34]= '\"';
xchr[35]= '#';
xchr[36]= '$';
xchr[37]= '%';
xchr[38]= '&';
xchr[39]= '\'';
xchr[40]= '(';
xchr[41]= ')';
xchr[42]= '*';
xchr[43]= '+';
xchr[44]= ',';
xchr[45]= '-';
xchr[46]= '.';
xchr[47]= '/';
xchr[48]= '0';
xchr[49]= '1';
xchr[50]= '2';
xchr[51]= '3';
xchr[52]= '4';
xchr[53]= '5';
xchr[54]= '6';
xchr[55]= '7';
xchr[56]= '8';
xchr[57]= '9';
xchr[58]= ':';
xchr[59]= ';';
xchr[60]= '<';
xchr[61]= '=';
xchr[62]= '>';
xchr[63]= '?';
xchr[64]= '@';
xchr[65]= 'A';
xchr[66]= 'B';
xchr[67]= 'C';
xchr[68]= 'D';
xchr[69]= 'E';
xchr[70]= 'F';
xchr[71]= 'G';
xchr[72]= 'H';
xchr[73]= 'I';
xchr[74]= 'J';
xchr[75]= 'K';
xchr[76]= 'L';
xchr[77]= 'M';
xchr[78]= 'N';
xchr[79]= 'O';
xchr[80]= 'P';
xchr[81]= 'Q';
xchr[82]= 'R';
xchr[83]= 'S';
xchr[84]= 'T';
xchr[85]= 'U';
xchr[86]= 'V';
xchr[87]= 'W';
xchr[88]= 'X';
xchr[89]= 'Y';
xchr[90]= 'Z';
xchr[91]= '[';
xchr[92]= '\\';
xchr[93]= ']';
xchr[94]= '^';
xchr[95]= '_';
xchr[96]= '`';
xchr[97]= 'a';
xchr[98]= 'b';
xchr[99]= 'c';
xchr[100]= 'd';
xchr[101]= 'e';
xchr[102]= 'f';
xchr[103]= 'g';
xchr[104]= 'h';
xchr[105]= 'i';
xchr[106]= 'j';
xchr[107]= 'k';
xchr[108]= 'l';
xchr[109]= 'm';
xchr[110]= 'n';
xchr[111]= 'o';
xchr[112]= 'p';
xchr[113]= 'q';
xchr[114]= 'r';
xchr[115]= 's';
xchr[116]= 't';
xchr[117]= 'u';
xchr[118]= 'v';
xchr[119]= 'w';
xchr[120]= 'x';
xchr[121]= 'y';
xchr[122]= 'z';
xchr[123]= '{';
xchr[124]= '|';
xchr[125]= '}';
xchr[126]= '~';
xchr[0]= ' ';xchr[0x7F]= ' ';


/*:10*//*13:*/
#line 429 "../../../texk/web2c/tiedir/tie.w"

for(i= 1;i<32;xchr[i++]= ' ');
xchr[tab_mark]= '\t';
xchr[form_feed]= '\f';
xchr[nl_mark]= '\n';


/*:13*//*14:*/
#line 440 "../../../texk/web2c/tiedir/tie.w"

for(i= first_text_char;i<=last_text_char;xord[i++]= 32)do_nothing;
for(i= 1;i<=126;i++)xord[xchr[i]]= i;





/*:14*/
#line 1239 "../../../texk/web2c/tiedir/tie.w"

}
#line 106 "../../../texk/web2c/tiedir/tie-w2c.ch"
print(banner);
print_ln(versionstring);
print_ln(copyright);
#line 1243 "../../../texk/web2c/tiedir/tie.w"
actual_input= 0;
out_mode= normal;
/*56:*/
#line 1177 "../../../texk/web2c/tiedir/tie.w"

{int act_arg;
if(argc<5||argc> max_file_index+4-1)usage();
no_ch= -1;
for(act_arg= 1;act_arg<argc;act_arg++){
if(argv[act_arg][0]=='-')/*57:*/
#line 1195 "../../../texk/web2c/tiedir/tie.w"

if(prod_chf!=unknown)usage();
else
switch(argv[act_arg][1]){
case'c':
case'C':prod_chf= chf;break;
case'm':
case'M':prod_chf= master;break;
default:usage();
}


/*:57*/
#line 1182 "../../../texk/web2c/tiedir/tie.w"

else/*58:*/
#line 1211 "../../../texk/web2c/tiedir/tie.w"

{if(no_ch==(-1)){
out_name= argv[act_arg];
}else{register input_description*inp_desc;
inp_desc= (input_description*)
malloc(sizeof(input_description));
if(inp_desc==NULL)
fatal_error("! No memory for descriptor");

inp_desc->mode= search;
inp_desc->line= 0;
inp_desc->type_of_file= chf;
inp_desc->limit= 0;
inp_desc->name_of_file= argv[act_arg];
input_organization[no_ch]= inp_desc;
}
incr(no_ch);
}


/*:58*/
#line 1183 "../../../texk/web2c/tiedir/tie.w"

}
if(no_ch<=0||prod_chf==unknown)usage();
}


/*:56*/
#line 1245 "../../../texk/web2c/tiedir/tie.w"

/*34:*/
#line 788 "../../../texk/web2c/tiedir/tie.w"

{
out_file= fopen(out_name,"w");
if(out_file==NULL){
fatal_error("! Could not open/create output file");

}
}


/*:34*/
#line 1246 "../../../texk/web2c/tiedir/tie.w"

/*36:*/
#line 809 "../../../texk/web2c/tiedir/tie.w"

{input_organization[0]->the_file= 
fopen(input_organization[0]->name_of_file,"r");
if(input_organization[0]->the_file==NULL)
fatal_error("! Could not open master file");

print2("(%s)",input_organization[0]->name_of_file);
term_new_line;
input_organization[0]->type_of_file= master;
get_line(0);
}

/*:36*/
#line 1247 "../../../texk/web2c/tiedir/tie.w"

/*37:*/
#line 825 "../../../texk/web2c/tiedir/tie.w"

{file_index i;
i= 1;
while(i<no_ch){
input_organization[i]->the_file= 
fopen(input_organization[i]->name_of_file,"r");
if(input_organization[i]->the_file==NULL)
fatal_error("!Could not open change file");

print2("(%s)",input_organization[i]->name_of_file);
term_new_line;
init_change_file(i,true);
incr(i);
}
}





/*:37*/
#line 1248 "../../../texk/web2c/tiedir/tie.w"

/*53:*/
#line 1128 "../../../texk/web2c/tiedir/tie.w"

actual_input= 0;
input_has_ended= false;
while(input_has_ended==false||actual_input!=0)
/*45:*/
#line 970 "../../../texk/web2c/tiedir/tie.w"

{file_index test_file;
/*46:*/
#line 985 "../../../texk/web2c/tiedir/tie.w"

{register input_description*inp_desc;
while(actual_input> 0&&e_of_ch_module(actual_input)){
inp_desc= input_organization[actual_input];
if(inp_desc->type_of_file==master){

fatal_error("! This can't happen: change file is master file");

}
inp_desc->mode= search;
init_change_file(actual_input,true);
while((input_organization[actual_input]->mode!=reading
&&actual_input> 0))decr(actual_input);
}
}


/*:46*/
#line 972 "../../../texk/web2c/tiedir/tie.w"

if(input_has_ended&&actual_input==0)break;
/*47:*/
#line 1009 "../../../texk/web2c/tiedir/tie.w"

test_input= none;
test_file= actual_input;
while(test_input==none&&test_file<no_ch-1){
incr(test_file);
switch(input_organization[test_file]->mode){
case search:if(lines_dont_match(actual_input,test_file)==false){
input_organization[test_file]->mode= test;
test_input= test_file;
}
break;
case test:if(lines_dont_match(actual_input,test_file)==true){

input_organization[test_file]->mode= search;
err_print("! Sections do not match")(actual_input);

err_loc(test_file);
init_change_file(test_file,false);
}else test_input= test_file;
break;
case reading:do_nothing;
break;
case ignore:do_nothing;
break;
}
}


/*:47*/
#line 974 "../../../texk/web2c/tiedir/tie.w"

/*48:*/
#line 1043 "../../../texk/web2c/tiedir/tie.w"

if(prod_chf==chf){
loop{
/*49:*/
#line 1057 "../../../texk/web2c/tiedir/tie.w"

if(out_mode==normal){
if(test_input!=none){
fputc(map_xchr(64),out_file);fputc(map_xchr(120),out_file);
new_line(out_file);
out_mode= pre;
}else break;
}


/*:49*/
#line 1046 "../../../texk/web2c/tiedir/tie.w"

/*50:*/
#line 1071 "../../../texk/web2c/tiedir/tie.w"


if(out_mode==pre){
if(test_input==none){
fputc(map_xchr(64),out_file);fputc(map_xchr(121),out_file);
new_line(out_file);
out_mode= post;
}else{
if(input_organization[actual_input]->type_of_file==master)
put_line(actual_input);
break;
}
}


/*:50*/
#line 1047 "../../../texk/web2c/tiedir/tie.w"

/*51:*/
#line 1092 "../../../texk/web2c/tiedir/tie.w"

if(out_mode==post){
if(input_organization[actual_input]->type_of_file==chf){
if(test_input==none)put_line(actual_input);
break;
}else{
fputc(map_xchr(64),out_file);fputc(map_xchr(122),out_file);
new_line(out_file);
new_line(out_file);
out_mode= normal;
}
}


/*:51*/
#line 1048 "../../../texk/web2c/tiedir/tie.w"

}
}else
if(test_input==none)put_line(actual_input);
コード例 #11
0
int CfgFileSetMib(struct net_device *dev, char *buf)
{
#ifdef NETDEV_NO_PRIV
	RTL_PRIV *priv = ((RTL_PRIV *)netdev_priv(dev))->wlan_priv;
#else
	RTL_PRIV *priv = dev->priv;
#endif
	unsigned char *line_head, *next_head;
	unsigned char *cmd_buf, *mibstr, *valstr, *mibstart;
	//struct mib_cfg_func *tmp_mibcfg;
	int ret = 0;
#ifdef VENDOR_PARAM_COMPATIBLE
	int arg_num = sizeof(RTL_SUPPORT_MIBCFG)/sizeof(struct mib_cfg_func);
#endif //VENDOR_PARAM_COMPATIBLE

	if((cmd_buf = (unsigned char *)kmalloc(MAX_PARAM_BUF_SIZE, GFP_ATOMIC)) == NULL) {
		printk("%s(%d): not enough memory\n", __FUNCTION__, __LINE__);
		return -1;
	}
	
	if((mibstr = (unsigned char *)kmalloc(20, GFP_ATOMIC)) == NULL) {
		printk("%s(%d): not enough memory\n", __FUNCTION__, __LINE__);
		return -1;
	}
	
	if((valstr = (unsigned char *)kmalloc(MAX_PARAM_BUF_SIZE, GFP_ATOMIC)) == NULL) {
		printk("%s(%d): not enough memory\n", __FUNCTION__, __LINE__);
		return -1;
	}
	
	next_head = buf;
	
	do {
		char *loc;
		int len = 0, miblen = 0, vallen = 0;
		//int i=0;
		
		memset(cmd_buf, 0, MAX_PARAM_BUF_SIZE);
		memset(mibstr, 0, 20);
		memset(valstr, 0, MAX_PARAM_BUF_SIZE);
		
		line_head = next_head;
		next_head = get_line(&line_head);
		if (line_head == NULL)
			break;
		
		if (line_head[0] == '#')
			continue;
		
		len = rewrite_line(&cmd_buf, &line_head);
		//printk("%s (%d)\n", cmd_buf, len);
		
#ifdef VENDOR_PARAM_COMPATIBLE	
		/* To compatible with other vendor's parameters, each parameter must have its own process function - chris*/
		loc = strchr(mibstart, '=');
		miblen = (u32)loc - (u32)mibstart;
		vallen = len - miblen -1;
		if (vallen>0) {			
			for (i=0; i<arg_num; i++) {
				if (strcmp(mibstr, RTL_SUPPORT_MIBCFG[i].name) == 0) {
					if(!RTL_SUPPORT_MIBCFG[i].set_proc(priv, valstr)) {
						printk("CFGFILE set %s failed \n", mibstr);
						return -1;
					}
					break;
				}
			}
		}
#else
			
		//printk(">>>>>>>> cmd=%s , %s, %c \n",cmd_buf, dev->name, cmd_buf[strlen(dev->name)]);
		if (!strncmp(dev->name, cmd_buf, strlen(dev->name))&&(cmd_buf[strlen(dev->name)]!='-')) {
			mibstart = cmd_buf + strlen(dev->name)+1;
		} else
			continue;
		
		loc = strchr(mibstart, '=');
		miblen = (u32)loc - (u32)mibstart;
		vallen = len - (strlen(dev->name)+1) - (miblen+1);
		
		if (vallen>0) {
			
			ret = set_mib(priv, mibstart);
			if (ret < 0) {
				strncpy(mibstr, mibstart, miblen);
				strncpy(valstr, (char*)((u32)loc+1), vallen);
				//printk("(%s) = (%s) (%d)\n", mibstr, valstr, vallen);
				printk("CFGFILE set_mib \"%s\" failed \n", mibstart);
				//return -1;
			}

#endif // VENDOR_PARAM_COMPATIBLE
		}
		
	} while (1);

	kfree(cmd_buf);
	kfree(mibstr);
	kfree(valstr);
	
	return ret;
}
コード例 #12
0
ファイル: tabdate.c プロジェクト: Milkyway-at-home/nemo
convert(stream instr, stream outstr)
{
  char   line[MAX_LINELEN];          /* input linelength */
  int  nlines, nwords, nskip;
  long long nt0, nt;
  real dt;
  struct tm tm, tm0;
  string *bp;


  if (time0) {
    tm0.tm_sec= tm0.tm_min = tm0.tm_hour = 0;
    strptime(time0,format1,&tm0);
    strftime(line,MAX_LINELEN,"%s",&tm0);
    nt0 = atoll(line);
    dprintf(0,"Using time0=%lld sec since 1970.0 using %s on %s \n",
	    nt0,format1,time0);
  }

  nlines=0;               /* count lines read so far */
  nskip=0;
  for(;;) {                       /* loop over all lines in file(s) */
    if (get_line(instr, line) < 0)
      return 0;
    dprintf(3,"LINE: (%s)\n",line);
    if(line[0] == '#') continue;		/* don't use comment lines */
    nlines++;
    tm.tm_sec= tm.tm_min = tm.tm_hour = 0;

    if (dcol>0) {
      bp = burststring(line,", ");                /* split line in words */
      nwords = xstrlen(bp,sizeof(string))-1;
      if (nwords<dcol) {
	nskip++;
	continue;
      }
      strcpy(line,bp[dcol-1]);                    /* only pick out 1 column now */
      freestrings(bp);
    }

    strptime(line,format1,&tm);
    if (need_time0) {
      dprintf(0,"First line: %s\n",line);
      strftime(line,MAX_LINELEN,"%s",&tm);
      time0 = strdup(line);
      nt0 = atoll(time0);
      dprintf(0,"First line uses: time0=%lld sec since 1970.0\n",nt0);
      need_time0 = FALSE;
    }
    strftime(line,MAX_LINELEN,format2,&tm);
    if (time0) {
      nt = atoll(line);
      if (use_scale) {
	dt = (nt-nt0)/scale;
	sprintf(line,"%g",dt);
      } else
	sprintf(line,"%lld",nt-nt0);
    }
    fputs(line,outstr);
    fputs("\n",outstr);
  } /* for(;;) */
  dprintf(1,"Processed %d lines\n",nlines);
  if (nskip) warning("%d/%d lines skipped because dcol too large",nskip,nlines);
}
コード例 #13
0
ファイル: single_star_io.C プロジェクト: Ingwar/amuse
istream & single_star::scan_star_story(istream& s)
{
    char input_line[MAX_INPUT_LINE_LENGTH];

    cerr << "\n\nUsing single_star_io version of scan_star_story()...\n\n";

    while(get_line(s,input_line), strcmp(END_STAR, input_line)){
	char keyword[MAX_INPUT_LINE_LENGTH];
	const char *val = getequals(input_line, keyword);

	if (val) {
	    real number;
	    if(0){   // trick to keep the if() statement, for the else below
	    }else if(!strcmp("Type",keyword)){
		char str_tpe[MAX_INPUT_LINE_LENGTH];
		sscanf(val,"%s",str_tpe);

	    }else if(!strcmp("Class",keyword)){
		char str_cls[MAX_INPUT_LINE_LENGTH];
		sscanf(val,"%s",str_cls);

	    }else if(!strcmp("T_cur",keyword)){
		set_current_time( strtod(val,NULL) );

	    }else if(!strcmp("T_rel",keyword)){
		set_relative_age( strtod(val,NULL) );

	    }else if(!strcmp("M_rel",keyword)){
		set_relative_mass( strtod(val,NULL) );

	    }else if(!strcmp("M_env",keyword)){
		set_envelope_mass( strtod(val,NULL) );

	    }else if(!strcmp("M_core",keyword)){
		set_core_mass( strtod(val,NULL) );

	    }else if(!strcmp("M_COcore",keyword)){
		set_COcore_mass( strtod(val,NULL) );

	    }else if(!strcmp("T_eff",keyword)){
		number = strtod(val,NULL);
		/* XXX ignore value?? */

	    }else if(!strcmp("L_eff",keyword)){
		set_luminosity( strtod(val,NULL) );

	    }else if(!strcmp("P_rot",keyword)){           // experimental extra 
	  					          // information for 
		set_rotation_period( strtod(val,NULL) );  // radio pulsars.

	    } else if(!strcmp("B_fld",keyword)){
		set_magnetic_field( strtod(val,NULL) );

	    }else{
		add_story_line(star_story, input_line);
	    }
	}
    }

    //if(current_time<=0) current_time = relative_age;
    return s;
}
コード例 #14
0
static int ass_read_header(AVFormatContext *s)
{
    ASSContext *ass = s->priv_data;
    AVBPrint header, line;
    int header_remaining, res = 0;
    AVStream *st;

    st = avformat_new_stream(s, NULL);
    if (!st)
        return AVERROR(ENOMEM);
    avpriv_set_pts_info(st, 64, 1, 100);
    st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
    st->codec->codec_id   = AV_CODEC_ID_SSA;

    header_remaining = INT_MAX;

    av_bprint_init(&header, 0, AV_BPRINT_SIZE_UNLIMITED);
    av_bprint_init(&line,   0, AV_BPRINT_SIZE_UNLIMITED);

    for (;;) {
        int64_t pos = get_line(&line, s->pb);

        if (!line.str[0]) // EOF
            break;

        if (!memcmp(line.str, "[Events]", 8))
            header_remaining = 2;
        else if (line.str[0] == '[')
            header_remaining = INT_MAX;

        if (header_remaining) {
            av_bprintf(&header, "%s", line.str);
            header_remaining--;
        } else {
            int64_t ts_start = AV_NOPTS_VALUE;
            int duration = -1;
            AVPacket *sub;

            if (read_ts(line.str, &ts_start, &duration) < 0)
                continue;
            sub = ff_subtitles_queue_insert(&ass->q, line.str, line.len, 0);
            if (!sub) {
                res = AVERROR(ENOMEM);
                goto end;
            }
            sub->pos = pos;
            sub->pts = ts_start;
            sub->duration = duration;
        }
    }

    av_bprint_finalize(&line, NULL);

    res = avpriv_bprint_to_extradata(st->codec, &header);
    if (res < 0)
        goto end;

    ff_subtitles_queue_finalize(&ass->q);

end:
    return res;
}
コード例 #15
0
ファイル: location_gui.c プロジェクト: Xastir/Xastir
void location_add(/*@unused@*/ Widget w, XtPointer clientData, /*@unused@*/ XtPointer callData) {
    char name[100];
    char s_long[20];
    char s_lat[20];
    FILE *f, *fout;
    char temp[200];
    char *temp_ptr;
    Widget my_text = (Widget) clientData;
    int len,n,found;
    char location_file_path[MAX_VALUE];
    char location_db_path[MAX_VALUE];

    get_user_base_dir("config/locations.sys", location_file_path, 
                      sizeof(location_file_path));

    get_user_base_dir("data/locations_db.dat", location_db_path, 
                      sizeof(location_db_path));


    temp_ptr = XmTextFieldGetString(my_text);
    xastir_snprintf(name,
        sizeof(name),
        "%s",
        temp_ptr);
    XtFree(temp_ptr);

    (void)remove_trailing_spaces(name);
    XmTextFieldSetString(my_text,"");
    /* should check for name used already */
    found=0;
    f=fopen(location_file_path,"r");
    if (f!=NULL) {
        while (!feof(f) && !found) {
            (void)get_line(f,temp,200);
            if (!feof(f) && strlen(temp)>8) {
                temp_ptr=strtok(temp,"|");  /* get the name */
                if (temp_ptr!=NULL) {
                    if (strcmp(name,temp)==0)
                        found=1;
                }
            }
        }
        (void)fclose(f);
    }
    else
        fprintf(stderr,"Couldn't open file: %s\n", location_file_path );

    if (!found) {
        /* delete entire list available */
        XmListDeleteAllItems(location_list);
        len = (int)strlen(name);
        if (len>0 && len<100){
            fout = fopen(location_file_path,"a");
            if (fout!=NULL) {
                convert_lat_l2s(center_latitude, s_lat, sizeof(s_lat), CONVERT_HP_NOSP);
                convert_lon_l2s(center_longitude, s_long, sizeof(s_long), CONVERT_HP_NOSP);
                fprintf(fout,"%s|%s %s %ld\n",name,s_lat,s_long,scale_y);
                (void)fclose(fout);
            }
            else
                fprintf(stderr,"Couldn't open file: %s\n", location_file_path );
        } else
            popup_message_always(langcode("POPEM00022"),langcode("POPEM00023"));

        /* resort the list and put it back up */
        n=1;
        clear_sort_file(location_db_path);
        jump_sort();
        sort_list(location_db_path,200,location_list,&n);
    } else
        popup_message_always(langcode("POPEM00022"),langcode("POPEM00024")); /* dupe name */
}
コード例 #16
0
ファイル: util.c プロジェクト: tgdiriba/os
bool parse_request(int connfd, struct request* req)
{
    char buf[BUFSIZE+1];
    char instr[20];
    char file[100];
    char type[20];

    int i=0;
    int j=0;


    char *bad_request = "HTTP/1.0 400 BAD REQUEST\r\n"\
                              "Content-type: text/html\r\n\r\n"\
                              "<html><body><h2>BAD REQUEST</h2>"\
                              "</body></html>\n";

    get_line(connfd, buf, BUFSIZE);

    //parse out instruction
    while( !isspace(buf[j]) && (i < sizeof(instr) - 1))
    {
        instr[i] = buf[i];
        i++;
        j++;
    }
    j+=2;
    instr[i] = '\0';

    //Only accept GET requests
    if (strncmp(instr, "GET", 3) != 0) {
        writenbytes(connfd, bad_request, strlen(bad_request));
        close(connfd);
        return false;
    }

    //parse out filename
    i=0;
    while (!isspace(buf[j]) && (i < sizeof(file) - 1))
    {
        file[i] = buf[j];
        i++;
        j++;
    }
    j++;
    file[i] = '\0';

    //parse out type
    i=0;
    while (!isspace(buf[j]) && (buf[j] != '\0') && (i < sizeof(type) - 1))
    {
        type[i] = buf[j];
        i++;
        j++;
    }
    type[i] = '\0';

    while (get_line(connfd, buf, BUFSIZE) > 0)
    {
        //ignore headers -> (for now)
    }

    int length;
    for(i = 0; i < strlen(file); i++)
    {
        if(file[i] == '?')
            break;
    }
    length = i;

    req->resource = malloc(length+1);

    if (length > strlen(file)) {
      length = strlen(file);
    }

    strncpy(req->resource, file, length);
    req->resource[length] = 0;

    req->seat_id = parse_int_arg(file, "seat=");
    req->user_id = parse_int_arg(file, "user="******"priority=");
    return true;
}
コード例 #17
0
ファイル: location_gui.c プロジェクト: Xastir/Xastir
void location_view(/*@unused@*/ Widget w, /*@unused@*/ XtPointer clientData, /*@unused@*/ XtPointer callData) {
    int i,x;
    char *location;
    XmString *list;
    int found,done;
    FILE *f;
    char temp[200];
    char name[100];
    char pos[100];
    char *temp_ptr;
    char s_lat[20];
    char s_long[20];
    char s_sz[10];
    char location_file_path[MAX_VALUE];

    found=0;
    XtVaGetValues(location_list,XmNitemCount,&i,XmNitems,&list,NULL);

    for (x=1; x<=i;x++) {
        if (XmListPosSelected(location_list,x)) {
            found=1;
            if (XmStringGetLtoR(list[(x-1)],XmFONTLIST_DEFAULT_TAG,&location))
                x=i+1;
        }
    }
    get_user_base_dir("config/locations.sys", location_file_path, 
                      sizeof(location_file_path));
    if (found) {
        f=fopen(location_file_path,"r");
        if (f!=NULL) {
            done=0;
            while (!feof(f) & !done) {
                (void)get_line(f,temp,200);
                if (!feof(f) && strlen(temp)>8) {
                    temp_ptr=strtok(temp,"|");  /* get the name */
                    if (temp_ptr!=NULL) {
                        xastir_snprintf(name,
                            sizeof(name),
                            "%s",
                            temp);
                        temp_ptr=strtok(NULL,"|");  /* get the pos */
                        xastir_snprintf(pos,
                            sizeof(pos),
                            "%s",
                            temp_ptr);
                        if (strcmp(location,name)==0) {
                            if (3 != sscanf(pos,"%19s %19s %9s", s_lat, s_long, s_sz)) {
                                fprintf(stderr,"location_view:sscanf parsing error\n");
                            }
                            map_pos(convert_lat_s2l(s_lat),convert_lon_s2l(s_long),atol(s_sz));
                            done=1;
                        }
                    }
                }
            }
            (void)fclose(f);
        }
        else {
            fprintf(stderr,"Couldn't open file: %s\n", location_file_path );
        }
        XtFree(location);
    }
}
コード例 #18
0
AVIStripeSystem::AVIStripeSystem(const char *szFile) {
	FILE *f = NULL;

	stripe = NULL;

	try {
		char linebuf[512];
		int stripe_cnt, cur;
		int lineno = 2;
		char *s, *t;

		// Type of lines we are trying to parse:
		//
		//	0   i   131072     65536      e:\capture_master.avi
		//	0   v   4194304    1048576   "e:\capture video stripe 1.avi"
		//  -1  v	1048576    524288    "i:\capture video stripe 2.avi"


		f = fopen(szFile, "r");
		if (!f) throw MyError("Couldn't open stripe definition file \"%s\"", szFile);

		if (!get_line(linebuf, sizeof linebuf, f))
				throw MyError("Failure reading first line of stripe def file");

		if (1!=sscanf(linebuf, " %d \n", &stripe_cnt))
			throw MyError("First line of stripe definition file must contain stripe count");

		if (stripe_cnt<=0)
			throw MyError("Invalid number of stripes (%d)", stripe_cnt);

		_construct(stripe_cnt);

		for(cur=0; cur<stripe_cnt; cur++) {
			int iPri, iName;
			long lBuffer, lChunk;
			char cMode[2];
			int match_count;

			if (!get_line(linebuf, sizeof linebuf, f))
				throw MyError("Failure reading stripe definition file");

			match_count = sscanf(linebuf, " %d %1s %ld %ld %n", &iPri, cMode, &lBuffer, &lChunk, &iName);

			if (match_count != 4)
				throw MyError("Stripe definition parse error: line %d", lineno);

			t = s = linebuf + iName;
			if (*s=='"') {
				++s, ++t;
				while(*t && *t!='\n' && *t!='"') ++t;
			} else
				while(*t && *t!='\n' && !isspace((unsigned char)*t)) ++t;

			if (t<=s)
				throw MyError("Stripe definition parse error: line %d -- no stripe filename!", lineno);

			switch(tolower(cMode[0])) {
			case 'm':	cMode[0] = AVIStripe::MODE_MASTER; break;
			case 'i':	cMode[0] = AVIStripe::MODE_INDEX; break;
			case 'v':	cMode[0] = AVIStripe::MODE_VIDEO; break;
			case 'a':	cMode[0] = AVIStripe::MODE_AUDIO; break;
			case 'b':	cMode[0] = AVIStripe::MODE_BOTH; break;
			default:
				throw MyError("Invalid stripe mode '%c'", cMode[0]);
			};

			// Allocate a stripe structure and copy the data into it

			if (!(stripe[cur] = new(t+1-s) AVIStripe))
				throw MyMemoryError();

			*t=0;

			stripe[cur]->lBufferSize = lBuffer;
			stripe[cur]->lChunkSize	= lChunk;
			stripe[cur]->iNameLen	= t+1-s;
			stripe[cur]->cStripeMode	= cMode[0];
			stripe[cur]->scPriority	= (signed char)iPri;
			strcpy(stripe[cur]->szName, s);

			++lineno;
		}
	} catch(...) {
		if (f) fclose(f);
		_destruct();
		throw;
	}
	fclose(f);
}
コード例 #19
0
/*
 * Checks if specified job name is in the printer's queue.
 * Returns:  negative (-1) if argument name is not in the queue.
 */
int
doarg(char *job)
{
	struct queue **qq;
	int jobnum, fd, n;
	char *cp, *machine;
	int cnt = 0;
	FILE *fp;

	/*
	 * Look for a job item consisting of system name, colon, number 
	 * (example: ucbarpa:114)  
	 */
	if ((cp = strchr(job, ':')) != NULL) {
		machine = job;
		*cp++ = '\0';
		job = cp;
	} else
		machine = NULL;

	/*
	 * Check for job specified by number (example: 112 or 235ucbarpa).
	 */
	if (isdigit(*job)) {
		jobnum = 0;
		do
			jobnum = jobnum * 10 + (*job++ - '0');
		while (isdigit(*job));
		for (qq = queue + nitems; --qq >= queue; ) {
			n = 0;
			for (cp = (*qq)->q_name+3; isdigit(*cp); )
				n = n * 10 + (*cp++ - '0');
			if (jobnum != n)
				continue;
			if (*job && strcmp(job, cp) != 0)
				continue;
			if (machine != NULL && strcmp(machine, cp) != 0)
				continue;
			if (touch(*qq) == 0) {
				printf("\tmoved %s\n", (*qq)->q_name);
				cnt++;
			}
		}
		return(cnt);
	}
	/*
	 * Process item consisting of owner's name (example: henry).
	 */
	for (qq = queue + nitems; --qq >= queue; ) {
		PRIV_START;
		fd = safe_open((*qq)->q_name, O_RDONLY|O_NOFOLLOW, 0);
		PRIV_END;
		if (fd < 0 || (fp = fdopen(fd, "r")) == NULL) {
			if (fd >= 0)
				close(fd);
			continue;
		}
		while (get_line(fp) > 0)
			if (line[0] == 'P')
				break;
		(void)fclose(fp);
		if (line[0] != 'P' || strcmp(job, line+1) != 0)
			continue;
		if (touch(*qq) == 0) {
			printf("\tmoved %s\n", (*qq)->q_name);
			cnt++;
		}
	}
	return(cnt);
}
コード例 #20
0
ファイル: parse.c プロジェクト: Vishv19/core
int find_includes(struct filepointer *filep, struct inclist *file, struct inclist *file_red, int recursion, boolean failOK, struct IncludesCollection* incCollection, struct symhash *symbols)
{
    register char   *line;
    register int    type;
    boolean recfailOK;

    while ((line = get_line(filep))) {
        switch(type = deftype(line, filep, file_red, file, TRUE, symbols)) {
        case IF:
        doif:
            type = find_includes(filep, file,
                file_red, recursion+1, failOK, incCollection, symbols);
            while ((type == ELIF) || (type == ELIFFALSE) ||
                   (type == ELIFGUESSFALSE))
                type = gobble(filep, file, file_red, symbols);
            if (type == ELSE)
                gobble(filep, file, file_red, symbols);
            break;
        case IFFALSE:
        case IFGUESSFALSE:
            doiffalse:
            if (type == IFGUESSFALSE || type == ELIFGUESSFALSE)
                recfailOK = TRUE;
            else
                recfailOK = failOK;
            type = gobble(filep, file, file_red, symbols);
            if (type == ELSE)
                find_includes(filep, file,
                      file_red, recursion+1, recfailOK, incCollection, symbols);
            else if (type == ELIF)
                goto doif;
            else if ((type == ELIFFALSE) || (type == ELIFGUESSFALSE))
                goto doiffalse;
            break;
        case IFDEF:
        case IFNDEF:
            if ((type == IFDEF && hash_lookup(line, symbols))
             || (type == IFNDEF && !hash_lookup(line, symbols))) {
                debug(1,(type == IFNDEF ?
                    "line %d: %s !def'd in %s via %s%s\n" : "",
                    filep->f_line, line,
                    file->i_file, file_red->i_file, ": doit"));
                type = find_includes(filep, file,
                    file_red, recursion+1, failOK, incCollection, symbols);
                while (type == ELIF || type == ELIFFALSE || type == ELIFGUESSFALSE)
                    type = gobble(filep, file, file_red, symbols);
                if (type == ELSE)
                    gobble(filep, file, file_red, symbols);
            }
            else {
                debug(1,(type == IFDEF ?
                    "line %d: %s !def'd in %s via %s%s\n" : "",
                    filep->f_line, line,
                    file->i_file, file_red->i_file, ": gobble"));
                type = gobble(filep, file, file_red, symbols);
                if (type == ELSE)
                    find_includes(filep, file,
                        file_red, recursion + 1, failOK, incCollection, symbols);
                else if (type == ELIF)
                        goto doif;
                else if (type == ELIFFALSE || type == ELIFGUESSFALSE)
                        goto doiffalse;
            }
            break;
        case ELSE:
        case ELIFFALSE:
        case ELIFGUESSFALSE:
        case ELIF:
            if (!recursion)
                gobble(filep, file, file_red, symbols);
        case ENDIF:
            if (recursion)
                return(type);
        case DEFINE:
            define(line, &symbols);
            break;
        case UNDEF:
            if (!*line) {
                warning("%s, line %d: incomplete undef == \"%s\"\n",
                file_red->i_file, filep->f_line, line);
                break;
            }
            hash_undefine(line, symbols);
            break;
        case INCLUDE:
            add_include(filep, file, file_red, line, FALSE, failOK, incCollection, symbols);
            break;
        case INCLUDEDOT:
            add_include(filep, file, file_red, line, TRUE, failOK, incCollection, symbols);
            break;
        case ERROR:
                warning("%s: %d: %s\n", file_red->i_file,
                 filep->f_line, line);
                break;

        case PRAGMA:
        case IDENT:
        case SCCS:
        case EJECT:
            break;
        case -1:
            warning("%s", file_red->i_file);
            if (file_red != file)
                warning1(" (reading %s)", file->i_file);
            warning1(", line %d: unknown directive == \"%s\"\n",
                 filep->f_line, line);
            break;
        case -2:
            warning("%s", file_red->i_file);
            if (file_red != file)
                warning1(" (reading %s)", file->i_file);
            warning1(", line %d: incomplete include == \"%s\"\n",
                 filep->f_line, line);
            break;
        }
    }
    return(-1);
}
コード例 #21
0
ファイル: tinyhttp.c プロジェクト: ywang2014/ProgramLearning
void execute_cgi(int client, const char *path, const char *method, const char *query_string)  
{  
    char buf[1024];  
    int cgi_output[2];  
    int cgi_input[2];  
    pid_t pid;  
    int status;  
    int i;  
    char c;  
    int numchars = 1;  
    int content_length = -1;  
  
    buf[0] = 'A'; buf[1] = '\0';  
    if (strcasecmp(method, "GET") == 0)  
        /*把所有的 HTTP header 读取并丢弃*/  
        while ((numchars > 0) && strcmp("\n", buf))  /* read & discard headers */  
            numchars = get_line(client, buf, sizeof(buf));  
    else    /* POST */  
    {  
        /* 对 POST 的 HTTP 请求中找出 content_length */  
        numchars = get_line(client, buf, sizeof(buf));  
        while ((numchars > 0) && strcmp("\n", buf))  
        {  
            /*利用 \0 进行分隔 */  
            buf[15] = '\0';  
            /* HTTP 请求的特点*/  
            if (strcasecmp(buf, "Content-Length:") == 0)  
                content_length = atoi(&(buf[16]));  
            numchars = get_line(client, buf, sizeof(buf));  
        }  
        /*没有找到 content_length */  
        if (content_length == -1) {  
            /*错误请求*/  
            bad_request(client);  
            return;  
        }  
    }  
  
    /* 正确,HTTP 状态码 200 */  
    sprintf(buf, "HTTP/1.0 200 OK\r\n");  
    send(client, buf, strlen(buf), 0);  
  
    /* 建立管道*/  
    if (pipe(cgi_output) < 0) {  
        /*错误处理*/  
        cannot_execute(client);  
        return;  
    }  
    /*建立管道*/  
    if (pipe(cgi_input) < 0) {  
        /*错误处理*/  
        cannot_execute(client);  
        return;  
    }  
  
    if ((pid = fork()) < 0 ) {  
        /*错误处理*/  
        cannot_execute(client);  
        return;  
    }  
    if (pid == 0)  /* child: CGI script */  
    {  
        char meth_env[255];  
        char query_env[255];  
        char length_env[255];  
  
        /* 把 STDOUT 重定向到 cgi_output 的写入端 */  
        dup2(cgi_output[1], 1);  
        /* 把 STDIN 重定向到 cgi_input 的读取端 */  
        dup2(cgi_input[0], 0);  
        /* 关闭 cgi_input 的写入端 和 cgi_output 的读取端 */  
        close(cgi_output[0]);  
        close(cgi_input[1]);  
        /*设置 request_method 的环境变量*/  
        sprintf(meth_env, "REQUEST_METHOD=%s", method);  
        putenv(meth_env);  
        if (strcasecmp(method, "GET") == 0) {  
            /*设置 query_string 的环境变量*/  
            sprintf(query_env, "QUERY_STRING=%s", query_string);  
            putenv(query_env);  
        }  
        else {   /* POST */  
            /*设置 content_length 的环境变量*/  
            sprintf(length_env, "CONTENT_LENGTH=%d", content_length);  
            putenv(length_env);  
        }  
        /*用 execl 运行 cgi 程序*/  
        execl(path, path, NULL);  
        exit(0);  
    } else {    /* parent */  
        /* 关闭 cgi_input 的读取端 和 cgi_output 的写入端 */  
        close(cgi_output[1]);  
        close(cgi_input[0]);  
        if (strcasecmp(method, "POST") == 0)  
            /*接收 POST 过来的数据*/  
            for (i = 0; i < content_length; i++) {  
                recv(client, &c, 1, 0);  
                /*把 POST 数据写入 cgi_input,现在重定向到 STDIN */  
                write(cgi_input[1], &c, 1);  
            }  
        /*读取 cgi_output 的管道输出到客户端,该管道输入是 STDOUT */  
        while (read(cgi_output[0], &c, 1) > 0)  
            send(client, &c, 1, 0);  
  
        /*关闭管道*/  
        close(cgi_output[0]);  
        close(cgi_input[1]);  
        /*等待子进程*/  
        waitpid(pid, &status, 0);  
    }  
}  
コード例 #22
0
ファイル: httpd.c プロジェクト: zw1510/HTTP
static void execut_cgi(int sock,const char* path,const char* method,const char* query_string)
{
		int content_len = -1;
		char buf[SIZE];
		memset(buf,'\0',sizeof(buf));
		int cgi_input[2];
		int cgi_output[2];
		
		printf("method: %s\n",method);


		if(strcasecmp(method,"GET") == 0)
		{
				clear_head(sock);
		}else  //POST
		{
				printf("aaaaaaaaaaaaaaaa\n");
				int ret = 0;
				do{
						ret = get_line(sock,buf,sizeof(buf));
						if(strncasecmp(buf,"Content-Length: ",16) == 0)
						{
								content_len = atoi(&buf[16]);				
						}
				}while((ret > 0) && strcmp(buf,"\n") != 0);
				printf("contlen:%d\n",content_len);
				if(content_len == -1)
				{
						echo_errno(sock,1);
						return ;
				}
		}
		if(pipe(cgi_output) < 0)
		{
			echo_errno(sock,1);
			return ;
		}
		if(pipe(cgi_input) < 0)
		{
			echo_errno(sock,1);
			return ;
		}

				
		sprintf(buf,"HTTP/1.0 200 OK\r\n\r\n");
		send(sock,buf,strlen(buf),0);
		pid_t id = fork();
		// 处理客户端请求
		if(id == 0)//child
		{
				close(cgi_input[1]);
				close(cgi_output[0]);
		
				dup2(cgi_input[0],0);
				dup2(cgi_output[1],1);
				
				sprintf(buf,"REQUEST_METHOD=%s",method);
				putenv(buf);

				if(strcasecmp(method,"GET") == 0)
				{
						sprintf(buf,"QUERY_STRING=%s",query_string);
						putenv(buf);
				}else
				{
						sprintf(buf,"CONTENT_LENGTH=%d",content_len);
						putenv(buf);
				}
				execl(path,path,NULL);
				exit(1);
		}else  //father
		{
				close(cgi_input[0]);
				close(cgi_output[1]);

				int i=0;
				char c = '\0';
				if(strcasecmp(method,"POST")==0)
				{
						printf("cccccccccccc\n");
						for(;i < content_len;++i)
						{
								recv(sock,&c,1,0);
								write(cgi_input[1],&c,1);
						}
				}
				printf("\n");

				while(read(cgi_output[0],&c,1) > 0)
				{
						send(sock,&c,1,0);
				}

				waitpid(id,NULL,0);
				close(cgi_input[1]);
				close(cgi_output[0]);

		}
}
コード例 #23
0
ファイル: cooc.c プロジェクト: Sandy4321/ancient-stats
void process(FILE *f, word_info *old, int history,
	     hash_table kill_file, int sentence_bound)
{
    int i;
    int current, wrapped;

    current = 0;
    wrapped = 0;
    while (get_line(f, old[current].w) != EOF) {
	if (sentence_bound && strcmp("#S", old[current].w->contents) == 0) {
	    current = wrapped = 0;
	}
	else {
	    total_count++;
	    old[current].killed = (kill_file &&
				   find(kill_file, old[current].w->contents));

	    if (old[current].killed) {
		killed_count++;
	    }
	    else {
		hash_bucket p;

		p = intern_word(words, old[current].w->contents);
		p->value.i++;

		old[current].right = intern_word(right,
						 old[current].w->contents);
		for (i=0;i<current;i++) {
		    old[current].right->value.i++;
		    if (!old[i].killed) {
			if (print_pairs) {
			    printf("%s\t%s\n",
				   old[i].w->contents,
				   old[current].w->contents);
			}
			else {
			    count_in_cache(pairs,
					   old[i].right->s,
					   old[current].right->s);
			}
		    }
		}
		if (wrapped) {
		    for (i=current+1;i<history;i++) {
			old[current].right->value.i++;
			if (!old[i].killed) {
			    if (print_pairs) {
				printf("%s\t%s\n",
				       old[i].w->contents,
				       old[current].w->contents);
			    }
			    else {
				count_in_cache(pairs,
					   old[i].right->s,
					   old[current].right->s);
			    }
			}
		    }
		}
	    }
	    current++;
	    if (current == history) {
		wrapped = 1;
		current = 0;
	    }
	}
    }
}
コード例 #24
0
ファイル: httpd.c プロジェクト: zw1510/HTTP
static void * accept_request(void* arg)
{
	int sock = (int)arg;
	printf("%d\n",sock);
	char buf[SIZE];
	int ret = 0;
#ifdef _DEBUG_
	do
	{
			ret = get_line(sock,buf,size);
			printf("%s",buf);
			fflush(stdout);
	}while(ret > 0 && strcmp(buf,'\n'));
#endif
	char method[SIZE / 10];
	char url[SIZE];

	char* query_string = NULL;
	int cgi = 0;
	char path[SIZE];
	memset(method,'\0',sizeof(method));
	memset(url,'\0',sizeof(url));

	ret = get_line(sock,buf,sizeof(buf));
	if(ret < 0)
	{
			echo_errno(sock,1);
			return (void*)1;
	}
	printf("%s\n",buf);
	//1 get method
	//GET //xx//yy HTTP/1.1
	int i = 0;
	int j =0;
	while(i< sizeof(method) - 1 && !isspace(buf[j])  && j < sizeof(buf) )
	{
			method[i]=buf[j];
			++i;
			++j;
	}

	method[i] = '\0';

	//2 check method
	if(strcasecmp(method,"GET")!=0 && strcasecmp(method,"POST") != 0)
	{
			echo_errno(sock,1);
			return (void*)2;
	}

	//3 get url first step space
	while(isspace(buf[j]))
	{
			++j;
	}

	i=0;
	while(!isspace(buf[j])&& (i < sizeof(url)-1) && j < sizeof(buf))
	{
		url[i] = buf [j];
		++i;
		++j;

	}

	if(strcasecmp(method,"POST") == 0)
	{
			cgi = 1;
	}
	printf("method: %s,url_path :%s\n ",method,url);

	if(strcasecmp(method,"GET") == 0)
	{
			query_string = url;
			
	}

	char *start = url;
	while( *start != '\0')
	{
			if( *start == '?')
			{
					cgi = 1;
					*start = '\0';
					query_string = start+1;
					break;
			}

			++start;

	}
	sprintf(path,"htdoc%s",url);
	if(path[strlen(path)-1] == '/')
	{
			strcat(path,"index.html");
	}

	//
	printf("path:%s\n",path);
	printf("cgi:%d\n",cgi);
	//method,query_string,cgi,path
	struct stat st;
	if(stat(path,&st) < 0)//default -> htdoc/index.html
	{
			printf("stat error\n");
			echo_errno(sock,1);
			return (void*)-3;
			
	}
	else
	{
			if(S_ISDIR(st.st_mode))
			{
					strcpy(path,"htdoc/index.html");
			}
			if(( st.st_mode & S_IXGRP)||\
					( st.st_mode & S_IXGRP)||\
					st.st_mode & S_IXOTH)
			{
					cgi = 1;
			}
			else
			{}

			//path cgi
			if(cgi)
			{
					printf("cgi mode\n");
					execut_cgi(sock,path,method,query_string);
			}
			else// 请求首页内容
			{
					clear_head(sock);
					echo_www(sock,path,st.st_size);
			}
	}

	close(sock);   //no face link
	return (void*) 0;
}
コード例 #25
0
ファイル: nconf.gui.c プロジェクト: AlexShiLucky/linux
/* get the message, and buttons.
 * each button must be a char*
 * return the selected button
 *
 * this dialog is used for 2 different things:
 * 1) show a text box, no buttons.
 * 2) show a dialog, with horizontal buttons
 */
int btn_dialog(WINDOW *main_window, const char *msg, int btn_num, ...)
{
	va_list ap;
	char *btn;
	int btns_width = 0;
	int msg_lines = 0;
	int msg_width = 0;
	int total_width;
	int win_rows = 0;
	WINDOW *win;
	WINDOW *msg_win;
	WINDOW *menu_win;
	MENU *menu;
	ITEM *btns[btn_num+1];
	int i, x, y;
	int res = -1;


	va_start(ap, btn_num);
	for (i = 0; i < btn_num; i++) {
		btn = va_arg(ap, char *);
		btns[i] = new_item(btn, "");
		btns_width += strlen(btn)+1;
	}
	va_end(ap);
	btns[btn_num] = NULL;

	/* find the widest line of msg: */
	msg_lines = get_line_no(msg);
	for (i = 0; i < msg_lines; i++) {
		const char *line = get_line(msg, i);
		int len = get_line_length(line);
		if (msg_width < len)
			msg_width = len;
	}

	total_width = max(msg_width, btns_width);
	/* place dialog in middle of screen */
	y = (getmaxy(stdscr)-(msg_lines+4))/2;
	x = (getmaxx(stdscr)-(total_width+4))/2;


	/* create the windows */
	if (btn_num > 0)
		win_rows = msg_lines+4;
	else
		win_rows = msg_lines+2;

	win = newwin(win_rows, total_width+4, y, x);
	keypad(win, TRUE);
	menu_win = derwin(win, 1, btns_width, win_rows-2,
			1+(total_width+2-btns_width)/2);
	menu = new_menu(btns);
	msg_win = derwin(win, win_rows-2, msg_width, 1,
			1+(total_width+2-msg_width)/2);

	set_menu_fore(menu, attributes[DIALOG_MENU_FORE]);
	set_menu_back(menu, attributes[DIALOG_MENU_BACK]);

	(void) wattrset(win, attributes[DIALOG_BOX]);
	box(win, 0, 0);

	/* print message */
	(void) wattrset(msg_win, attributes[DIALOG_TEXT]);
	fill_window(msg_win, msg);

	set_menu_win(menu, win);
	set_menu_sub(menu, menu_win);
	set_menu_format(menu, 1, btn_num);
	menu_opts_off(menu, O_SHOWDESC);
	menu_opts_off(menu, O_SHOWMATCH);
	menu_opts_on(menu, O_ONEVALUE);
	menu_opts_on(menu, O_NONCYCLIC);
	set_menu_mark(menu, "");
	post_menu(menu);


	touchwin(win);
	refresh_all_windows(main_window);
	while ((res = wgetch(win))) {
		switch (res) {
		case KEY_LEFT:
			menu_driver(menu, REQ_LEFT_ITEM);
			break;
		case KEY_RIGHT:
			menu_driver(menu, REQ_RIGHT_ITEM);
			break;
		case 10: /* ENTER */
		case 27: /* ESCAPE */
		case ' ':
		case KEY_F(F_BACK):
		case KEY_F(F_EXIT):
			break;
		}
		touchwin(win);
		refresh_all_windows(main_window);

		if (res == 10 || res == ' ') {
			res = item_index(current_item(menu));
			break;
		} else if (res == 27 || res == KEY_F(F_BACK) ||
				res == KEY_F(F_EXIT)) {
			res = KEY_EXIT;
			break;
		}
	}

	unpost_menu(menu);
	free_menu(menu);
	for (i = 0; i < btn_num; i++)
		free_item(btns[i]);

	delwin(win);
	return res;
}
コード例 #26
0
ファイル: ctie-k.c プロジェクト: luigiScarso/mflua
int main P2C(int,argc,string*,argv)
#line 104 "./ctie.w"
{
#line 38 "./ctie-k.ch"
/*5:*/
#line 84 "./ctie-k.ch"

kpse_set_program_name(argv[0],"ctie");

/*:5*/
#line 38 "./ctie-k.ch"
;
/*19:*/
#line 300 "./ctie.w"

actual_input= 0;
out_mode= normal;

/*:19*/
#line 39 "./ctie-k.ch"
;
#line 106 "./ctie.w"
/*63:*/
#line 1135 "./ctie.w"

{
if(argc> max_file_index+5-1)usage_error();
no_ch= -1;
while(--argc> 0){
argv++;
if(strcmp("-help",*argv)==0||strcmp("--help",*argv)==0)
/*66:*/
#line 1202 "./ctie.w"

usage_help();



/*:66*/
#line 1142 "./ctie.w"
;
if(strcmp("-version",*argv)==0||strcmp("--version",*argv)==0)
/*67:*/
#line 1208 "./ctie.w"

{
print_version_and_exit("CTIE",version_number);

}


/*:67*/
#line 1144 "./ctie.w"
;
if(**argv=='-')/*64:*/
#line 1158 "./ctie.w"

if(prod_chf!=unknown)usage_error();
else
switch(*(*argv+1)){
case'c':case'C':prod_chf= chf;break;
case'm':case'M':prod_chf= master;break;
default:usage_error();
}


/*:64*/
#line 1145 "./ctie.w"

else/*65:*/
#line 1172 "./ctie.w"

{
if(no_ch==(-1)){
out_name= *argv;
}else{
register input_description*inp_desc;

inp_desc= (input_description*)malloc(sizeof(input_description));
if(inp_desc==NULL)
fatal_error(-1,"! No memory for input descriptor","");

inp_desc->mode= search;
inp_desc->line= 0;
inp_desc->type_of_file= chf;
inp_desc->limit= inp_desc->buffer;
inp_desc->buffer[0]= ' ';
inp_desc->loc= inp_desc->buffer+1;
inp_desc->buffer_end= inp_desc->buffer+buf_size-2;
inp_desc->file_name= *argv;
inp_desc->current_include= NULL;
input_organisation[no_ch]= inp_desc;
}
no_ch++;
}


/*:65*/
#line 1146 "./ctie.w"

}
if(no_ch<=0||prod_chf==unknown)usage_error();
}


/*:63*/
#line 106 "./ctie.w"

/*62:*/
#line 1118 "./ctie.w"

#line 382 "./ctie-k.ch"
{
extern KPSEDLL string kpathsea_version_string;
printf("%s (%s)\n",banner,kpathsea_version_string);
}
#line 1120 "./ctie.w"
printf("%s\n",copyright);


/*:62*/
#line 107 "./ctie.w"
;
/*42:*/
#line 277 "./ctie-k.ch"

{
string fullname;

fullname= kpse_find_cweb(input_organisation[0]->file_name);
if(fullname)
input_organisation[0]->the_file= fopen(fullname,"r");

if(fullname==NULL||input_organisation[0]->the_file==NULL){
if(fullname){
pfatal_error("! Cannot open master file ",
input_organisation[0]->file_name);
}else{
fatal_error(-1,"! Cannot find master file ",
input_organisation[0]->file_name);
}
}
else free(fullname);


#line 759 "./ctie.w"
printf("(%s)\n",input_organisation[0]->file_name);
input_organisation[0]->type_of_file= master;
get_line(0,true);
}


/*:42*/
#line 108 "./ctie.w"

/*43:*/
#line 313 "./ctie-k.ch"

{
file_index i;
string fullname;

i= 1;
while(i<no_ch){
fullname= kpse_find_cweb(input_organisation[i]->file_name);
if(fullname)
input_organisation[i]->the_file= fopen(fullname,"r");

if(fullname==NULL||input_organisation[i]->the_file==NULL){
if(fullname){
pfatal_error("! Cannot open change file ",
input_organisation[i]->file_name);
}else{
fatal_error(-1,"! Cannot find change file ",
input_organisation[i]->file_name);
}
}
else free(fullname);


#line 780 "./ctie.w"
printf("(%s)\n",input_organisation[i]->file_name);
init_change_file(i);
i++;
}
}


/*:43*/
#line 109 "./ctie.w"

/*40:*/
#line 729 "./ctie.w"

{
out_file= fopen(out_name,"w");
if(out_file==NULL){
pfatal_error("! Cannot open/create output file","");

}
}


/*:40*/
#line 110 "./ctie.w"

/*59:*/
#line 1074 "./ctie.w"

actual_input= 0;
input_has_ended= false;
while(input_has_ended==false||actual_input!=0)
/*51:*/
#line 917 "./ctie.w"

{
file_index test_file;

/*52:*/
#line 934 "./ctie.w"

{
register input_description*inp_desc;
while(actual_input> 0&&e_of_ch_module(actual_input)){
inp_desc= input_organisation[actual_input];
if(inp_desc->type_of_file==master){

fatal_error(-1,"! This can't happen: change file is master file","");

}
inp_desc->mode= search;
init_change_file(actual_input);
while((input_organisation[actual_input]->mode!=reading
&&actual_input> 0))
actual_input--;
}
}


/*:52*/
#line 921 "./ctie.w"

if(input_has_ended&&actual_input==0)break;
/*53:*/
#line 960 "./ctie.w"

test_input= none;
test_file= actual_input;
while(test_input==none&&test_file<no_ch-1){
test_file++;
switch(input_organisation[test_file]->mode){
case search:
if(lines_dont_match(actual_input,test_file)==false){
input_organisation[test_file]->mode= test;
test_input= test_file;
}
break;
case test:
if(lines_dont_match(actual_input,test_file)){

input_organisation[test_file]->dont_match++;
}
test_input= test_file;
break;
case reading:
break;
case ignore:
break;
}
}


/*:53*/
#line 923 "./ctie.w"

/*54:*/
#line 993 "./ctie.w"

if(prod_chf==chf){
while(1){
/*55:*/
#line 1007 "./ctie.w"

if(out_mode==normal){
if(test_input!=none){
fprintf(out_file,"@x\n");
out_mode= pre;
}else break;
}


/*:55*/
#line 996 "./ctie.w"

/*56:*/
#line 1021 "./ctie.w"

if(out_mode==pre){
if(test_input==none){
fprintf(out_file,"@y\n");
out_mode= post;
}else{
if(input_organisation[actual_input]->type_of_file==master)
put_line(actual_input);
break;
}
}


/*:56*/
#line 997 "./ctie.w"

/*57:*/
#line 1040 "./ctie.w"

if(out_mode==post){
if(input_organisation[actual_input]->type_of_file==chf){
if(test_input==none)put_line(actual_input);
break;
}else{
fprintf(out_file,"@z\n\n");
out_mode= normal;
}
}


/*:57*/
#line 998 "./ctie.w"

}
}else
if(test_input==none)put_line(actual_input);


/*:54*/
#line 924 "./ctie.w"

/*58:*/
#line 1055 "./ctie.w"

get_line(actual_input,true);
if(test_input!=none){
get_line(test_input,true);
if(e_of_ch_preamble(test_input)==true){
get_line(test_input,true);
input_organisation[test_input]->mode= reading;
actual_input= test_input;
test_input= none;
}
}


/*:58*/
#line 925 "./ctie.w"

}


/*:51*/
#line 1078 "./ctie.w"

if(out_mode==post)
fprintf(out_file,"@z\n");


/*:59*/
#line 111 "./ctie.w"

/*60:*/
#line 1087 "./ctie.w"

{
file_index i;

for(i= 1;i<no_ch;i++){
if(input_organisation[i]->mode!=ignore){
input_organisation[i]->loc= input_organisation[i]->buffer;
err_print(i,"! Change file entry did not match");

}
}
}


/*:60*/
#line 112 "./ctie.w"

exit(wrap_up());
}
コード例 #27
0
ファイル: nconf.gui.c プロジェクト: AlexShiLucky/linux
/* layman's scrollable window... */
void show_scroll_win(WINDOW *main_window,
		const char *title,
		const char *text)
{
	int res;
	int total_lines = get_line_no(text);
	int x, y, lines, columns;
	int start_x = 0, start_y = 0;
	int text_lines = 0, text_cols = 0;
	int total_cols = 0;
	int win_cols = 0;
	int win_lines = 0;
	int i = 0;
	WINDOW *win;
	WINDOW *pad;
	PANEL *panel;

	getmaxyx(stdscr, lines, columns);

	/* find the widest line of msg: */
	total_lines = get_line_no(text);
	for (i = 0; i < total_lines; i++) {
		const char *line = get_line(text, i);
		int len = get_line_length(line);
		total_cols = max(total_cols, len+2);
	}

	/* create the pad */
	pad = newpad(total_lines+10, total_cols+10);
	(void) wattrset(pad, attributes[SCROLLWIN_TEXT]);
	fill_window(pad, text);

	win_lines = min(total_lines+4, lines-2);
	win_cols = min(total_cols+2, columns-2);
	text_lines = max(win_lines-4, 0);
	text_cols = max(win_cols-2, 0);

	/* place window in middle of screen */
	y = (lines-win_lines)/2;
	x = (columns-win_cols)/2;

	win = newwin(win_lines, win_cols, y, x);
	keypad(win, TRUE);
	/* show the help in the help window, and show the help panel */
	(void) wattrset(win, attributes[SCROLLWIN_BOX]);
	box(win, 0, 0);
	(void) wattrset(win, attributes[SCROLLWIN_HEADING]);
	mvwprintw(win, 0, 3, " %s ", title);
	panel = new_panel(win);

	/* handle scrolling */
	do {

		copywin(pad, win, start_y, start_x, 2, 2, text_lines,
				text_cols, 0);
		print_in_middle(win,
				text_lines+2,
				0,
				text_cols,
				"<OK>",
				attributes[DIALOG_MENU_FORE]);
		wrefresh(win);

		res = wgetch(win);
		switch (res) {
		case KEY_NPAGE:
		case ' ':
		case 'd':
			start_y += text_lines-2;
			break;
		case KEY_PPAGE:
		case 'u':
			start_y -= text_lines+2;
			break;
		case KEY_HOME:
			start_y = 0;
			break;
		case KEY_END:
			start_y = total_lines-text_lines;
			break;
		case KEY_DOWN:
		case 'j':
			start_y++;
			break;
		case KEY_UP:
		case 'k':
			start_y--;
			break;
		case KEY_LEFT:
		case 'h':
			start_x--;
			break;
		case KEY_RIGHT:
		case 'l':
			start_x++;
			break;
		}
		if (res == 10 || res == 27 || res == 'q' ||
			res == KEY_F(F_HELP) || res == KEY_F(F_BACK) ||
			res == KEY_F(F_EXIT))
			break;
		if (start_y < 0)
			start_y = 0;
		if (start_y >= total_lines-text_lines)
			start_y = total_lines-text_lines;
		if (start_x < 0)
			start_x = 0;
		if (start_x >= total_cols-text_cols)
			start_x = total_cols-text_cols;
	} while (res);

	del_panel(panel);
	delwin(win);
	refresh_all_windows(main_window);
}
コード例 #28
0
ファイル: location_gui.c プロジェクト: Xastir/Xastir
void location_delete(/*@unused@*/ Widget w, /*@unused@*/ XtPointer clientData, /*@unused@*/ XtPointer callData) {
    int i,x;
    char *location;
    XmString *list;
    int found,ok;
    FILE *f,*fout;
    char temp[200];
    char name[100];
    char pos[100];
    char *temp_ptr;
    char filen[400];
    char filen_bak[400];
    char location_file_path[MAX_VALUE];
    char location_sys_path[MAX_VALUE];

    get_user_base_dir("config/locations.sys", location_file_path, 
                      sizeof(location_file_path));
    get_user_base_dir("config/locations.sys-tmp", location_sys_path, 
                      sizeof(location_sys_path));

    found=0;
    ok=0;
    XtVaGetValues(location_list,XmNitemCount,&i,XmNitems,&list,NULL);

    for (x=1; x<=i;x++) {
        if (XmListPosSelected(location_list,x)) {
            found=1;
            if (XmStringGetLtoR(list[(x-1)],XmFONTLIST_DEFAULT_TAG,&location)) {
                XmListDeletePos(location_list,x);
                x=i+1;
            }
        }
    }
    if(found) {
        f=fopen(location_file_path,"r");
        if (f!=NULL) {
            fout=fopen(location_sys_path,"a");
            if (fout!=NULL) {
                while (!feof(f)) {
                    (void)get_line(f,temp,200);
                    if (!feof(f) && strlen(temp)>8) {
                        temp_ptr=strtok(temp,"|");  /* get the name */
                        if (temp_ptr!=NULL) {
                            xastir_snprintf(name,
                                sizeof(name),
                                "%s",
                                temp);
                            temp_ptr=strtok(NULL,"|");  /* get the pos */
                            xastir_snprintf(pos,
                                sizeof(pos),
                                "%s",
                                temp_ptr);
                            if (strcmp(location,name)!=0) {
                                fprintf(fout,"%s|%s\n",name,pos);
                            }
                        }
                    }
                }
                (void)fclose(fout);
                ok=1;
            }
            else
              fprintf(stderr,"Couldn't open file: %s\n", location_sys_path );

            (void)fclose(f);
        }
        else {
            fprintf(stderr,"Couldn't open file: %s\n", location_file_path );
        }
        XtFree(location);
    }

    if (ok==1){

        xastir_snprintf(filen,
            sizeof(filen),
            "%s",
            location_file_path);

        xastir_snprintf(filen_bak,
            sizeof(filen_bak),
            "%s",
            location_sys_path);

        (void)unlink(filen);
        (void)rename(filen_bak,filen);
    }

}
コード例 #29
0
ファイル: get_param.c プロジェクト: visintainer/Epi
int get_param(char file[], char sep){
  int out_get_line=2;
  char * line;
  char * string_who;
  char * string_value;
  FILE *fp;
  string_who = (char *)calloc(100,sizeof(char));
  string_value = (char *)calloc(100,sizeof(char));
  if(!(fp = fopen(file,"r"))){
    printf("merda! in get param\n");
    return 1;
  }
  while(out_get_line>=2){
    out_get_line=get_line(&line,fp);
    if(out_get_line<3){
      switch(out_get_line){
      case 2:
	fprintf(stderr,"read_param: line of file %s does not end in newline\n",file);
	break;
      case 1:
	fprintf(stderr,"read_param: file %s contains an empty line\n",file);
	return 1;
	break;
      case 0:
	fclose(fp);
	return 0;
	break;
      case -1:
	fprintf(stderr,"read_param: get_line error on file %s\n",
		file);
	return 1;
      default:
	fprintf(stderr,"read_param: unrecognized exit status of get_line on file %s\n",file);
	return 1;
	break;
      }
    }
    sscanf(line,"%s", string_who);
    line = (char *)strchr(line, sep);
    line++;
    sscanf(line,"%s", string_value);
    if(strcmp(string_who,"N")==0)
      N = atoi(string_value);
    if(strcmp(string_who,"NI")==0)
      NI = atoi(string_value);
    if(strcmp(string_who,"ALPHAstart")==0)
      ALPHAstart = atof(string_value);
    if(strcmp(string_who,"BETAstart")==0)
      BETAstart = atof(string_value);
    if(strcmp(string_who,"DURATIONstart")==0)
      DURATIONstart = atof(string_value);
    if(strcmp(string_who,"IMMUNEstart")==0)
      IMMUNEstart = atof(string_value);
    if(strcmp(string_who,"iter")==0)
      ITER = atoi(string_value);
    if(strcmp(string_who,"sigmaALPHA")==0)
      sigmaALPHA = atof(string_value);
    if(strcmp(string_who,"sigmaBETA")==0)
      sigmaBETA = atof(string_value);
    if(strcmp(string_who,"sigmaDURATION")==0)
      sigmaDURATION = atof(string_value);
    if(strcmp(string_who,"sigmaIMMUNE")==0)
      sigmaIMMUNE = atof(string_value);
    if(strcmp(string_who,"lat")==0)
      LAT = atof(string_value);
    if(strcmp(string_who,"firstPROXY")==0)
      firstPROXY = atoi(string_value);
    if(strcmp(string_who,"lastPROXY")==0)
      lastPROXY = atoi(string_value);
    if(strcmp(string_who,"firstILI")==0){
      firstILI = atoi(string_value);
      /* int i=6; */
      /* fprintf(stderr,"in mcmc AS[%d]=%d\n",i,firstILI); */
    }
  }
 
  return 0;
}
コード例 #30
0
ファイル: exons_files_v2.c プロジェクト: doricke/RepairShop
main ()
{
  int     count;	/* bases printed */
  long    index;        /* line index */
  t_text  trapped;	/* trapped exons sequence file */
  t_text  sequence;	/* trapped exon sequence */
  FILE    *fopen ();	/* file open function */


  printf ( "This is the Trapped_Exons->files program.\n\n" );

  /* Prompt for the input file name. */
  prompt_file ( &trapped, "What is the Trapped Exons file name?" );

  /* Process the sequences. */
  while ( trapped.eof != TRUE )
  {
    /* Open the sequence output file. */
    strcpy ( sequence.name, trapped.token );

    if ( strlen ( sequence.name ) < 2 )
      sequence.data = NULL;
    else
      sequence.data = fopen ( sequence.name, "w" );

    if ( ( trapped.eof != TRUE ) && ( sequence.data != NULL ) )
    {
      printf ( "%s\n", sequence.name );

      /* Check for newline separator. */
      if ( strlen ( trapped.line ) <= 10 )
        get_line ( &trapped );

      get_line ( &trapped );

      /* Copy the sequence file. */
      count = 0;
      for ( index = 0; (index < MAX_LINE) && 
          (trapped.line [ index ] != '\0'); index++ )
      { 
        if ( ( trapped.line [ index ] != '\t' ) &&
             ( trapped.line [ index ] != ' ' ) )
        {
          fprintf ( sequence.data, "%c", trapped.line [ index ] );

          count++;
        }  /* if */

        if ( ( ( count % 50 ) == 0 ) && ( count > 1 ) )
        {
          fprintf ( sequence.data, "\n" );

          count = 0;
        }  /* if */
      }  /* for */

      fprintf ( sequence.data, "\n" );
      fclose ( sequence.data );
    }  /* if */

    /* Get the trapped exon name and sequence. */
    get_line ( &trapped );
  }  /* while */

  printf ( "\nEnd of Trapped Exons->files program.\n" );
}  /* main */