Ejemplo n.º 1
0
static void decode_rgb_frame(FFV1Context *s, uint8_t *src[3], int w, int h, int stride[3])
{
    int x, y, p;
    int16_t *sample[4][2];
    int lbd    = s->avctx->bits_per_raw_sample <= 8;
    int bits   = s->avctx->bits_per_raw_sample > 0 ? s->avctx->bits_per_raw_sample : 8;
    int offset = 1 << bits;

    for (x = 0; x < 4; x++) {
        sample[x][0] = s->sample_buffer +  x * 2      * (w + 6) + 3;
        sample[x][1] = s->sample_buffer + (x * 2 + 1) * (w + 6) + 3;
    }

    s->run_index = 0;

    memset(s->sample_buffer, 0, 8 * (w + 6) * sizeof(*s->sample_buffer));

    for (y = 0; y < h; y++) {
        for (p = 0; p < 3 + s->transparency; p++) {
            int16_t *temp = sample[p][0]; // FIXME: try a normal buffer

            sample[p][0] = sample[p][1];
            sample[p][1] = temp;

            sample[p][1][-1]= sample[p][0][0  ];
            sample[p][0][ w]= sample[p][0][w-1];
            if (lbd && s->slice_coding_mode == 0)
                decode_line(s, w, sample[p], (p + 1)/2, 9);
            else
                decode_line(s, w, sample[p], (p + 1)/2, bits + (s->slice_coding_mode != 1));
        }
        for (x = 0; x < w; x++) {
            int g = sample[0][1][x];
            int b = sample[1][1][x];
            int r = sample[2][1][x];
            int a = sample[3][1][x];

            if (s->slice_coding_mode != 1) {
                b -= offset;
                r -= offset;
                g -= (b * s->slice_rct_by_coef + r * s->slice_rct_ry_coef) >> 2;
                b += g;
                r += g;
            }

            if (lbd)
                *((uint32_t*)(src[0] + x*4 + stride[0]*y)) = b + (g<<8) + (r<<16) + (a<<24);
            else {
                *((uint16_t*)(src[0] + x*2 + stride[0]*y)) = b;
                *((uint16_t*)(src[1] + x*2 + stride[1]*y)) = g;
                *((uint16_t*)(src[2] + x*2 + stride[2]*y)) = r;
            }
        }
    }
Ejemplo n.º 2
0
void
create_piece_xpm (char *outname, FILE *fpin, int W, int H)
{
  FILE *fpout;
  int w, h, i, j, c;
  unsigned char *lump, *p, *line;
  long size;
  z2xpm *cv;
  
  fpout = fopen( outname, "wb" );
  if ( !fpout )
	fatal( "Can't create output file.");

  /* Header is two ints -- Width then Height, x86 format */
  c = fgetc( fpin );
  w = (fgetc(fpin) << 8) | c;

  c = fgetc( fpin );
  h = (fgetc(fpin) << 8) | c;
  
  ++w; ++h;

  if ( w != W || h != H )
	fatal( "Bad header." );	  

  size = vga_imagesize( w, h ) - 4;
  lump = (unsigned char*)malloc( size );
  line = (unsigned char*)malloc( w );

  if ( !lump || !line )
	fatal( "Out of memory." );

  fread( lump, 1, size, fpin );

  /* Write XPM header */
  write_xpm_header( fpout, w, h );

  p = lump;
  
  /* Write XPM data */
  for( i=0; i<h; ++i )
	{
	  p = decode_line( line, p, w );
	  
	  fprintf( fpout, "\"" );
	  for( j=0; j<w; ++j )
		{
		  cv = lookup_xpm_color( line[j] );
		  fprintf( fpout, "%c", cv->xchar );
		}
	  fprintf( fpout, "\",\n" );
	}

  fprintf( fpout, "};\n" );
  
  free( lump );
  free( line );
  fclose( fpout );
}
Ejemplo n.º 3
0
void decode_polygon(uint8_t byte_order, InputIterator& in_itr, std::ostringstream& out_stream)
{
  out_stream << "(";
  for (uint32_t i(0), count(brig::detail::ogc::read<uint32_t>(byte_order, in_itr)); i < count; ++i)
  {
    if (i > 0) out_stream << ", ";
    decode_line(byte_order, in_itr, out_stream);
  }
  out_stream << ")";
}
Ejemplo n.º 4
0
static void decode_plane(FFV1Context *s, uint8_t *src,
                         int w, int h, int stride, int plane_index,
                         int pixel_stride)
{
    int x, y;
    int16_t *sample[2];
    sample[0] = s->sample_buffer + 3;
    sample[1] = s->sample_buffer + w + 6 + 3;

    s->run_index = 0;

    memset(s->sample_buffer, 0, 2 * (w + 6) * sizeof(*s->sample_buffer));

    for (y = 0; y < h; y++) {
        int16_t *temp = sample[0]; // FIXME: try a normal buffer

        sample[0] = sample[1];
        sample[1] = temp;

        sample[1][-1] = sample[0][0];
        sample[0][w]  = sample[0][w - 1];

// { START_TIMER
        if (s->avctx->bits_per_raw_sample <= 8) {
            decode_line(s, w, sample, plane_index, 8);
            for (x = 0; x < w; x++)
                src[x*pixel_stride + stride * y] = sample[1][x];
        } else {
            decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);
            if (s->packed_at_lsb) {
                for (x = 0; x < w; x++) {
                    ((uint16_t*)(src + stride*y))[x*pixel_stride] = sample[1][x];
                }
            } else {
                for (x = 0; x < w; x++) {
                    ((uint16_t*)(src + stride*y))[x*pixel_stride] = sample[1][x] << (16 - s->avctx->bits_per_raw_sample);
                }
            }
        }
// STOP_TIMER("decode-line") }
    }
}
Ejemplo n.º 5
0
/*--------------------------------------------------------------------*/
INT read_job_file(FILE * pF, INT action, CAMAC **job, char *name)
{
   DWORD n;
   char line[128];
   CAMAC *pjob;

   if (action == CHECK) {
      if (*name == 0)
         sprintf(name, "%s", job_name);
      pF = fopen(name, "r");
      if (pF) {
         fclose(pF);
         return JOB;
      }
      printf("CNAF-I- File not found :%s\n", name);
      return SKIP;
   } else if (action == READ) {
      pF = fopen(name, "r");
      if (pF) {
         n = 0;
         /* count the total number of line */
         while (fgets(line, 128, pF))
            n++;
         /* allocate memory for full job */
         *job = malloc((n + 1) * sizeof(CAMAC));
         pjob = *job;
         /* preset the full job with 0 */
         memset((char *) pjob, 0, (n + 1) * sizeof(CAMAC));
         /* preset the first entry with the predefined CAMAC access */
         memcpy((char *) pjob, (char *) Prompt, sizeof(CAMAC));
         rewind(pF);
         while (fgets(line, 128, pF)) {
            if (pjob->m == 0) {
               /* load previous command before overwriting */
               memcpy((char *) pjob, (char *) (pjob - 1), sizeof(CAMAC));
            }
            decode_line(pjob++, line);
         }
         fclose(pF);
         return JOB;
      }
   } else
      printf("CNAF-I- Cmd not found :%s\n", name);
   return SKIP;
}
Ejemplo n.º 6
0
int main(){
  char buf[80];
  char *p;
  int head;
  int key;
  char *tokp;
  int toklen;

  while (gets(buf)){
    head = 0;
    key = -1;
    p = buf;
    printf("==>%s\n", p);
    while(chop_slen(&p, &len, &tokp, &toklen)){
      if (key = test_the(tokp, toklen) > -1) break;
      if (key = test_this_(tokp, toklen) > -1) break;
      if (key = test_that_(tokp, toklen) > -1) break;
      if (key = test_this(tokp, toklen) > -1) break;
      if (key = test_that(tokp, toklen) > -1) break;
    }
    decode_line(buf, key);
  }
  return 0;
}
Ejemplo n.º 7
0
Archivo: more.c Proyecto: wtj/formosa
int ShowArticle(char *filename, BOOL body_only, BOOL process)
{   /* body only .. */
    FILE *fp;
    char *p, *data;
    BOOL inHeader = TRUE;

#ifdef PARSE_ANSI
    char *HTMLColor[] =
    {   "000000", "8f0000", "008f00", "8f8f00", "00008f", "8f008f", "008f8f", "cfcfcf",
        /* HiColor */
        "8f8f8f", "ff0000", "00ff00", "ffff00", "0000ff", "ff00ff", "00ffff", "ffffff"
    };

    char *BgColor[] =
    {"000000", "a00000", "00a000", "a0a000", "0000a0", "a000a0", "00a0a0", "cfcfcf"};

    int font_fg_color, font_bg_color;
    BOOL font_hilight, font_blink;
    static char ANSI[] = "\033[";	/* lthuang */
    char FontStr[STRLEN];
#endif
#ifdef PARSE_HYPERLINK
    HYPER_LINK hlink[] =
    {
        /*
           format:
           hyperlink keyword, keyword length, hyperlink legal character , open target
         */

        {"http", 4, "./:~?'=-_!&#%*+@\\", " TARGET=\"new\""},
        {"ftp", 3, "./:@-_&%", " TARGET=\"new\""},
        {"news", 4, "./:", "\0"},
        {"telnet", 6, ".:", "\0"},
        {"gopher", 6, ".:/", "\0"}
    };
#endif
    char pbuf[2048], buffer[2028];

#ifdef PARSE_ANSI
    int	color_set_count = 0, reset_ansi = FALSE;
    font_fg_color = font_bg_color = 0;
    font_hilight = font_blink = FALSE;
#endif
    if ((fp = fopen(filename, "r")) == NULL)
        return FALSE;

    if (!process && !body_only)
    {
        if (strstr(skin_file->filename, HTML_SkinModify))
        {
            while (fgets(pbuf, sizeof(pbuf), fp))
            {
                if ((p = strchr(pbuf, '\n')) != NULL)
                    *p = '\0';
                data = pbuf;

                /* find </TEXTAREA> */
                if ((p = strstr(data, "</")) != NULL
                        && !strncasecmp(p + 2, "TEXTAREA>", 9))
                {
                    *p = '\0';
                    fprintf(fp_out, "%s</TEXT-AREA>", data);
                    data = p + 11;	/* strlen("</TEXTAREA>") */
                }
                else
                    fprintf(fp_out, "%s\n", data);
            }
        }
        else
        {
            int size;
            while ((size = fread(pbuf, 1, sizeof(pbuf), fp)) != 0)
                fwrite(pbuf, 1, size, fp_out);
        }

        fclose(fp);
        return TRUE;
    }

    if (request_rec->URLParaType != PostRead
            && request_rec->URLParaType != TreaRead
            && request_rec->URLParaType != MailRead)
        inHeader = FALSE;

    while (fgets(pbuf, sizeof(pbuf), fp))
    {
        if ((p = strchr(pbuf, '\n')) != NULL)
            *p = '\0';

        buffer[0] = '\0';
        data = pbuf;

        if (inHeader && *data == '\0')
        {
            inHeader = FALSE;
            fprintf(fp_out, "\r\n");
            continue;
        }

        if (body_only)	/* skip article header and footer */
        {

            if (inHeader)
                continue;
#if 0
            /*
               break if find "--\r\n" when PostRead (signature below --)
               TreaRead and MailRead should continue
             */
            if (request_rec->URLParaType == PostRead && !strcmp(data, "--"))
                break;
#endif

            if (!process)
            {
                if (!strcmp(data, "--"))
                {
                    break;
                }
                else
                {
                    fprintf(fp_out, "%s\n", data);
                    continue;
                }
            }
        }

        if (inHeader)
        {
            souts(data, sizeof(pbuf));
        }

#ifdef QP_BASE64_DECODE
        if ((p = strstr(data, "=?")) != NULL)	/* content maybe encoded */
        {
            decode_line(buffer, data);
            xstrncpy(data, buffer, sizeof(pbuf));
            buffer[0] = '\0';
        }
#endif

#ifdef PARSE_ANSI
        /* search article content for ANSI CODE and convert to HTML code */
        while ((p = strstr(data, ANSI)) != NULL)
        {
            int i;
            char ansi_code[32];
            int color;
            int end = FALSE, skip = FALSE, set_fg_color = FALSE, set_bg_color = FALSE, had_set_bg_color = FALSE;
            char *ansi_str = ansi_code;

#if 0
            fprintf(fp_out, "<!--DATA=%s-->\n", data);
            fflush(fp_out);
#endif

            *p = '\0';
            p += 2;

            xstrcat(buffer, data, sizeof(buffer));

            for (i = 0; i < sizeof(ansi_code); i++)
                if (*(p + i) == 'm')
                    break;

            if (i >= sizeof(ansi_code))
            {
                fprintf(fp_out, "\r\n<!--BBS ANSI CODE FORMAT ERROR-->\r\n");
                data += 2;
                continue;
            }

            xstrncpy(ansi_str, p, i + 1);

#if 0
            {
                char buffer1[STRLEN];
                sprintf(buffer1, "<!--ANSI=%s LEN=%d-->", ansi_code, strlen(ansi_code));
                xstrcat(buffer, buffer1, sizeof(buffer));
            }
#endif

            data = p + i + 1;

            if (i == 0						/* case: \033[m */
                    || (i == 1 && *(p)=='0'))		/* case: \033[0m */
            {
#if 0
                set_bg_color = FALSE;
#endif
                font_fg_color = 7;
                font_bg_color = 0;
                font_hilight = FALSE;
                reset_ansi = TRUE;
            }

            /* parse ansi control code */

            while (*ansi_str)
            {
                if ((p = strchr(ansi_str, ';')) != NULL)
                    *p = 0x00;
                else
                    end = TRUE;

                color = atoi(ansi_str);
#if 0
                {
                    char buffer1[STRLEN];
                    sprintf(buffer1, "<!--token=%d-->", color);
                    xstrcat(buffer, buffer1, sizeof(buffer));
                }
#endif

                /* 1: hi light, 5: blink, 7: reverse */
                if (color == 0)
                {
                    font_fg_color = 7;
                    font_bg_color = 0;
                    font_hilight = FALSE;
                    reset_ansi = TRUE;
#if 0
                    set_bg_color = FALSE;
#endif
                }
                else if (color == 1)
                {
                    if(font_hilight==FALSE)
                    {
                        font_hilight = TRUE;
                        set_fg_color = TRUE;
                    }
                }
                else if (color == 5)
                {

                }
                else if (color == 7)
                {

                }
                else if (color >= 30 && color <= 37)	/* set fg color */
                {
                    if(font_fg_color != color - 30)
                    {
                        set_fg_color = TRUE;
                        font_fg_color = color - 30;
                    }
                }
                else if(color >= 40 && color <= 47)		/* set bg color */
                {
                    if(font_bg_color != color - 40)
                    {
                        set_bg_color = TRUE;
                        font_bg_color = color - 40;
                    }
                }
                else
                    skip = TRUE;

                if (end == FALSE)
                    ansi_str = p + 1;
                else
                    break;

            }

            if (skip == FALSE)
            {
                /* reset_ansi should return all </font>
                	and set new font attrib (if any) */
                if(reset_ansi == TRUE)
                {
                    while(color_set_count>0)
                    {
                        xstrcat(buffer, "</FONT>", sizeof(buffer));
                        color_set_count--;
                    }
                    reset_ansi = FALSE;
#if 0
                    continue;
#endif
                }

                if(set_bg_color == TRUE)
                {
                    sprintf(FontStr, "<FONT COLOR=\"#%s\" STYLE=\"Background-Color:#%s\">",
                            HTMLColor[font_fg_color + (font_hilight == TRUE ? 8 : 0)],
                            BgColor[font_bg_color]);
                    had_set_bg_color = TRUE;
                } else if(set_fg_color == TRUE) {
                    if(had_set_bg_color == TRUE)
                    {
                        /* reset bg-color style */
                        sprintf(FontStr, "<FONT COLOR=\"#%s\" STYLE=\"\">",
                                HTMLColor[font_fg_color + (font_hilight == TRUE ? 8 : 0)]);
                        had_set_bg_color = FALSE;
                    }
                    else
                    {
                        sprintf(FontStr, "<FONT COLOR=\"#%s\">",
                                HTMLColor[font_fg_color + (font_hilight == TRUE ? 8 : 0)]);
                    }
                    set_fg_color = FALSE;
                }
                else
                {
                    continue;
                }
                xstrcat(buffer, FontStr, sizeof(buffer));
                color_set_count++;
            }
        }

        xstrcat(buffer, data, sizeof(buffer));
        xstrncpy(pbuf, buffer, sizeof(pbuf));
        data = pbuf;
        buffer[0] = '\0';

#endif /* PARSE_ANSI */



#ifdef PARSE_HYPERLINK
#if 0
        printf("\n[");
        for (i = 0; i < strlen(data) + 10; i++)
            printf("%d,", data[i]);
        printf("]\n");
#endif
        while ((p = strstr(data, "://")) != NULL)
        {
            int type;

            for (type = 0; type < HyperLinkType; type++)
                if (!strncasecmp(p - (hlink[type].len), hlink[type].type, hlink[type].len))
                    break;

            /* exam article content for hyperlink */
            if (type < HyperLinkType)
            {
                p -= hlink[type].len;

                /*
                   ignore '<a href' HTML Tag
                   ie: <a href="http://www.nsysu.edu.tw"> www homepage</a>
                   ie: <a href=http://www.nsysu.edu.tw> www homepage</a>
                   ignore '<img src' HTML Tag
                   ie: <img src="http://www.nsysu.edu.tw/title.jpg">
                   ie: <img src=http://www.nsysu.edu.tw/title.jpg>
                   ignore '<body background' HTML Tag
                   ie: <body background="http://www.wow.org.tw/show/m-9.jpg"
                   ignore 'URL' HTML Tag
                 */
                if (!strncasecmp((p - 5), "href", 4)
                        || !strncasecmp((p - 6), "href", 4)
                        || !strncasecmp((p - 4), "src", 3)
                        || !strncasecmp((p - 5), "src", 3)
                        || !strncasecmp((p - 11), "background", 10)
                        || !strncasecmp((p - 12), "background", 10)
                        || !strncasecmp((p - 4), "URL=", 4))
                {
                    *(p + hlink[type].len + 2) = '\0';
                    fprintf(fp_out, "%s/", data);
                    data = p + hlink[type].len + 3;
                }
                else
                {
                    /* now, converting... */

                    char url[HTTP_REQUEST_LINE_BUF];
                    int i = hlink[type].len + 3; /* 3=strlen("://") */

                    while (((*(p + i) > 0x00)
                            && ((isalnum((int) *(p + i))
                                 || (strchr(hlink[type].allow, (int) *(p + i)) != NULL)))))
                    {
#if 0
                        printf("{%d}", *(p + i));
#endif
                        i++;
                    }

                    if (i > hlink[type].len + 3 && i < sizeof(url))
                    {
                        xstrncpy(url, p, i + 1);
#if 0
                        printf("[*p=%c,*(p+%d)=%d]", *p, i, *(p + i));
#endif
                        *p = '\0';
                        fprintf(fp_out, "%s<A HREF=\"%s\"%s>%s</A>", data, url, hlink[type].target, url);
                    }

                    data = p + i;
#if 0
                    printf("[data5=%d, %d, %d, %d, %d, %d, %d]\n", *(data - 4), *(data - 3), *(data - 2), *(data - 1), *data, *(data + 1), *(data + 2));
#endif

                }
            }
            else
            {
                *p = '\0';
                fprintf(fp_out, "%s://", data);
                data = p + 3;
            }
        }

#endif /* PARSE_HYPERLINK */

        fprintf(fp_out, "%s\n", data);
    }

    while(color_set_count>0)
    {
        xstrcat(buffer, "</FONT>", sizeof(buffer));
        color_set_count--;
    }

    fclose(fp);
    return TRUE;
}
Ejemplo n.º 8
0
static int
ListPostRecord(char *tag, BOARDHEADER * board, POST_FILE * pf, char *format, int start, int end)
{
	FORMAT_ARRAY format_array[32];
#ifdef USE_MMAP
	FILEHEADER *fip;
#endif
	int recidx, fd;
	FILEHEADER fileinfo;
	BOOL hasUpperDir = FALSE;
	char senderid[STRLEN], sender[STRLEN], date[STRLEN];
	char title[STRLEN + PATHLEN + 1];
	char UpperDir[PATHLEN];
	char *p;
	char *type;
	char *tags[6] = {"Num", "Sender", "Date", "Title", "SenderID", "READ"};
	char *strings[6];
	char recidx_string[10];


	if (request_rec->URLParaType == MailList && PSCorrect != Correct)
		return FALSE;

	if (pf->total_rec <= 0)
		return TRUE;

	if (strlen(format) == 0)
		return FALSE;

#if 11
	fprintf(fp_out, "\r\ntest[%s]!!<br>\r\n", pf->POST_NAME);
#endif

	/* set pf->POST_NAME to current dir */
	if ((p = strrchr(pf->POST_NAME, '/')) == NULL)
		return FALSE;	/* invalid format */
	*p = '\0';

	if ((fd = open(pf->POST_NAME, O_RDONLY)) < 0)
	{
		return FALSE;
	}

	/* check if treasure has upper dir */
	if (request_rec->URLParaType == TreaList)
	{
		xstrncpy(UpperDir, pf->POST_NAME, sizeof(UpperDir));
		if ((p = strrchr(UpperDir, '/')) != NULL)
			*p = '\0';
		if ((p = strrchr(UpperDir + 9, '/')) != NULL)	/* find sub dir */
		{
			*p = '\0';
			hasUpperDir = TRUE;
		}
		else
			hasUpperDir = FALSE;
	}

#if 11
	fprintf(fp_out, "Start=%d, End=%d, B_totla=%d", start, end, pf->total_rec);
	fflush(fp_out);
#endif

#ifdef USE_MMAP
	fip = (FILEHEADER *) mmap((caddr_t) 0,
			  (size_t) (pf->total_rec * FH_SIZE),
		      PROT_READ, MAP_SHARED, fd, (off_t) 0);
	if (fip == MAP_FAILED)
	{
		close(fd);
#if 11
		fprintf(fp_out, "\r\ntest2!![%d]<br>\r\n", errno);
#endif
		return FALSE;
	}
	close(fd);

#else
	if (lseek(fd, (long) (FH_SIZE * (start - 1)), SEEK_SET) == -1)
	{
		close(fd);
		return FALSE;
	}
#endif

#if 11
	fprintf(fp_out, "\r\ntest3!!<br>\r\n");
#endif
	bzero(format_array, sizeof(format_array));
	if (build_format_array(format_array, format, "%", "%", 32) == -1)
	{
#if 11
	fprintf(fp_out, "\r\ntest4!!<br>\r\n");
#endif

		return FALSE;
	}

#if 11
	{
		int i;
		for (i = 0; format_array[i].type; i++)
		fprintf(fp_out, "<%d:[%c,%d]>\r\n", i, format_array[i].type, format_array[i].offset);
		fflush(fp_out);
	}
#endif

	for (recidx = start; recidx <= end; recidx++)
	{
		int i;

		if (fileinfo.accessed & FILE_REPD)
			type = "r";
		else if (fileinfo.accessed & FILE_READ)
			type = "-";
		else
			type = "N";

		if (hasUpperDir)
		{
			strcpy(sender, MSG_TreaDir);
			strcpy(senderid, MSG_TreaDir);
			sprintf(title, "<A HREF=\"/%s%s/\">%s</A> ", BBS_SUBDIR, UpperDir, MSG_TreaUpperDir);	/* add space at last prevent html tag error */
			strcpy(date, "--/--/--");

			hasUpperDir = FALSE;
			recidx = start - 1;
		}
		else
		{
			time_t fdate;
#ifdef USE_MMAP
			memcpy(&fileinfo, fip + recidx - 1, FH_SIZE);
#else
			if (read(fd, &fileinfo, FH_SIZE) != FH_SIZE)
				break;
#endif
			/* check FILEHEADER data overflow */
			if (invalid_fileheader(&fileinfo))
			{
				strcpy(sender, "unknow");
				strcpy(senderid, "unknow");
				strcpy(title, "<< Invalid Entry >> ");	/* add space at last prevent html tag error */
			}
			else if (fileinfo.accessed & FILE_TREA)		/* file is treasure dir */
			{
				if (request_rec->URLParaType == TreaList)
				{
					strcpy(sender, MSG_TreaDir);

					/* transform special chars to html code */
					souts(fileinfo.title, sizeof(fileinfo.title));
					sprintf(title, "<A HREF=\"/%s%s/%s/\">%s </A> ",
						BBS_SUBDIR, pf->POST_NAME, fileinfo.filename, fileinfo.title);	/* add space at last prevent html tag error */
				}
				else
				{
					strcpy(sender, "unknow");
					strcpy(title, "<< Invalid Entry >> ");	/* add space at last prevent html tag error */
				}
			}
			else
					/* file is post */
			{
#ifdef QP_BASE64_DECODE
				if (strstr(fileinfo.owner, "=?"))	/* maybe encoded */
				{
					char source[STRLEN];

					xstrncpy(source, fileinfo.owner, STRLEN);
					decode_line(fileinfo.owner, source);
				}
#endif
				if (*fileinfo.owner == '#')	/* outsite post */
				{
					strtok(fileinfo.owner, ".@");
					sprintf(sender, "&nbsp; %.12s", fileinfo.owner);
				}
				else if (request_rec->URLParaType == MailList
					 && strchr(fileinfo.owner, '@') != NULL)	/* outsit email */
				{
					strtok(fileinfo.owner, ".@");
					sprintf(sender, "&nbsp;#%.12s", fileinfo.owner);
				}
				else
				{
#ifdef USE_IDENT
					sprintf(sender, "%s<A HREF=\"/%susers/%.12s\">%.12s</A>",
						fileinfo.ident == 7 ? MSG_IdentMark : "&nbsp;&nbsp;",
						BBS_SUBDIR, fileinfo.owner, fileinfo.owner);
#else
					sprintf(sender, "<A HREF=\"/%susers/%s\">%s</A>",
						BBS_SUBDIR, fileinfo.owner, fileinfo.owner);
#endif
					xstrncpy(senderid, fileinfo.owner, sizeof(senderid));
				}

				if ((fileinfo.accessed & FILE_DELE))
					sprintf(title, "<<本篇已被 %s 刪除>> ", fileinfo.delby);	/* add space at last prevent html tag error */
				else
				{
#ifdef QP_BASE64_DECODE
					if (strstr(fileinfo.title, "=?"))	/* maybe encoded */
					{
						char source[STRLEN * 2];

						strcpy(source, fileinfo.title);
						decode_line(fileinfo.title, source);
					}
#endif
					if (strlen(fileinfo.title) > 40)	/* title too long */
					{
						fileinfo.title[39] = '\0';
						fileinfo.title[40] = '\0';
						strcat(fileinfo.title, ".....");
					}

					/* transform special chars to html code */
					souts(fileinfo.title, sizeof(fileinfo.title));
					if (fileinfo.accessed & FILE_HTML)
						sprintf(title, "<A HREF=\"/%s%s/%s/PostHtml.html\" Target=\"new\">%s </A> ",
							BBS_SUBDIR, request_rec->URLParaType == MailList ? "mail" : pf->POST_NAME, fileinfo.filename, fileinfo.title);	/* add space at last prevent html tag error */
					else
						sprintf(title, "<A HREF=\"/%s%s/%s.html\">%s </A> ",
							BBS_SUBDIR, request_rec->URLParaType == MailList ? "mail" : pf->POST_NAME, fileinfo.filename, fileinfo.title);	/* add space at last prevent html tag error */
				}
			}

			if ((fdate = (time_t) atol((fileinfo.filename) + 2)) == 0)
				strcpy(date, "unknow");
			else
				mk_timestr1(date, (time_t) fdate);
		}

		/* output data according to format */
		sprintf(recidx_string, "%d", recidx);
		strings[0] = recidx_string;
		strings[1] = sender;
		strings[2] = date;
		strings[3] = title;
		strings[4] = senderid;
		strings[5] = type;	/* used in MailList */
		for (i = 0; format_array[i].type; i++)
		{
			int offset1 = format_array[i].offset;
			int offset2 = format_array[i+1].offset;

			if (format_array[i].type == 'S')	/* not BBS TAG */
			{
				fwrite(&(format[offset1]), sizeof(char), offset2 - offset1,
					fp_out);
			}
			else
			{
				int j;
			/* BBS TAG */
				for (j = 0; j < 6; j++)
				{
					if (!strncasecmp(&(format[offset1 + 1]), tags[j], offset2 - offset1 - 2))
					{
						fprintf(fp_out, "%s", strings[j]);
						break;
					}
				}
			}
		}
		fprintf(fp_out, "\r\n");
	}
#ifdef USE_MMAP
	munmap((void *) fip, pf->total_rec * FH_SIZE);
#else
	close(fd);
#endif
	return TRUE;
}
Ejemplo n.º 9
0
/*******************************************************************
 *	顯示佈告相關 TAG (一般區 & 精華區 & 信件 通用)
 *
 *
 *******************************************************************/
