Пример #1
0
static int query_action_proc(int def, int qtype, char *query)
{
 char reply_text[INPUT_LENGTH];
 int sel, key, ukey;
 char *sel_ptr, *rt_ptr;
 int rt_len;

 if(query!=NULL)
  msg_cprintf(H_PROMPT, (FMSG *)strform, query);
 #if SFX_LEVEL>=ARJ
  if(qtype!=QUERY_CRITICAL&&queries_assume_no[qtype])
  {
   msg_cprintf(H_OPER, M_NO);
   msg_cprintf(0, (FMSG *)lf);
   return(0);
  }
  if(qtype!=QUERY_CRITICAL&&queries_assume_yes[qtype])
  {
   msg_cprintf(H_OPER, M_YES);
   msg_cprintf(0, (FMSG *)lf);
   return(1);
  }
 #endif
 if(kbd_cleanup_on_input)
  fetch_keystrokes();
 #if SFX_LEVEL>=ARJ
  if(accept_shortcut_keys)
  {
   while(1)
   {
    do
    {
     while(1)
     {
      key=uni_getch();
      /* If possible default action selected */
      if(def!=0&&key==LF)
      {
       msg_cprintf(0, (FMSG *)lf);
       if(def==1)
        return(1);
       if(def==2)
        return(0);
      }
      ukey=toupper(key);
      far_strcpy(strcpy_buf, M_REPLIES);
      sel_ptr=strchr(strcpy_buf, ukey);
      sel=sel_ptr-strcpy_buf;
      if(ukey!=0&&sel_ptr!=NULL&&(qtype!=QUERY_CRITICAL||sel<=REPLY_QUIT))
       break;
      fetch_keystrokes();
      nputc(BEL);
     }
     nputc(key);
     msg_cprintf(0, (FMSG *)lf);
    } while(sel>MAX_REPLY);
    switch(sel)
    {
     case REPLY_YES:
      return(1);
     case REPLY_NO:
      return(0);
     case REPLY_QUIT:
      exit(ARJ_ERL_WARNING);
     case REPLY_ALL:
      if(qtype!=QUERY_CRITICAL)
       queries_assume_yes[qtype]=1;
      return(1);
     case REPLY_SKIP:
      if(qtype!=QUERY_CRITICAL)
       queries_assume_no[qtype]=1;
      return(0);
     case REPLY_GLOBAL:
      yes_on_all_queries=1;
      return(1);
     case REPLY_COMMAND:
      query_cmd();
      if(query!=NULL)
       msg_cprintf(H_PROMPT, (FMSG *)strform, query);
    }
   }
   /* There is no way down here */
  }
 #endif
 /* Use an editable field */
 while(1)
 {
  read_line(reply_text, INPUT_LENGTH);
  for(rt_ptr=reply_text; rt_ptr[0]==' '; rt_ptr++);
  if((rt_len=strlen(rt_ptr))>0)
  {
   strupper(rt_ptr);
   if(!msg_strncmp(rt_ptr, reply_help, rt_len))
   {
    far_strcpy(strcpy_buf, (qtype==QUERY_CRITICAL)?M_REPLIES_HELP:M_ALL_REPLIES_HELP);
    msg_cprintf(0, (FMSG *)strcpy_buf);
    continue;
   }
   else if(!msg_strncmp(rt_ptr, M_NO, rt_len))
    return(0);
   else if(!msg_strncmp(rt_ptr, M_YES, rt_len))
    return(1);
   else if(!msg_strncmp(rt_ptr, M_QUIT, rt_len))
    exit(1);
   else if(qtype!=QUERY_CRITICAL)
   {
    #if SFX_LEVEL>=ARJ
     if(!msg_strncmp(rt_ptr, M_ALWAYS, rt_len))
     {
      if(qtype!=QUERY_CRITICAL)
       queries_assume_yes[qtype]=1;
      return(1);
     }
     if(!msg_strncmp(rt_ptr, M_SKIP, rt_len))
     {
      if(qtype!=QUERY_CRITICAL)
       queries_assume_no[qtype]=1;
      return(0);
     }
    #endif
    if(!msg_strncmp(rt_ptr, M_GLOBAL, rt_len))
    {
     yes_on_all_queries=1;
     return(1);
    }
    #if SFX_LEVEL>=ARJ
     if(!msg_strncmp(rt_ptr, M_COMMAND, rt_len))
     {
      query_cmd();
      if(query!=NULL)
       msg_cprintf(H_PROMPT, (FMSG *)strform, query);
      continue;
     }
    #endif
   }
  }
  else
  {
   if(def==1)
    return(1);
   if(def==2)
    return(0);
  }
  fetch_keystrokes();
  nputc(BEL);
  msg_cprintf(0, M_REPLIES_HELP);
 }
}
Пример #2
0
int main()
{
    /* we will just use ordinary idle mode */
    set_sleep_mode(SLEEP_MODE_IDLE);

    /* setup uart */
    uart_init();

    while(1)
    {
        /* setup sd card slot */
        if(!sd_raw_init())
        {
#if DEBUG
            uart_puts_p(PSTR("MMC/SD initialization failed\n"));
#endif
            continue;
        }

        /* open first partition */
        struct partition_struct* partition = partition_open(sd_raw_read,
                                             sd_raw_read_interval,
#if SD_RAW_WRITE_SUPPORT
                                             sd_raw_write,
                                             sd_raw_write_interval,
#else
                                             0,
                                             0,
#endif
                                             0
                                                           );

        if(!partition)
        {
            /* If the partition did not open, assume the storage device
             * is a "superfloppy", i.e. has no MBR.
             */
            partition = partition_open(sd_raw_read,
                                       sd_raw_read_interval,
#if SD_RAW_WRITE_SUPPORT
                                       sd_raw_write,
                                       sd_raw_write_interval,
#else
                                       0,
                                       0,
#endif
                                       -1
                                      );
            if(!partition)
            {
#if DEBUG
                uart_puts_p(PSTR("opening partition failed\n"));
#endif
                continue;
            }
        }

        /* open file system */
        struct fat_fs_struct* fs = fat_open(partition);
        if(!fs)
        {
#if DEBUG
            uart_puts_p(PSTR("opening filesystem failed\n"));
#endif
            continue;
        }

        /* open root directory */
        struct fat_dir_entry_struct directory;
        fat_get_dir_entry_of_path(fs, "/", &directory);

        struct fat_dir_struct* dd = fat_open_dir(fs, &directory);
        if(!dd)
        {
#if DEBUG
            uart_puts_p(PSTR("opening root directory failed\n"));
#endif
            continue;
        }

        /* print some card information as a boot message */
        print_disk_info(fs);

        /* provide a simple shell */
        char buffer[24];
        while(1)
        {
            /* print prompt */
            uart_putc('>');
            uart_putc(' ');

            /* read command */
            char* command = buffer;
            if(read_line(command, sizeof(buffer)) < 1)
                continue;

            /* execute command */
            if(strcmp_P(command, PSTR("init")) == 0)
            {
                break;
            }
            else if(strncmp_P(command, PSTR("cd "), 3) == 0)
            {
                command += 3;
                if(command[0] == '\0')
                    continue;

                /* change directory */
                struct fat_dir_entry_struct subdir_entry;
                if(find_file_in_dir(fs, dd, command, &subdir_entry))
                {
                    struct fat_dir_struct* dd_new = fat_open_dir(fs, &subdir_entry);
                    if(dd_new)
                    {
                        fat_close_dir(dd);
                        dd = dd_new;
                        continue;
                    }
                }

                uart_puts_p(PSTR("directory not found: "));
                uart_puts(command);
                uart_putc('\n');
            }
            else if(strcmp_P(command, PSTR("ls")) == 0)
            {
                /* print directory listing */
                struct fat_dir_entry_struct dir_entry;
                while(fat_read_dir(dd, &dir_entry))
                {
                    uint8_t spaces = sizeof(dir_entry.long_name) - strlen(dir_entry.long_name) + 4;

                    uart_puts(dir_entry.long_name);
                    uart_putc(dir_entry.attributes & FAT_ATTRIB_DIR ? '/' : ' ');
                    while(spaces--)
                        uart_putc(' ');
                    uart_putdw_dec(dir_entry.file_size);
                    uart_putc('\n');
                }
            }
            else if(strncmp_P(command, PSTR("cat "), 4) == 0)
            {
                command += 4;
                if(command[0] == '\0')
                    continue;

                /* search file in current directory and open it */
                struct fat_file_struct* fd = open_file_in_dir(fs, dd, command);
                if(!fd)
                {
                    uart_puts_p(PSTR("error opening "));
                    uart_puts(command);
                    uart_putc('\n');
                    continue;
                }

                /* print file contents */
                uint8_t buffer[8];
                uint32_t offset = 0;
                while(fat_read_file(fd, buffer, sizeof(buffer)) > 0)
                {
                    uart_putdw_hex(offset);
                    uart_putc(':');
                    for(uint8_t i = 0; i < 8; ++i)
                    {
                        uart_putc(' ');
                        uart_putc_hex(buffer[i]);
                    }
                    uart_putc('\n');
                    offset += 8;
                }

                fat_close_file(fd);
            }
            else if(strcmp_P(command, PSTR("disk")) == 0)
            {
                if(!print_disk_info(fs))
                    uart_puts_p(PSTR("error reading disk info\n"));
            }
#if FAT_WRITE_SUPPORT
            else if(strncmp_P(command, PSTR("rm "), 3) == 0)
            {
                command += 3;
                if(command[0] == '\0')
                    continue;

                struct fat_dir_entry_struct file_entry;
                if(find_file_in_dir(fs, dd, command, &file_entry))
                {
                    if(fat_delete_file(fs, &file_entry))
                        continue;
                }

                uart_puts_p(PSTR("error deleting file: "));
                uart_puts(command);
                uart_putc('\n');
            }
            else if(strncmp_P(command, PSTR("touch "), 6) == 0)
            {
                command += 6;
                if(command[0] == '\0')
                    continue;

                struct fat_dir_entry_struct file_entry;
                if(!fat_create_file(dd, command, &file_entry))
                {
                    uart_puts_p(PSTR("error creating file: "));
                    uart_puts(command);
                    uart_putc('\n');
                }
            }
            else if(strncmp_P(command, PSTR("write "), 6) == 0)
            {
                command += 6;
                if(command[0] == '\0')
                    continue;

                char* offset_value = command;
                while(*offset_value != ' ' && *offset_value != '\0')
                    ++offset_value;

                if(*offset_value == ' ')
                    *offset_value++ = '\0';
                else
                    continue;

                /* search file in current directory and open it */
                struct fat_file_struct* fd = open_file_in_dir(fs, dd, command);
                if(!fd)
                {
                    uart_puts_p(PSTR("error opening "));
                    uart_puts(command);
                    uart_putc('\n');
                    continue;
                }

                int32_t offset = strtolong(offset_value);
                if(!fat_seek_file(fd, &offset, FAT_SEEK_SET))
                {
                    uart_puts_p(PSTR("error seeking on "));
                    uart_puts(command);
                    uart_putc('\n');

                    fat_close_file(fd);
                    continue;
                }

                /* read text from the shell and write it to the file */
                uint8_t data_len;
                while(1)
                {
                    /* give a different prompt */
                    uart_putc('<');
                    uart_putc(' ');

                    /* read one line of text */
                    data_len = read_line(buffer, sizeof(buffer));
                    if(!data_len)
                        break;

                    /* write text to file */
                    if(fat_write_file(fd, (uint8_t*) buffer, data_len) != data_len)
                    {
                        uart_puts_p(PSTR("error writing to file\n"));
                        break;
                    }
                }

                fat_close_file(fd);
            }
            else if(strncmp_P(command, PSTR("mkdir "), 6) == 0)
            {
                command += 6;
                if(command[0] == '\0')
                    continue;

                struct fat_dir_entry_struct dir_entry;
                if(!fat_create_dir(dd, command, &dir_entry))
                {
                    uart_puts_p(PSTR("error creating directory: "));
                    uart_puts(command);
                    uart_putc('\n');
                }
            }
#endif
#if SD_RAW_WRITE_BUFFERING
            else if(strcmp_P(command, PSTR("sync")) == 0)
            {
                if(!sd_raw_sync())
                    uart_puts_p(PSTR("error syncing disk\n"));
            }
#endif
            else
            {
                uart_puts_p(PSTR("unknown command: "));
                uart_puts(command);
                uart_putc('\n');
            }
        }

        /* close directory */
        fat_close_dir(dd);

        /* close file system */
        fat_close(fs);

        /* close partition */
        partition_close(partition);
    }

    return 0;
}
Пример #3
0
rt_err_t load_setup(void)
{
    int fd, length;
    char line[64];

    fd = open(setup_fn, O_RDONLY, 0);
    if (fd >= 0)
    {
        length = read_line(fd, line, sizeof(line));
        if (strcmp(line, "[config]") == 0)
        {
            char* begin;

            // default_volume
            length = read_line(fd, line, sizeof(line));
            if (length == 0)
            {
                close(fd);
                load_default();
                return RT_EOK;
            }
            if (strncmp(line, kn_volume, sizeof(kn_volume) - 1) == 0)
            {
                begin = strchr(line, '=');
                begin++;
                radio_setup.default_volume = atoi(begin);
            }

            // lcd_brightness
            length = read_line(fd, line, sizeof(line));
            if (length == 0)
            {
                close(fd);
                load_default();
                return RT_EOK;
            }
            if (strncmp(line, kn_brightness, sizeof(kn_brightness) - 1) == 0)
            {
                begin = strchr(line, '=');
                begin++;
                radio_setup.lcd_brightness = atoi(begin);
            }

            // touch_min_x
            length = read_line(fd, line, sizeof(line));
            if (length == 0)
            {
                close(fd);
                load_default();
                return RT_EOK;
            }
            if (strncmp(line, kn_touch_min_x, sizeof(kn_touch_min_x) - 1) == 0)
            {
                begin = strchr(line, '=');
                begin++;
                radio_setup.touch_min_x = atoi(begin);
            }

            // touch_max_x
            length = read_line(fd, line, sizeof(line));
            if (length == 0)
            {
                close(fd);
                load_default();
                return RT_EOK;
            }
            if (strncmp(line, kn_touch_max_x, sizeof(kn_touch_max_x) - 1) == 0)
            {
                begin = strchr(line, '=');
                begin++;
                radio_setup.touch_max_x = atoi(begin);
            }

            // touch_min_y
            length = read_line(fd, line, sizeof(line));
            if (length == 0)
            {
                close(fd);
                load_default();
                return RT_EOK;
            }
            if (strncmp(line, kn_touch_min_y, sizeof(kn_touch_min_y) - 1) == 0)
            {
                begin = strchr(line, '=');
                begin++;
                radio_setup.touch_min_y = atoi(begin);
            }

            // touch_max_y
            length = read_line(fd, line, sizeof(line));
            if (length == 0)
            {
                close(fd);
                load_default();
                return RT_EOK;
            }
            if (strncmp(line, kn_touch_max_y, sizeof(kn_touch_max_y) - 1) == 0)
            {
                begin = strchr(line, '=');
                begin++;
                radio_setup.touch_max_y = atoi(begin);
            }

        }
        else
        {
            close(fd);
            load_default();
            return RT_EOK;
        }
    }
    else
    {
        load_default();
    }

    close(fd);
    return RT_EOK;
}
Пример #4
0
int
main (int argc, char *argv[])
{
  int starting_line = 0;	/* line to start editing at */
  char command[QXE_PATH_MAX + 512];/* emacs command buffer */
  char fullpath[QXE_PATH_MAX+1];/* full pathname to file */
  char *eval_form = NULL;	/* form to evaluate with `-eval' */
  char *eval_function = NULL;	/* function to evaluate with `-f' */
  char *load_library = NULL;	/* library to load */
  int quick = 0;	       	/* quick edit, don't wait for user to
				   finish */
  int batch = 0;		/* batch mode */
  int view = 0;			/* view only. */
  int nofiles = 0;
  int errflg = 0;		/* option error */
  int s;			/* socket / msqid to server */
  int connect_type;		/* CONN_UNIX, CONN_INTERNET, or
				 * CONN_IPC */
  int suppress_windows_system = 0;
  char *display = NULL;
#ifdef INTERNET_DOMAIN_SOCKETS
  char *hostarg = NULL;		/* remote hostname */
  char *remotearg;
  char thishost[HOSTNAMSZ];	/* this hostname */
  char remotepath[QXE_PATH_MAX+1]; /* remote pathname */
  char *path;
  int rflg = 0;			/* pathname given on cmdline */
  char *portarg;
  unsigned short port = 0;	/* port to server */
#endif /* INTERNET_DOMAIN_SOCKETS */
#ifdef SYSV_IPC
  struct msgbuf *msgp;		/* message */
#endif /* SYSV_IPC */
  char *tty = NULL;
  char buffer[GSERV_BUFSZ + 1];	/* buffer to read pid */
  char result[GSERV_BUFSZ + 1];
  int i;

#ifdef INTERNET_DOMAIN_SOCKETS
  memset (remotepath, 0, sizeof (remotepath));
#endif /* INTERNET_DOMAIN_SOCKETS */

  progname = strrchr (argv[0], '/');
  if (progname)
    ++progname;
  else
    progname = argv[0];

#ifdef WIN32_NATIVE
  tmpdir = getenv ("TEMP");
  if (!tmpdir)
    tmpdir = getenv ("TMP");
  if (!tmpdir)
    tmpdir = "c:\\";
#else
#ifdef USE_TMPDIR
  tmpdir = getenv ("TMPDIR");
#endif
  if (!tmpdir)
    tmpdir = "/tmp";
#endif /* WIN32_NATIVE */
  display = getenv ("DISPLAY");
  if (display)
    display = my_strdup (display);
#ifndef HAVE_MS_WINDOWS
  else
    suppress_windows_system = 1;
#endif

  for (i = 1; argv[i] && !errflg; i++)
    {
      if (*argv[i] != '-')
	break;
      else if (*argv[i] == '-'
	       && (*(argv[i] + 1) == '\0'
		   || (*(argv[i] + 1) == '-' && *(argv[i] + 2) == '\0')))
	{
	  /* `-' or `--' */
	  ++i;
	  break;
	}

      if (!strcmp (argv[i], "-batch") || !strcmp (argv[i], "--batch"))
	batch = 1;
      else if (!strcmp (argv[i], "-eval") || !strcmp (argv[i], "--eval"))
	{
	  if (!argv[++i])
	    {
	      fprintf (stderr, "%s: `-eval' must be followed by an argument\n",
		       progname);
	      exit (1);
	    }
	  eval_form = argv[i];
	}
      else if (!strcmp (argv[i], "-display") || !strcmp (argv[i], "--display"))
	{
	  suppress_windows_system = 0;
	  if (!argv[++i])
	    {
	      fprintf (stderr,
		       "%s: `-display' must be followed by an argument\n",
		       progname);
	      exit (1);
	    }
	  if (display)
	    free (display);
	  /* no need to strdup. */
	  display = argv[i];
	}
      else if (!strcmp (argv[i], "-nw"))
	suppress_windows_system = 1;
      else
	{
	  /* Iterate over one-letter options. */
	  char *p;
	  int over = 0;
	  for (p = argv[i] + 1; *p && !over; p++)
	    {
	      switch (*p)
		{
		case 'q':
		  quick = 1;
		  break;
		case 'v':
		  view = 1;
		  break;
		case 'f':
		  GET_ARGUMENT (eval_function, "-f");
		  break;
		case 'l':
		  GET_ARGUMENT (load_library, "-l");
		  break;
#ifdef INTERNET_DOMAIN_SOCKETS
		case 'h':
		  GET_ARGUMENT (hostarg, "-h");
		  break;
		case 'p':
		  GET_ARGUMENT (portarg, "-p");
		  port = atoi (portarg);
		  break;
		case 'r':
		  GET_ARGUMENT (remotearg, "-r");
		  strncpy (remotepath, remotearg, QXE_PATH_MAX);
		  rflg = 1;
		  break;
#endif /* INTERNET_DOMAIN_SOCKETS */
		default:
		  errflg = 1;
		}
	    } /* for */
	} /* else */
    } /* for */

  if (errflg)
    {
      fprintf (stderr,
#ifdef INTERNET_DOMAIN_SOCKETS
	       "Usage: %s [-nw] [-display display] [-q] [-v] [-l library]\n"
               "       [-batch] [-f function] [-eval form]\n"
	       "       [-h host] [-p port] [-r remote-path] [[+line] file] ...\n",
#else /* !INTERNET_DOMAIN_SOCKETS */
	       "Usage: %s [-nw] [-q] [-v] [-l library] [-f function] [-eval form] "
	       "[[+line] path] ...\n",
#endif /* !INTERNET_DOMAIN_SOCKETS */
	       progname);
      exit (1);
    }
  if (batch && argv[i])
    {
      fprintf (stderr, "%s: Cannot specify `-batch' with file names\n",
	       progname);
      exit (1);
    }
#if defined(INTERNET_DOMAIN_SOCKETS)
  if (suppress_windows_system && hostarg)
    {
      fprintf (stderr, "%s: Remote editing is available only on X\n",
	       progname);
      exit (1);
    }
#endif
  *result = '\0';
  if (eval_function || eval_form || load_library)
    {
#if defined(INTERNET_DOMAIN_SOCKETS)
      connect_type = make_connection (hostarg, port, &s);
#else
      connect_type = make_connection (NULL, 0, &s);
#endif
      sprintf (command, "(gnuserv-eval%s '(progn ", quick ? "-quickly" : "");
      send_string (s, command);
      if (load_library)
	{
	  send_string (s , "(load-library ");
	  send_string (s, clean_string(load_library));
	  send_string (s, ") ");
	}
      if (eval_form)
	{
	  send_string (s, eval_form);
	}
      if (eval_function)
	{
	  send_string (s, "(");
	  send_string (s, eval_function);
	  send_string (s, ")");
	}
      send_string (s, "))");
      /* disconnect already sends EOT_STR */
#ifdef SYSV_IPC
      if (connect_type == (int) CONN_IPC)
	disconnect_from_ipc_server (s, msgp, batch && !quick);
#else /* !SYSV_IPC */
      if (connect_type != (int) CONN_IPC)
	disconnect_from_server (s, batch && !quick);
#endif /* !SYSV_IPC */
    } /* eval_function || eval_form || load_library */
  else if (batch)
    {
      /* no sexp on the command line, so read it from stdin */
      int nb;

#if defined(INTERNET_DOMAIN_SOCKETS)
      connect_type = make_connection (hostarg, port, &s);
#else
      connect_type = make_connection (NULL, 0, &s);
#endif
      sprintf (command, "(gnuserv-eval%s '(progn ", quick ? "-quickly" : "");
      send_string (s, command);

      while ((nb = read(fileno(stdin), buffer, GSERV_BUFSZ-1)) > 0)
	{
	  buffer[nb] = '\0';
	  send_string(s, buffer);
	}
      send_string(s,"))");
      /* disconnect already sends EOT_STR */
#ifdef SYSV_IPC
      if (connect_type == (int) CONN_IPC)
	disconnect_from_ipc_server (s, msgp, batch && !quick);
#else /* !SYSV_IPC */
      if (connect_type != (int) CONN_IPC)
	disconnect_from_server (s, batch && !quick);
#endif /* !SYSV_IPC */
    }

  if (!batch)
    {
      if (suppress_windows_system)
	{
	  tty = ttyname (0);
	  if (!tty)
	    {
	      fprintf (stderr, "%s: Not connected to a tty", progname);
	      exit (1);
	    }
#if defined(INTERNET_DOMAIN_SOCKETS)
	  connect_type = make_connection (hostarg, port, &s);
#else
	  connect_type = make_connection (NULL, 0, &s);
#endif
	  send_string (s, "(gnuserv-eval '(emacs-pid))");
	  send_string (s, EOT_STR);

	  if (read_line (s, buffer) == 0)
	    {
	      fprintf (stderr, "%s: Could not establish Emacs process id\n",
		       progname);
	      exit (1);
	    }
      /* Don't do disconnect_from_server because we have already read
	 data, and disconnect doesn't do anything else. */
#ifdef SYSV_IPC
	  if (connect_type == (int) CONN_IPC)
	    disconnect_from_ipc_server (s, msgp, FALSE);
#endif /* !SYSV_IPC */

	  emacs_pid = (pid_t)atol(buffer);
	  initialize_signals();
	} /* suppress_windows_system */

#if defined(INTERNET_DOMAIN_SOCKETS)
      connect_type = make_connection (hostarg, port, &s);
#else
      connect_type = make_connection (NULL, 0, &s);
#endif

#ifdef INTERNET_DOMAIN_SOCKETS
      if (connect_type == (int) CONN_INTERNET)
	{
	  char *ptr;
	  gethostname (thishost, HOSTNAMSZ);
	  if (!rflg)
	    {				/* attempt to generate a path
					 * to this machine */
	      if ((ptr = getenv ("GNU_NODE")) != NULL)
		/* user specified a path */
		strncpy (remotepath, ptr, QXE_PATH_MAX);
	    }
#if 0  /* This is really bogus... re-enable it if you must have it! */
#if defined (hp9000s800)
	  else if (strcmp (thishost,hostarg))
	    {	/* try /net/thishost */
	      strcpy (remotepath, "/net/");		/* (this fails using internet
							   addresses) */
	      strcat (remotepath, thishost);
	    }
#endif
#endif
	}
      else
	{			/* same machines, no need for path */
	  remotepath[0] = '\0';	/* default is the empty path */
	}
#endif /* INTERNET_DOMAIN_SOCKETS */

#ifdef SYSV_IPC
      if ((msgp = (struct msgbuf *)
	   malloc (sizeof *msgp + GSERV_BUFSZ)) == NULL)
	{
	  fprintf (stderr, "%s: not enough memory for message buffer\n", progname);
	  exit (1);
	} /* if */

      msgp->mtext[0] = '\0';			/* ready for later strcats */
#endif /* SYSV_IPC */

      if (suppress_windows_system)
	{
	  char *term = getenv ("TERM");
	  if (!term)
	    {
	      fprintf (stderr, "%s: unknown terminal type\n", progname);
	      exit (1);
	    }
	  sprintf (command, "(gnuserv-edit-files '(tty %s %s %d) '(",
		   clean_string (tty), clean_string (term), (int)getpid ());
	}
      else /* !suppress_windows_system */
	{
	  if (0)
	    ;
#ifdef HAVE_X_WINDOWS
	  else if (display)
	    sprintf (command, "(gnuserv-edit-files '(x %s) '(",
		     clean_string (display));
#endif
#ifdef HAVE_GTK
	  else if (display)
	    sprintf (command, 
                     /* #### We should probably do this sort of thing for
                        other window systems. */
                     "(gnuserv-edit-files (assoc* t '((gtk nil) (x %s)) "
                     ":key #'valid-device-type-p) '(", clean_string (display));
#endif
#ifdef HAVE_MS_WINDOWS
	  else
	    sprintf (command, "(gnuserv-edit-files '(mswindows nil) '(");
#endif
	} /* !suppress_windows_system */
      send_string (s, command);

      if (!argv[i])
	nofiles = 1;

      for (; argv[i]; i++)
	{
	  if (i < argc - 1 && *argv[i] == '+')
	    starting_line = atoi (argv[i++]);

	  /* If the last argument is +something, treat it as a file. */
	  if (i == argc) --i;

	  filename_expand (fullpath, argv[i]);
#ifdef INTERNET_DOMAIN_SOCKETS
	  path = (char *) malloc (strlen (remotepath) + strlen (fullpath) + 1);
	  sprintf (path, "%s%s", remotepath, fullpath);
#else
	  path = my_strdup (fullpath);
#endif
	  if ( starting_line ) {
	    sprintf (command, "(%d . %s)", starting_line, clean_string (path));
	  } else {
	    sprintf (command, "(nil . %s)", clean_string (path));
	  }

	  send_string (s, command);
	  free (path);
	} /* for */

      sprintf (command, ")%s%s",
	       (quick || (nofiles && !suppress_windows_system)) ? " 'quick" : "",
	       view ? " 'view" : "");
      send_string (s, command);
      send_string (s, ")");

#ifdef SYSV_IPC
      if (connect_type == (int) CONN_IPC)
	disconnect_from_ipc_server (s, msgp, FALSE);
#else /* !SYSV_IPC */
      if (connect_type != (int) CONN_IPC)
	disconnect_from_server (s, FALSE);
#endif /* !SYSV_IPC */
    } /* not batch */


  return 0;

} /* main */
Пример #5
0
static int rpl_read_header(AVFormatContext *s)
{
    AVIOContext *pb = s->pb;
    RPLContext *rpl = s->priv_data;
    AVStream *vst = NULL, *ast = NULL;
    int total_audio_size;
    int error = 0;

    uint32_t i;

    int32_t audio_format, chunk_catalog_offset, number_of_chunks;
    AVRational fps;

    char line[RPL_LINE_LENGTH];

    // The header for RPL/ARMovie files is 21 lines of text
    // containing the various header fields.  The fields are always
    // in the same order, and other text besides the first
    // number usually isn't important.
    // (The spec says that there exists some significance
    // for the text in a few cases; samples needed.)
    error |= read_line(pb, line, sizeof(line));      // ARMovie
    error |= read_line(pb, line, sizeof(line));      // movie name
    av_dict_set(&s->metadata, "title"    , line, 0);
    error |= read_line(pb, line, sizeof(line));      // date/copyright
    av_dict_set(&s->metadata, "copyright", line, 0);
    error |= read_line(pb, line, sizeof(line));      // author and other
    av_dict_set(&s->metadata, "author"   , line, 0);

    // video headers
    vst = avformat_new_stream(s, NULL);
    if (!vst)
        return AVERROR(ENOMEM);
    vst->codec->codec_type      = AVMEDIA_TYPE_VIDEO;
    vst->codec->codec_tag       = read_line_and_int(pb, &error);  // video format
    vst->codec->width           = read_line_and_int(pb, &error);  // video width
    vst->codec->height          = read_line_and_int(pb, &error);  // video height
    vst->codec->bits_per_coded_sample = read_line_and_int(pb, &error);  // video bits per sample
    error |= read_line(pb, line, sizeof(line));                   // video frames per second
    fps = read_fps(line, &error);
    avpriv_set_pts_info(vst, 32, fps.den, fps.num);

    // Figure out the video codec
    switch (vst->codec->codec_tag) {
#if 0
        case 122:
            vst->codec->codec_id = CODEC_ID_ESCAPE122;
            break;
#endif
        case 124:
            vst->codec->codec_id = CODEC_ID_ESCAPE124;
            // The header is wrong here, at least sometimes
            vst->codec->bits_per_coded_sample = 16;
            break;
        case 130:
            vst->codec->codec_id = CODEC_ID_ESCAPE130;
            break;
        default:
            av_log(s, AV_LOG_WARNING,
                   "RPL video format %i not supported yet!\n",
                   vst->codec->codec_tag);
            vst->codec->codec_id = CODEC_ID_NONE;
    }

    // Audio headers

    // ARMovie supports multiple audio tracks; I don't have any
    // samples, though. This code will ignore additional tracks.
    audio_format = read_line_and_int(pb, &error);  // audio format ID
    if (audio_format) {
        ast = avformat_new_stream(s, NULL);
        if (!ast)
            return AVERROR(ENOMEM);
        ast->codec->codec_type      = AVMEDIA_TYPE_AUDIO;
        ast->codec->codec_tag       = audio_format;
        ast->codec->sample_rate     = read_line_and_int(pb, &error);  // audio bitrate
        ast->codec->channels        = read_line_and_int(pb, &error);  // number of audio channels
        ast->codec->bits_per_coded_sample = read_line_and_int(pb, &error);  // audio bits per sample
        // At least one sample uses 0 for ADPCM, which is really 4 bits
        // per sample.
        if (ast->codec->bits_per_coded_sample == 0)
            ast->codec->bits_per_coded_sample = 4;

        ast->codec->bit_rate = ast->codec->sample_rate *
                               ast->codec->bits_per_coded_sample *
                               ast->codec->channels;

        ast->codec->codec_id = CODEC_ID_NONE;
        switch (audio_format) {
            case 1:
                if (ast->codec->bits_per_coded_sample == 16) {
                    // 16-bit audio is always signed
                    ast->codec->codec_id = CODEC_ID_PCM_S16LE;
                    break;
                }
                // There are some other formats listed as legal per the spec;
                // samples needed.
                break;
            case 101:
                if (ast->codec->bits_per_coded_sample == 8) {
                    // The samples with this kind of audio that I have
                    // are all unsigned.
                    ast->codec->codec_id = CODEC_ID_PCM_U8;
                    break;
                } else if (ast->codec->bits_per_coded_sample == 4) {
                    ast->codec->codec_id = CODEC_ID_ADPCM_IMA_EA_SEAD;
                    break;
                }
                break;
        }
        if (ast->codec->codec_id == CODEC_ID_NONE) {
            av_log(s, AV_LOG_WARNING,
                   "RPL audio format %i not supported yet!\n",
                   audio_format);
        }
        avpriv_set_pts_info(ast, 32, 1, ast->codec->bit_rate);
    } else {
        for (i = 0; i < 3; i++)
            error |= read_line(pb, line, sizeof(line));
    }

    rpl->frames_per_chunk = read_line_and_int(pb, &error);  // video frames per chunk
    if (rpl->frames_per_chunk > 1 && vst->codec->codec_tag != 124)
        av_log(s, AV_LOG_WARNING,
               "Don't know how to split frames for video format %i. "
               "Video stream will be broken!\n", vst->codec->codec_tag);

    number_of_chunks = read_line_and_int(pb, &error);  // number of chunks in the file
    // The number in the header is actually the index of the last chunk.
    number_of_chunks++;

    error |= read_line(pb, line, sizeof(line));  // "even" chunk size in bytes
    error |= read_line(pb, line, sizeof(line));  // "odd" chunk size in bytes
    chunk_catalog_offset =                       // offset of the "chunk catalog"
        read_line_and_int(pb, &error);           //   (file index)
    error |= read_line(pb, line, sizeof(line));  // offset to "helpful" sprite
    error |= read_line(pb, line, sizeof(line));  // size of "helpful" sprite
    error |= read_line(pb, line, sizeof(line));  // offset to key frame list

    // Read the index
    avio_seek(pb, chunk_catalog_offset, SEEK_SET);
    total_audio_size = 0;
    for (i = 0; !error && i < number_of_chunks; i++) {
        int64_t offset, video_size, audio_size;
        error |= read_line(pb, line, sizeof(line));
        if (3 != sscanf(line, "%"PRId64" , %"PRId64" ; %"PRId64,
                        &offset, &video_size, &audio_size))
            error = -1;
        av_add_index_entry(vst, offset, i * rpl->frames_per_chunk,
                           video_size, rpl->frames_per_chunk, 0);
        if (ast)
            av_add_index_entry(ast, offset + video_size, total_audio_size,
                               audio_size, audio_size * 8, 0);
        total_audio_size += audio_size * 8;
    }

    if (error) return AVERROR(EIO);

    return 0;
}
Пример #6
0
static void
read_passwd(FILE *pfile, char *fname)
{
	char  line[1024], *p, *k, *u, *g;
	int   line_no = 0, len, colon;

	while (read_line(pfile, line, sizeof(line))) {
		line_no++;
		len = strlen(line);

		if (len > 0) {
			if (line[0] == '#')
				continue;
		}

		/*
		 * Check if we have the whole line
		 */
		if (line[len-1] != '\n') {
			fprintf(stderr, "line %d in \"%s\" is too long\n",
			    line_no, fname);
		} else {
			line[len-1] = '\0';
		}

		p = (char *)&line;

		k = p; colon = 0;
		while (*k != '\0') {
			if (*k == ':')
				colon++;
			k++;
		}

		if (colon > 0) {
			k = p;			/* save start of key  */
			while (*p != ':')
				p++;		/* find first "colon" */
			if (*p==':')
				*p++ = '\0';	/* terminate key */
			if (strlen(k) == 1) {
				if (*k == '+')
					continue;
			}
		}

		if (colon < 4) {
			fprintf(stderr, "syntax error at line %d in \"%s\"\n",
			    line_no, fname);
			continue;
		}

		while (*p != ':')
			p++;			/* find second "colon" */
		if (*p==':')
			*p++ = '\0';		/* terminate passwd */
		u = p;
		while (*p != ':')
			p++;			/* find third "colon" */
		if (*p==':')
			*p++ = '\0';		/* terminate uid */
		g = p;
		while (*p != ':')
			p++;			/* find fourth "colon" */
		if (*p==':')
			*p++ = '\0';		/* terminate gid */
		while (*p != '\0')
			p++;	/* find end of string */

		add_user(k, u, g);
	}
}
Пример #7
0
int read_poscar( FILE *fp, int *p_title_line, 
                 atom *p_molecule, int *p_date_line, int *p_pbc, int *p_num_atoms, 
                 int *p_num_of_mols, int *p_num_mol_members, int *p_mol_number, 
                 double *p_latt_vec, double *p_recip_latt_vec, double *p_abc, int *p_been_before, 
		 int *p_is_fract, int *p_is_cart, int *p_ion_number, int *p_num_types, 
                 double *p_scale_factor, coord_flags *p_fix_flags)

