Esempio n. 1
0
/*!

\brief Loads session data.
\details Attempts to load session data using the \a Name and \a Domain from the
constructor. The session file for the various platforms is as follows:
- Win32 \$(HOME)/\$(Domain)/\$(Name).xml
- MacOS ~/Library/Preferences/\$(Domain)/\$(Name).xml
- Linux ~/.\$(Domain)/\$(Name).xml

\return Returns dmz::True if the session data was read successfully.

*/
dmz::Boolean
dmz::ApplicationiPhone::load_session () {

    Boolean result (True);

    _state.sessionDir = dmz_get_document_directory ();

    if (_state.sessionDir) {

        _state.sessionFile << "session.xml";

        _state.sessionPath = format_path (_state.sessionDir + "/" + _state.sessionFile);

        if (is_valid_path (_state.sessionPath)) {

            Config data ("global");

            if (xml_to_config (_state.sessionPath, data, &(_state.log))) {

                if (!_state.quiet) {

                    _state.log.info << "Loaded session file: " << _state.sessionPath << endl;
                }

                Config session;
                _state.rt.get_session_config (session);

                if (data.lookup_all_config_merged (session.get_name (), session)) {

                    const String DefaultDir (config_to_string (DefaultDirName, session));

                    if (DefaultDir && is_valid_path (DefaultDir)) {

                        _state.appState.set_default_directory (DefaultDir);
                    }
                    else {
                        _state.appState.set_default_directory (dmz_get_main_bundle_directory ());
                    }

                    _state.rt.set_session_config (session);
                }
            }
            else {

                _state.log.error << "Failed parsing session file: " << _state.sessionPath
                                 << endl;
            }
        }
        else if (!_state.quiet) {

            _state.log.info << "Session file: " << _state.sessionPath << " does not exist"
                            << endl;
            result = False;
        }
    }

    return result;
}
Esempio n. 2
0
void
dmz::ArchivePluginAutoSave::update_plugin_state (
      const PluginStateEnum State,
      const UInt32 Level) {

   if (State == PluginStateStart) {

      if (_firstStart && _saveFile && is_valid_path (_saveFile) && _archiveMod) {

         _log.info << "Restoring from auto save archive: " << _saveFile << endl;

         Config global ("global");
         XMLParser parser;
         XMLInterpreterConfig interpreter (global);
         parser.set_interpreter (&interpreter);

         FILE *file = open_file (_saveFile, "rb");

         if (file) {

            Boolean error (False);
            String buffer;

            while (read_file (file, 1024, buffer) && !error) {

               const Int32 Length = buffer.get_length ();
               const char *cbuf = buffer.get_buffer ();

               if (!parser.parse_buffer (cbuf, Length, Length < 1024)) {

                  error = True;
                  _log.error << "Unable to restore from auto save archive: " << _saveFile
                     << " : " << parser.get_error ();
               }
            }

            close_file (file);

            Config data;

            if (!error && global.lookup_all_config_merged ("dmz", data)) {

               _archiveMod->process_archive (_archiveHandle, data);
            }
         }
      }

      _firstStart = False;
   }
   else if (State == PluginStateShutdown) {

      if (is_valid_path (_saveFile)) { remove_file (_saveFile); }
   }
}
Esempio n. 3
0
/*!

\brief Gets a list of files found at the specified path.
\details Defined in dmzSystemFile.h.
\param[in] Path String containing path used to find the file list.
\param[out] container dmz::StringContainer used to store files found at the specified
\a Path
\return Returns dmz::True if the specified \a Path is valid.
\sa dmz::get_directory_list

*/
dmz::Boolean
dmz::get_file_list (
      const String &Path,
      StringContainer &container) {

   Boolean result (False);

   container.clear ();

   if (is_valid_path (Path)) {

      DIR *dir = opendir (Path.get_buffer ());

      if (dir) {

         result = True;

         struct dirent *current = readdir (dir);

         while (current) {

            if (current->d_type != DT_DIR) {

               container.add (current->d_name);
            }

            current = readdir (dir);
         }

         closedir (dir); dir = 0;
      }
   }

   return result;
}
Esempio n. 4
0
/*!

\brief Creates a directory.
\details Defined in dmzSystemFile.h. Function will create a path as deep as is
requested in \a Path. Function returns dmz::True if path already exists.
\param[in] Path String containing directory to create.
\return Returns dmz::True if directory was successfully created.

*/
dmz::Boolean
dmz::create_directory (const String &Path) {

   Boolean result (False);

   if (Path) {

      result = True;
      const String FormattedPath (format_path (Path));
      StringTokenizer st (FormattedPath, '/');
      String dir;
      if (FormattedPath.get_char (0) == '/') { dir << "/"; }
      String part (st.get_next ());

      while (part) {

         if (dir) { dir << "/" << part; }
         else { dir = part; }

         if (!is_valid_path (dir)) {

            if (mkdir (dir.get_buffer (), S_IRUSR | S_IWUSR | S_IXUSR) != 0) {

               result = False;
            }
         }

         if (result) { part = st.get_next (); }
         else { part.flush (); }
      }
   }

   return result;
}
Esempio n. 5
0
/*!

\brief Finds absolute path.
\details Defined in dmzSystemFile.h.
\param[in] Path String containing path used to find the absolute (a.k.a. canonical) path
\param[out] absPath String in which the found absolute path is stored.
\return Returns dmz::True if absolute path is found.

*/
dmz::Boolean
dmz::get_absolute_path (const String &Path, String &absPath) {

   Boolean result (False);

   if (is_valid_path (Path)) {

      if (is_directory (Path)) {

         const PushDirectory Push (Path);

         if (Push.is_valid ()) { result = True; absPath = get_current_directory (); }
      }
      else {

         String spath, file, ext;
         split_path_file_ext (Path, spath, file, ext);

         if (!spath) { spath = "."; }

         const PushDirectory Push (spath);

         if (Push.is_valid ()) {

            result = True;
            absPath.flush () <<  get_current_directory () << file << ext;
         }
      }

      absPath = format_path (absPath);
   }
   else { absPath.flush (); }

   return result;
}
Esempio n. 6
0
void
RRT_Lane::build_rrt_path_from_robot_pose(Robot_State &robot_pose)
{

	double path_distance, theta_diff;
	Robot_State path_pose;

	if ((GlobalState::current_algorithm != CARMEN_BEHAVIOR_SELECTOR_RRT) ||
		!goal_pose || !GlobalState::cost_map_initialized || Obstacle_Detection::is_obstacle(*goal_pose))
		return;

	old_path = path;
	old_path_timestamp = path_timestamp;
	old_build_time = build_time;

	// Remove nos ja percorridos do path anterior. O path anterior eh incluido na arvore de busca em build_rrt_path().
	while(Ackerman::remove_front_node_of_the_path(robot_pose.pose, old_path, path_distance, theta_diff, &path_pose))
		;

	clear_the_search_tree_and_current_path();

	// if (!old_path.empty())
	//	robot_pose.command = path_pose.command;
	//tree.add_root_node(robot_pose.pose, robot_pose.command);
	tree.add_root_node(robot_pose.pose, GlobalState::last_odometry);

	if (!tree.root_node || node_reaches_goal(tree.root_node))
		return;

	build_rrt_path();
	if (!is_valid_path())
		clear_the_search_tree_and_current_path();
}
Esempio n. 7
0
char *
tr_sys_path_basename (const char  * path,
                      tr_error   ** error)
{
  if (path == NULL || path[0] == '\0')
    return tr_strdup (".");

  if (!is_valid_path (path))
    {
      set_system_error (error, ERROR_PATH_NOT_FOUND);
      return NULL;
    }

  const char * end = path + strlen (path);
  while (end > path && is_slash (*(end - 1)))
    --end;

  if (end == path)
    return tr_strdup ("/");

  const char * name = end;
  while (name > path && *(name - 1) != ':' && !is_slash (*(name - 1)))
    --name;

  if (name == end)
    return tr_strdup ("/");

  return tr_strndup (name, end - name);
}
int find_path(int maze[N][N], int x, int y, int sol[N][N])
{
	if(x== N-1 && y ==N-1)
	{
	  sol[x][y]=1;
	  return 1;
	}
	
	if(is_valid_path(x,y,maze) == 1)
	{
		sol[x][y]=1;
		//now move forward in x direction ie right
		if(find_path(maze, x+1, y, sol) == 1)
		  return 1;
		
		//moving right did not yield soln ,so move down 
		if(find_path(maze, x, y+1, sol) == 1)
		  return 1;
		  
		//nothing gives soln, mark sol array as 0 and backtrack
		sol[x][y]=0;
		return 0;
	}
	
	return 0;
}
Esempio n. 9
0
int     create_full_dir(const char *fullname)