void
ShowPost(char *tag, BOARDHEADER * board, POST_FILE * pf)
{
	char *p, *para = NULL;
	int pagesize, start, end;
	char value[256];

	if (request_rec->URLParaType != PostRead
	    && request_rec->URLParaType != TreaRead
	    && request_rec->URLParaType != MailRead
	    && request_rec->URLParaType != SkinModify)
	{
		return;
	}

	if ((p = strchr(tag, ' ')) != NULL)
	{
		*p = '\0';
		para = p + 1;
	}

#if 0
	fprintf(fp_out, "<%d>, tag=[%s], \n", request_rec->URLParaType, tag);
	fflush(fp_out);
#endif

	if (!strcasecmp(tag, "Num"))
	{
		fprintf(fp_out, "%d", pf->num);
	}
	else if (!strcasecmp(tag, "Date"))
	{
		fprintf(fp_out, "%s", pf->date);
	}
	else if (!strcasecmp(tag, "Sender"))
	{
		fprintf(fp_out, "%s", pf->fh.owner);
	}
	else if (!strcasecmp(tag, "BackList"))
	{
#ifdef TORNADO_OPTIMIZE
		if (isTORNADO)
			return;
#endif

		GetPara3(value, "PAGE", para, 4, "-1");
		pagesize = atoi(value);
		find_list_range(&start, &end, pf->num, pagesize, pf->total_rec);

		GetPara3(value, "VALUE", para, sizeof(value), MSG_PostBackList);
		fprintf(fp_out, "<A HREF=\"%d-%d\">%s</A>", start, end, value);
	}
	else if (!strcasecmp(tag, "BackListNum"))
	{
		GetPara3(value, "PAGE", para, 3, "-1");
		pagesize = atoi(value);
		find_list_range(&start, &end, pf->num, pagesize, pf->total_rec);

		fprintf(fp_out, "%d-%d", start, end);
	}
	else if (!strcasecmp(tag, "Last"))
	{
#if 0
		if (isTORNADO)
			return;
#endif
		GetPara3(value, "VALUE", para, sizeof(value), MSG_PostLast);

		if (!strcmp(pf->lfname, "-1"))
		{
			fprintf(fp_out, "%s", value);
		}
		else
		{
			if (pf->type & LAST_POST_IS_HTML)
				fprintf(fp_out, "<A HREF=\"%s/PostHtml.html\" target=\"new\">%s</A>", pf->lfname, value);
			else
				fprintf(fp_out, "<A HREF=\"%s.html\">%s</A>", pf->lfname, value);
		}
	}
	else if (!strcasecmp(tag, "Next"))
	{
#if 0
		if (isTORNADO)
			return;
#endif
		GetPara3(value, "VALUE", para, sizeof(value), MSG_PostNext);

		if (!strcmp(pf->nfname, "-1"))
		{
			fprintf(fp_out, "%s", value);
		}
		else
		{
			if (pf->type & NEXT_POST_IS_HTML)
				fprintf(fp_out, "<A HREF=\"%s/PostHtml.html\" Target=\"new\">%s</A>", pf->nfname, value);
			else
				fprintf(fp_out, "<A HREF=\"%s.html\">%s</A>", pf->nfname, value);
		}
	}
#ifdef TTT
	else if (!strcasecmp(tag, "LastRelated"))
	{
		GetPara3(value, "VALUE", para, sizeof(value), MSG_PostLastRelated);

		if (!strcmp(pf->lrfname, "-1"))
		{
			fprintf(fp_out, "%s", value);
		}
		else
		{
			fprintf(fp_out, "<A HREF=\"%s.html\">%s</A>", pf->lrfname, value);
		}
	}
	else if (!strcasecmp(tag, "NextRelated"))
	{
		GetPara3(value, "VALUE", para, sizeof(value), MSG_PostNextRelated);

		if (!strcmp(pf->nrfname, "-1"))
		{
			fprintf(fp_out, "%s", value);
		}
		else
		{
			fprintf(fp_out, "<A HREF=\"%s.html\">%s</A>", pf->nrfname, value);
		}
	}
#endif
	else if (!strcasecmp(tag, "Reply"))
	{
#ifdef TORNADO_OPTIMIZE
		if (isTORNADO)
			return;
#endif
		GetPara3(value, "VALUE", para, sizeof(value), MSG_PostReply);

		fprintf(fp_out, "<A HREF=\"%s/%s\">%s</A>",
			pf->fh.filename,
			(request_rec->URLParaType == MailRead) ? HTML_MailReply : HTML_PostReply,
			value);
	}
	else if (!strcasecmp(tag, "Send"))
	{
#ifdef TORNADO_OPTIMIZE
		if (isTORNADO)
			return;
#endif
		GetPara3(value, "VALUE", para, sizeof(value), MSG_PostSend);
		fprintf(fp_out, "<A HREF=\"%s\">%s</A>", HTML_PostSend, value);
	}
	else if (!strcasecmp(tag, "Edit"))
	{
#ifdef TORNADO_OPTIMIZE
		if (isTORNADO)
			return;
#endif
		if (PSCorrect != Correct)
			return;

		GetPara3(value, "VALUE", para, sizeof(value), MSG_PostEdit);
		fprintf(fp_out, "<A HREF=\"%s/%s\">%s</A>",
			pf->fh.filename, HTML_PostEdit, value);
	}
	else if (!strcasecmp(tag, "Forward"))
	{
#ifdef TORNADO_OPTIMIZE
		if (isTORNADO)
			return;
#endif
		if (request_rec->URLParaType != MailRead && PSCorrect != Correct)
			return;

		GetPara3(value, "VALUE", para, sizeof(value), MSG_PostForward);

		fprintf(fp_out, "<A HREF=\"%s/%s\">%s</A>",
			pf->fh.filename,
			(request_rec->URLParaType == MailRead) ? HTML_MailForward : HTML_PostForward,
			value);
	}
	else if (!strcasecmp(tag, "Delete"))
	{
#ifdef TORNADO_OPTIMIZE
		if (isTORNADO)
			return;
#endif
		if (request_rec->URLParaType != MailRead && PSCorrect != Correct)
			return;

		GetPara3(value, "VALUE", para, sizeof(value), MSG_PostDelete);

		fprintf(fp_out, "<A HREF=\"%s/%s\">%s</A>",
			pf->fh.filename,
			(request_rec->URLParaType == MailRead) ? HTML_MailDelete : HTML_PostDelete,
			value);
	}
	else if (!strcasecmp(tag, "Content"))
	{
		if (request_rec->URLParaType == MailRead && PSCorrect != Correct)
			return;

		if (request_rec->URLParaType == SkinModify)
			ShowArticle(pf->POST_NAME, FALSE, FALSE);
		else
			ShowArticle(pf->POST_NAME, FALSE, TRUE);
	}
	else if (!strcasecmp(tag, "Title") || !strcasecmp(tag, "Subject"))
	{
#ifdef QP_BASE64_DECODE
		if (strstr(pf->fh.title, "=?"))		/* title maybe encoded */
		{
			char source[STRLEN];

			strcpy(source, pf->fh.title);
			decode_line(pf->fh.title, source);
		}
#endif
		souts(pf->fh.title, STRLEN);
		fprintf(fp_out, "%s", pf->fh.title);
	}
	else if (!strcasecmp(tag, "ReplyContent"))
	{
		if (request_rec->URLParaType == MailRead && PSCorrect != Correct)
			return;

		include_ori(pf->POST_NAME, NULL);	/* lthuang */
	}
	else if (!strcasecmp(tag, "ReplyTitle") || !strcasecmp(tag, "ReplySubject"))
	{
#ifdef QP_BASE64_DECODE
		if (strstr(pf->fh.title, "=?"))		/* title maybe encoded */
		{
			strcpy(value, pf->fh.title);
			decode_line(pf->fh.title, value);
		}
#endif
		souts(pf->fh.title, STRLEN);
		if (strncmp(pf->fh.title, STR_REPLY, REPLY_LEN))
			fprintf(fp_out, "%s", STR_REPLY);

		fprintf(fp_out, "%s", pf->fh.title);
	}
	else if (!strcasecmp(tag, "Body"))
	{
		if (request_rec->URLParaType == MailRead && PSCorrect != Correct)
			return;

		if (strstr(skin_file->filename, "PostHtml.html")
		    || strstr(skin_file->filename, HTML_PostEdit))
		{
			ShowArticle(pf->POST_NAME, TRUE, FALSE);
		}
		else
			ShowArticle(pf->POST_NAME, TRUE, TRUE);

	}
	else if (!strcasecmp(tag, "FileName"))
	{
		fprintf(fp_out, "%s", pf->fh.filename);
	}
	else if (!strcasecmp(tag, "LastFileName"))
	{
		fprintf(fp_out, "%s.html", pf->lfname);
	}
	else if (!strcasecmp(tag, "NextFileName"))
	{
		fprintf(fp_out, "%s.html", pf->nfname);
	}
}
Ejemplo n.º 10
0
/*--------------------------------------------------------------------*/
INT cnafsub(BOOL cmd_mode, char *cmd)
{
  char str[128], line[128];
  INT status, j;
  CAMAC *P, *p = NULL, *job;

  /* Loop return label */
  if (jobflag) {
    jobflag = FALSE;
  }

  /* Load default CAMAC */
  P = Prompt;
  while (1) {
    if (!cmd_mode) {
      make_display_string(MAIN, P, addr);
      /* prompt */
      printf("mCNAF> [%s] :", addr);
      ss_gets(str, 128);
    } else {
      strcpy(str, cmd);
    }

    /* decode line */
    status = decode_line(P, str);
    if (status == QUIT)
      return status;
    else if (status == MCSTD) {
      mcstd_func(P);
      status = decode_line(P, str);
    } else if (status == HELP)
      help_page(MAIN);
    else if (status == JOB) {
      if (!cmd_mode) {
        /* interactive session, display default job name */
        printf("\nmCNAF> Job file name [%s]:", job_name);
        ss_gets(line, 128);
        if (strlen(line) == 0)
          strcpy(line, job_name);  // Use default
        else {
          strcpy(job_name, line);
        }
      } else {
        /* from command line, skip @ */
        strcpy(line, &str[1]);
      }
      /* Check if file exists */
      status = read_job_file(pF, CHECK, &job, line);
      if (status == JOB)
        status = read_job_file(pF, READ, &job, line);
    }

    if (status == LOOP || status == JOB) {
      for (j = 0; j < P->r; j++) {
        if (status == LOOP)
          p = P;
        if (status == JOB)
          p = job;
        while (p->m) {
          if (p->n == 28 || p->n == 29 || p->n == 30)
            cc_services(p);
          else if (p->m == 24) {    /* Actual 24 bits CAMAC operation */
            if (p->f < 8)
              cam24i_q(p->c, p->n, p->a, p->f, &p->d24, &p->x, &p->q);
            else if (p->f < 16)
              camc_q(p->c, p->n, p->a, p->f, &p->q);
            else if (p->f < 24)
              cam24o_q(p->c, p->n, p->a, p->f, p->d24, &p->x, &p->q);
            else 
              camc_q(p->c, p->n, p->a, p->f, &p->q);
          }
          else {
            if (p->f < 16)  /* Actual 16 bits CAMAC operation */ 
              cam16i_q(p->c, p->n, p->a, p->f, &p->d16, &p->x, &p->q);
            else if (p->f < 24)
              cam16o_q(p->c, p->n, p->a, p->f, (WORD)p->d24, &p->x, &p->q);
            else 
              camc_q(p->c, p->n, p->a, p->f, &p->q);
          }
          make_display_string(MAIN, p, addr);

          /* Result display */
          if (p->r > 1) {
            /* repeat mode */
            if (status == JOB) {
              if (!cmd_mode)
                printf("\nmCNAF> [%s]", addr);
              if (p->w != 0)
                ss_sleep(p->w);
            } else {
              if (!cmd_mode)
                printf("mCNAF> [%s] <-%03i\n", addr, j + 1);
              if (p->w != 0)
                ss_sleep(p->w);
              if (j > p->r - 1)
                break;
            }
          } else {
            /* single command */
            if (status == JOB) {
              if (!cmd_mode)
                printf("mCNAF> [%s]\n", addr);
              if (p->w != 0)
                ss_sleep(p->w);
            }
          }
          p++;
        }
      };
      if (status == JOB) {
        free(job);
        if (!cmd_mode)
          printf("\n");
      }
    }
    if (cmd_mode)
      break;
  }
  return status;
}
Ejemplo n.º 11
0
/*--------------------------------------------------------------------*/
void mcstd_func(CAMAC * PP)
{
   char paddr[128], pstr[128];
   int i, status, pstatus = 0;
   WORD dd16[100];
   WORD *pdd16;
   DWORD dd24[100];
   DWORD *pdd24;
   DWORD lam;
   CAMAC *p;

   /* Load default CAMAC */
   // PP = &Prompt[1];
   while (1) {
      make_display_string(MCSTD, PP, paddr);
      /* prompt */
      printf("MCStd> [%s] :", paddr);
      ss_gets(pstr, 128);

      /* decode line */
      status = decode_line(PP, pstr);
      p = PP;
      if (status == LOOP)
         status = pstatus;
      if (status != SKIP && status != HELP)
         pstatus = status;
      i = 0;
      pdd16 = dd16;
      pdd24 = dd24;
      switch (status) {
         /* system */
      case CAMST:
         printf("cam_op\n");
         cam_op();
         break;
      case CAM_LAM_ENABLE:
         cam_lam_enable(p->c, p->n);
         printf("cam_lam_enable:C%i-N%i\n", p->c, p->n);
         break;
      case CAM_LAM_DISABLE:
         cam_lam_disable(p->c, p->n);
         printf("cam_lam_disable:C%i-N%i\n", p->c, p->n);
         break;
      case CAM_LAM_READ:
         cam_lam_read(p->c, &lam);
         printf("cam_lam_read:C%i-> 0x%x\n", p->c, lam);
         break;
      case CAM_LAM_CLEAR:
         cam_lam_clear(p->c, p->n);
         printf("cam_lam_clear:C%i \n", p->c);
         break;
      case CAM_INHIBIT_SET:
         cam_inhibit_set(p->c);
         printf("cam_inhibit_set:C%i\n", p->c);
         break;
      case CAM_INHIBIT_CLEAR:
         cam_inhibit_clear(p->c);
         printf("cam_inhibit_clear:C%i\n", p->c);
         break;
      case CAM_CRATE_CLEAR:
         cam_crate_clear(p->c);
         printf("cam_crate_clear:C%i\n", p->c);
         break;
      case CAM_CRATE_ZINIT:
         cam_crate_zinit(p->c);
         printf("cam_crate_zinit:C%i\n", p->c);
         break;
         /* command */
      case CAMC:
         do {
            camc(p->c, p->n, p->a, p->f);
            printf("camc:[R%i]-C%i-N%i-A%i-F%i\n", ++i, p->c, p->n, p->a, p->f);
         } while (i < p->r);
         break;
      case CAMC_Q:
         do {
            camc_q(p->c, p->n, p->a, p->f, &p->q);
            printf("camc_q:[R%i]-C%i-N%i-A%i-F%i -Q:%i\n", ++i, p->c, p->n, p->a, p->f,
                   p->q);
         } while (i < p->r);
         break;
      case CAMC_SA:
         camc(p->c, p->n, p->a, p->f);
         printf("camc_sa:C%i-N%i-A%i-F%i\n", p->c, p->n, p->a, p->f);
         break;
      case CAMC_SN:
         camc(p->c, p->n, p->a, p->f);
         printf("camc_sn:C%i-N%i-A%i-F%i\n", p->c, p->n, p->a, p->f);
         break;
         /* output */
      case CAM16O:
         do {
            cam16o(p->c, p->n, p->a, p->f, p->d16);
            printf("cam16o:[R%i]-C%i-N%i-A%i-F%i <- 0x%x\n", ++i, p->c, p->n, p->a, p->f,
                   p->d16);
         } while (i < p->r);
         break;
      case CAM24O:
         do {
            cam24o(p->c, p->n, p->a, p->f, p->d24);
            printf("cam24o:[R%i]-C%i-N%i-A%i-F%i <- 0x%x\n", ++i, p->c, p->n, p->a, p->f,
                   p->d24);
         } while (i < p->r);
         break;
      case CAM16O_Q:
         do {
            cam16o_q(p->c, p->n, p->a, p->f, p->d16, &p->x, &p->q);
            printf("cam16o_q:[R%i]-C%i-N%i-A%i-F%i <- 0x%x X:%i-Q:%i\n", ++i, p->c, p->n,
                   p->a, p->f, p->d16, p->x, p->q);
         } while (i < p->r);
         break;
      case CAM24O_Q:
         do {
            cam24o_q(p->c, p->n, p->a, p->f, p->d24, &p->x, &p->q);
            printf("cam24o_q:[R%i]-C%i-N%i-A%i-F%i <- 0x%x X:%i-Q:%i\n", ++i, p->c, p->n,
                   p->a, p->f, p->d24, p->x, p->q);
         } while (i < p->r);
         break;
      case CAM16O_R:
         cam16o_r(p->c, p->n, p->a, p->f, pdd16, p->r);
         printf("cam16o_r:C%i-N%i-A%i-F%i <- 0x%x\n", p->c, p->n, p->a, p->f, p->d16);
         break;
      case CAM24O_R:
         cam24o_r(p->c, p->n, p->a, p->f, pdd24, p->r);
         printf("cam24o_r:C%i-N%i-A%i-F%i <- 0x%x\n", p->c, p->n, p->a, p->f, p->d24);
         break;
         /* inputs */
      case CAM16I:
         do {
            cam16i(p->c, p->n, p->a, p->f, &p->d16);
            printf("cam16i:[R%i]-C%i-N%i-A%i-F%i-> 0x%4.4x\n", ++i, p->c, p->n, p->a,
                   p->f, p->d16);
         } while (i < p->r);
         break;
      case CAM24I:
         do {
            cam24i(p->c, p->n, p->a, p->f, &p->d24);
            printf("cam24i:[R%i]-C%i-N%i-A%i-F%i-> 0x%6.6x\n", ++i, p->c, p->n, p->a,
                   p->f, p->d24);
         } while (i < p->r);
         break;
      case CAM16I_Q:
         do {
            cam16i_q(p->c, p->n, p->a, p->f, &p->d16, &p->x, &p->q);
            printf("cam16i_q:[R%i]-C%i-N%i-A%i-F%i-> 0x%4.4x X:%i-Q:%i\n", ++i, p->c,
                   p->n, p->a, p->f, p->d16, p->x, p->q);
         } while (i < p->r);
         break;
      case CAM24I_Q:
         do {
            cam24i_q(p->c, p->n, p->a, p->f, &p->d24, &p->x, &p->q);
            printf("cam24i_q:[R%i]-C%i-N%i-A%i-F%i-> 0x%6.6x X:%i-Q:%i\n", ++i, p->c,
                   p->n, p->a, p->f, p->d24, p->x, p->q);
         } while (i < p->r);
         break;
      case CAM16I_R:
         memset(pdd16, 0, sizeof(dd16));
         cam16i_r(p->c, p->n, p->a, p->f, &pdd16, p->r);
         for (i = 0; i < p->r; i++)
            printf("cam16i_r:[R%i]-C%i-N%i-A%i-F%i-> 0x%4.4x\n", i + 1, p->c, p->n, p->a,
                   p->f, dd16[i]);
         break;
      case CAM24I_R:
         memset(pdd24, 0, sizeof(dd24));
         cam24i_r(p->c, p->n, p->a, p->f, &pdd24, p->r);
         for (i = 0; i < p->r; i++)
            printf("cam24i_r:[R%i]-C%i-N%i-A%i-F%i-> 0x%6.6x\n", i + 1, p->c, p->n, p->a,
                   p->f, dd24[i]);
         break;
      case CAM16I_RQ:
         memset(pdd16, 0, sizeof(dd16));
         cam16i_rq(p->c, p->n, p->a, p->f, &pdd16, p->r);
         for (i = 0; i < p->r; i++)
            printf("cam16i_rq:[R%i]-C%i-N%i-A%i-F%i-> 0x%4.4x\n", i + 1, p->c, p->n, p->a,
                   p->f, dd16[i]);
         break;
      case CAM24I_RQ:
         memset(pdd24, 0, sizeof(dd24));
         cam24i_rq(p->c, p->n, p->a, p->f, &pdd24, p->r);
         for (i = 0; i < p->r; i++)
            printf("cam24i_rq:[R%i]-C%i-N%i-A%i-F%i-> 0x%6.6x\n", i + 1, p->c, p->n,
                   p->a, p->f, dd24[i]);
         break;
      case CAM16I_SA:
         memset(pdd16, 0, sizeof(dd16));
         cam16i_sa(p->c, p->n, p->a, p->f, &pdd16, p->r);
         for (i = 0; i < p->r; i++)
            printf("cam16i_sa:[R%i]-C%i-N%i-A%i-F%i-> 0x%4.4x\n", i + 1, p->c, p->n,
                   p->a + i, p->f, dd16[i]);
         break;
      case CAM24I_SA:
         memset(pdd24, 0, sizeof(dd24));
         cam24i_sa(p->c, p->n, p->a, p->f, &pdd24, p->r);
         for (i = 0; i < p->r; i++)
            printf("cam24i_sa:[R%i]-C%i-N%i-A%i-F%i-> 0x%6.6x\n", i + 1, p->c, p->n,
                   p->a + i, p->f, dd24[i]);
         break;
      case CAM16I_SN:
         memset(pdd16, 0, sizeof(dd16));
         cam16i_sa(p->c, p->n, p->a, p->f, &pdd16, p->r);
         for (i = 0; i < p->r; i++)
            printf("cam16i_sn:[R%i]-C%i-N%i-A%i-F%i-> 0x%x\n", i + 1, p->c, p->n + i,
                   p->a, p->f, dd16[i]);
         break;
      case CAM24I_SN:
         memset(pdd24, 0, sizeof(dd24));
         cam24i_sn(p->c, p->n, p->a, p->f, &pdd24, p->r);
         for (i = 0; i < p->r; i++)
            printf("cam24i_sn:[R%i]-C%i-N%i-A%i-F%i-> 0x%x\n", i + 1, p->c, p->n + i,
                   p->a, p->f, dd24[i]);
         break;
      case QUIT:
         p->r = 1;
         return;
      case HELP:
         help_page(MCSTD);
         break;
      case SKIP:
         break;
      default:
         status = SKIP;
         break;
      }
   }
}
Ejemplo n.º 12
0
/*
 * Decode the data between BEGIN and END, and stash it in the staging area.
 * Multiple pieces can be present in a single file, bracketed by BEGIN/END.
 * If we have all pieces of a delta, combine them.  Returns 0 on success,
 * and 1 for any sort of failure.
 */