{
  int ichar[LINESIZ];
  int place,itsanum;
  int idave,num_of_chars,is_biosym,idummy,iloop;
  int at_end, skip, lower_case;
  int start,start2,start3,start4;
  int error, good_read;
  int *p_this_ion_number;

  double dot, cell_volume;
  double a_cross_b[3], b_cross_c[3], c_cross_a[3];

  char *p_key;
  char *tok;

  atom *p_atom;

/* assume poscar file only ever contains one molecule */

     *p_num_of_mols=1;

/* get title line */

     num_of_chars= read_line ( fp, p_title_line);
     printf("Read title line: \n");
     put_string(stdout, p_title_line, num_of_chars);
     printf("\n");

/* get scale factor */

     skip= TRUE;
     lower_case= TRUE;
     
     *p_scale_factor = get_double( fp, skip, &error);

     if (!error)
       printf("Scale factor %10.6f\n", *p_scale_factor);
     else
       printf("Error while reading scale factor from POSCAR\n");

/* VASP POSCAR is always periodic, work out cell vectors and angles */
/* VASP POSCAR has lattice vectors in array as:   ax ay az          */
/* VASP POSCAR                                    bx by bz          */
/* VASP POSCAR                                    cx cy cz          */

     skip= TRUE;
     *p_latt_vec        = get_double(fp, skip, &error);
     skip= FALSE;
     *(p_latt_vec+1)    = get_double(fp, skip, &error);
     *(p_latt_vec+2)    = get_double(fp, skip, &error);

     skip= TRUE;
     *(p_latt_vec+3)    = get_double(fp, skip, &error);
     skip= FALSE;
     *(p_latt_vec+4)    = get_double(fp, skip, &error);
     *(p_latt_vec+5)    = get_double(fp, skip, &error);

     skip= TRUE;
     *(p_latt_vec+6)    = get_double(fp, skip, &error);
     skip= FALSE;
     *(p_latt_vec+7)    = get_double(fp, skip, &error);
     *(p_latt_vec+8)    = get_double(fp, skip, &error);

    latt_vecs_from_cart( p_latt_vec, p_recip_latt_vec, p_abc );

/* Read in the ion number flags */

      skip = TRUE;
	      
      error = FALSE;
      *p_num_types=0;
      p_this_ion_number =p_ion_number;
      while (!error)
	{
          *p_this_ion_number=get_integer( fp, skip, &error );

          skip = FALSE;
          ++*p_num_types;
          if (*p_num_types < MAXTYPES)
            {
               p_this_ion_number++;
            }
          else
            {
               printf("ERROR: MAXTYPES exceeded while reading VASP POSCAR file\n");
               exit(0);
            }
        }

      --*p_num_types;

      printf("Have %d types of ion with ",*p_num_types);

      *p_num_atoms=0;
      p_this_ion_number =p_ion_number;
      for (iloop=0; iloop < *p_num_types; iloop++)
	{
	   printf("%d, ", *p_this_ion_number);
	   *p_num_atoms += *p_this_ion_number;
           p_this_ion_number++;
	}

      printf(" instances of each, totaling %d\n", *p_num_atoms);

/* Read in the direct/cartesian flag data */

    skip=TRUE;
    tok = tok_get( fp, skip, TRUE);
    printf("Next read >>%s<<\n",tok);

/* Ignore Selective Dynamics line if present */

    if (!strncmp(tok,"sel",3))
      {
        tok = tok_get( fp, skip, TRUE);
        printf("Trying to skip Selective Dynamics, read >>%s<<\n",tok);
      }

    if (!strcmp(tok,"direct"))
    {
       printf("We have fractionals\n");
       *p_is_fract = TRUE;
    }
    else
    {
       printf("We have cartesians\n");
       *p_is_fract = FALSE;
    }

/* Read in the atomic data */

      for (iloop=0; iloop < *p_num_atoms; iloop++)
       {
        good_read= read_atom_data_vasp( fp, p_molecule+iloop, p_mol_number,  
                                                  p_fix_flags );
        p_fix_flags++;
       }

      printf("Co-ordinates read in:\n");
      for (iloop=0; iloop < *p_num_atoms; iloop++)
	      printf("%10.6f %10.6f %10.6f\n", (p_molecule+iloop)->x,
			                       (p_molecule+iloop)->y,
					       (p_molecule+iloop)->z);

  return 0;
}
Пример #8
0
Файл: ppm.c Проект: Athas/statml
pnm_img *pnm_read(const char file_name[]){
	FILE* fp;
	int status;
	int p;
	char buffer[MAX_LINE_SIZE];

	// open file
	fp = fopen(file_name,"r"); 
	if(fp == NULL) {
		path_error(file_name);
		return NULL;
	}
	
	// get PPM type	
	read_line(buffer,MAX_LINE_SIZE,fp);
	if(buffer[0] != 'P') {
		printf("Bad header format\n");
		return NULL;
	}
	p = atoi(buffer+1);
	// read past any comments
	do {
		read_line(buffer,MAX_LINE_SIZE,fp);
	} while(buffer[0] == '#');

	// get dimensions 
	char* current_position;
	int width = strtol(buffer,&current_position,10);
	if (*current_position == '\n'){
		read_line(buffer,MAX_LINE_SIZE,fp);
		current_position = buffer;
	}
	int height = strtol(current_position,&current_position,10);

	pnm_img* img = pnm_create(width, height, p);

	if (*current_position == '\n'){
		read_line(buffer,MAX_LINE_SIZE,fp);
		current_position = buffer;
	}
	img->max_color = strtol(current_position,&current_position,10);

	// extract pixel data
	if(p == 5 || p == 6){
		fread(img->pixels, sizeof(char),height*width*num_channels(p),fp);
	}
	else{
		int R, G, B;
		if (num_channels(p) == 3){
			pnm_pixmap* pm = (pnm_pixmap*)img->pixels;
			for(int i = 0; i< height*width; i++){
				status = fscanf(fp," %i %i %i", &R, &G, &B);
				if(status == EOF) {
					printf("Bad file format\n");
					return NULL;		
				}
				pm[i].R = (unsigned char)R;
				pm[i].G = (unsigned char)G;
				pm[i].B = (unsigned char)B;
			}
		}
		else{
			int grey;
			for(int i = 0; i< height*width; i++){
				status = fscanf(fp," %i", &grey);
				if(status == EOF) {
					printf("Bad file format\n");
					return NULL;		
				}
				*((unsigned char*)img->pixels+i) = (unsigned char)grey;
			}
		}
	}
	fclose(fp); 
	return img;
}
Пример #9
0
int main(int argc, char** argv)
{
    if (argc < 3)
    {
        error("Usage: ./program [sourceFile] [subtitleOffset]\n");
    }

    char *subtitleFileName = argv[1];
    size_t subtitleOfcet = atoi(argv[2]);
    
    if (subtitleOfcet == 0)
    {
        error("There is nothing to change!");
    }

    FILE *subtitleFile = fopen(subtitleFileName, "r+");
    if (!subtitleFile)
    {
        error(subtitleFileName);
    }

    size_t readBytes = 0;
    char *buffer = NULL;
    size_t bufferSize = 0;

    while (!feof(subtitleFile) || !ferror(subtitleFile))
    {
        long fileIndex = set_to_subtitle_timnig(&buffer, &bufferSize, subtitleFile);
        if (fileIndex == EOF)
        {
            break;
        }

        readBytes = read_line(&buffer, &bufferSize, subtitleFile);

        char temp[readBytes];
        strcpy(temp, buffer);

        char *firstTime = strtok(temp, " --> ");
        char *secondTime = strtok(NULL, " --> ");

        Times first, second;

        add_delay(&first, firstTime, subtitleOfcet);
        add_delay(&second, secondTime, subtitleOfcet);

        sprintf(temp, "%02d:%02d:%02d,%03d --> %02d:%02d:%02d,%03d\n",
                first.hours, first.minutes,
                first.seconds, first.milliseconds,
                second.hours, second.minutes,
                second.seconds, second.milliseconds);

        strncpy(buffer, temp, readBytes);

        fseek(subtitleFile, fileIndex, SEEK_SET);
        fwrite(buffer, 1, readBytes, subtitleFile);
    }

    fclose(subtitleFile);
    free(buffer);


    return (EXIT_SUCCESS);
}
Пример #10
0
static char *splice_lines(int *peof)
{
	static int n_nls;
	char *line;
	char *last_backslash;
	int splice = 0;

	if(n_nls){
		n_nls--;
		return ustrdup("");
	}

	line = read_line();
	if(!line){
		*peof = 1;
		return NULL;
	}
	if(option_trigraphs)
		line = expand_trigraphs(line);


	last_backslash = strrchr(line, '\\');
	if(last_backslash){
		char *i;
		/* is this the end of the line? */
		i = str_spc_skip(last_backslash + 1);
		if(*i == '\0'){
			splice = 1;

			if(i > last_backslash + 1){
				CPP_WARN(WBACKSLASH_SPACE_NEWLINE,
						"backslash and newline separated by space");
			}
		}
	}

	if(splice){
		char *next = splice_lines(peof);

		/* remove in any case */
		*last_backslash = '\0';

		if(next){
			const size_t this_len = last_backslash - line;
			const size_t next_len = strlen(next);

			n_nls++;

			line = urealloc1(line, this_len + next_len + 1);
			strcpy(line + this_len, next);
			free(next);
		}else{
			/* backslash-newline at eof
			 * else we may return non-null on eof,
			 * so we need an eof-check in read_line()
			 */
			CPP_WARN(WFINALESCAPE, "backslash-escape at eof");
			*peof = 1;
		}
	}

	return line;
}
Пример #11
0
jac0dim_ASL(ASL *asl, char *stub, ftnlen stub_len)
#endif
{
	FILE *nl;
	int i, k, nlv;
	char *s, *se;
	EdRead ER, *R;

	if (!asl)
		badasl_ASL(asl,0,"jac0dim");
	fpinit_ASL();	/* get IEEE arithmetic, if possible */

	if (stub_len <= 0)
		for(i = 0; stub[i]; i++);
	else
		for(i = stub_len; stub[i-1] == ' ' && i > 0; --i);
	filename = (char *)M1alloc(i + 5);
	s = stub_end = filename + i;
	strncpy(filename, stub, i);
	strcpy(s, ".nl");
	nl = fopen(filename, "rb");
	if (!nl && i > 3 && !strncmp(s-3, ".nl", 3)) {
		*s = 0;
		stub_end = s - 3;
		nl = fopen(filename, "rb");
		}
	if (!nl) {
		if (return_nofile)
			return 0;
		fflush(stdout);
		what_prog();
		fprintf(Stderr, "can't open %s\n", filename);
		exit(1);
		}
	R = EdReadInit_ASL(&ER, asl, nl, 0);
	R->Line = 0;
	s = read_line(R);
	binary_nl = 0;
	switch(*s) {
#ifdef DEPRECATED
		case 'E':	/* deprecated "-oe" format */
			{int ncsi = 0;
			k = Sscanf(s, "E%d %d %d %d %d %d", &n_var, &n_con,
				&n_obj, &maxrownamelen, &maxcolnamelen, &ncsi);
			if (k < 5)
				badints(R, k, 5);
			if (ncsi) {
				if (ncsi != 6) {
					badread(R);
					fprintf(Stderr,
					 "expected 6th integer to be 0 or 6, not %d\n",
						ncsi);
					exit(1);
					}
				s = read_line(R);
				k = Sscanf(s, " %d %d %d %d %d %d",
					&comb, &comc, &como, &comc1, &como1, &nfunc);
				if (k != 6)
					badints(R, k, 6);
				}
			}
			break;
#endif
		case 'b':
			binary_nl = 1;
		case 'g':
			if (k = ampl_options[0] = strtol(++s, &se, 10)) {
				if (k > 9) {
					fprintf(Stderr,
					"ampl_options = %d is too large\n", k);
					exit(1);
					}
				for(i = 1; i <= k && se > s; i++)
					ampl_options[i] = strtol(s = se,&se,10);
				if (ampl_options[2] == 3)
					ampl_vbtol = strtod(s = se, &se);
				}
			s = read_line(R);
			n_eqn = -1;
			k = Sscanf(s, " %d %d %d %d %d %d", &n_var, &n_con,
				&n_obj, &nranges, &n_eqn, &n_lcon);
			if (k < 3)
				badints(R,k,3);
			nclcon = n_con + n_lcon;

			/* formerly read2(R, &nlc, &nlo); */
			s = read_line(R);
			n_cc = nlcc = 0;
			k = Sscanf(s, " %d %d %d %d", &nlc, &nlo, &n_cc, &nlcc);
			if (k < 2)
				badints(R,k,2);
			n_cc += nlcc;

			read2(R, &nlnc, &lnc);
			nlvb = -1;
			s = read_line(R);
			k = Sscanf(s, " %d %d %d", &nlvc, &nlvo, &nlvb);
			if (k < 2)
				badints(R,k,2);

			/* read2(R, &nwv, &nfunc); */
			s = read_line(R);
			asl->i.flags = 0;
			k = Sscanf(s, " %d %d %d %d", &nwv, &nfunc, &i,
				&asl->i.flags);
			if (k < 2)
				badints(R,k,2);
			else if (k >= 3 && i != Arith_Kind_ASL && i) {
#ifdef Want_bswap
				if (i > 0 && i + Arith_Kind_ASL == 3) {
					asl->i.iadjfcn = asl->i.dadjfcn = bswap_ASL;
					binary_nl = i << 1;
					}
				else
#endif
					badfmt(R);
				}

			if (nlvb < 0)	/* ampl versions < 19930630 */
				read2(R, &nbv, &niv);
			else {
				s = read_line(R);
				k = Sscanf(s, " %d %d %d %d %d", &nbv, &niv,
					&nlvbi, &nlvci, &nlvoi);
				if (k != 5)
					badints(R,k,5);
				}
			read2(R, &nzc, &nzo);
			read2(R, &maxrownamelen, &maxcolnamelen);
			s = read_line(R);
			k = Sscanf(s, " %d %d %d %d %d", &comb, &comc, &como,
					&comc1, &como1);
			if (k != 5)
				badints(R,k,5);
		}
	student_check_ASL(asl);
	if (n_con < 0 || n_var <= 0 || n_obj < 0) {
		what_prog();
		fprintf(Stderr,
		"jacdim: got M = %d, N = %d, NO = %d\n", n_con, n_var, n_obj);
		exit(1);
		}
	asl->i.n_var0 = n_var;
	asl->i.n_con0 = n_con;
	if ((nlv = nlvc) < nlvo)
		nlv = nlvo;
	if (nlv <= 0)
		nlv = 1;
	x0len = nlv * sizeof(real);
	x0kind = ASL_first_x;
	n_conjac[0] = 0;
	n_conjac[1] = n_con;
	c_vars = o_vars = n_var;	/* confusion arises otherwise */
	return nl;
	}