{
    PATH    fin;
    char    *one_path, *one_dir;
    int     progress = 1, err = 0, fullen;

    one_path   =  (char *)malloc(_MAX_PATH + 2);
    one_dir    =  (char *)malloc(_MAX_PATH + 2);

	ASSERT(one_path);
	ASSERT(one_dir);

    if(!one_path || !one_dir)
        {
        printf("Out of memory.");
        //err = SYSTEM_NO_MEMORY;
        goto endd;
        }

    _splitpath(fullname, fin.drive, fin.dir, fin.fname, fin.ext);

    fullen = strlen(fin.dir);

    while(TRUE)
        {
        int len = strcspn(fin.dir + progress, "\\/");

        if(progress >= fullen)
            break;

        len = min(len, _MAX_PATH-1);

        if(len)
            strncpy(one_dir, fin.dir, progress + len);

        one_dir[progress +len] = '\0';
        progress += len + 1;

        _makepath(one_path, fin.drive, one_dir, "", "");

        //P2N("Component: '%s'\r\n", one_path);

        if(!is_valid_path(one_path))
            {
            if(!CreateDirectory(one_path, NULL))
                {
                err = TRUE; break;
                }
            }
        }

    endd:
        free(one_path);
        free(one_dir);

    return(err);
}
Esempio n. 10
0
char* tr_sys_path_dirname(char const* path, tr_error** error)
{
    if (path == NULL || path[0] == '\0')
    {
        return tr_strdup(".");
    }

    if (!is_valid_path(path))
    {
        set_system_error(error, ERROR_PATH_NOT_FOUND);
        return NULL;
    }

    bool const is_unc = is_unc_path(path);

    if (is_unc && path[2] == '\0')
    {
        return tr_strdup(path);
    }

    char const* end = path + strlen(path);

    while (end > path && is_slash(*(end - 1)))
    {
        --end;
    }

    if (end == path)
    {
        return tr_strdup("/");
    }

    char const* name = end;

    while (name > path && *(name - 1) != ':' && !is_slash(*(name - 1)))
    {
        --name;
    }

    while (name > path && is_slash(*(name - 1)))
    {
        --name;
    }

    if (name == path)
    {
        return tr_strdup(is_unc ? "\\\\" : ".");
    }

    if (name > path && *(name - 1) == ':' && *name != '\0' && !is_slash(*name))
    {
        return tr_strdup_printf("%c:.", path[0]);
    }

    return tr_strndup(path, name - path);
}
// Time Slice Interface
void
dmz::ForgePluginScreenCaptureMulti::update_time_slice (const Float64 TimeDelta) {

   if (_fileIndex > 0) {

      if (_fileIndex > 1) {

         _heading += TwoPi64 / Float64 (_maxFiles);
         _update_portal ();
      }

      String count (String::number (_fileIndex));
      if (count.get_length () < _maxLength) {

         count.shift (_maxLength - count.get_length (), '0');
      }

      String file (_fileRoot);
      file << count << ".png";
      _fileList.add (file);

      Data out = _convertString.to_data (file);
      _doCaptureMsg.send (&out);

      _fileIndex++;
      if (_fileIndex > _maxFiles) { _fileIndex = -1; }
   }
   else if (_fileIndex < 0) {

      const Int32 Size (_fileList.get_count ());

      Int32 count (0);
      StringContainerIterator it;
      String file;
      while (_fileList.get_next (it, file)) {

         if (is_valid_path (file)) { count++; }
         else { break; }
      }

      _update_portal ();

      if (Size == count) {

         Data out = _convertList.to_data (_fileList);
         _finishedCaptureMsg.send (&out);
         _fileIndex = 0;
      }
      else {

_log.error << "Not all screen capture images created. Created " << count << " of " << Size << endl;
      }
   }
}
Esempio n. 12
0
int create_pid_file(const char *path)
{
    char pid_buffer[12];
    struct flock lock;
    int rval;
    int fd;

    if (!path) {
        path = config.pidfile;
    }
    if (!is_valid_path(path)) {
        printf("PID path \"%s\" aint writable", path);
    }

    if ((fd = open(path, O_CREAT | O_WRONLY,
                   S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1) {
        return ERROR;
    }

    /*
     * pid file locking 
     */
    lock.l_type = F_WRLCK;
    lock.l_start = 0;
    lock.l_whence = SEEK_SET;
    lock.l_len = 0;

    if (fcntl(fd, F_SETLK, &lock) == -1) {
        if (errno == EACCES || errno == EAGAIN) {
            rval = ERROR;
        } else {
            rval = ERROR;
        }
        close(fd);
        return rval;
    }
    snprintf(pid_buffer, sizeof(pid_buffer), "%d\n", (int)getpid());
    if (ftruncate(fd, 0) != 0) {
        close(fd);
        return ERROR;
    }
    if (write(fd, pid_buffer, strlen(pid_buffer)) != 0) {
        close(fd);
        return ERROR;
    }
    close(fd);
    return SUCCESS;
}
Esempio n. 13
0
/*!

\brief Gets a list of directories found at the specified path.
\details Defined in dmzSystemFile.h.
\param[in] Path String containing path used to find the directory list.
\param[out] container dmz::StringContainer used to store directories found at the specified
\a Path
\return Returns dmz::True if the specified \a Path is valid.
\sa dmz::get_file_list

*/
dmz::Boolean
dmz::get_directory_list (
      const String &Path,
      StringContainer &container) {

   Boolean result (False);

   container.clear ();

   if (is_valid_path (Path)) {

      DIR *dir = opendir (Path.get_buffer ());

      if (dir) {

         result = True;

         struct dirent *current = readdir (dir);

         while (current) {

            if (current->d_type == DT_DIR) {

               Boolean store (True);

               // Filter out . and .. directories
               if (current->d_name[0] == '.') {

                  if ((current->d_name[1] == '\0') ||
                     ((current->d_name[1] == '.') && (current->d_name[2] == '\0'))) {

                     store = False;
                  }
               }

               if (store) { container.add (current->d_name); }
            }

            current = readdir (dir);
         }

         closedir (dir); dir = 0;
      }
   }

   return result;
}
Esempio n. 14
0
static int url_parse_path(const char **url,
                          size_t *data_out_ptr,
                          size_t out_limit,
                          avs_url_t *parsed_url) {
    parsed_url->path_ptr = *data_out_ptr;
    if (!**url || **url == '?') {
        parsed_url->data[(*data_out_ptr)++] = '/';
    }
    while (*data_out_ptr < out_limit && **url != '\0') {
        parsed_url->data[(*data_out_ptr)++] = *(*url)++;
    }
    assert(*data_out_ptr < out_limit);
    parsed_url->data[(*data_out_ptr)++] = '\0';

    if (!is_valid_path(&parsed_url->data[parsed_url->path_ptr])) {
        return -1;
    }
    return 0;
}
Esempio n. 15
0
/*!

\brief Loads session data.
\details Attempts to load session data using the \a Name and \a Domain from the
constructor. The session file for the various platforms is as follows:
- Win32 \$(HOME)/\$(Domain)/\$(Name).xml
- MacOS ~/Library/Preferences/\$(Domain)/\$(Name).xml
- Linux ~/.\$(Domain)/\$(Name).xml

\return Returns dmz::True if the session data was read successfully.

*/
dmz::Boolean
dmz::Application::load_session () {

   Boolean result (True);

   _state.sessionDir = get_home_directory ();

   if (is_valid_path (_state.sessionDir)) {

#if defined (_WIN32)
      if (_state.Domain) { _state.sessionDir << "/" << _state.Domain; }
      else { _state.sessionDir << "/dmz"; }
#elif defined (__APPLE__) || defined (MACOSX)
      _state.sessionDir << "/Library/Preferences";
      if (_state.Domain) { _state.sessionDir << "/" << _state.Domain; }
      else { _state.sessionDir << "/dmz"; }
#else
      if (_state.Domain) { _state.sessionDir << "/." << _state.Domain; }
      else { _state.sessionDir << "/.dmz"; }
#endif
   }
   else { result = False; }

   if (_state.sessionDir) {

      if (_state.Name) { _state.sessionFile << _state.Name << ".xml"; }
      else { _state.sessionFile << "session.xml"; }

      _state.sessionPath = format_path (_state.sessionDir + "/" + _state.sessionFile);

      if (is_valid_path (_state.sessionPath)) {

         Config data ("global");

         if (xml_to_config (_state.sessionPath, data, &(_state.log))) {

            if (!_state.quiet) {

               _state.log.info << "Loaded session file: " << _state.sessionPath << endl;
            }

            Config session;
            _state.rt.get_session_config (session);

            if (data.lookup_all_config_merged (session.get_name (), session)) {

               const String DefaultDir (config_to_string (DefaultDirName, session));

               if (DefaultDir && is_valid_path (DefaultDir)) {

                  _state.appState.set_default_directory (DefaultDir);
               }
               else { _state.appState.set_default_directory (get_home_directory ()); }

               _state.rt.set_session_config (session);
            }
         }
         else {

            _state.log.error << "Failed parsing session file: " << _state.sessionPath
               << endl;
         }
      }
      else if (!_state.quiet) {

         _state.log.info << "Session file: " << _state.sessionPath << " does not exist"
            << endl;
         result = False;
      }
   }

   return result;
}
Esempio n. 16
0
/* magic main */
int main(int argc, char *argv[])
{
    int ch = 0; // verbose_already = 0;
    int daemon = 0;
    memset(&config, 0, sizeof(globalconfig));
    //set_default_config_options();
    config.inpacket = config.intr_flag = 0;
    config.dnslastchk = 0;
    //char *pconfile;
#define BPFF "port 53"
    config.bpff = BPFF;
    config.logfile = "/var/log/passivedns.log";
    config.logfile_nxd = "/var/log/passivedns.log";
    config.pidfile = "/var/run/passivedns.pid";
    config.mem_limit_max = (256 * 1024 * 1024); // 256 MB - default try to limit dns caching to this
    config.dnsprinttime = DNSPRINTTIME;
    config.dnscachetimeout =  DNSCACHETIMEOUT;
    config.dnsf = 0;
    config.dnsf |= DNS_CHK_A;
    config.dnsf |= DNS_CHK_AAAA;
    config.dnsf |= DNS_CHK_PTR;
    config.dnsf |= DNS_CHK_CNAME;
    config.dnsf |= DNS_CHK_DNAME;
    config.dnsf |= DNS_CHK_NAPTR;
    config.dnsf |= DNS_CHK_RP;
    config.dnsf |= DNS_CHK_SRV;
//    config.dnsf |= DNS_CHK_TXT;
//    config.dnsf |= DNS_CHK_SOA;
//    config.dnsf |= DNS_CHK_NS;
//    config.dnsf |= DNS_CHK_MX;
//    config.dnsf |= DNS_CHK_NXDOMAIN;

    signal(SIGTERM, game_over);
    signal(SIGINT, game_over);
    signal(SIGQUIT, game_over);
    signal(SIGALRM, sig_alarm_handler);

#define ARGS "i:r:l:L:hb:Dp:C:P:S:X:u:g:T:"

    while ((ch = getopt(argc, argv, ARGS)) != -1)
        switch (ch) {
        case 'i':
            config.dev = strdup(optarg);
            break;
        case 'r':
            config.pcap_file = strdup(optarg);
            break;
        case 'L':
            config.logfile_nxd = strdup(optarg);
            break;
        case 'l':
            config.logfile = strdup(optarg);
            break;
        case 'b':
            config.bpff = strdup(optarg);
            break;
        case 'p':
            config.pidfile = strdup(optarg);
            break;
        case 'C':
            config.dnscachetimeout = strtol(optarg, NULL, 0);
            break;
        case 'P':
            config.dnsprinttime = strtol(optarg, NULL, 0);
            break;
        case 'S':
            config.mem_limit_max = (strtol(optarg, NULL, 0) * 1024 * 1024);
            break;
        case 'X':
            parse_dns_flags(optarg);
            break;
        case 'D':
            daemon = 1;
            break;
        case 'T':
            config.chroot_dir = strdup(optarg);
            config.chroot_flag = 1;
            break;
        case 'u':
            config.user_name = strdup(optarg);
            config.drop_privs_flag = 1;
            break;
        case 'g':
            config.group_name = strdup(optarg);
            config.drop_privs_flag = 1;
            break;
        case 'h':
            usage();
            exit(0);
            break;
        case '?':
            elog("unrecognized argument: '%c'\n", optopt);
            break;
        default:
            elog("Did not recognize argument '%c'\n", ch);
        }

    olog("\n[*] Running passivedns %s\n", VERSION);
    olog("    Using %s\n", pcap_lib_version());

    if (config.pcap_file) {
        /* Read from PCAP file specified by '-r' switch. */
        olog("[*] Reading from file %s\n", config.pcap_file);
        if (!(config.handle = pcap_open_offline(config.pcap_file, config.errbuf))) {
            olog("[*] Unable to open %s.  (%s)", config.pcap_file, config.errbuf);
        }

    } else {

        /* * look up an available device if non specified */
        if (config.dev == 0x0)
            config.dev = pcap_lookupdev(config.errbuf);
        olog("[*] Device: %s\n", config.dev);

        if ((config.handle = pcap_open_live(config.dev, SNAPLENGTH, 1, 500, config.errbuf)) == NULL) {
            olog("[*] Error pcap_open_live: %s \n", config.errbuf);
            exit(1);
        }
        /* * B0rk if we see an error... */
        if (strlen(config.errbuf) > 0) {
            elog("[*] Error errbuf: %s \n", config.errbuf);
            exit(1);
        }

        if(config.chroot_dir){
            olog("[*] Chrooting to dir '%s'..\n", config.chroot_dir);
            if(set_chroot()){
                elog("[!] failed to chroot\n");
                exit(1);
            }
        }

        if (config.drop_privs_flag) {
            olog("[*] Dropping privs...\n");
            drop_privs();
        }

        if (daemon) {
            if (!is_valid_path(config.pidfile))
                elog("[*] Unable to create pidfile '%s'\n", config.pidfile);
            openlog("passivedns", LOG_PID | LOG_CONS, LOG_DAEMON);
            olog("[*] Daemonizing...\n\n");
            daemonize();
        }

    }

    if (config.handle == NULL) {
       game_over();
       return (1);
    }

    /** segfaults on empty pcap! */
    if ((pcap_compile(config.handle, &config.cfilter, config.bpff, 1, config.net_mask)) == -1) {
            olog("[*] Error pcap_compile user_filter: %s\n", pcap_geterr(config.handle));
            exit(1);
    }

    if (pcap_setfilter(config.handle, &config.cfilter)) {
            olog("[*] Unable to set pcap filter!  %s", pcap_geterr(config.handle));
    }

    alarm(TIMEOUT);

    olog("[*] Sniffing...\n\n");
    pcap_loop(config.handle, -1, got_packet, NULL);

    game_over();
    return (0);
}
Esempio n. 17
0
int
is_valid_exe(const char *path)
{
    return is_valid_path(path, IS_EXE);
}
Esempio n. 18
0
int main(int argc, char *argv[]) {

   int ch, fromfile, setfilter, version, drop_privs_flag, daemon_flag, chroot_flag;
   char *bpff, errbuf[PCAP_ERRBUF_SIZE];
   extern char *optarg;
   char roll_metric = 0;
   char roll_type = GIGABYTES;
   size_t roll_point = 2;
   roll_size = roll_point * GIGABYTE;

   int long_option_index = 0;
   static struct option long_options[] = {
     {"help", 0, NULL, '?'},
     {"interface", 1, NULL, 'i'},
     {"format", 1, NULL, 'f'},
     {"bpf", 1, NULL, 'b'},
     {"log-dir", 1, NULL, 'd'},
     {"daemonize", 0, NULL, 'D'},
     {"user", 1, NULL, 'u'},
     {"group", 1, NULL, 'g'},
     {"chroot-dir", 1, NULL, 'T'},
     {"pid-file", 1, NULL, 'p'},
     {"pcap-file", 1, NULL, 'r'},
     {0, 0, 0, 0}
   };


   bpf_u_int32 net_mask = 0;
   ch = fromfile = setfilter = version = drop_privs_flag = daemon_flag = 0;
   dev = "eth0";
   bpff = "";
   chroot_dir = "/tmp/";
   output_format = "sguil";
   cxtbuffer = NULL;
   cxtrackerid  = 0;
   dump_with_flush = inpacket = intr_flag = chroot_flag = 0;
   mode = 0;

   signal(SIGTERM, game_over);
   signal(SIGINT,  game_over);
   signal(SIGQUIT, game_over);
   signal(SIGHUP,  dump_active);
   signal(SIGALRM, set_end_sessions);

   while( (ch=getopt_long(argc, argv, "?b:d:DT:f:g:i:p:P:r:u:vw:s:t:", long_options, &long_option_index)) != EOF )
     switch (ch) {
      case 'i':
         dev = strdup(optarg);
         mode |= MODE_DEV;
         break;
      case 'b':
         bpff = strdup(optarg);
         break;
      case 'v':
         verbose = 1;
         break;
      case 'f':
         output_format = strdup(optarg);
         break;
      case 'd':
         snprintf(dpath, STDBUF, "%s", optarg);

         // normalise the directory path to ensure it's slash terminated
         if( dpath[strlen(dpath)-1] != '/' )
            strncat(dpath, "/", STDBUF);
         break;
      case '?':
         usage(argv[0]);
         exit_clean(0);
         break;
      case 'D':
         daemon_flag = 1;
         break;
      case 'T':
         chroot_flag = 1;
         break;
      case 'u':
         user_name = strdup(optarg);
         drop_privs_flag = 1;
         break;
      case 'g':
         group_name = strdup(optarg);
         drop_privs_flag = 1;
         break;
      case 'p':
         pidfile = strdup(optarg);
         break;
      case 'P':
         pidpath = strdup(optarg);
         break;
      case 'r':
         read_file = strdup(optarg);
         mode |= MODE_FILE;
         dev = NULL;
         break;
      case 'w':
         dump_file_prefix = strdup(optarg);
         mode |= MODE_DUMP;
         break;
      case 'F':
         dump_with_flush = 1;
         break;
      case 's':
         sscanf(optarg, "%zu%c", &roll_point, &roll_metric);

         switch( tolower(roll_metric) ) {
            case 'k':
               roll_size = roll_point * KILOBYTE;
               roll_type = KILOBYTES;
               break;
            case 'm':
               roll_size = roll_point * MEGABYTE;
               roll_type = MEGABYTES;
               break;
            case 'g':
               roll_size = roll_point * GIGABYTE;
               roll_type = GIGABYTES;
               break;
            case 't':
               roll_size = roll_point * TERABYTE;
               roll_type = TERABYTES;
               break;
            default:
               printf("[*] Invalid size metric: %c\n", roll_metric ? roll_metric : '-');
               break;
         }

         break;
      case 't':
         sscanf(optarg, "%zu%c", &roll_point, &roll_metric);

         switch( tolower(roll_metric) ) {
            case 's':
               roll_time = roll_point;
               roll_type = SECONDS;
               break;
            case 'm':
               roll_time = roll_point * 60;
               roll_type = MINUTES;
               break;
            case 'h':
               roll_time = roll_point * 60 * 60;
               roll_type = HOURS;
               break;
            case 'd':
               roll_time = roll_point * 60 * 60 * 24;
               roll_type = DAYS;
               break;
            default:
               printf("[*] Invalid size metric: %c\n", roll_metric ? roll_metric : '-');
               break;
         }

         break;
      default:
         exit_clean(1);
         break;
   }

   errbuf[0] = '\0';

   // validate the output format string
   format_validate(output_format);

   // specify reading from a device OR a file and not both
   if ( (mode & MODE_DEV) && (mode & MODE_FILE) )
   {
      printf("[!] You must specify a device OR file to read from, not both.\n");
      usage(argv[0]);
      exit_clean(1);
   }
   else if ( (mode & MODE_FILE) && read_file) {
      /* Read from PCAP file specified by '-r' switch. */
      printf("[*] Reading from file %s", read_file);
      if (!(handle = pcap_open_offline(read_file, errbuf))) {
         printf("\n");
         printf("[*] Unable to open %s. (%s)\n", read_file, errbuf);
         exit_clean(1);
      } else {
         printf(" - OK\n");
      }

      // in pcap_open_offline(), libpcap appears to use a static buffer
      // for reading in the file. we must use memcpy's to ensure data
      // persists as expected
      if ( ip_init(&ip_config, IP_SET_MEMCPY) )
      {
        printf("[!] Unable to initialise the IP library.\n");
        exit_clean(1);
      }
      else
        printf("[*] IP library using \"memcpy\" set.\n");
   }
   else if ( (mode & MODE_DEV) && dev) {
      if (getuid()) {
         printf("[*] You must be root..\n");
         exit_clean(1);
      }

      printf("[*] Running cxtracker %s\n",VERSION);

      //errbuf[0] = '\0';
      /* look up an availible device if non specified */
      if (dev == 0x0) dev = pcap_lookupdev(errbuf);
      printf("[*] Device: %s\n", dev);

      if ((handle = pcap_open_live(dev, SNAPLENGTH, 1, 500, errbuf)) == NULL) {
         printf("[*] Error pcap_open_live: %s \n", errbuf);
         exit_clean(1);
      }

      // in pcap_open_live(), libpcap maintains a heap allocated buffer
      // for reading off the wire. we can use pointer copies here for 
      // improved speed
      if ( ip_init(&ip_config, IP_SET_MEMCPY) )
      {
        printf("[*] Unable to initialise the IP library.\n");
        exit_clean(1);
      }
      else
        printf("[*] IP library using \"memcpy\" set.\n");

      if ( chroot_flag == 1 ) {
         set_chroot();
      }

      if(daemon_flag) {
         if(!is_valid_path(pidpath))
            printf("[*] PID path \"%s\" is bad, check privilege.",pidpath);
            openlog("cxtracker", LOG_PID | LOG_CONS, LOG_DAEMON);
            printf("[*] Daemonizing...\n\n");
            go_daemon();
      }
   }
   else
   {
      printf("[*] You must specify where to read from.\n");
      exit_clean(1);
   }

   if ((pcap_compile(handle, &cfilter, bpff, 1 ,net_mask)) == -1) {
      printf("[*] Error pcap_compile user_filter: %s\n", pcap_geterr(handle));
      exit_clean(1);
   }

   if (pcap_setfilter(handle, &cfilter)) {
      printf("[*] Unable to set pcap filter!  (%s)\n", pcap_geterr(handle));
   } else {
      pcap_freecode(&cfilter); // filter code not needed after setfilter
   }

   // set up dump mode now as appropriate
   if (mode & MODE_DUMP ) {
      printf("[*] Writing traffic to %s%s.*, rolling every %d %s\n",
          dpath, dump_file_prefix, (int)roll_point, rollover_names[(int)roll_type]);
      dump_file_open();
   }

   /* B0rk if we see an error... */
   if (strlen(errbuf) > 0) {
      printf("[*] Error errbuf: %s \n", errbuf);
      exit_clean(1);
   }

   if(drop_privs_flag) {
      printf("[*] Dropping privs...\n\n");
      drop_privs();
   }

   bucket_keys_NULL();

   alarm(TIMEOUT);
   if (read_file) {
      printf("[*] Reading packets...\n");
   } else {
      printf("[*] Sniffing...\n");
   }

   roll_time_last = time(NULL);
   pcap_loop(handle,-1,got_packet,NULL);

   game_over();

   return 0;
}
Esempio n. 19
0
/* Dissect OSC message */
static int
dissect_osc_message(tvbuff_t *tvb, proto_item *ti, proto_tree *osc_tree, gint offset, gint len)
{
    proto_tree *message_tree = NULL;
    proto_tree *header_tree = NULL;
    gint slen;
    gint rem;
    gint end = offset + len;
    const gchar *path = NULL;
    gint path_len;
    gint path_offset;
    const gchar *format = NULL;
    gint format_offset;
    gint format_len;
    const gchar *ptr = NULL;

    /* peek/read path */
    path_offset = offset;
    path = tvb_get_const_stringz(tvb, path_offset, &path_len);
    if( (rem = path_len%4) ) path_len += 4-rem;

    if(!is_valid_path(path))
        return -1;

    /* peek/read fmt */
    format_offset = path_offset + path_len;
    format = tvb_get_const_stringz(tvb, format_offset, &format_len);
    if( (rem = format_len%4) ) format_len += 4-rem;

    if(!is_valid_format(format))
        return -1;

    /* create message */
    ti = proto_tree_add_none_format(osc_tree, hf_osc_message_type, tvb, offset, len, "Message: %s %s", path, format);
    message_tree = proto_item_add_subtree(ti, ett_osc_message);

    /* append header */
    ti = proto_tree_add_item(message_tree, hf_osc_message_header_type, tvb, offset, path_len+format_len, ENC_NA);
    header_tree = proto_item_add_subtree(ti, ett_osc_message_header);

    /* append path */
    proto_tree_add_item(header_tree, hf_osc_message_path_type, tvb, path_offset, path_len, ENC_ASCII | ENC_NA);

    /* append format */
    proto_tree_add_item(header_tree, hf_osc_message_format_type, tvb, format_offset, format_len, ENC_ASCII | ENC_NA);

    offset += path_len + format_len;

    /* ::parse argument:: */
    ptr = format + 1; /* skip ',' */
    while( (*ptr != '\0') && (offset < end) )
    {
        switch(*ptr)
        {
            case OSC_INT32:
                proto_tree_add_item(message_tree, hf_osc_message_int32_type, tvb, offset, 4, ENC_BIG_ENDIAN);
                offset += 4;
                break;
            case OSC_FLOAT:
                proto_tree_add_item(message_tree, hf_osc_message_float_type, tvb, offset, 4, ENC_BIG_ENDIAN);
                offset += 4;
                break;
            case OSC_STRING:
                slen = tvb_strsize(tvb, offset);
                if( (rem = slen%4) ) slen += 4-rem;
                proto_tree_add_item(message_tree, hf_osc_message_string_type, tvb, offset, slen, ENC_ASCII | ENC_NA);
                offset += slen;
                break;
            case OSC_BLOB:
            {
                proto_item *bi = NULL;
                proto_tree *blob_tree = NULL;

                gint32 blen = tvb_get_ntohl(tvb, offset);
                slen = blen;
                if( (rem = slen%4) ) slen += 4-rem;

                bi = proto_tree_add_none_format(message_tree, hf_osc_message_blob_type, tvb, offset, 4+slen, "Blob: %i bytes", blen);
                blob_tree = proto_item_add_subtree(bi, ett_osc_blob);

                proto_tree_add_int_format_value(blob_tree, hf_osc_message_blob_size_type, tvb, offset, 4, blen, "%i bytes", blen);
                offset += 4;

                /* check for zero length blob */
                if(blen == 0)
                    break;

                proto_tree_add_item(blob_tree, hf_osc_message_blob_data_type, tvb, offset, slen, ENC_NA);
                offset += slen;
                break;
            }

            case OSC_TRUE:
                proto_tree_add_item(message_tree, hf_osc_message_true_type, tvb, offset, 0, ENC_NA);
                break;
            case OSC_FALSE:
                proto_tree_add_item(message_tree, hf_osc_message_false_type, tvb, offset, 0, ENC_NA);
                break;
            case OSC_NIL:
                proto_tree_add_item(message_tree, hf_osc_message_nil_type, tvb, offset, 0, ENC_NA);
                break;
            case OSC_BANG:
                proto_tree_add_item(message_tree, hf_osc_message_bang_type, tvb, offset, 0, ENC_NA);
                break;

            case OSC_INT64:
                proto_tree_add_item(message_tree, hf_osc_message_int64_type, tvb, offset, 8, ENC_BIG_ENDIAN);
                offset += 8;
                break;
            case OSC_DOUBLE:
                proto_tree_add_item(message_tree, hf_osc_message_double_type, tvb, offset, 8, ENC_BIG_ENDIAN);
                offset += 8;
                break;
            case OSC_TIMETAG:
            {
                guint32 sec = tvb_get_ntohl(tvb, offset);
                guint32 frac = tvb_get_ntohl(tvb, offset+4);
                nstime_t ns;
                if( (sec == 0UL) && (frac == 1UL) )
                    proto_tree_add_time_format_value(message_tree, hf_osc_message_timetag_type, tvb, offset, 8, &ns, immediate_fmt, immediate_str);
                else
                    proto_tree_add_item(message_tree, hf_osc_message_timetag_type, tvb, offset, 8, ENC_TIME_NTP | ENC_BIG_ENDIAN);
                offset += 8;
            }
                break;

            case OSC_SYMBOL:
                slen = tvb_strsize(tvb, offset);
                if( (rem = slen%4) ) slen += 4-rem;
                proto_tree_add_item(message_tree, hf_osc_message_symbol_type, tvb, offset, slen, ENC_ASCII | ENC_NA);
                offset += slen;
                break;
            case OSC_CHAR:
                offset += 3;
                proto_tree_add_item(message_tree, hf_osc_message_char_type, tvb, offset, 1, ENC_ASCII | ENC_NA);
                offset += 1;
                break;
            case OSC_RGBA:
            {
                proto_item *ri = NULL;
                proto_tree *rgba_tree = NULL;

                ri = proto_tree_add_item(message_tree, hf_osc_message_rgba_type, tvb, offset, 4, ENC_BIG_ENDIAN);
                rgba_tree = proto_item_add_subtree(ri, ett_osc_rgba);

                proto_tree_add_item(rgba_tree, hf_osc_message_rgba_red_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                offset += 1;
                proto_tree_add_item(rgba_tree, hf_osc_message_rgba_green_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                offset += 1;
                proto_tree_add_item(rgba_tree, hf_osc_message_rgba_blue_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                offset += 1;
                proto_tree_add_item(rgba_tree, hf_osc_message_rgba_alpha_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                offset += 1;
                break;
            }
            case OSC_MIDI:
            {
                const gchar *status_str = NULL;
                const gchar *control_str = NULL;
                proto_item *mi = NULL;
                proto_tree *midi_tree = NULL;
                guint8 channel;
                guint8 status;
                guint8 data1;
                guint8 data2;

                channel = tvb_get_guint8(tvb, offset);
                status = tvb_get_guint8(tvb, offset+1);
                data1 = tvb_get_guint8(tvb, offset+2);
                data2 = tvb_get_guint8(tvb, offset+3);

                status_str = val_to_str_const(status, MIDI_status, "Unknown");

                if(status == MIDI_STATUS_CONTROLLER) /* MIDI Controller */
                {
                    control_str = val_to_str_const(data1, MIDI_control, "Unknown");

                    mi = proto_tree_add_none_format(message_tree, hf_osc_message_midi_type, tvb, offset, 4,
                            "MIDI: Channel %2i, %s (0x%02x), %s (0x%02x), 0x%02x",
                            channel,
                            status_str, status,
                            control_str, data1,
                            data2);
                }
                else
                    mi = proto_tree_add_none_format(message_tree, hf_osc_message_midi_type, tvb, offset, 4,
                            "MIDI: Channel %2i, %s (0x%02x), 0x%02x, 0x%02x",
                            channel,
                            status_str, status,
                            data1, data2);
                midi_tree = proto_item_add_subtree(mi, ett_osc_midi);

                proto_tree_add_item(midi_tree, hf_osc_message_midi_channel_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                offset += 1;

                proto_tree_add_item(midi_tree, hf_osc_message_midi_status_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                offset += 1;

                if(status == MIDI_STATUS_CONTROLLER)
                {
                    proto_tree_add_item(midi_tree, hf_osc_message_midi_controller_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                    offset += 1;

                    proto_tree_add_item(midi_tree, hf_osc_message_midi_value_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                    offset += 1;
                }
                else
                {
                    proto_tree_add_item(midi_tree, hf_osc_message_midi_data1_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                    offset += 1;

                    proto_tree_add_item(midi_tree, hf_osc_message_midi_data2_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                    offset += 1;
                }

                break;
            }

            default:
                /* if we get here, there must be a bug in the dissector  */
                DISSECTOR_ASSERT_NOT_REACHED();
                break;
        }
        ptr++;
    }

    if(offset != end)
        return -1;
    else
        return 0;
}
Esempio n. 20
0
/* Dissect OSC message */
static int
dissect_osc_message(tvbuff_t *tvb, proto_item *ti, proto_tree *osc_tree, gint offset, gint len)
{
    proto_tree  *message_tree;
    proto_tree  *header_tree;
    gint         slen;
    gint         rem;
    gint         end = offset + len;
    const gchar *path;
    gint         path_len;
    gint         path_offset;
    const gchar *format;
    gint         format_offset;
    gint         format_len;
    const gchar *ptr;

    /* peek/read path */
    path_offset = offset;
    path = tvb_get_const_stringz(tvb, path_offset, &path_len);
    if( (rem = path_len%4) ) path_len += 4-rem;

    if(!is_valid_path(path))
        return -1;

    /* peek/read fmt */
    format_offset = path_offset + path_len;
    format = tvb_get_const_stringz(tvb, format_offset, &format_len);
    if( (rem = format_len%4) ) format_len += 4-rem;

    if(!is_valid_format(format))
        return -1;

    /* create message */
    ti = proto_tree_add_none_format(osc_tree, hf_osc_message_type, tvb, offset, len, "Message: %s %s", path, format);
    message_tree = proto_item_add_subtree(ti, ett_osc_message);

    /* append header */
    ti = proto_tree_add_item(message_tree, hf_osc_message_header_type, tvb, offset, path_len+format_len, ENC_NA);
    header_tree = proto_item_add_subtree(ti, ett_osc_message_header);

    /* append path */
    proto_tree_add_item(header_tree, hf_osc_message_path_type, tvb, path_offset, path_len, ENC_ASCII | ENC_NA);

    /* append format */
    proto_tree_add_item(header_tree, hf_osc_message_format_type, tvb, format_offset, format_len, ENC_ASCII | ENC_NA);

    offset += path_len + format_len;

    /* ::parse argument:: */
    ptr = format + 1; /* skip ',' */
    while( (*ptr != '\0') && (offset < end) )
    {
        switch(*ptr)
        {
            case OSC_INT32:
                proto_tree_add_item(message_tree, hf_osc_message_int32_type, tvb, offset, 4, ENC_BIG_ENDIAN);
                offset += 4;
                break;
            case OSC_FLOAT:
                proto_tree_add_item(message_tree, hf_osc_message_float_type, tvb, offset, 4, ENC_BIG_ENDIAN);
                offset += 4;
                break;
            case OSC_STRING:
                slen = tvb_strsize(tvb, offset);
                if( (rem = slen%4) ) slen += 4-rem;
                proto_tree_add_item(message_tree, hf_osc_message_string_type, tvb, offset, slen, ENC_ASCII | ENC_NA);
                offset += slen;
                break;
            case OSC_BLOB:
            {
                proto_item *bi;
                proto_tree *blob_tree;

                gint32 blen = tvb_get_ntohl(tvb, offset);
                slen = blen;
                if( (rem = slen%4) ) slen += 4-rem;

                bi = proto_tree_add_none_format(message_tree, hf_osc_message_blob_type, tvb, offset, 4+slen, "Blob: %i bytes", blen);
                blob_tree = proto_item_add_subtree(bi, ett_osc_blob);

                proto_tree_add_int_format_value(blob_tree, hf_osc_message_blob_size_type, tvb, offset, 4, blen, "%i bytes", blen);
                offset += 4;

                /* check for zero length blob */
                if(blen == 0)
                    break;

                proto_tree_add_item(blob_tree, hf_osc_message_blob_data_type, tvb, offset, slen, ENC_NA);
                offset += slen;
                break;
            }

            case OSC_TRUE:
                proto_tree_add_item(message_tree, hf_osc_message_true_type, tvb, offset, 0, ENC_NA);
                break;
            case OSC_FALSE:
                proto_tree_add_item(message_tree, hf_osc_message_false_type, tvb, offset, 0, ENC_NA);
                break;
            case OSC_NIL:
                proto_tree_add_item(message_tree, hf_osc_message_nil_type, tvb, offset, 0, ENC_NA);
                break;
            case OSC_BANG:
                proto_tree_add_item(message_tree, hf_osc_message_bang_type, tvb, offset, 0, ENC_NA);
                break;

            case OSC_INT64:
                proto_tree_add_item(message_tree, hf_osc_message_int64_type, tvb, offset, 8, ENC_BIG_ENDIAN);
                offset += 8;
                break;
            case OSC_DOUBLE:
                proto_tree_add_item(message_tree, hf_osc_message_double_type, tvb, offset, 8, ENC_BIG_ENDIAN);
                offset += 8;
                break;
            case OSC_TIMETAG:
            {
                guint32  sec  = tvb_get_ntohl(tvb, offset);
                guint32  frac = tvb_get_ntohl(tvb, offset+4);
                nstime_t ns;
                if( (sec == 0) && (frac == 1) )
                    proto_tree_add_time_format_value(message_tree, hf_osc_message_timetag_type, tvb, offset, 8, &ns, immediate_fmt, immediate_str);
                else
                    proto_tree_add_item(message_tree, hf_osc_message_timetag_type, tvb, offset, 8, ENC_TIME_NTP | ENC_BIG_ENDIAN);
                offset += 8;
            }
                break;

            case OSC_SYMBOL:
                slen = tvb_strsize(tvb, offset);
                if( (rem = slen%4) ) slen += 4-rem;
                proto_tree_add_item(message_tree, hf_osc_message_symbol_type, tvb, offset, slen, ENC_ASCII | ENC_NA);
                offset += slen;
                break;
            case OSC_CHAR:
                offset += 3;
                proto_tree_add_item(message_tree, hf_osc_message_char_type, tvb, offset, 1, ENC_ASCII | ENC_NA);
                offset += 1;
                break;
            case OSC_RGBA:
            {
                proto_item *ri;
                proto_tree *rgba_tree;

                ri = proto_tree_add_item(message_tree, hf_osc_message_rgba_type, tvb, offset, 4, ENC_BIG_ENDIAN);
                rgba_tree = proto_item_add_subtree(ri, ett_osc_rgba);

                proto_tree_add_item(rgba_tree, hf_osc_message_rgba_red_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                offset += 1;
                proto_tree_add_item(rgba_tree, hf_osc_message_rgba_green_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                offset += 1;
                proto_tree_add_item(rgba_tree, hf_osc_message_rgba_blue_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                offset += 1;
                proto_tree_add_item(rgba_tree, hf_osc_message_rgba_alpha_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                offset += 1;
                break;
            }
            case OSC_MIDI:
            {
                const gchar *status_str;
                proto_item  *mi = NULL;
                proto_tree  *midi_tree;
                guint8       port;
                guint8       command;
                guint8       data1;
                guint8       data2;
                guint8       status;
                guint8       channel;
                gboolean     system_msg;
                guint8       status_shifted;

                port = tvb_get_guint8(tvb, offset);
                command  = tvb_get_guint8(tvb, offset+1);
                data1   = tvb_get_guint8(tvb, offset+2);
                data2   = tvb_get_guint8(tvb, offset+3);

                status  = command & 0xF0;
                channel = command & 0x0F;

                system_msg = status == 0xF0; /* is system message */
                status_shifted = status >> 4;

                if(system_msg)
                    status_str = val_to_str_ext_const(command, &MIDI_system_ext, "Unknown");
                else
                    status_str = val_to_str_ext_const(status_shifted, &MIDI_status_ext, "Unknown");

                if(system_msg)
                {
                    mi = proto_tree_add_none_format(message_tree, hf_osc_message_midi_type, tvb, offset, 4,
                            "MIDI: Port %i, %s, %i, %i",
                            port, status_str, data1, data2);
                }
                else
                {
                    switch(status_shifted)
                    {
                        case MIDI_STATUS_NOTE_ON:
                        case MIDI_STATUS_NOTE_OFF:
                        case MIDI_STATUS_NOTE_PRESSURE:
                        {
                            const gchar *note_str;
                            note_str = val_to_str_ext_const(data1, &MIDI_note_ext, "Unknown");

                            mi = proto_tree_add_none_format(message_tree, hf_osc_message_midi_type, tvb, offset, 4,
                                    "MIDI: Port %i, Channel %i, %s, %s, %i",
                                    port, channel, status_str, note_str, data2);
                            break;
                        }
                        case MIDI_STATUS_CONTROLLER:
                        {
                            const gchar *control_str;
                            control_str = val_to_str_ext_const(data1, &MIDI_control_ext, "Unknown");

                            mi = proto_tree_add_none_format(message_tree, hf_osc_message_midi_type, tvb, offset, 4,
                                    "MIDI: Port %i, Channel %i, %s, %s, %i",
                                    port, channel, status_str, control_str, data2);
                            break;
                        }
                        case MIDI_STATUS_PITCH_BENDER:
                        {
                            const gint bender = (((gint)data2 << 7) | (gint)data1) - 0x2000;

                            mi = proto_tree_add_none_format(message_tree, hf_osc_message_midi_type, tvb, offset, 4,
                                    "MIDI: Port %i, Channel %i, %s, %i",
                                    port, channel, status_str, bender);
                            break;
                        }
                        default:
                        {
                            mi = proto_tree_add_none_format(message_tree, hf_osc_message_midi_type, tvb, offset, 4,
                                    "MIDI: Port %i, Channel %i, %s, %i, %i",
                                    port, channel, status_str, data1, data2);
                            break;
                        }
                    }
                }
                midi_tree = proto_item_add_subtree(mi, ett_osc_midi);

                proto_tree_add_item(midi_tree, hf_osc_message_midi_port_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                offset += 1;

                if(system_msg)
                {
                    proto_tree_add_item(midi_tree, hf_osc_message_midi_system_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                    offset += 1;

                    proto_tree_add_item(midi_tree, hf_osc_message_midi_data1_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                    offset += 1;

                    proto_tree_add_item(midi_tree, hf_osc_message_midi_data2_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                    offset += 1;
                }
                else
                {
                    proto_tree_add_item(midi_tree, hf_osc_message_midi_status_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                    proto_tree_add_item(midi_tree, hf_osc_message_midi_channel_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                    offset += 1;

                    switch(status_shifted)
                    {
                        case MIDI_STATUS_NOTE_ON:
                        case MIDI_STATUS_NOTE_OFF:
                        {
                            proto_tree_add_item(midi_tree, hf_osc_message_midi_note_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                            offset += 1;

                            proto_tree_add_item(midi_tree, hf_osc_message_midi_velocity_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                            offset += 1;

                            break;
                        }
                        case MIDI_STATUS_NOTE_PRESSURE:
                        {
                            proto_tree_add_item(midi_tree, hf_osc_message_midi_note_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                            offset += 1;

                            proto_tree_add_item(midi_tree, hf_osc_message_midi_pressure_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                            offset += 1;

                            break;
                        }
                        case MIDI_STATUS_CONTROLLER:
                        {
                            proto_tree_add_item(midi_tree, hf_osc_message_midi_controller_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                            offset += 1;

                            proto_tree_add_item(midi_tree, hf_osc_message_midi_data2_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                            offset += 1;

                            break;
                        }
                        case MIDI_STATUS_CHANNEL_PRESSURE:
                        {
                            proto_tree_add_item(midi_tree, hf_osc_message_midi_pressure_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                            offset += 1;

                            proto_tree_add_item(midi_tree, hf_osc_message_midi_data2_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                            offset += 1;

                            break;
                        }
                        case MIDI_STATUS_PITCH_BENDER:
                        {
                            const gint bender = (((gint)data2 << 7) | (gint)data1) - 0x2000;

                            proto_tree_add_int(midi_tree, hf_osc_message_midi_bender_type, tvb, offset, 2, bender);
                            offset += 2;

                            break;
                        }
                        default:
                        {
                            proto_tree_add_item(midi_tree, hf_osc_message_midi_data1_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                            offset += 1;

                            proto_tree_add_item(midi_tree, hf_osc_message_midi_data2_type, tvb, offset, 1, ENC_BIG_ENDIAN);
                            offset += 1;

                            break;
                        }
                    }
                }

                break;
            }

            default:
                /* if we get here, there must be a bug in the dissector  */
                DISSECTOR_ASSERT_NOT_REACHED();
                break;
        }
        ptr++;
    }

    if(offset != end)
        return -1;
    else
        return 0;
}
Esempio n. 21
0
/**
 * Checks command line arguments once and for all. Handles (de)allocation for config_t structure
 *
 * @return 0 if successfully parsed and allocated
 * @return -1
 */
int parse_options (int argc, char** argv)
{
	int curopt, curopt_idx;
	char *logfile, *path, *keyfile, *certfile;
	char *proxy_host, *proxy_port;

	proxy_host = proxy_port = NULL;
	
	const struct option long_opts[] = {
		{ "help",       0, 0, 'h' },
		{ "verbose",    0, 0, 'v' },
		{ "nb-threads", 1, 0, 't' },
		{ "lbind",      1, 0, 'b' },
		{ "lport",      1, 0, 'p' },
		{ "logfile",    1, 0, 'l' },
		{ "certfile",   1, 0, 'c' },
		{ "keyfile",    1, 0, 'k' },
		{ "plugins",    1, 0, 'x' },
		{ "proxy-host", 1, 0, 'X' },
		{ "proxy-port", 1, 0, 'P' },
		{ "no-color",   0, 0, 'n' },
		{ "version",    0, 0, 'V' },
		{ 0, 0, 0, 0 } 
	};
	
	cfg->iface		= CFG_DEFAULT_BIND_ADDR;
	cfg->port		= CFG_DEFAULT_PORT;
	cfg->logfile_fd		= CFG_DEFAULT_OUTPUT;
	cfg->nb_threads		= CFG_DEFAULT_NB_THREAD;
	cfg->use_color		= true;
	cfg->ip_version		= CFG_DEFAULT_IP_VERSION;
	cfg->try_exit		= 0;
	cfg->try_exit_max	= CFG_DEFAULT_TRY_EXIT_MAX;
	
	path			= CFG_DEFAULT_PLUGINS_PATH;
	keyfile			= CFG_DEFAULT_SSL_KEYFILE;
	certfile		= CFG_DEFAULT_SSL_CERTFILE;
	logfile			= NULL;
	
	/* parse command line arguments */
	while (1) {
		curopt = -1;
		curopt_idx = 0;
		curopt = getopt_long (argc,argv,"n46Vhvb:p:l:t:c:k:x:X:P:",long_opts, &curopt_idx);
		if (curopt == -1) break;
		
		switch (curopt) {
			case 'v': cfg->verbose++; break;
			case 'b': cfg->iface = optarg; break;
			case 'p': cfg->port = optarg; break;
			case 'l': logfile = optarg; break;
			case 't': cfg->nb_threads = (unsigned short)atoi(optarg); break;
			case 'X':
				proxy_host = optarg;
				proxy_port = CFG_DEFAULT_PROXY_PORT;
				break;
			case 'P': proxy_port = optarg; break;
			case 'c': certfile = optarg; break;
			case 'k': keyfile = optarg; break;	   
			case 'h': help(argv[0]); break;
			case 'V': version(true); break;
			case 'n': cfg->use_color = false; break;
			case '4': cfg->ip_version = AF_INET; break;
			case '6': cfg->ip_version = AF_INET6; break;
			case 'x': path = optarg; break;
			case '?':
			default:
				usage (EXIT_FAILURE);
		}
		curopt_idx = 0;
	}

	/* validate command line arguments */

	/* logfile validation : if a logfile is given, use its FILE* for output */
	if (logfile) {
		cfg->logfile = realpath(logfile, NULL);
		if (cfg->logfile == NULL){
			xlog(LOG_CRITICAL, "realpath(logfile) failed: %s\n", strerror(errno));
			return -1;
		}
		if(is_readable_file(cfg->logfile)) {
			cfg->logfile_fd = fopen(cfg->logfile, "w");
			if(!cfg->logfile_fd) {
				cfg->logfile_fd = stderr;
				xlog(LOG_CRITICAL, "[-] Failed to open '%s': %s\n", cfg->logfile, strerror(errno));
				return -1;
			}
		}
	}

	/* check if nb of threads is in boundaries */
	if (cfg->nb_threads > MAX_THREADS) {
		fprintf(stderr, "Too many threads. Setting to default.\n");
		cfg->nb_threads = CFG_DEFAULT_NB_THREAD;
	}
	
	/* check plugins path */
	cfg->plugins_path = realpath(path, NULL);
	if (cfg->plugins_path == NULL){
		xlog(LOG_CRITICAL, "realpath(plugins_path) failed: %s\n", strerror(errno));
		return -1;
	}
	if (!is_valid_path(cfg->plugins_path)) {
		xlog(LOG_CRITICAL, "%s\n", "Invalid plugins path provided");
		return -1;
	}

	/* check ssl certificate */
	cfg->certfile = realpath(certfile, NULL);
	if (cfg->certfile == NULL){
		xlog(LOG_CRITICAL, "realpath(certfile) failed: %s\n", strerror(errno));
		return -1;
	}
	if ( !is_readable_file(cfg->certfile) ) {
		xlog(LOG_CRITICAL, "Failed to read certificate '%s'\n", cfg->certfile);
		return -1;
	}

	/* check ssl key */
	cfg->keyfile = realpath(keyfile, NULL);
	if (cfg->certfile == NULL){
		xlog(LOG_CRITICAL, "realpath(certfile) failed: %s\n", strerror(errno));
		return -1;
	}
	if ( !is_readable_file(cfg->keyfile) ){
		xlog(LOG_CRITICAL, "Failed to read private key '%s'\n", cfg->keyfile);
		return -1;
	}

	/* check proxy values (if any) */
	if ( proxy_port && !proxy_host) {
		xlog(LOG_CRITICAL, "%s\n", "Cannot use proxy-port without proxy-host");
		return -1;
	}

	if (proxy_host) {
		cfg->proxy.host = strdup(proxy_host);
		if (!cfg->proxy.host) {
			xlog(LOG_CRITICAL, "proxy %s\n", strerror(errno));
			return -1;
		}

		cfg->proxy.port = strdup(proxy_port);
		if (!cfg->proxy.port) {
			xlog(LOG_CRITICAL, "proxy_port %s\n", strerror(errno));
			return -1;
		}
	}
	
	return 0;

}
Esempio n. 22
0
static int create_pid_file(char *path, char *filename) {
   char filepath[STDBUF];
   char *fp = NULL;
   char *fn = NULL;
   char pid_buffer[12];
   struct flock lock;
   int rval;
   int fd;

   memset(filepath, 0, STDBUF);

   if ( !filename ) {
      fn = pidfile;
   }
   else {
      fn = filename;
   }

   if ( !path ) {
      fp = pidpath;
   }
   else {
      fp = path;
   }

   if ( is_valid_path(fp) ) {
      snprintf(filepath, STDBUF-1, "%s/%s", fp, fn);
   }
   else {
      printf("PID path \"%s\" isn't a writeable directory!", fp);
   }

   true_pid_name = strdup(filename);

   if ( (fd = open(filepath, O_CREAT | O_WRONLY,
                    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1 ) {
      return ERROR;
   }

   /* pid file locking */
   lock.l_type = F_WRLCK;
   lock.l_start = 0;
   lock.l_whence = SEEK_SET;
   lock.l_len = 0;

   if ( fcntl(fd, F_SETLK, &lock) == -1 ) {
      if ( errno == EACCES || errno == EAGAIN ) {
         rval = ERROR;
      }
      else {
         rval = ERROR;
      }
      close(fd);
      return rval;
   }

   snprintf(pid_buffer, sizeof(pid_buffer), "%d\n", (int) getpid());
   if ( ftruncate(fd, 0) != 0 ) { return ERROR; }
   if ( write(fd, pid_buffer, strlen(pid_buffer)) != 0 ) { return ERROR; }

   close(fd);

   return SUCCESS;
}
Esempio n. 23
0
int
is_valid_file(const char *path)
{
    return is_valid_path(path, IS_FILE);
}
Esempio n. 24
0
/*!

\brief Finds file on file system.
\ingroup System
\details Defined in dmzSystemFile.h.
This function takes three steps to locate the file. First it attempts to validate the
file as it is passed in. If the file is not found. All leading path information is
stripped from the file and then each path in the StringContainer is used to try
and locate the file. If the file is not found, each path in the StringContainer is
searched with out the leading path information stripped from the \a FileName.
\param[in] Container StringContainer with list of paths to use in the file search.
\param[in] FileName String containing the name of the file to search for.
\param[out] foundFile String containing the absolute path to the found file.
\return Returns dmz::True if the file is found.

*/
dmz::Boolean
dmz::find_file (
    const StringContainer &Container,
    const String &FileName,
    String &foundFile) {

    Boolean result (False);

    if (is_valid_path (FileName)) {
        result = get_absolute_path (FileName, foundFile);
    }

    if (!result) {

        String path, file, ext;
        split_path_file_ext (FileName, path, file, ext);

        if (file) {

            file << ext;

            Boolean done (!Container.get_first (path));

            while (!done) {

                const String CleanPath (format_path (path + "/" + file));

                if (is_valid_path (CleanPath)) {

                    result = get_absolute_path (CleanPath, foundFile);
                    done = True;
                }
                else {
                    done = !Container.get_next (path);
                }
            }
        }
    }

    if (!result) {

        String path;

        Boolean done (!Container.get_first (path));

        while (!done) {

            const String CleanPath (format_path (path + "/" + FileName));

            if (is_valid_path (CleanPath)) {

                result = get_absolute_path (CleanPath, foundFile);
                done = True;
            }
            else {
                done = !Container.get_next (path);
            }
        }
    }

    return result;
}
Esempio n. 25
0
int
is_valid_dir(const char *path)
{
    return is_valid_path(path, IS_DIR);
}