int
read_piece(char *input_file)
    {
    int status = 0;
    FILE *ifp, *ofp = 0;
    int decoding = 0;
    int got_one = 0;
    int line_no = 0;
    int i, n;
    int pce, npieces;
    unsigned claimed_cksum;
    unsigned short cksum = 0;
    char out_buf[200];
    char line[200];
    char delta[30];
    char pname[PATH_MAX];
    char tname[PATH_MAX];
    char junk[2];

    ifp = stdin;
    if (input_file != NULL && (ifp = fopen(input_file, "r")) == NULL)
	{
	err("cannot open '%s' for reading", input_file);
	return 1;
	}

    while (fgets(line, sizeof(line), ifp) != NULL)
	{
	line_no++;

	/*
	 * Remove all trailing white space.
	 */
	i = strlen(line) - 1;
	while (i > 0 && isspace(line[i]))
		line[i--] = '\0';

	/*
	 * Look for the beginning of an encoded piece.
	 */
	if (!decoding)
	    {
	    char *s;
	    int fd = -1;

	    if (sscanf(line, "CTM_MAIL BEGIN %29s %d %d %c",
		    delta, &pce, &npieces, junk) != 3)
		continue;

	    while ((s = strchr(delta, '/')) != NULL)
		*s = '_';

	    got_one++;
	    strcpy(tname, piece_dir);
	    strcat(tname, "/p.XXXXXXXXXX");
	    if ((fd = mkstemp(tname)) == -1 ||
		(ofp = fdopen(fd, "w")) == NULL)
		{
		if (fd != -1) {
		    err("cannot open '%s' for writing", tname);
		    close(fd);
		    }
		else
		    err("*mkstemp: '%s'", tname);
		status++;
		continue;
		}

	    cksum = 0xffff;
	    decoding++;
	    continue;
	    }

	/*
	 * We are decoding.  Stop if we see the end flag.
	 */
	if (sscanf(line, "CTM_MAIL END %d %c", &claimed_cksum, junk) == 1)
	    {
	    int e;

	    decoding = 0;

	    fflush(ofp);
	    e = ferror(ofp);
	    fclose(ofp);

	    if (e)
		err("error writing %s", tname);

	    if (cksum != claimed_cksum)
		err("checksum: read %d, calculated %d", claimed_cksum, cksum);

	    if (e || cksum != claimed_cksum)
		{
		err("%s %d/%d discarded", delta, pce, npieces);
		unlink(tname);
		status++;
		continue;
		}

	    mk_piece_name(pname, delta, pce, npieces);
	    if (rename(tname, pname) < 0)
		{
		err("*rename: '%s' to '%s'", tname, pname);
		err("%s %d/%d lost!", delta, pce, npieces);
		unlink(tname);
		status++;
		continue;
		}

	    err("%s %d/%d stored", delta, pce, npieces);

	    if (!combine_if_complete(delta, pce, npieces))
		status++;
	    continue;
	    }

	/*
	 * Must be a line of encoded data.  Decode it, sum it, and save it.
	 */
	n = decode_line(line, out_buf);
	if (n <= 0)
	    {
	    err("line %d: illegal character: '%c'", line_no, line[-n]);
	    err("%s %d/%d discarded", delta, pce, npieces);

	    fclose(ofp);
	    unlink(tname);

	    status++;
	    decoding = 0;
	    continue;
	    }

	for (i = 0; i < n; i++)
	    add_ck(cksum, out_buf[i]);

	fwrite(out_buf, sizeof(char), n, ofp);
	}

    if (decoding)
	{
	err("truncated file");
	err("%s %d/%d discarded", delta, pce, npieces);

	fclose(ofp);
	unlink(tname);

	status++;
	}

    if (ferror(ifp))
	{
	err("error reading %s", input_file == NULL ? "stdin" : input_file);
	status++;
	}

    if (input_file != NULL)
	fclose(ifp);

    if (!got_one)
	{
	err("message contains no delta");
	status++;
	}

    return (status != 0);
    }