Пример #12
0
bool read_config(FILE *file, bool is_active) {
	struct sway_config *old_config = config;
	config = malloc(sizeof(struct sway_config));

	config_defaults(config);
	config->reading = true;
	if (is_active) {
		sway_log(L_DEBUG, "Performing configuration file reload");
		config->reloading = true;
		config->active = true;
	}
	bool success = true;
	enum cmd_status block = CMD_BLOCK_END;

	int line_number = 0;
	char *line;
	while (!feof(file)) {
		line = read_line(file);
		line_number++;
		line = strip_comments(line);
		struct cmd_results *res = config_command(line);
		switch(res->status) {
		case CMD_FAILURE:
		case CMD_INVALID:
			sway_log(L_ERROR, "Error on line %i '%s': %s", line_number, line,
				res->error);
			success = false;
			break;

		case CMD_DEFER:
			sway_log(L_DEBUG, "Defferring command `%s'", line);
			list_add(config->cmd_queue, strdup(line));
			break;

		case CMD_BLOCK_MODE:
			if (block == CMD_BLOCK_END) {
				block = CMD_BLOCK_MODE;
			} else {
				sway_log(L_ERROR, "Invalid block '%s'", line);
			}
			break;

		case CMD_BLOCK_END:
			switch(block) {
			case CMD_BLOCK_MODE:
				sway_log(L_DEBUG, "End of mode block");
				config->current_mode = config->modes->items[0];
				break;

			case CMD_BLOCK_END:
				sway_log(L_ERROR, "Unmatched }");
				break;

			default:;
			}
		default:;
		}
		free(line);
		free(res);
	}

	if (is_active) {
		config->reloading = false;
		arrange_windows(&root_container, -1, -1);
	}
	if (old_config) {
		free_config(old_config);
	}

	config->reading = false;
	return success;
}
Пример #13
0
static void
process_stream(vector_t *keywords_vec, int need_bob)
{
	unsigned int i;
	keyword_t *keyword_vec;
	char *str;
	char *buf;
	vector_t *strvec;
	vector_t *prev_keywords = current_keywords;
	current_keywords = keywords_vec;
	int bob_needed = 0;

	buf = MALLOC(MAXBUF);
	while (read_line(buf, MAXBUF)) {
		strvec = alloc_strvec(buf);

		if (!strvec)
			continue;

		str = vector_slot(strvec, 0);

		if (skip_sublevel == -1) {
			/* There wasn't a '{' on the keyword line */
			if (!strcmp(str, BOB)) {
				/* We've got the opening '{' now */
				skip_sublevel = 1;
				free_strvec(strvec);
				continue;
			}
			else {
				/* The skipped keyword doesn't have a {} block, so we no longer want to skip */
				skip_sublevel = 0;
			}
		}
		if (skip_sublevel) {
			for (i = 0; i < vector_size(strvec); i++) {
				str = vector_slot(strvec,i);
				if (!strcmp(str,BOB))
					skip_sublevel++;
				else if (!strcmp(str,EOB)) {
					if (--skip_sublevel == 0)
						break;
				}
			}

			free_strvec(strvec);
			continue;
		}

		if (need_bob) {
			need_bob = 0;
			if (!strcmp(str, BOB) && kw_level > 0) {
				free_strvec(strvec);
				continue;
			}
			else
				log_message(LOG_INFO, "Missing '{' at beginning of configuration block");
		}
		else if (!strcmp(str, BOB)) {
			log_message(LOG_INFO, "Unexpected '{' - ignoring");
			free_strvec(strvec);
			continue;
		}

		if (!strcmp(str, EOB) && kw_level > 0) {
			free_strvec(strvec);
			break;
		}

		for (i = 0; i < vector_size(keywords_vec); i++) {
			keyword_vec = vector_slot(keywords_vec, i);

			if (!strcmp(keyword_vec->string, str)) {
				if (!keyword_vec->active) {
					if (!strcmp(vector_slot(strvec, vector_size(strvec)-1), BOB))
						skip_sublevel = 1;
					else
						skip_sublevel = -1;
				}

				/* There is an inconsistency here. 'static_ipaddress' for example
				 * does not have sub levels, but needs a '{' */
				if (keyword_vec->sub) {
					/* Remove a trailing '{' */
					char *bob = vector_slot(strvec, vector_size(strvec)-1) ;
					if (!strcmp(bob, BOB)) {
						vector_unset(strvec, vector_size(strvec)-1);
						FREE(bob);
						bob_needed = 0;
					}
					else
						bob_needed = 1;
				}

				if (keyword_vec->handler)
					(*keyword_vec->handler) (strvec);

				if (keyword_vec->sub) {
					kw_level++;
					process_stream(keyword_vec->sub, bob_needed);
					kw_level--;
					if (keyword_vec->active && keyword_vec->sub_close_handler)
						(*keyword_vec->sub_close_handler) ();
				}
				break;
			}
		}

		if (i >= vector_size(keywords_vec))
			log_message(LOG_INFO, "Unknown keyword '%s'", str );

		free_strvec(strvec);
	}

	current_keywords = prev_keywords;
	FREE(buf);
	return;
}
Пример #14
0
/* read old 3.0 or 4.0 dig file into array 
   returns number of elements read into array
   or -1 on error */
int read_dig(FILE * Digin, struct Map_info *Mapout,
	     struct Line **plines, int endian, int att)
{
    char buf[100];
    struct dig_head In_head;
    int lalloc, line = 0, type, portable = 1;
    int npoints = 0, nlines = 0, nbounds = 0;
    int ndpoints = 0, ndlines = 0, ndbounds = 0, nunknown = 0;
    struct Line *lines;
    struct line_pnts *nline;
    struct line_cats *cat_out;
    double dbuf;
    int ibuf;
    long lbuf;
    struct gvfile gvf;

    dig_file_init(&gvf);
    gvf.file = Digin;

    Vect__init_head(Mapout);
    /* set conversion matrices */
    dig_init_portable(&(In_head.port), endian);

    /* Version 3 dig files were not portable and some version 4 
     * files may be also non portable */

    G_message(_("Reading dig file..."));

    /* read and copy head */
    dig_fseek(&gvf, 0L, SEEK_SET);	/* set to beginning */

    if (0 >= dig__fread_port_C(buf, DIG4_ORGAN_LEN, &gvf))
	return -1;
    buf[DIG4_ORGAN_LEN - 1] = '\0';
    Vect_set_organization(Mapout, buf);

    if (0 >= dig__fread_port_C(buf, DIG4_DATE_LEN, &gvf))
	return -1;
    buf[DIG4_DATE_LEN - 1] = '\0';
    Vect_set_date(Mapout, buf);