Ejemplo n.º 13
0
int main(int argc, char *argv[]) {
        char configtype[STRING_SIZE];
        char redtype[STRING_SIZE] = "";
        struct keyvalue *kv = NULL;
                        
        if (argc < 2) {
                usage();
                exit(1);
        }
        if (!(initsetuid()))
                exit(1);
                
 FILE *file = NULL;
                

        if (strcmp(argv[1], "I") == 0) {
                safe_system("/usr/sbin/ipsec status");
                exit(0);
        }

        if (strcmp(argv[1], "R") == 0) {
                safe_system("/usr/sbin/ipsec reload >/dev/null 2>&1");
                exit(0);
        }

        /* FIXME: workaround for pclose() issue - still no real idea why
         * this is happening */
        signal(SIGCHLD, SIG_DFL);

        /* handle operations that doesn't need start the ipsec system */
        if (argc == 2) {
                if (strcmp(argv[1], "D") == 0) {
                        safe_system("/usr/sbin/ipsec stop >/dev/null 2>&1");
                        ipsec_norules();
                        exit(0);
                }
        }

        /* read vpn config */
        kv=initkeyvalues();
        if (!readkeyvalues(kv, CONFIG_ROOT "/vpn/settings"))
        {
                fprintf(stderr, "Cannot read vpn settings\n");
                exit(1);
        }

        /* check is the vpn system is enabled */
        {
            char s[STRING_SIZE];
            findkey(kv, "ENABLED", s);
            freekeyvalues(kv);
            if (strcmp (s, "on") != 0)
                exit(0);
        }

        /* read interface settings */
        kv=initkeyvalues();
        if (!readkeyvalues(kv, CONFIG_ROOT "/ethernet/settings"))
        {
                fprintf(stderr, "Cannot read ethernet settings\n");
                exit(1);
        }
        if (!findkey(kv, "CONFIG_TYPE", configtype))
        {
                fprintf(stderr, "Cannot read CONFIG_TYPE\n");
                exit(1);
        }
        findkey(kv, "RED_TYPE", redtype);


        /* Loop through the config file to find physical interface that will accept IPSEC */
        int enable_red=0;       // states 0: not used
        int enable_green=0;     //        1: error condition
        int enable_orange=0;    //        2: good
        int enable_blue=0;
        char if_red[STRING_SIZE] = "";
        char if_green[STRING_SIZE] = "";
        char if_orange[STRING_SIZE] = "";
        char if_blue[STRING_SIZE] = "";
        char s[STRING_SIZE];

        // when RED is up, find interface name in special file
        FILE *ifacefile = NULL;
        if ((ifacefile = fopen(CONFIG_ROOT "/red/iface", "r"))) {
                if (fgets(if_red, STRING_SIZE, ifacefile)) {
                        if (if_red[strlen(if_red) - 1] == '\n')
                                if_red[strlen(if_red) - 1] = '\0';
                }
                fclose (ifacefile);

                if (VALID_DEVICE(if_red))
                        enable_red++;
        }

	// Check if GREEN is enabled.
        findkey(kv, "GREEN_DEV", if_green);
        if (VALID_DEVICE(if_green))
                enable_green++;

	// Check if ORANGE is enabled.
        findkey(kv, "ORANGE_DEV", if_orange);
        if (VALID_DEVICE(if_orange))
                enable_orange++;

	// Check if BLUE is enabled.
        findkey(kv, "BLUE_DEV", if_blue);
        if (VALID_DEVICE(if_blue))
                enable_blue++;

        freekeyvalues(kv);

        // exit if nothing to do
        if ((enable_red+enable_green+enable_orange+enable_blue) == 0)
            exit(0);

        // open needed ports
        if (enable_red > 0)
                open_physical(if_red, 4500);

        if (enable_green > 0)
                open_physical(if_green, 4500);

        if (enable_orange > 0)
                open_physical(if_orange, 4500);

        if (enable_blue > 0)
                open_physical(if_blue, 4500);

        // start the system
        if ((argc == 2) && strcmp(argv[1], "S") == 0) {
		safe_system("/usr/sbin/ipsec restart >/dev/null");
                exit(0);
        }

        // it is a selective start or stop
        // second param is only a number 'key'
        if ((argc == 2) || strspn(argv[2], NUMBERS) != strlen(argv[2])) {
                fprintf(stderr, "Bad arg: %s\n", argv[2]);
                usage();
                exit(1);
        }

        // search the vpn pointed by 'key'
        if (!(file = fopen(CONFIG_ROOT "/vpn/config", "r"))) {
                fprintf(stderr, "Couldn't open vpn settings file");
                exit(1);
        }
        while (fgets(s, STRING_SIZE, file) != NULL) {
                char *key;
                char *name;
                char *type;
                if (!decode_line(s,&key,&name,&type))
                        continue;

                // is it the 'key' requested ?
                if (strcmp(argv[2], key) != 0)
                        continue;

                // Start or Delete this Connection
                if (strcmp(argv[1], "S") == 0)
                        turn_connection_on (name, type);
                else if (strcmp(argv[1], "D") == 0)
                        turn_connection_off (name);
                else {
                        fprintf(stderr, "Bad command\n");
                        exit(1);
                }
        }
        fclose(file);

        return 0;
}
Ejemplo n.º 14
0
int main(){
  char t[] = "TMP01:200001:1";
  decode_line(t, strlen(t)+1);
}
Ejemplo n.º 15
0
/*** End of Protocol Prototype ***/
int handle_command(int sock, char *cmd, FILE *fptr, struct config_params *params, struct city **headlist, int *auth_success)
{
    int counter;
    char commandname[MAXLEN];//also used for return:command
    char tablename[MAXLEN];//also used for return:status
    char keyname[MAXLEN];
    char valuename[MAXLEN];//also used for return:secondstatus (may be detail OR value)
    char retline[MAXLEN];
    char encoded_value[MAXLEN];
    //char returncmd[MAXLEN+1]; //To send back to client
    time_t rawtime;
    struct tm * timeinfo;
    int index = 0;
    int tempcmd = 1;
    int tempcommand = 0;
    int i = 0;//common-purpose counter
    printf("command received: %s\n", cmd);
    while(cmd[tempcmd] != '&'){
	if(cmd[tempcmd] != '&'){
	    commandname[tempcommand] = cmd[tempcmd];
	    tempcommand++;
	    tempcmd++;
	}
    }
    commandname[tempcommand] = '\0';
    tempcommand = 0;
    tempcmd++;
    tempcmd++;
    while(cmd[tempcmd] != '^'){
	tablename[tempcommand] = cmd[tempcmd];
	tempcommand++;
	tempcmd++;
    }
    tablename[tempcommand] = '\0';
    tempcommand = 0;
    tempcmd++;
    while(cmd[tempcmd] != '\0'){
	valuename[tempcommand] = cmd[tempcmd];
	tempcommand++;
	tempcmd++;
    }
    valuename[tempcommand] = '\0';
    tempcommand = 0;
    if(strcmp(commandname, "QUERY") == 0){
	printf("command is: %s\n", commandname);
	printf("table is: %s\n", tablename);
	printf("valuename: %s\n", valuename);
    }
    else {
	decode_line(cmd, commandname, tablename, keyname, valuename, &counter);
    }
    //printf("commandname: %s\n", commandname);
    //printf("tablename: %s\n", tablename);
    //printf("keyname: %s\n", keyname);
    //printf("valuename: %s\n", valuename);
    char namegen[MAXLEN+1];
    if(LOGGING==2){
	char tempstr[MAXLEN+1];
	time(&rawtime);
	timeinfo=localtime(&rawtime);
	sprintf(namegen,"%.4d-%.2d-%.2d-%.2d-%.2d-%.2d: ",timeinfo->tm_year+1900,timeinfo->tm_mon+1,timeinfo->tm_mday,timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
	//sprintf(tempstr,"Processing command '%s'\n",commandname);
	printf("Processing line \"%s\"\n", cmd);
	logger(fptr,namegen);//Timestamp
	logger(fptr,tempstr);
    }
    else if(LOGGING==1){
	time(&rawtime);
	timeinfo=localtime(&rawtime);
	sprintf(namegen,"%.4d-%.2d-%.2d-%.2d-%.2d-%.2d: ",timeinfo->tm_year+1900,timeinfo->tm_mon+1,timeinfo->tm_mday,timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
	printf("%s",namegen);//Timestamp
	//printf("Processing command '%s'\n",commandname);
	printf("Processing line \"%s\"\n", cmd);
    }
    
    if (strcmp(commandname, "SET") == 0){
	
    	pthread_mutex_lock( &setMutex );
    	
	//SET below
	// check if authorized
	if ((*auth_success) == 0){
	    //printf("inside if statement.\n");
	    //strncpy(success, "AUTH", sizeof(success));
	    //sendall(sock, success, sizeof(success));
	    cleanstring(tablename);
	    cleanstring(valuename);
	    sprintf(tablename, "FAIL");
	    sprintf(valuename, "AUTH");
	    encode_line(commandname, tablename, valuename, retline);
	    sendall(sock, retline, sizeof(retline));
	}
	else {
	    index = find_index(params->tablelist, tablename);
	    if(index != -1){
		//name found
		struct city *head = headlist[index];
		struct city *temp = find_city(head, keyname);
		printf("valuename: %s\n", valuename);
		if(temp == NULL){
		    //entry doesn't exist
		    if(strcmp(valuename, "@NULL@?") == 0){
			//deleting a key that doesn't exist
			//sprintf(success, "SET$KEY");
			//sendall(sock, success, sizeof(success));
			cleanstring(tablename);
			cleanstring(valuename);
			sprintf(tablename, "FAIL");
			sprintf(valuename, "KEY");
			encode_line(commandname, tablename, valuename, retline);
			sendall(sock, retline, sizeof(retline));
		    }
		    else{
			int column_count = 0;
			column_count = count_column(valuename);		
			if (params->num_columns[index] == column_count)
			    {
				insert_city(headlist[index], keyname, valuename);
				//VALUE IS INSERTED AS A STRING
				cleanstring(tablename);
				cleanstring(valuename);
				sprintf(tablename, "SUCCESS");
				sprintf(valuename, "CREATE");
				encode_line(commandname, tablename, valuename, retline);
				sendall(sock, retline, sizeof(retline));
			    }
			else
			    {
				sprintf(retline, "SET FAIL COLUMN\n");
				sendall(sock, retline, sizeof(retline));						
			    }
		    }
		}
		else {
		    //entry exists, temp != NULL
		    if(strcmp(valuename, "@NULL@?") == 0){
			//delete
			//printf("delete entry\n");
			delete_city(&head, keyname);
			temp = NULL;
			//sprintf(success, "SET$SUCCESS");
			//sendall(sock, success, sizeof(success));
			cleanstring(tablename);
			cleanstring(valuename);
			sprintf(tablename, "SUCCESS");
			sprintf(valuename, "DELETE");
			encode_line(commandname, tablename, valuename, retline);
			sendall(sock, retline, sizeof(retline));
		    }
		    else{
			//modify record
			//strncpy(temp->population, , sizeof(temp->population));
			//sprintf(success, "SET$SUCCESS");
			//sendall(sock, success, sizeof(success));
			//printf("valuename: %s\n", valuename);
			if (counter == temp->counter || counter == 0)
			    {
				int column_count = 0;
				temp = find_city(headlist[index], keyname);
				column_count = count_column(valuename);
				
				if (temp->numocolumns == column_count)
				    {
					modify_city(temp, valuename);
					cleanstring(tablename);
					cleanstring(valuename);
					sprintf(tablename, "SUCCESS");
					sprintf(valuename, "MODIFY");
					encode_line(commandname, tablename, valuename, retline);
					sendall(sock, retline, sizeof(retline));							
				    }
				else
				    {
					sprintf(retline, "SET FAIL COLUMN\n");
					sendall(sock, retline, sizeof(retline));						
				    }
			    }
			else
			    {
				char temp[100];
				sprintf(temp, "%s", "SET FAIL COUNTER");
				sendall(sock, temp, sizeof(temp));	
			    }
		    }
		}
	    }
	    else {
		//table doesn't exist
		//strncpy(fail, "SET$TABLE", sizeof(fail));
		//sendall(sock, fail, sizeof(fail));
		cleanstring(tablename);
		cleanstring(valuename);
		sprintf(tablename, "FAIL");
		sprintf(valuename, "TABLE");
			encode_line(commandname, tablename, valuename, retline);
			sendall(sock, retline, sizeof(retline));
	    }
	}
	
	pthread_mutex_unlock( &setMutex );
    }
    
    // For now, just send back the command to the client.
    //command cases: get, set
    
    else if(strcmp(commandname, "AUTH") == 0){
	//AUTH below
	if(strcmp(tablename, params->username) == 0){
	    if (strcmp(keyname, params->password) == 0){
		(*auth_success) = 1;
		printf("authenticated\n");
		//strncpy(success, "AUTH$SUCCESS", sizeof(success));
		//sendall(sock, success, sizeof(success));
		cleanstring(tablename);
		cleanstring(valuename);
		sprintf(tablename, "SUCCESS");
		sprintf(valuename, " ");
		encode_line(commandname, tablename, valuename, retline);
		sendall(sock, retline, sizeof(retline));
	    }
	    else {
		printf("authenticated\n");
		cleanstring(tablename);
		cleanstring(valuename);
		sprintf(tablename, "FAIL");
		sprintf(valuename, " ");
		encode_line(commandname, tablename, valuename, retline);
		sendall(sock, retline, sizeof(retline));
		//strncpy(fail, "AUTH$FAIL", sizeof(fail));
		//sendall(sock, fail, sizeof(fail));
			}
	}
	else {
	    cleanstring(tablename);
	    cleanstring(valuename);
	    sprintf(tablename, "FAIL");
	    sprintf(valuename, "");
	    encode_line(commandname, tablename, valuename, retline);
	    sendall(sock, retline, sizeof(retline));
	    //strncpy(fail, "AUTH$FAIL", sizeof(fail));
	    //sendall(sock, fail, sizeof(fail));
	}
    }
    else if(strcmp(commandname, "GET") == 0){
	// check if authenticated
	if ((*auth_success) == 0){
	    //not authenticated
	    cleanstring(tablename);
	    cleanstring(valuename);
	    sprintf(tablename, "FAIL");
	    sprintf(valuename, "AUTH");
	    encode_line(commandname, tablename, valuename, retline);
	    sendall(sock, retline, sizeof(retline));
	    //strncpy(success, "AUTH", sizeof(success));
	    //sendall(sock, success, sizeof(success));
	}
	printf("tablename: %s\n", tablename);
	index=find_index(params->tablelist, tablename);
	printf("index: %d\n", index);
	if(index != -1) {
	    //name found
	    struct city *head = (headlist)[index];
	    print_city(head);
	    struct city *temp = find_city(head, keyname);
	    //printf("temp key: %s\n", temp->name);
	    //printf("temp colnum: %d\n", temp->numocolumns);
	    if(temp == NULL){
		//key doesn't exist
		//strncpy(fail, "GET$KEY$FAIL$FAIL", sizeof(fail));
		//sendall(sock, fail, sizeof(fail))
		
		cleanstring(tablename);
		cleanstring(valuename);
		sprintf(tablename, "FAIL");
		sprintf(valuename, "KEY");
		//printf("key doesn't exist\n");
		encode_line(commandname, tablename, valuename, retline);
		sendall(sock, retline, sizeof(retline));
		
	    }
	    else {
		//key exists
		//printf("columnlist: %s\n", temp->columnlist);
		//printf("encoded_value: %s\n", encoded_value);
		//printf("temp->numocolumns: %d\n", temp->numocolumns);
		cleanstring(encoded_value);
		encode_retval(temp->columnlist, encoded_value, temp->numocolumns);
		cleanstring(tablename);
		cleanstring(valuename);
		sprintf(tablename, "SUCCESS");
		sprintf(valuename, "%s", encoded_value);
		printf("serverside\n");
		printf("tablename: %s\n", tablename);
		printf("valuename: %s\n", valuename);
		encode_line(commandname, tablename, valuename, retline);

		
		char temp_str[100];
		char number[100];
		strcpy(temp_str, " COUNTER ");
		sprintf(number, "%d", temp->counter);
		strcat(temp_str, number);
		strcat(retline, temp_str);
		sendall(sock, retline, sizeof(retline));
		//sprintf(success, "GET$SUCCESS$%s$%s", temp->name, temp->population);
		//sendall(sock, success, sizeof(success));
	    }
	}
	else {
	    //table doesn't exist
	    cleanstring(tablename);
	    cleanstring(valuename);
	    sprintf(tablename, "FAIL");
	    sprintf(valuename, "TABLE");
	    encode_line(commandname, tablename, valuename, retline);
	    sendall(sock, retline, sizeof(retline));
	    //strncpy(fail, "GET$TABLE$FAIL$FAIL", sizeof(fail));
	    //sendall(sock, fail, sizeof(fail));
	}
    }
    else if(strcmp(commandname, "QUERY") == 0) {//query
	//what to do?
	//first allocate a keylist
	//then do searching
	//when done, encode the keylist and send back to client
	puts("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$HANDLEQUERY$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
	struct queryarg *testque = (struct queryarg *)malloc(sizeof(struct queryarg));
	int numque = 0;
	int questatus = 0;
	char server_keylist[1000][1024];
	for(i = 0; i < 1000; i++){
	    cleanstring(server_keylist[i]);
	}
	strncpy(server_keylist[0], "testcopy", sizeof(server_keylist[0]));
	index = find_index(params->tablelist, tablename);
	//printf("index is %d\n", index);
	if(index != -1){
	    //found matching name in tablelist
	    struct city *node = (headlist)[index];
	    numque = query_argument(testque, valuename);
	    //printf("numque = %d\n", numque);
	    testque->max_keys++;
	    questatus = query_write(server_keylist, testque, node, &testque->max_keys, &numque);
	    if(questatus == -1) {
		//printf("query incorrect\n");
	    }
	    else if(questatus == 0) {
		//printf("query correct\n");
		i = 1;
		if(server_keylist[i][0] == '\0') {
		    printf("no matching keys detected.\n");
		}
		while(server_keylist[i][0] != '\0'){
		    printf("keylist[%d]: %s\n", i, server_keylist[i]);
		    i++;
		}
		if(i > testque->max_keys){
		    i = testque->max_keys;
		}
		encode_queryret(i, server_keylist, retline);
		//printf("query retline: %s\n", retline);
		sendall(sock, retline, sizeof(retline));
	    }
	    free(testque);
	    testque = NULL;
	}
	else{
	    //table doesn't exist
	    printf("table doesn't exist\n");
	    cleanstring(retline);
	    sprintf(retline, "&QUERY&$FAIL$^TABLE^");
	    sendall(sock, retline, sizeof(retline));
	}
	puts("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%HANDLEQUERY_END%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
    }
    sendall(sock, "\n", 1);
    return 0;
}
Ejemplo n.º 16
0
/* Load the configuration file if necessary.
 * Return non-zero if we've successifully read the file or if the
 * file hasn't changed.
 */
static inline int load_file(const char *fname)
{
	int		 fp;
	struct stat	 lst, fst;
	char		 buf[BUFSIZ];
	centry		 task, next_task;
	char		*p;
	int		 line = 0;
	int		 res;
	int		 moreinput;
	static time_t	 file_mtime = 0;

	/* Stage one is open the file for read */
	fp = open(fname, O_RDONLY);
	if (fp == -1) {
		syslog(LOG_ERR, "cannot open crontab");
		goto failed;
	}
	
	/* Stage two is check permissions on file */
	if (0 != lstat(fname, &lst) || 0 != fstat(fp, &fst)) {
		syslog(LOG_ERR, "cannot stat crontab");
		goto failed;
	}
	if ((lst.st_mode & S_IFREG) == 0) {
		syslog(LOG_ERR, "crontab not regular file");
		goto failed;
	}
	if (fst.st_ino != lst.st_ino) {
		syslog(LOG_ERR, "crontab inode changed between stat and open");
		goto failed;
	}
	if (fst.st_dev != lst.st_dev) {
		syslog(LOG_ERR, "crontab device changed between stat and open");
		goto failed;
	}
	if (fst.st_uid) {
		syslog(LOG_ERR, "crontab not owned by uid 0");
		goto failed;
	}
	if (fst.st_mode & (S_IWGRP | S_IWOTH)) {
		syslog(LOG_ERR, "crontab group and/or world writable");
		goto failed;
	}

	/* Check to see if the file has been modified */
	if (fst.st_mtime == file_mtime)
		goto success;
	file_mtime = fst.st_mtime;
	syslog(LOG_INFO, "loading crontab file %s", fname);

	/* Purge any existing tasks from the task list */
	for (task = tasklist; task != NULL; task=next_task) {
		next_task = task->next;
		if (task->username != NULL)
			free(task->username);
		if (task->prog != NULL)
			free(task->prog);
		if (task->environ != NULL)
			free(task->environ);
		free(task);
	}
	tasklist = NULL;
	
	/* Purge any saved environment and restore to default */
	zapenv();
	stoenv("SHELL", "/bin/sh");
	stoenv("PATH", "/bin:/usr/bin:/etc");

	/* Finally get around to reading the file */
	do {
		moreinput = fdgets(buf, BUFSIZ, fp);
		line++;
		/* Remove trailing newline and spaces if present */
		if ((p = strchr(buf, '\n')) == NULL)
			goto failed;
		while (isspace(*p))
			*p-- = '\0';

		/* Remove leading spaces */
		for (p = buf; *p != '\0' && isspace(*p); p++);
		if (*p == '\0') continue;
		if (*p == '#') continue;

		/* Now decode everything */
		if (isdigit(*p) || *p == '*') {		/* Assume this is a command */
			res = decode_line(p);
		} else {			/* This will be an environment variable setting */
			res = decode_env(p);
		}
		if (!res) {
			syslog(LOG_ERR, "crontab has malformed input line %d", line);
		}
	} while (moreinput);
	zapenv();		/* Do it again to save memory */
success:
	close(fp);
	return 1;
/* Come here on failure for any reason */
failed:
	if (fp >= 0)
		close(fp);
	return 0;
}
Ejemplo n.º 17
0
    void push_back(bool bit) {
      bits_.push_back(bit);
      switch (get_state()) {
      case STATE_UNLOCKED:
        data_.clear();
        data_ok_ = false;
        if (bits_.size() == 44) {
#if 0
          std::cout << "D ";
          std::copy(bits_.begin(),    bits_.begin()+11, std::ostream_iterator<bool>(std::cout, ""));
          std::cout << "\nD ";
          std::copy(bits_.begin()+33, bits_.begin()+44, std::ostream_iterator<bool>(std::cout, ""));
          std::cout << "\nS ";
          std::copy(start_sequence(), start_sequence()+11, std::ostream_iterator<bool>(std::cout, ""));
          std::cout << std::endl;
          std::cout << "TESTs: "
                    << std::equal(bits_.begin(),    bits_.begin()+11, start_sequence()) << " "
                    << std::equal(bits_.begin()+11, bits_.begin()+22, bits_.begin()+22) << " "
                    << std::equal(bits_.begin()+33, bits_.begin()+44, start_sequence()) << std::endl;

#endif
          if (std::equal(bits_.begin(),    bits_.begin()+11, start_sequence()) &&
              std::equal(bits_.begin()+11, bits_.begin()+22, bits_.begin()+22) &&
              std::equal(bits_.begin()+33, bits_.begin()+44, start_sequence())) {
            const std::pair<unsigned char, bool> len1(decode_line(bits_.begin()+11));
            const std::pair<unsigned char, bool> len2(decode_line(bits_.begin()+22));
#if 0
            std::cout << "D found start: length = "
                      << int(len1.first) << " "
                      << int(len2.first) << " "
                      << len1.second << "," << len2.second
                      << std::endl;
#endif
            if (len1.second && len2.second && len1.first == len2.first) {
              len_ = len1.first;
              for (size_t i(0); i<44; ++i)
                bits_.pop_front();
              set_state(STATE_LOCKED);
              break;
            }
          }
          if (get_state() == STATE_UNLOCKED)
            bits_.pop_front();
        }
        break;
      case STATE_LOCKED:
        if (bits_.size() == 11) {
          const std::pair<unsigned char, bool> b(decode_line(bits_.begin()));
          if (not b.second)
            set_state(STATE_UNLOCKED);
          else {
            if (data_.size() < len_)  {
              data_.push_back(b.first);
            } else {
#if 0
              std::cout << "D checksum: "
                        << (std::accumulate(data_.begin(), data_.end(), 0) % 256) << " == " << int(b.first) << std::endl;
#endif
              if (std::accumulate(data_.begin(), data_.end(), 0) % 256 == b.first) {
#if 0
                std::cout << "D data= ";
                std::copy(data_.begin(), data_.end(), std::ostream_iterator<int>(std::cout, " "));
                std::cout << std::endl;
#endif
                set_state(STATE_FINISH_PACKET);
              }
            }
            bits_.clear();
          }
        }
        break;
      case STATE_FINISH_PACKET:
        if (bits_.size() == 11) {
          if (std::equal(bits_.begin(), bits_.begin()+11, finish_sequence())) {
#if 0
            std::cout << "D everything OK!\n";
#endif
            data_ok_ = true;
          }
          set_state(STATE_UNLOCKED);
          bits_.clear();
        }
        break;
      default:
        ;
      }
    }