    if (0 >= dig__fread_port_C(buf, DIG4_YOUR_NAME_LEN, &gvf))
	return -1;
    buf[DIG4_YOUR_NAME_LEN - 1] = '\0';
    Vect_set_person(Mapout, buf);

    if (0 >= dig__fread_port_C(buf, DIG4_MAP_NAME_LEN, &gvf))
	return -1;
    buf[DIG4_MAP_NAME_LEN - 1] = '\0';
    Vect_set_map_name(Mapout, buf);

    if (0 >= dig__fread_port_C(buf, DIG4_SOURCE_DATE_LEN, &gvf))
	return -1;
    buf[DIG4_SOURCE_DATE_LEN - 1] = '\0';
    Vect_set_map_date(Mapout, buf);

    if (0 >= dig__fread_port_C(buf, DIG4_LINE_3_LEN, &gvf))
	return -1;
    buf[DIG4_LINE_3_LEN - 1] = '\0';
    Vect_set_comment(Mapout, buf);

    if (0 >= dig__fread_port_C(buf, VERS_4_DATA_SIZE, &gvf))
	return -1;

    if (buf[0] != '%' || buf[1] != '%') {	/* Version3.0 */
	In_head.Version_Major = 3;
	portable = 0;		/* input vector is not portable format */
	G_message(_("Input file is version 3."));
    }
    else {
	In_head.Version_Major = 4;
	G_message(_("Input file is version 4."));
	/* determine if in portable format or not */
	if (buf[6] == 1 && (~buf[6] & 0xff) == (buf[7] & 0xff)) {	/* portable ? */
	    portable = 1;	/* input vector is portable format */
	}
	else {
	    portable = 0;	/* input vector is not portable format */
	}
    }
    if (portable == 1) {
	G_message(_("Input file is portable."));
    }
    else {
	G_warning(_("Input file is not portable. "
		    "We will attempt to convert anyway but conversion may fail. "
		    "Please read manual for detail information."));
    }

    /* set Cur_Head because it is used by dig__*_convert()
       called by dig__fread_port_*() */
    dig_set_cur_port(&(In_head.port));

    if (0 >= dig__fread_port_L(&lbuf, 1, &gvf))
	return -1;
    Vect_set_scale(Mapout, (int)lbuf);
    if (0 >= dig__fread_port_I(&ibuf, 1, &gvf))
	return -1;
    Vect_set_zone(Mapout, ibuf);
    if (0 >= dig__fread_port_D(&dbuf, 1, &gvf))
	return -1;		/* W */
    if (0 >= dig__fread_port_D(&dbuf, 1, &gvf))
	return -1;		/* E */
    if (0 >= dig__fread_port_D(&dbuf, 1, &gvf))
	return -1;		/* S */
    if (0 >= dig__fread_port_D(&dbuf, 1, &gvf))
	return -1;		/* N */
    if (0 >= dig__fread_port_D(&dbuf, 1, &gvf))
	return -1;
    Vect_set_thresh(Mapout, dbuf);

    /* reading dig file body (elements) */
    nline = Vect_new_line_struct();
    cat_out = Vect_new_cats_struct();

    lalloc = 0;
    lines = NULL;

    line = 0;
    while (1) {
	type = read_line(&gvf, nline);
	G_debug(3, "read line = %d, type = %d", line, type);
	if (type == -2)
	    break;		/* EOF */
	switch (type) {
	case GV_POINT:
	    npoints++;
	    break;
	case GV_LINE:
	    nlines++;
	    break;
	case GV_BOUNDARY:
	    nbounds++;
	    break;
	case 0:		/* dead */
	    break;
	default:
	    nunknown++;
	    break;
	}
	if (!(type & (GV_POINT | GV_LINE | GV_BOUNDARY)))
	    continue;

	if ((type & GV_BOUNDARY) || !att) {
	    Vect_write_line(Mapout, type, nline, cat_out);
	    /* reset In_head */
	    dig_set_cur_port(&(In_head.port));
	}
	else {			/* GV_POINT or GV_LINE */
	    if (line >= lalloc) {
		lalloc += 10000;
		lines =
		    (struct Line *)G_realloc(lines,
					     lalloc * sizeof(struct Line));
	    }
	    lines[line].type = type;
	    lines[line].n_points = nline->n_points;
	    lines[line].cat = -1;
	    lines[line].x =
		(double *)G_malloc(nline->n_points * sizeof(double));
	    lines[line].y =
		(double *)G_malloc(nline->n_points * sizeof(double));
	    memcpy((void *)lines[line].x, (void *)nline->x,
		   nline->n_points * sizeof(double));
	    memcpy((void *)lines[line].y, (void *)nline->y,
		   nline->n_points * sizeof(double));
	    line++;
	}
    }
    if (att) {
	G_message(_("[%d] points read to memory"), npoints);
	G_message(_("[%d] lines read to memory"), nlines);
    }
    else {
	G_message(_("[%d] points read and written to output"), npoints);
	G_message(_("[%d] lines read and written to output"), nlines);
    }
    G_message(_("[%d] area boundaries read and written to output"), nbounds);
    G_message(_("[%d] dead points skipped"), ndpoints);
    G_message(_("[%d] dead lines skipped"), ndlines);
    G_message(_("[%d] dead area boundaries skipped"), ndbounds);
    G_message(_("[%d] elements of unknown type skipped"), nunknown);

    G_message(_("[%d] elements read to memory"), line);

    *plines = lines;
    return (line);
}
Пример #15
0
int mailpop3_auth(mailpop3 * f, const char * auth_type,
    const char * server_fqdn,
    const char * local_ip_port,
    const char * remote_ip_port,
    const char * login, const char * auth_name,
    const char * password, const char * realm)
{
#ifdef USE_SASL
  int r;
  char command[POP3_STRING_SIZE];
  sasl_callback_t sasl_callback[5];
  const char * sasl_out;
  unsigned sasl_out_len;
  const char * mechusing;
  sasl_secret_t * secret;
  int res;
  size_t len;
  char * encoded;
  unsigned int encoded_len;
  unsigned int max_encoded;
  
  sasl_callback[0].id = SASL_CB_GETREALM;
  sasl_callback[0].proc =  sasl_getrealm;
  sasl_callback[0].context = f;
  sasl_callback[1].id = SASL_CB_USER;
  sasl_callback[1].proc =  sasl_getsimple;
  sasl_callback[1].context = f;
  sasl_callback[2].id = SASL_CB_AUTHNAME;
  sasl_callback[2].proc =  sasl_getsimple;
  sasl_callback[2].context = f; 
  sasl_callback[3].id = SASL_CB_PASS;
  sasl_callback[3].proc =  sasl_getsecret;
  sasl_callback[3].context = f;
  sasl_callback[4].id = SASL_CB_LIST_END;
  sasl_callback[4].proc =  NULL;
  sasl_callback[4].context = NULL;
  
  len = strlen(password);
  secret = malloc(sizeof(* secret) + len);
  if (secret == NULL) {
    res = MAILPOP3_ERROR_MEMORY;
    goto err;
  }
  secret->len = len;
  memcpy(secret->data, password, len + 1);
  
  f->pop3_sasl.sasl_server_fqdn = server_fqdn;
  f->pop3_sasl.sasl_login = login;
  f->pop3_sasl.sasl_auth_name = auth_name;
  f->pop3_sasl.sasl_password = password;
  f->pop3_sasl.sasl_realm = realm;
  f->pop3_sasl.sasl_secret = secret;
  
  /* init SASL */
  if (f->pop3_sasl.sasl_conn != NULL) {
    sasl_dispose((sasl_conn_t **) &f->pop3_sasl.sasl_conn);
    f->pop3_sasl.sasl_conn = NULL;
  }
  else {
    mailsasl_ref();
  }
  
  r = sasl_client_new("pop", server_fqdn,
      local_ip_port, remote_ip_port, sasl_callback, 0,
      (sasl_conn_t **) &f->pop3_sasl.sasl_conn);
  if (r != SASL_OK) {
    res = MAILPOP3_ERROR_BAD_USER;
    goto free_secret;
  }
  
  r = sasl_client_start(f->pop3_sasl.sasl_conn,
      auth_type, NULL, &sasl_out, &sasl_out_len, &mechusing);
  if ((r != SASL_CONTINUE) && (r != SASL_OK)) {
    res = MAILPOP3_ERROR_BAD_USER;
    goto free_sasl_conn;
  }
  
  snprintf(command, POP3_STRING_SIZE, "AUTH %s\r\n", auth_type);
  
  r = send_command(f, command);
  if (r == -1) {
    res = MAILPOP3_ERROR_STREAM;
    goto free_sasl_conn;
  }
  
  while (1) {
    char * response;
    
    response = read_line(f);
    
    r = parse_auth(f, response);
    switch (r) {
    case RESPONSE_OK:
      f->pop3_state = POP3_STATE_TRANSACTION;
      res = MAILPOP3_NO_ERROR;
      goto free_sasl_conn;
      
    case RESPONSE_ERR:
      res = MAILPOP3_ERROR_BAD_USER;
      goto free_sasl_conn;
    
    case RESPONSE_AUTH_CONT:
      {
        size_t response_len;
        char * decoded;
        unsigned int decoded_len;
        unsigned int max_decoded;
        int got_response;
        
        got_response = 1;
        if (* f->pop3_response == '\0')
          got_response = 0;
        
        if (got_response) {
          char * p;
          
          p = strchr(f->pop3_response, '\r');
          if (p != NULL) {
            * p = '\0';
          }
          p = strchr(f->pop3_response, '\n');
          if (p != NULL) {
            * p = '\0';
          }
          response_len = strlen(f->pop3_response);
          max_decoded = response_len * 3 / 4;
          decoded = malloc(max_decoded + 1);
          if (decoded == NULL) {
            res = MAILPOP3_ERROR_MEMORY;
            goto free_sasl_conn;
          }
          
          r = sasl_decode64(f->pop3_response, response_len,
              decoded, max_decoded + 1, &decoded_len);
          
          if (r != SASL_OK) {
            free(decoded);
            res = MAILPOP3_ERROR_MEMORY;
            goto free_sasl_conn;
          }
          
          r = sasl_client_step(f->pop3_sasl.sasl_conn,
              decoded, decoded_len, NULL, &sasl_out, &sasl_out_len);
          
          free(decoded);
          
          if ((r != SASL_CONTINUE) && (r != SASL_OK)) {
            res = MAILPOP3_ERROR_BAD_USER;
            goto free_sasl_conn;
          }
        }
        
        max_encoded = ((sasl_out_len + 2) / 3) * 4;
        encoded = malloc(max_encoded + 1);
        if (encoded == NULL) {
          res = MAILPOP3_ERROR_MEMORY;
          goto free_sasl_conn;
        }
        
        r = sasl_encode64(sasl_out, sasl_out_len,
            encoded, max_encoded + 1, &encoded_len);
        if (r != SASL_OK) {
          free(encoded);
          res = MAILPOP3_ERROR_MEMORY;
          goto free_sasl_conn;
        }
        
        snprintf(command, POP3_STRING_SIZE, "%s\r\n", encoded);
        r = send_command(f, command);
        
        free(encoded);
        
        if (r == -1) {
          res = MAILPOP3_ERROR_STREAM;
          goto free_sasl_conn;
        }
      }
      break;
    }
  }

  f->pop3_state = POP3_STATE_TRANSACTION;
  res = MAILPOP3_NO_ERROR;
  
 free_sasl_conn:
  sasl_dispose((sasl_conn_t **) &f->pop3_sasl.sasl_conn);
  f->pop3_sasl.sasl_conn = NULL;
  mailsasl_unref();
 free_secret:
  free(f->pop3_sasl.sasl_secret);
  f->pop3_sasl.sasl_secret = NULL;
 err:
  return res;
#else
  return MAILPOP3_ERROR_BAD_USER;
#endif
}
// Read VCF file
void vcf_file::scan_file(const string &chr, const string &exclude_chr)
{
	printLOG("Scanning " + filename + " ... \n");

	bool filter_by_chr = (chr != "");
	bool exclude_by_chr = (exclude_chr != "");
	string line, tmp;
	N_indv = 0;
	unsigned int N_read = 0;
	istringstream ss;
	string last_CHROM = "";
	N_entries=0;
	string CHROM;
	bool finish = false;
	int last_POS = -1;
	int POS;
	streampos filepos;

	while(!feof())
	{
		filepos = get_filepos();
		read_line(line);

		if (line.length() <= 2)
			continue;

		if (line[0] == '#')
		{
			if (line[1] == '#')
			{	// Meta information
				parse_meta(line);
			}
			else
			{	// Must be header information: #CHROM	POS	ID	REF	ALT	QUAL	FILTER	INFO	(FORMAT	NA00001 NA00002 ... )
				parse_header(line);
			}
		}
		else
		{	// Must be a data line
			ss.clear(); ss.str(line);
			ss >> CHROM;

			N_read++;

			if ((filter_by_chr == true) && (last_CHROM == chr) && (CHROM != chr))
			{	// Presuming the file to be sorted (it should be), we have already found the chromosome we wanted, so there's no need to continue.
				printLOG("\tCompleted reading required chromosome. Skipping remainder of file.\n");
				finish = true;
				break;
			}

			if (CHROM != last_CHROM)
			{
				printLOG("Currently scanning CHROM: " + CHROM);
				if ((exclude_by_chr == true) && (CHROM == exclude_chr))
					printLOG(" - excluded.");
				printLOG("\n");
				last_CHROM = CHROM;
				last_POS = -1;
			}

			if ((exclude_by_chr == true) && (CHROM == exclude_chr))
				continue;

			if (filter_by_chr == true)
			{	// For speed, only parse the entry if it's needed
				if (CHROM == chr)
				{
					ss >> POS;
					if (POS < last_POS)
						error("VCF file is not sorted at: " + CHROM + ":" + int2str(POS));
					last_POS = POS;
					entry_file_locations.push_back(filepos);
					N_entries++;
				}
			}
			else
			{
				ss >> POS;
				if (POS < last_POS)
					error("VCF file is not sorted at: " + CHROM + ":" + int2str(POS));
				last_POS = POS;
				entry_file_locations.push_back(filepos);
				N_entries++;
			}
		}
Пример #17
0
static void *receive_thread(void *thread) {
    int client_fd = ((thread_data *) thread)->socket;

    while(true) {
        bool should_leave = false;
        message incoming_message;
        int bytes_handled;
        char buffer[BUFFER_SIZE];
        char username_buffer[BUFFER_SIZE], username[BUFFER_SIZE], *username_position;
        time_t current_time;
        size_t time_buffer_bytes;
        struct tm *local_time;
        int do_not_dispatch_incoming_message = 0, line_index;

        incoming_message.header_size = 0;
        incoming_message.headers =
            (char **) malloc(MAX_HEADERS * sizeof(char *));
        incoming_message.message_size = 0;
        incoming_message.message =
            (char **) malloc(MAX_MESSAGES * sizeof(char *));

        while(true) {
            memset(buffer, 0, BUFFER_SIZE);
            bytes_handled = read_line(client_fd, buffer, BUFFER_SIZE);

            if(bytes_handled < 1 || strcmp("\r\n", buffer) == 0 ||
                    incoming_message.header_size == MAX_HEADERS) {
                should_leave == bytes_handled < 1;
                break;
            }

            strncpy(username_buffer, buffer, strlen("Username: "******"Username: "******"Username: "******"\r\n", buffer) == 0 ||
                    incoming_message.message_size == MAX_MESSAGES) {
                should_leave = bytes_handled < 1;
                break;
            }

            incoming_message.message[incoming_message.message_size] =
                (char *) malloc(strlen(buffer));
            strcpy(incoming_message.message[incoming_message.message_size],
                   buffer);

            incoming_message.message_size++;
        }

        current_time = time(NULL);
        local_time = localtime(&current_time);
        if(local_time != NULL && !should_leave) {
            time_buffer_bytes = strftime(buffer, BUFFER_SIZE,
                                         "%a, %d %b %Y %T %Z", local_time);
            if(time_buffer_bytes != 0) {
                incoming_message.headers[incoming_message.header_size] =
                    (char *) malloc(strlen("Received-at: ") +
                                    strlen(buffer) + strlen("\r\r") + 1);
                strcpy(incoming_message.headers[incoming_message.header_size],
                       "Received-at: ");
                strcat(incoming_message.headers[incoming_message.header_size],
                       buffer);
                strcat(incoming_message.headers[incoming_message.header_size],
                       "\r\n");
                incoming_message.header_size++;
            }
        }

        if(incoming_message.header_size > 0 && strcmp(incoming_message.headers[0], "Join\r\n") == 0) {
            message *join_message = malloc(sizeof(message));
            join_message->header_size = 1;
            join_message->message_size = 1;
            join_message->headers = (char **) malloc(MAX_HEADERS * sizeof(char *));
            join_message->message = (char **) malloc(MAX_MESSAGES * sizeof(char *));
            join_message->headers[0] = (char *) malloc(strlen("Message\r\n") + 1);
            strcpy(join_message->headers[0], "Message\r\n");
            join_message->message[0] = (char *) malloc(BUFFER_SIZE);
            strcpy(join_message->message[0], username);
            strcat(join_message->message[0], " has joined the chat\r\n");

            if(local_time != NULL && !should_leave) {
                time_buffer_bytes = strftime(buffer, BUFFER_SIZE,
                                             "%a, %d %b %Y %T %Z", local_time);
                if(time_buffer_bytes != 0) {
                    join_message->headers[join_message->header_size] =
                        (char *) malloc(strlen("Received-at: ") +
                                        strlen(buffer) + strlen("\r\r") + 1);
                    strcpy(join_message->headers[join_message->header_size],
                           "Received-at: ");
                    strcat(join_message->headers[join_message->header_size],
                           buffer);
                    strcat(join_message->headers[join_message->header_size],
                           "\r\n");
                    join_message->header_size++;
                }
            }

            dispatch_message(join_message);
            do_not_dispatch_incoming_message = 1;

            for(line_index = 0; line_index < join_message->header_size; line_index++) {
                free(join_message->headers[line_index]);
            }
            for(line_index = 0; line_index < join_message->message_size; line_index++) {
                free(join_message->message[line_index]);
            }
            free(join_message->headers);
            free(join_message->message);
            free(join_message);
        }

        if(incoming_message.header_size > 0 && strcmp(incoming_message.headers[0], "Leave\r\n") == 0) {
            message *leave_message = malloc(sizeof(message));
            leave_message->header_size = 1;
            leave_message->message_size = 1;
            leave_message->headers = (char **) malloc(MAX_HEADERS * sizeof(char *));
            leave_message->message = (char **) malloc(MAX_MESSAGES * sizeof(char *));
            leave_message->headers[0] = (char *) malloc(strlen("Message\r\n") + 1);
            strcpy(leave_message->headers[0], "Message\r\n");
            leave_message->message[0] = (char *) malloc(BUFFER_SIZE);
            strcpy(leave_message->message[0], username);
            strcat(leave_message->message[0], " has left the chat\r\n");

            if(local_time != NULL && !should_leave) {
                time_buffer_bytes = strftime(buffer, BUFFER_SIZE,
                                             "%a, %d %b %Y %T %Z", local_time);
                if(time_buffer_bytes != 0) {
                    leave_message->headers[leave_message->header_size] =
                        (char *) malloc(strlen("Received-at: ") +
                                        strlen(buffer) + strlen("\r\r") + 1);
                    strcpy(leave_message->headers[leave_message->header_size],
                           "Received-at: ");
                    strcat(leave_message->headers[leave_message->header_size],
                           buffer);
                    strcat(leave_message->headers[leave_message->header_size],
                           "\r\n");
                    leave_message->header_size++;
                }
            }

            dispatch_message(leave_message);
            do_not_dispatch_incoming_message = 1;

            for(line_index = 0; line_index < leave_message->header_size; line_index++) {
                free(leave_message->headers[line_index]);
            }
            for(line_index = 0; line_index < leave_message->message_size; line_index++) {
                free(leave_message->message[line_index]);
            }
            free(leave_message->headers);
            free(leave_message->message);
            free(leave_message);
        }

        if(incoming_message.header_size > 0 && strcmp(incoming_message.headers[0], "Leave\r\n") == 0) {
            ((thread_data *) thread)->should_shutdown = 1;
        }

        if(!do_not_dispatch_incoming_message) {
            dispatch_message(&incoming_message);
        }
        do_not_dispatch_incoming_message = 0;

        for(line_index = 0; line_index < incoming_message.header_size; line_index++) {
            free(incoming_message.headers[line_index]);
        }
        for(line_index = 0; line_index < incoming_message.message_size; line_index++) {
            free(incoming_message.message[line_index]);
        }
        free(incoming_message.headers);
        free(incoming_message.message);

        if(should_leave) {
            break;
        }

        if(((thread_data *) thread)->should_shutdown == 1) {
            return NULL;
        }
    }

    return NULL;
}
Пример #18
0
/* Read a value from the given section from .INI file.  File should be opened
 * and seeking will be performed on it.  Return the malloc()ed value or NULL
 * if not present or error occurred. */
static char *read_ini_value (FILE *file, const char *section, const char *key)
{
    char *line = NULL;
    int in_section = 0;
    char *value = NULL;
    int key_len;

    if (fseek(file, 0, SEEK_SET)) {
        error_errno ("File fseek() error", errno);
        return NULL;
    }

    key_len = strlen (key);

    while ((line = read_line(file))) {
        if (line[0] == '[') {
            if (in_section) {

                /* we are outside of the interesting section */
                free (line);
                break;
            }
            else {
                char *close = strchr (line, ']');

                if (!close) {
                    error ("Parse error in the INI file");
                    free (line);
                    break;
                }

                if (!strncasecmp(line + 1, section,
                                 close - line - 1))
                    in_section = 1;
            }
        }
        else if (in_section && line[0] != '#' && !is_blank_line(line)) {
            char *t, *t2;

            t2 = t = strchr (line, '=');

            if (!t) {
                error ("Parse error in the INI file");
                free (line);
                break;
            }

            /* go back to the last char in the name */
            while (t2 >= t && (isblank(*t2) || *t2 == '='))
                t2--;

            if (t2 == t) {
                error ("Parse error in the INI file");
                free (line);
                break;
            }

            if (!strncasecmp(line, key,
                             MAX(t2 - line + 1, key_len))) {
                value = t + 1;

                while (isblank(value[0]))
                    value++;

                if (value[0] == '"') {
                    char *q = strchr (value + 1, '"');

                    if (!q) {
                        error ("Parse error in the INI file");
                        free (line);
                        break;
                    }

                    *q = 0;
                }

                value = xstrdup (value);
                free (line);
                break;
            }
        }

        free (line);
    }

    return value;
}
Пример #19
0
static void
read_group(FILE *gfile, char *fname)
{
	char  line[2048], *p, *k, *u, *g;
	int   line_no = 0, len, colon;

	while (read_line(gfile, line, sizeof(line))) {
		line_no++;
		len = strlen(line);

		if (len > 0) {
			if (line[0] == '#')
				continue;
		}

		/*
		 * Check if we have the whole line
		 */
		if (line[len-1] != '\n') {
			fprintf(stderr, "line %d in \"%s\" is too long\n",
			    line_no, fname);
		} else {
			line[len-1] = '\0';
		}

		p = (char *)&line;

		k = p; colon = 0;
		while (*k != '\0') {
			if (*k == ':')
				colon++;
			k++;
		}

		if (colon > 0) {
			k = p;			/* save start of key  */
			while (*p != ':')
				p++;		/* find first "colon" */
			if (*p==':')
				*p++ = '\0';	/* terminate key */
			if (strlen(k) == 1) {
				if (*k == '+')
					continue;
			}
		}

		if (colon < 3) {
			fprintf(stderr, "syntax error at line %d in \"%s\"\n",
			    line_no, fname);
			continue;
		}

		while (*p != ':')
			p++;			/* find second "colon" */
		if (*p==':')
			*p++ = '\0';		/* terminate passwd */
		g = p;
		while (*p != ':')
			p++;			/* find third "colon" */
		if (*p==':')
			*p++ = '\0';		/* terminate gid */

		u = p;

		while (*u != '\0') {
			while (!isgsep(*p))
				p++;		/* find separator */
			if (*p != '\0') {
				*p = '\0';
				if (u != p)
					add_group(u, g);
				p++;
			} else {
				if (u != p)
					add_group(u, g);
			}
			u = p;
		}
	}
}
Пример #20
0
/* Load M3U file into plist.  Return the number of items read. */
static int plist_load_m3u (struct plist *plist, const char *fname,
                           const char *cwd, const int load_serial)
{
    FILE *file;
    char *line = NULL;
    int last_added = -1;
    int after_extinf = 0;
    int added = 0;

    file = fopen (fname, "r");
    if (!file) {
        error_errno ("Can't open playlist file", errno);
        return 0;
    }

    /* Lock gets released by fclose(). */
    if (lockf (fileno (file), F_LOCK, 0) == -1)
        log_errno ("Can't lock the playlist file", errno);

    while ((line = read_line (file))) {
        if (!strncmp (line, "#EXTINF:", sizeof("#EXTINF:") - 1)) {
            char *comma, *num_err;
            char time_text[10] = "";
            int time_sec;

            if (after_extinf) {
                error ("Broken M3U file: double #EXTINF!");
                plist_delete (plist, last_added);
                goto err;
            }

            /* Find the comma */
            comma = strchr (line + (sizeof("#EXTINF:") - 1), ',');
            if (!comma) {
                error ("Broken M3U file: no comma in #EXTINF!");
                goto err;
            }

            /* Get the time string */
            time_text[sizeof(time_text) - 1] = 0;
            strncpy (time_text, line + sizeof("#EXTINF:") - 1,
                     MIN(comma - line - (sizeof("#EXTINF:") - 1),
                         sizeof(time_text)));
            if (time_text[sizeof(time_text) - 1]) {
                error ("Broken M3U file: wrong time!");
                goto err;
            }

            /* Extract the time. */
            time_sec = strtol (time_text, &num_err, 10);
            if (*num_err) {
                error ("Broken M3U file: time is not a number!");
                goto err;
            }

            after_extinf = 1;
            last_added = plist_add (plist, NULL);
            plist_set_title_tags (plist, last_added, comma + 1);

            if (*time_text)
                plist_set_item_time (plist, last_added, time_sec);
        }
        else if (line[0] != '#') {
            char path[2 * PATH_MAX];

            strip_string (line);
            if (strlen (line) <= PATH_MAX) {
                make_path (path, sizeof(path), cwd, line);

                if (plist_find_fname (plist, path) == -1) {
                    if (after_extinf)
                        plist_set_file (plist, last_added, path);
                    else
                        plist_add (plist, path);
                    added += 1;
                }
                else if (after_extinf)
                    plist_delete (plist, last_added);
            }
            else if (after_extinf)
                plist_delete (plist, last_added);

            after_extinf = 0;
        }
        else if (load_serial &&
                 !strncmp (line, "#MOCSERIAL: ", sizeof("#MOCSERIAL: ") - 1)) {
            char *serial_str = line + sizeof("#MOCSERIAL: ") - 1;

            if (serial_str[0]) {
                char *err;
                long serial;

                serial = strtol (serial_str, &err, 0);
                if (!*err) {
                    plist_set_serial (plist, serial);
                    logit ("Got MOCSERIAL tag with serial %ld", serial);
                }
            }
        }
        free (line);
    }

err:
    free (line);
    fclose (file);
    return added;
}
Пример #21
0
int ima_setup(void) {
#if ENABLE_IMA
        _cleanup_fclose_ FILE *input = NULL;
        _cleanup_close_ int imafd = -1;
        unsigned lineno = 0;
        int r;

        if (access(IMA_SECFS_DIR, F_OK) < 0) {
                log_debug_errno(errno, "IMA support is disabled in the kernel, ignoring: %m");
                return 0;
        }

        if (access(IMA_SECFS_POLICY, W_OK) < 0) {
                log_warning_errno(errno, "Another IMA custom policy has already been loaded, ignoring: %m");
                return 0;
        }

        if (access(IMA_POLICY_PATH, F_OK) < 0) {
                log_debug_errno(errno, "No IMA custom policy file "IMA_POLICY_PATH", ignoring: %m");
                return 0;
        }

        imafd = open(IMA_SECFS_POLICY, O_WRONLY|O_CLOEXEC);
        if (imafd < 0) {
                log_error_errno(errno, "Failed to open the IMA kernel interface "IMA_SECFS_POLICY", ignoring: %m");
                return 0;
        }

        /* attempt to write the name of the policy file into sysfs file */
        if (write(imafd, IMA_POLICY_PATH, STRLEN(IMA_POLICY_PATH)) > 0)
                goto done;

        /* fall back to copying the policy line-by-line */
        input = fopen(IMA_POLICY_PATH, "re");
        if (!input) {
                log_warning_errno(errno, "Failed to open the IMA custom policy file "IMA_POLICY_PATH", ignoring: %m");
                return 0;
        }

        safe_close(imafd);

        imafd = open(IMA_SECFS_POLICY, O_WRONLY|O_CLOEXEC);
        if (imafd < 0) {
                log_error_errno(errno, "Failed to open the IMA kernel interface "IMA_SECFS_POLICY", ignoring: %m");
                return 0;
        }

        for (;;) {
                _cleanup_free_ char *line = NULL;
                size_t len;

                r = read_line(input, LONG_LINE_MAX, &line);
                if (r < 0)
                        return log_error_errno(r, "Failed to read the IMA custom policy file "IMA_POLICY_PATH": %m");
                if (r == 0)
                        break;

                len = strlen(line);
                lineno++;

                if (len > 0 && write(imafd, line, len) < 0)
                        return log_error_errno(errno, "Failed to load the IMA custom policy file "IMA_POLICY_PATH"%u: %m",
                                               lineno);
        }

done:
        log_info("Successfully loaded the IMA custom policy "IMA_POLICY_PATH".");
#endif /* ENABLE_IMA */
        return 0;
}
Пример #22
0
static int read_cwdb(char *filename, char *gameid)
{
	int pos=0;
	char *p;
	char cw_buf[300];
	u32 address,val;
	t_mem_table	t;
	PspFile pf;

	if(openfile(filename, &pf)==0) return 1;
	
	if(gameid!=NULL){
		char codename[11];
		mips_memcpy(codename,gameid,10);
		codename[10]=0;
		do{
			pos=read_sect(pos,&pf);
			p=strstr(pf.buf,codename);
			if(p) break;
		}
		while(pos);
	}
	else{
		read_sect(pos,&pf);
		p=pf.buf;
		p=read_line(p,cw_buf);
	}
	
		if(p==0) {
			closefile(&pf);
			return 1;
		}

#ifdef BIG5_ENCODE_TEXT
	t_encodepack pack;
	char *big5buf = malloc(41688);
	if(big5buf==NULL) return 1;
	if(big5_init(big5buf,&pack)==0 && encode_init(&pack)==0)
	{
		charsets_big5_conv(p,&pack);
		encode_free(&pack);
	}
	free(big5buf);
#endif
	
	p=read_line(p,cw_buf);
	mips_memcpy(ui_get_gamename()+12,cw_buf+3,0x40);
	
	int repeat=0;
	int lock =0;
	char namebuf[80];
	char *namep;
	char nullcode=0;
	while(1){
	//金手指码部分	
		p=read_line(p,cw_buf);
		
		if(cw_buf[0]=='_'){
		if(cw_buf[1]=='C'){
			if(nullcode==1) {
			t.addr=0x8800000;
			t.value=0;
			t.type=0;
			t.lock=0;
			if(mem_table_add(&t)<0) goto READOUT;
			}
		repeat=0;
		namep = namebuf;
		mips_memcpy(namebuf,cw_buf+4,70);
		lock = strtoul(cw_buf+2,NULL,16);
		namep = read_name(namep, t.name, 10);
		mips_memcpy(t.name,namebuf,30);
		t.name[30]=0;
		t.name[31]=0;
		nullcode=1;
		}
		else if(cw_buf[1]=='L'){
			nullcode=0;
			if(repeat<5){
				if(repeat==0) {
				}
				else{
					t.name[0] = '+';
					namep = read_name(namep, t.name+1, 9);
				}
				repeat++;
			}
			else{//strcpy(t.name,"+");
				t.name[0]='+';
				t.name[1]=0;
			}
			char *tempptr;
			address=strtoul(cw_buf+2,&tempptr,16)+0x08800000;
			val=strtoul(tempptr,NULL,16);
			t.addr=address;
			t.value=val;
			t.type=0;
			t.lock=lock;
			if(mem_table_add(&t)<0) goto READOUT;
		}
		else if(cw_buf[1]=='S'){
			break;
		}
		}
		if(p==0) break;
		if(p[0]=='_' && p[1]=='S') break;
	}
	
READOUT:
	closefile(&pf);
	return 0;
}
Пример #23
0
static int rtsp_listen(AVFormatContext *s)
{
    RTSPState *rt = s->priv_data;
    char proto[128], host[128], path[512], auth[128];
    char uri[500];
    int port;
    int default_port = RTSP_DEFAULT_PORT;
    char tcpname[500];
    const char *lower_proto = "tcp";
    unsigned char rbuf[4096];
    unsigned char method[10];
    int rbuflen = 0;
    int ret;
    enum RTSPMethod methodcode;

    if (!rt->protocols) {
        rt->protocols = ffurl_get_protocols(s->protocol_whitelist,
                                            s->protocol_blacklist);
        if (!rt->protocols)
            return AVERROR(ENOMEM);
    }

    /* extract hostname and port */
    av_url_split(proto, sizeof(proto), auth, sizeof(auth), host, sizeof(host),
                 &port, path, sizeof(path), s->filename);

    /* ff_url_join. No authorization by now (NULL) */
    ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL, host,
                port, "%s", path);

    if (!strcmp(proto, "rtsps")) {
        lower_proto  = "tls";
        default_port = RTSPS_DEFAULT_PORT;
    }

    if (port < 0)
        port = default_port;

    /* Create TCP connection */
    ff_url_join(tcpname, sizeof(tcpname), lower_proto, NULL, host, port,
                "?listen&listen_timeout=%d", rt->initial_timeout * 1000);

    if (ret = ffurl_open(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
                         &s->interrupt_callback, NULL, rt->protocols)) {
        av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n");
        return ret;
    }
    rt->state       = RTSP_STATE_IDLE;
    rt->rtsp_hd_out = rt->rtsp_hd;
    for (;;) { /* Wait for incoming RTSP messages */
        ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
        if (ret < 0)
            return ret;
        ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
                                 sizeof(method), &methodcode);
        if (ret) {
            av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
            return ret;
        }

        if (methodcode == ANNOUNCE) {
            ret       = rtsp_read_announce(s);
            rt->state = RTSP_STATE_PAUSED;
        } else if (methodcode == OPTIONS) {
            ret = rtsp_read_options(s);
        } else if (methodcode == RECORD) {
            ret = rtsp_read_record(s);
            if (!ret)
                return 0; // We are ready for streaming
        } else if (methodcode == SETUP)
            ret = rtsp_read_setup(s, host, uri);
        if (ret) {
            ffurl_close(rt->rtsp_hd);
            return AVERROR_INVALIDDATA;
        }
    }
    return 0;
}
Пример #24
0
/*
 * variable_help()
 *
 * it shows help about variable from file ${datadir}/ekg/vars.txt
 * or ${datadir}/ekg/plugins/{plugin_name}/vars.txt
 *
 * name - name of the variable
 */
void variable_help(const char *name) {
	GIOChannel *f; 
	gchar *type = NULL, *def = NULL, *tmp;
	const gchar *line, *seeking_name;
	string_t s;
	int found = 0;
	variable_t *v = variable_find(name);

	if (!v) {
		print("variable_not_found", name);
		return;
	}

	if (v->plugin && v->plugin->name) {
		char *tmp2;

		if (!(f = help_open("vars", v->plugin->name))) {
			print("help_set_file_not_found_plugin", v->plugin->name);
			return;
		}

		tmp2 = xstrchr(name, ':');
		if (tmp2)
			seeking_name = tmp2+1;
		else
			seeking_name = name;
	} else {
		if (!(f = help_open("vars", NULL))) {
			print("help_set_file_not_found");
			return;
		}
		
		seeking_name = name;
	}

	while ((line = read_line(f))) {
		if (!xstrcasecmp(line, seeking_name)) {
			found = 1;
			break;
		}
	}

	if (!found) {
		g_io_channel_unref(f);
		print("help_set_var_not_found", name);
		return;
	}

	line = read_line(f);
	
	if ((tmp = xstrstr(line, (": "))))
		type = xstrdup(tmp + 2);
	else
		type = xstrdup(("?"));
	
	line = read_line(f);
	if ((tmp = xstrstr(line, (": "))))
		def = xstrdup(tmp + 2);
	else
		def = xstrdup(("?"));

	print("help_set_header", name, type, def);

	xfree(type);
	xfree(def);

	if (tmp)		/* je¶li nie jest to ukryta zmienna... */
		read_line(f);	/* ... pomijamy liniê */
	s = string_init(NULL);
	while ((line = read_line(f))) {
		if (line[0] != '\t')
			break;

		if (!xstrncmp(line, ("\t- "), 3) && xstrcmp(s->str, (""))) {
			print("help_set_body", s->str);
			string_clear(s);
		}

		if (!xstrncmp(line, ("\t"), 1) && xstrlen(line) == 1) {
			string_append(s, ("\n\r"));
			continue;
		}
	
		string_append(s, line + 1);

		if (line[xstrlen(line) - 1] != ' ')
			string_append_c(s, ' ');
	}

	if (xstrcmp(s->str, ("")))
		print("help_set_body", s->str);

	string_free(s, 1);
	
	if (format_exists("help_set_footer"))
		print("help_set_footer", name);

	g_io_channel_unref(f);
}
Пример #25
0
int main (int argc, const char* argv[])
{
    char *line, *cmd, *args;
    ChessGame* game;
    ChessGameIterator iter;
    int quit = 0;

    chess_generate_init();

    game = chess_game_new();
    chess_game_iterator_init(&iter, game);
    print_board(&iter);

    line = 0;

    for (;;)
    {
        if (line)
            free(line);

        if (quit)
            break;

        line = read_line("> ");
        if (!parse_line(line, &cmd, &args))
            continue;

        if (!strcmp(cmd, "quit") || !strcmp(cmd, "q"))
        {
            quit = 1;
        }
        else if (!strcmp(cmd, "new"))
        {
            chess_game_iterator_cleanup(&iter);
            chess_game_reset(game);
            chess_game_iterator_init(&iter, game);
            print_board(&iter);
        }
        else if (!strcmp(cmd, "fen"))
        {
            load_fen(game, args);
        }
        else if (!strcmp(cmd, "pgn"))
        {
            save_pgn(game);
        }
        else if (!strcmp(cmd, "ls"))
        {
            list_moves(&iter);
        }
        else if (!strcmp(cmd, "moves"))
        {
            game_moves(game);
        }
        else if (!strcmp(cmd, "bd"))
        {
            print_board(&iter);
        }
        else if (!strcmp(cmd, "undo"))
        {
            undo_move(&iter);
        }
        else if (!strcmp(cmd, "event"))
        {
            set_event(game, args);
        }
        else if (!strcmp(cmd, "site"))
        {
            set_site(game, args);
        }
        else if (!strcmp(cmd, "date"))
        {
            set_date(game, args);
        }
        else if (!strcmp(cmd, "round"))
        {
            set_round(game, args);
        }
        else if (!strcmp(cmd, "white"))
        {
            set_white(game, args);
        }
        else if (!strcmp(cmd, "black"))
        {
            set_black(game, args);
        }
        else if (!strcmp(cmd, "result"))
        {
            set_result(game, args);
        }
        else
        {
            handle_move(&iter, cmd);
        }
    }

    chess_game_iterator_cleanup(&iter);
    chess_game_destroy(game);

    return 0;
}
static gssize
_gtk_source_buffer_input_stream_read (GInputStream  *input_stream,
				      void          *buffer,
				      gsize          count,
				      GCancellable  *cancellable,
				      GError       **error)
{
	GtkSourceBufferInputStream *stream;
	GtkTextIter iter;
	gssize space_left, read, n;

	stream = GTK_SOURCE_BUFFER_INPUT_STREAM (input_stream);

	if (count < 6)
	{
		g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NO_SPACE,
				     "Not enougth space in destination");
		return -1;
	}

	if (g_cancellable_set_error_if_cancelled (cancellable, error))
	{
		return -1;
	}

	if (stream->priv->buffer == NULL)
	{
		return 0;
	}

	/* Initialize the mark to the first char in the text buffer */
	if (!stream->priv->is_initialized)
	{
		gtk_text_buffer_get_start_iter (stream->priv->buffer, &iter);
		stream->priv->pos = gtk_text_buffer_create_mark (stream->priv->buffer,
								 NULL,
								 &iter,
								 FALSE);

		stream->priv->is_initialized = TRUE;
	}

	space_left = count;
	read = 0;

	do
	{
		n = read_line (stream, (gchar *)buffer + read, space_left);
		read += n;
		space_left -= n;
	} while (space_left > 0 && n != 0 && stream->priv->bytes_partial == 0);

	/* Make sure that non-empty files are always terminated with \n (see bug #95676).
	 * Note that we strip the trailing \n when loading the file */
	gtk_text_buffer_get_iter_at_mark (stream->priv->buffer,
					  &iter,
					  stream->priv->pos);

	if (gtk_text_iter_is_end (&iter) &&
	    !gtk_text_iter_is_start (&iter) &&
	    stream->priv->add_trailing_newline)
	{
		gssize newline_size;

		newline_size = get_new_line_size (stream);

		if (space_left >= newline_size &&
		    !stream->priv->newline_added)
		{
			const gchar *newline;

			newline = get_new_line (stream);

			memcpy ((gchar *)buffer + read, newline, newline_size);

			read += newline_size;
			stream->priv->newline_added = TRUE;
		}
	}

	return read;
}
Пример #27
0
static boolean
db_build (kpathsea kpse, hash_table_type *table,  const_string db_filename)
{
  string line;
  unsigned dir_count = 0, file_count = 0, ignore_dir_count = 0;
  unsigned len = strlen (db_filename) - sizeof (DB_NAME) + 1; /* Keep the /. */
  string top_dir = (string)xmalloc (len + 1);
  string cur_dir = NULL; /* First thing in ls-R might be a filename.  */
  FILE *db_file = fopen (db_filename, FOPEN_R_MODE);
#if defined(WIN32)
  string pp;
#endif

  strncpy (top_dir, db_filename, len);
  top_dir[len] = 0;

  if (db_file) {
    while ((line = read_line (db_file)) != NULL) {
      len = strlen (line);

#if defined(WIN32)
      for (pp = line; *pp; pp++) {
        if (kpathsea_IS_KANJI(kpse, pp))
          pp++;
        else
          *pp = TRANSFORM(*pp);
      }
#endif

      /* A line like `/foo:' = new dir foo.  Allow both absolute (/...)
         and explicitly relative (./...) names here.  It's a kludge to
         pass in the directory name with the trailing : still attached,
         but it doesn't actually hurt.  */
      if (len > 0 && line[len - 1] == ':'
          && kpathsea_absolute_p (kpse, line, true)) {
        /* New directory line.  */
        if (!ignore_dir_p (line)) {
          /* If they gave a relative name, prepend full directory name now.  */
          line[len - 1] = DIR_SEP;
          /* Skip over leading `./', it confuses `match' and is just a
             waste of space, anyway.  This will lose on `../', but `match'
             won't work there, either, so it doesn't matter.  */
          cur_dir = *line == '.' ? concat (top_dir, line + 2) : xstrdup (line);
          dir_count++;
        } else {
          cur_dir = NULL;
          ignore_dir_count++;
        }

      /* Ignore blank, `.' and `..' lines.  */
      } else if (*line != 0 && cur_dir   /* a file line? */
                 && !(*line == '.'
                      && (line[1] == 0 || (line[1] == '.' && line[2] == 0))))
      {
        /* Make a new hash table entry with a key of `line' and a data
           of `cur_dir'.  An already-existing identical key is ok, since
           a file named `foo' can be in more than one directory.  Share
           `cur_dir' among all its files (and hence never free it).

           Note that we assume that all names in the ls-R file have already
           been case-smashed to lowercase where appropriate.
        */
        hash_insert_normalized (table, xstrdup (line), cur_dir);
        file_count++;

      } /* else ignore blank lines or top-level files
           or files in ignored directories*/

      free (line);
    }

    xfclose (db_file, db_filename);

    if (file_count == 0) {
      WARNING1 ("kpathsea: %s: No usable entries in ls-R", db_filename);
      WARNING ("kpathsea: See the manual for how to generate ls-R");
      db_file = NULL;
    } else {
      str_list_add (&(kpse->db_dir_list), xstrdup (top_dir));
    }

#ifdef KPSE_DEBUG
    if (KPATHSEA_DEBUG_P (KPSE_DEBUG_HASH)) {
      /* Don't make this a debugging bit, since the output is so
         voluminous, and being able to specify -1 is too useful.
         Instead, let people who want it run the program under
         a debugger and change the variable that way.  */
      boolean hash_summary_only = true;

      DEBUGF4 ("%s: %u entries in %d directories (%d hidden).\n",
               db_filename, file_count, dir_count, ignore_dir_count);
      DEBUGF ("ls-R hash table:");
      hash_print (*table, hash_summary_only);
      fflush (stderr);
    }
#endif /* KPSE_DEBUG */
  }

  free (top_dir);

  return db_file != NULL;
}
Пример #28
0
static int read_capa_resp(mailpop3 * f, clist ** result)
{
  char * line;
  int res;
  clist * list;
  int r;
  char * name;
  clist * param_list;

  list = clist_new();
  if (list == NULL) {
    res = MAILPOP3_NO_ERROR;
    goto err;
  }

  while (1) {
    char * next_token;
    char * param;
    struct mailpop3_capa * capa;

    line = read_line(f);
    if (line == NULL) {
      res = MAILPOP3_ERROR_STREAM;
      goto free_list;
    }
    
    if (mailstream_is_end_multiline(line))
      break;

    next_token = cut_token(line);
    name = strdup(line);
    if (name == NULL) {
      res = MAILPOP3_ERROR_MEMORY;
      goto free_list;
    }

    param_list = clist_new();
    if (param_list == NULL) {
      res = MAILPOP3_ERROR_MEMORY;
      goto free_capa_name;
    }

    while (next_token != NULL) {
      line = next_token;
      next_token = cut_token(line);
      param = strdup(line);
      if (param == NULL) {
	res = MAILPOP3_ERROR_MEMORY;
	goto free_param_list;
      }
      r = clist_append(param_list, param);
      if (r < 0) {
	free(param);
	res = MAILPOP3_ERROR_MEMORY;
	goto free_param_list;
      }
    }

    capa = mailpop3_capa_new(name, param_list);
    if (capa == NULL) {
      res = MAILPOP3_ERROR_MEMORY;
      goto free_param_list;
    }

    r = clist_append(list, capa);
    if (r < 0) {
      mailpop3_capa_free(capa);
      res = MAILPOP3_ERROR_MEMORY;
      goto free_list;
    }
  }

  * result = list;
  
  return MAILPOP3_NO_ERROR;

 free_param_list:
  clist_foreach(param_list, (clist_func) free, NULL);
  clist_free(param_list);
 free_capa_name:
  free(name);
 free_list:
  clist_foreach(list, (clist_func) mailpop3_capa_free, NULL);
  clist_free(list);
 err:
  return res;
}
Пример #29
0
/**
 *  Read a whole DChat PDU from a file descriptor.
 *  Read linewise from a file descriptor to form a DChat protocol data unit.
 *  Information read from the file descriptor will be stored in this pdu.
 *  @param fd  File descriptor to read from
 *  @param pdu Pointer to a PDU structure whose headers will be filled.
 *  @return amount of bytes read in total if a protocol data unit has been read successfully, 0 on EOF ,
 *  -1 on error
 */
int
read_pdu(int fd, dchat_pdu_t* pdu)
{
    char* line;     // line read from file descriptor
    char* contentp; // content pointer
    int ret;        // return value
    int b;          // amount of bytes read as content
    int len = 0;    // amount of bytes read in total
    // zero out structure
    memset(pdu, 0, sizeof(*pdu));

    // read each line of the received pdu
    if ((ret = read_line(fd, &line)) == -1 || !ret)
    {
        return ret;
    }

    // first header must be version header
    if (decode_header(pdu, line) == -1 || pdu->version != DCHAT_V1)
    {
        ret = -1;
    }

    if (ret != -1)
    {
        len += strlen(line);
        free(line);

        // read header lines from file descriptors, until
        // an empty line is received
        while ((ret = read_line(fd, &line)) != -1 || ret == 0)
        {
            len += strlen(line);

            if (decode_header(pdu, line) == -1)
            {
                // if line is not a header, it must be an empty line
                if (!strcmp(line, "\n") || !strcmp(line, "\r\n"))
                {
                    break; // All headers have been read
                }

                ret = -1;
                break;
            }

            free(line);
        }
    }

    // On error print illegal line
    if (ret == -1)
    {
        ui_log(LOG_ERR, "Illegal PDU header received: '%s'", line);
    }

    // EOF or ERROR
    if (ret <= 0)
    {
        free(line);
        return ret;
    }

    // has content type, onion-id and listen-port been specified?
    if (pdu->content_type == 0 || pdu->onion_id == NULL || pdu->lport == 0)
    {
        ui_log(LOG_ERR, "Mandatory PDU headers are missing!");
        free(line);
        return -1;
    }

    // allocate memory for content
    pdu->content = malloc(pdu->content_length + 1);
    contentp = pdu->content; // point to the beginning

    // read content frm file descriptor
    // read x bytes defined by Content-Length
    for (b = 0, contentp = pdu->content; b < pdu->content_length;
         b++, contentp++, len++)
    {
        if ((ret = read(fd, contentp, 1)) == -1 || !ret)
        {
            free(pdu->content);
            return ret;
        }
    }

    *contentp = '\0'; // NULL terminate potential string
    return len; // amount of bytes read as content == content length
}
Пример #30
0
int main() {
    int count;
    char *rest, *command_str, *param_str, *param2_str;

    //Inicializar terminal... 

    devreq(KEYBOARD);
    devreq(SCREEN);
    devreq(TERMINAL);

    while(TRUE) {
        write(TERMINAL, PROMPT, strlen(PROMPT));
        count = read_line(line_buffer, BUFF_LEN);

        if (count == -1) {
            while (read_line(line_buffer, BUFF_LEN) != 1);

            write_line("Line too long");
        } else {
            line_buffer[count -1] = NULL;
            rest = skip_spaces(line_buffer);

            if (!*rest) {
                command_use_error();
                continue;
            }

            command_str = get_word(&rest);
            rest = skip_spaces(rest);
            param_str = get_word(&rest);
            rest = skip_spaces(rest);

            if (strcmp(HELP, command_str) == 0) {
                print_shell_use();
            } else if (strcmp(ECHO, command_str) == 0) {
                write_line(param_str);
            } else if (strcmp(PS, command_str) == 0) {
                //Imprimir informacion de programas en ejecucion
                print_ps(param_str);
            } else if (strcmp(LS, command_str) == 0) {
                //Imprimir lista de programas disponibles
                print_ls(param_str);
            } else if (strcmp(RUN, command_str) == 0) {
                //Ejecutar un programa en foreground
                do_run(param_str);
            } else if (strcmp(RUN_BG, command_str) == 0) {
                //Ejecutar un programa en background
                do_runbg(param_str);
            } else if (strcmp(NICE, command_str) == 0) {
                param2_str = get_word(&rest);
                //Cambiar prioridad de un proceso
                do_nice(param_str, param2_str);
            } else if (strcmp(KILL, command_str) == 0) {
                //Ejecutar un programa en background
                do_kill(param_str);
            }  else
                command_use_error();
        }
    }

   return 0;
}