コード例 #1
0
ファイル: config_load.c プロジェクト: ironpinguin/rpi-gpiod
void load_params(int argc, char **argv) {
  config_t cfg;
  config_setting_t *setting, *interrupt_setting;
  char const *config_socket, *inter_name, *inter_type_string, *inter_pud;
  char *config_file_name;
  int ch, inter_pin, inter_type, inter_wait, r, pud;
  int lcd_di, lcd_led, lcd_spics, read_config = 0;
  InterruptInfo *interrupt_info;

  while ((ch = getopt(argc, argv, "dhvs:a:l:c:i:")) != -1) {
    switch (ch) {
      case 'd':
        set_flag_dont_detach(1);
        break;
      case 'h':
        usage();
        exit(EXIT_SUCCESS);
        break;
     case 'v':
       set_flag_verbose(1);
       break;
     case 's':
       set_socket_filename(optarg);
       break;
     case 'a':
       if (is_valid_pin_num(atoi(optarg))) {
         set_lcd_di(atoi(optarg));
       } else {
         printf("Only valid Pinnumber between 1 and 16 allowed!\n");
         usage();
         exit(EXIT_FAILURE);
       }
       break;
     case 'l':
       if (is_valid_pin_num(atoi(optarg))) {
         set_lcd_led(atoi(optarg));
       } else {
         printf("Only valid Pinnumber between 1 and 16 allowed!\n");
         usage();
         exit(EXIT_FAILURE);
       }
       break;
     case 'c':
       if (is_valid_pin_num(atoi(optarg))) {
         set_lcd_spics(atoi(optarg));
       } else {
         printf("Only 0 or 1 allowed!\n");
         usage();
         exit(EXIT_FAILURE);
       }
       break;
     case 'i':
       read_config = 1;
       config_file_name = optarg;
       break;
     default:
       usage();
       exit(1);
    }
  }

  if (read_config) {
    config_init(&cfg);
    /* Read the config file and about on error */
    if (!config_read_file(&cfg, config_file_name)) {
      printf("\n%s:%d - %s\n", config_file_name, config_error_line(&cfg), config_error_text(&cfg));
      config_destroy(&cfg);
      exit(1);
    }

    if (config_lookup_string(&cfg, "socket", &config_socket)) {
      set_socket_filename(strndup(config_socket, strlen(config_socket)));
      printf("Socket file configured from config file as: %s\n", get_socket_filename());
    }

    setting = config_lookup(&cfg, "lcd");

    if (setting != NULL) {
      if (!config_setting_lookup_int(setting, "di_pin", &lcd_di)) {
    	  set_lcd_di(lcd_di);
    	  if (get_flag_verbose()) {
    		  printf("Set DI Pin of the LCD Display to %i with config file\n", lcd_di);
    	  }
      }
      if (!config_setting_lookup_int(setting, "led_pin", &lcd_led)) {
    	  set_lcd_led(lcd_led);
    	  if (get_flag_verbose()) {
    		  printf("Set PWM LED Pin of the LCD Display to %i with config file\n", lcd_led);
    	  }
      }
      if (!config_setting_lookup_int(setting, "spi_cs", &lcd_spics)) {
    	  set_lcd_spics(lcd_spics);
    	  if (get_flag_verbose()) {
    		  printf("Set SPI CS Pin of the LCD Display to %i with config file\n", lcd_spics);
    	  }
      }
    }

    setting = config_lookup(&cfg, "interrupt");

    if (setting != NULL)
    {
      if (config_setting_type(setting) == CONFIG_TYPE_LIST) {
        set_interrupts_count(config_setting_length(setting));
        // Max interrupts are 10 if more configured only the first 10 are used!
        if (get_interrupts_count() > 10) {
          set_interrupts_count(10);
        }
        for (r=0; r < get_interrupts_count(); r++) {
          interrupt_setting = config_setting_get_elem(setting, r);
          if (!(config_setting_lookup_int(interrupt_setting, "pin", &inter_pin)
              && config_setting_lookup_string(interrupt_setting, "type", &inter_type_string)
              && config_setting_lookup_string(interrupt_setting, "name", &inter_name)
              && config_setting_lookup_int(interrupt_setting, "wait", &inter_wait)
              && config_setting_lookup_string(interrupt_setting, "pud", &inter_pud))) {
            // TODO: Error message if configuration is not valid
            continue;
          }

          if(strncmp(inter_pud, "none", strlen("none")) == 0) {
            pud = PUD_OFF;
          } else if (strncmp(inter_pud, "up", strlen("up")) == 0) {
            pud = PUD_UP;
          } else if (strncmp(inter_pud, "down", strlen("down")) == 0) {
            pud = PUD_DOWN;
          } else {
            // TODO: Error message if configuration is not valid
            continue;
          }

          if(strncmp(inter_type_string, "falling", strlen("falling")) == 0) {
            inter_type = INT_EDGE_FALLING;
          } else if (strncmp(inter_type_string, "rising", strlen("rising")) == 0) {
            inter_type = INT_EDGE_RISING;
          } else if (strncmp(inter_type_string, "both", strlen("both")) == 0) {
            inter_type = INT_EDGE_BOTH;
          } else {
            // TODO: Error message if configuration is not valid
            continue;
          }
          interrupt_info = malloc(sizeof(InterruptInfo));

          if (r <= 10) {
            interrupt_info->pin    = inter_pin;
            interrupt_info->wait   = inter_wait;
            interrupt_info->type   = inter_type;
            interrupt_info->name   = strndup(inter_name, strlen(inter_name));
            interrupt_info->occure = 0;
            interrupt_info->pud    = pud;
            set_interrupt_info(r, *interrupt_info);
          }
        }
      }
    }

    config_destroy(&cfg);
  }
}
コード例 #2
0
ファイル: gtLog.cpp プロジェクト: hammer/genetorrent
// priority determines if messages are sent to stderr if logging to a file, syslog, or none
gtLogger::gtLogger (std::string progName, std::string log, int childID, std::string UUID) : m_mode (gtLoggerOutputNone), m_fd (NULL), m_last_timestamp (0)
{
   m_progname = strdup (progName.c_str());
   m_filename = strdup (log.c_str());

   // m_filename is one of "none", "syslog", "stdout", "stderr", or a filename
   if (!strcmp(m_filename, "none")) 
   {
      m_mode = gtLoggerOutputNone;
   } 
   else if (!strcmp(m_filename, "stdout")) 
   {
      m_fd = stdout;
      m_mode = gtLoggerOutputStdout;
   } 
   else if (!strcmp(m_filename, "stderr")) 
   {
      m_fd = stderr;
      m_mode = gtLoggerOutputStderr;
   }
   else if (!strcmp(m_filename, "syslog")) 
   {
      m_mode = gtLoggerOutputSyslog;
      openlog (m_progname, LOG_PID, LOG_LOCAL0);
   }
   else 
   {
      // GeneTorrent Download child processes have their own log, childID is inserted after the last dot (.) in the specified filename
      // or the childID is appended to the file name if no dot (.) is present in the filename.
      // The parent download process sends output to filename
      if (childID > 0)   
      {
         char timebuf[1024];
         struct timeval now;
         struct tm time_tm;

         gettimeofday(&now,  NULL);
         time_t nowSec = now.tv_sec;
         localtime_r(&nowSec, &time_tm);
         strftime(timebuf, sizeof(timebuf), "%Y-%m-%d-%H%M", &time_tm);

         std::ostringstream outbuff;
         std::string work=m_filename;
         free (m_filename);

         std::ostringstream midBuff;
         midBuff << '.' << childID << '.' << timebuf;

         if (UUID.size())
         {
            midBuff << '.' << UUID;
         }

         size_t pos = work.rfind ('.');
  
         if (std::string::npos != pos)
         {
            outbuff << work.substr(0,pos) << midBuff.str() << work.substr(pos);
         }
         else
         {
            outbuff << work << midBuff.str();
         }

         m_filename = strndup (outbuff.str().c_str(), outbuff.str().size());
      }

      m_fd = fopen(m_filename, "w");
      if (m_fd == NULL) 
      {
         m_mode = gtLoggerOutputNone;
         fprintf(stderr, "Error opening log file %s\n", m_filename);
         fprintf(stderr, "Error %s\n", strerror(errno));
         exit(1);
      }

      m_mode = gtLoggerOutputFile;
   }

   time_t clocktime;
   time(&clocktime);

   if (m_mode == gtLoggerOutputFile) 
   {
      // Write a log header
      fprintf(m_fd, "Log file initiated at %s", ctime(&clocktime));
      fprintf(m_fd, "Process id: %d\n", getpid());
      fputs("=============================================================\n", m_fd);
      fflush(m_fd);
   }
}
コード例 #3
0
static
uintptr_t
load_ppp_module()
{
    if (module_dl_handler) {
        // already loaded
        return 0;
    }

    // allocate auxiliary instance
    if (!aux_instance) {
        aux_instance = calloc(1, sizeof(*aux_instance));
        if (!aux_instance)
            return 1;

        aux_instance->id = tables_generate_new_pp_instance_id();
        tables_add_pp_instance(aux_instance->id, aux_instance);
    }

    // allocate message loop for browser thread
    if (ppb_message_loop_get_current() == 0) {
        PP_Resource message_loop = ppb_message_loop_create(aux_instance->id);
        ppb_message_loop_attach_to_current_thread(message_loop);
        ppb_message_loop_proclaim_this_thread_browser();
    }

    // allocate message loop for plugin thread (main thread)
    if (ppb_message_loop_get_for_main_thread() == 0) {
        pthread_barrier_init(&aux_instance->main_thread_barrier, NULL, 2);
        pthread_create(&aux_instance->main_thread, NULL, fresh_wrapper_main_thread, aux_instance);
        pthread_detach(aux_instance->main_thread);
        pthread_barrier_wait(&aux_instance->main_thread_barrier);
        pthread_barrier_destroy(&aux_instance->main_thread_barrier);
    }

    fpp_config_initialize();

    if (tried_files) {
        g_list_free_full(tried_files, g_free);
        tried_files = NULL;
    }

    if (fpp_config_get_plugin_path()) {
        const char *ptr = fpp_config_get_plugin_path();
        const char *last = strchr(ptr, ':');
        uintptr_t   ret;

        // parse ':'-separated list
        while (last != NULL) {
            // try entries one by one
            char *entry = strndup(ptr, last - ptr);
            ret = do_load_ppp_module(entry);
            free(entry);
            if (ret == 0)
                return 0;

            ptr = last + 1;
            last = strchr(ptr, ':');
        }

        // and the last entry
        ret = do_load_ppp_module(ptr);
        if (ret == 0)
            return 0;

        goto failure;
    }

    // try all paths
    const char **path_list = fpp_config_get_plugin_path_list();
    while (*path_list) {
        gchar *fname = g_strdup_printf("%s/%s", *path_list, fpp_config_get_plugin_file_name());
        uintptr_t ret = do_load_ppp_module(fname);
        g_free(fname);
        if (ret == 0)
            return 0;
        path_list ++;
    }

failure:
    config.quirks.plugin_missing = 1;
    use_fallback_version_strings();
    trace_error("%s, can't find %s\n", __func__, fpp_config_get_plugin_file_name());
    return 1;
}
コード例 #4
0
ファイル: config.c プロジェクト: crazylife/jabberd2
static char *_config_expandx(config_t c, const char *value, int l)
{
	const char *var_value;

#ifdef CONFIGEXPAND_GUARDED
    static char guard[] = "deadbeaf";
#endif

//     fprintf(stderr, "config_expand: Expanding '%s'\n", value);
    char *s = strndup(value, l);

    char *var_start, *var_end;

    while ((var_start = strstr(s, "${")) != 0) {
//         fprintf(stderr, "config_expand: processing '%s'\n", s);
        var_end = strstr(var_start + 2, "}");

        if (var_end) {
            char *tail = var_end + 1;
            char *var = var_start + 2;
            *var_end = 0;

//             fprintf(stderr, "config_expand: Var '%s', tail is '%s'\n", var, tail);

			var_value = config_get_one(c, var, 0);

            if (var_value) {
                int len = (var_start - s) + strlen(tail) + strlen(var_value) + 1;

#ifdef CONFIGEXPAND_GUARDED
                len += sizeof(guard);
#endif
                char *expanded_str = (char *)calloc(len, 1);

#ifdef CONFIGEXPAND_GUARDED
                char *p_guard = expanded_str + len - sizeof(guard);
                strncpy(p_guard, guard, sizeof(guard));
#endif

                char *p = expanded_str;
                strncpy(expanded_str, s, var_start - s);
                p += var_start - s;

                strcpy(p, var_value);
                p += strlen(var_value);

                strcpy(p, tail);

                free(s);
                s = expanded_str;
            } else {
                fprintf(stderr, "config_expand: Have no '%s' defined\n", var);
                free(s);
                s = 0;
                break;
            }
        } else {
            fprintf(stderr, "config_expand: } missmatch\n");
            free(s);
            s = 0;
            break;
        }
    }

    if (s) {
        char *retval = pstrdup(xhash_pool(c->hash), s);
        free(s);
        return retval;
    } else {
        return 0;
    }
}
コード例 #5
0
ファイル: sagan-bluedot.c プロジェクト: carriercomm/sagan
size_t static write_callback_func(void *buffer, size_t size, size_t nmemb, void *userp)
{
    char **response_ptr =  (char**)userp;
    *response_ptr = strndup(buffer, (size_t)(size *nmemb));     /* Return the string */
}
コード例 #6
0
static subpicture_region_t *CreateTextRegion( decoder_t *p_dec,
                                              char *psz_subtitle,
                                              int i_len,
                                              int i_sys_align )
{
    decoder_sys_t        *p_sys = p_dec->p_sys;
    subpicture_region_t  *p_text_region;
    video_format_t        fmt;

    /* Create a new subpicture region */
    memset( &fmt, 0, sizeof(video_format_t) );
    fmt.i_chroma = VLC_CODEC_TEXT;
    fmt.i_width = fmt.i_height = 0;
    fmt.i_x_offset = fmt.i_y_offset = 0;
    p_text_region = subpicture_region_New( &fmt );

    if( p_text_region != NULL )
    {
        ssa_style_t  *p_ssa_style = NULL;

        p_text_region->psz_text = NULL;
        p_text_region->psz_html = strndup( psz_subtitle, i_len );
        if( ! p_text_region->psz_html )
        {
            subpicture_region_Delete( p_text_region );
            return NULL;
        }

        p_ssa_style = ParseStyle( p_sys, p_text_region->psz_html );
        if( !p_ssa_style )
        {
            int i;

            for( i = 0; i < p_sys->i_ssa_styles; i++ )
            {
                if( !strcasecmp( p_sys->pp_ssa_styles[i]->psz_stylename, "Default" ) )
                    p_ssa_style = p_sys->pp_ssa_styles[i];
            }
        }

        if( p_ssa_style )
        {
            msg_Dbg( p_dec, "style is: %s", p_ssa_style->psz_stylename );

            p_text_region->p_style = text_style_Duplicate( &p_ssa_style->font_style );
            p_text_region->i_align = p_ssa_style->i_align;

            /* TODO: Setup % based offsets properly, without adversely affecting
             *       everything else in vlc. Will address with separate patch,
             *       to prevent this one being any more complicated.

                     * p_ssa_style->i_margin_percent_h;
                     * p_ssa_style->i_margin_percent_v;
             */
            p_text_region->i_x         = p_ssa_style->i_margin_h;
            p_text_region->i_y         = p_ssa_style->i_margin_v;

        }
        else
        {
            p_text_region->i_align = SUBPICTURE_ALIGN_BOTTOM | i_sys_align;
            p_text_region->i_x = i_sys_align ? 20 : 0;
            p_text_region->i_y = 10;
        }
        /* Look for position arguments which may override the style-based
         * defaults.
         */
        SetupPositions( p_text_region, psz_subtitle );

        p_text_region->p_next = NULL;
    }
    return p_text_region;
}
コード例 #7
0
ファイル: pkg_create.c プロジェクト: dumbbell/pkg
int
pkg_create_staged(const char *outdir, pkg_formats format, const char *rootdir,
    const char *md_dir, char *plist, bool old)
{
	struct pkg	*pkg = NULL;
	struct pkg_file	*file = NULL;
	struct pkg_dir	*dir = NULL;
	struct packing	*pkg_archive = NULL;
	char		*manifest = NULL;
	char		 arch[BUFSIZ];
	int		 ret = ENOMEM;
	int		 i, mfd;
	regex_t		 preg;
	regmatch_t	 pmatch[2];
	size_t		 size;
	struct pkg_manifest_key *keys = NULL;

	mfd = -1;

	pkg_debug(1, "Creating package from stage directory: '%s'", rootdir);

	if ((mfd = open(md_dir, O_DIRECTORY)) == -1) {
		pkg_emit_errno("open", md_dir);
		goto cleanup;
	}

	if(pkg_new(&pkg, old ? PKG_OLD_FILE : PKG_FILE) != EPKG_OK) {
		ret = EPKG_FATAL;
		goto cleanup;
	}

	pkg_manifest_keys_new(&keys);
	/* Load the manifest from the metadata directory */
	if ((ret = pkg_parse_manifest_fileat(mfd, pkg, "+MANIFEST", keys))
	    != EPKG_OK) {
		ret = EPKG_FATAL;
		goto cleanup;
	}

	/* if no descriptions provided then try to get it from a file */
	if (pkg->desc == NULL)
		pkg_load_from_file(mfd, pkg, PKG_DESC, "+DESC");

	/* if no message try to get it from a file */
	if (pkg->message == NULL)
		pkg_load_from_file(mfd, pkg, PKG_MESSAGE, "+DISPLAY");

	/* if no arch autodetermine it */
	if (pkg->abi == NULL) {
		pkg_get_myarch(arch, BUFSIZ);
		pkg->abi = strdup(arch);
	}

	for (i = 0; scripts[i] != NULL; i++) {
		if (faccessat(mfd, scripts[i], F_OK, 0) == 0)
			pkg_addscript_fileat(mfd, pkg, scripts[i]);
	}

	if (plist != NULL &&
	    ports_parse_plist(pkg, plist, rootdir) != EPKG_OK) {
		ret = EPKG_FATAL;
		goto cleanup;
	}

	if (pkg->www == NULL) {
		if (pkg->desc == NULL) {
			pkg_emit_error("No www or desc defined in manifest");
			ret = EPKG_FATAL;
			goto cleanup;
		}
		regcomp(&preg, "^WWW:[[:space:]]*(.*)$",
		    REG_EXTENDED|REG_ICASE|REG_NEWLINE);
		if (regexec(&preg, pkg->desc, 2, pmatch, 0) == 0) {
			size = pmatch[1].rm_eo - pmatch[1].rm_so;
			pkg->www = strndup(&pkg->desc[pmatch[1].rm_so], size);
		} else {
			pkg->www = strdup("UNKNOWN");
		}
		regfree(&preg);
	}

	/* Create the archive */
	pkg_archive = pkg_create_archive(outdir, pkg, format, 0);
	if (pkg_archive == NULL) {
		ret = EPKG_FATAL; /* XXX do better */
		goto cleanup;
	}

	/* XXX: autoplist support doesn't work right with meta-ports */
	if (0 && pkg_files(pkg, &file) != EPKG_OK &&
	    pkg_dirs(pkg, &dir) != EPKG_OK) {
		/* Now traverse the file directories, adding to the archive */
		packing_append_tree(pkg_archive, md_dir, NULL);
		packing_append_tree(pkg_archive, rootdir, "/");
	} else {
		pkg_create_from_dir(pkg, rootdir, pkg_archive);
	}

	ret = EPKG_OK;

cleanup:
	if (mfd != -1)
		close(mfd);
	free(pkg);
	free(manifest);
	pkg_manifest_keys_free(keys);
	if (ret == EPKG_OK)
		ret = packing_finish(pkg_archive);
	return (ret);
}
int env_set (HASHTBL *task_tbl, oph_operator_struct *handle)
{
  if (!handle){
  	pmesg(LOG_ERROR, __FILE__, __LINE__, "Null Handle\n");
 	logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_NULL_OPERATOR_HANDLE);
	  return OPH_ANALYTICS_OPERATOR_NULL_OPERATOR_HANDLE;
  }

  if (!task_tbl){
	  pmesg(LOG_ERROR, __FILE__, __LINE__, "Null operator string\n");
 	  logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_NULL_TASK_TABLE);
      return OPH_ANALYTICS_OPERATOR_BAD_PARAMETER;
  }

  if (handle->operator_handle){
	pmesg(LOG_ERROR, __FILE__, __LINE__, "Operator handle already initialized\n");
 	logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_HANDLE_ALREADY_INITIALIZED);
    return OPH_ANALYTICS_OPERATOR_NOT_NULL_OPERATOR_HANDLE;
  }

  if (!(handle->operator_handle = (OPH_METADATA_operator_handle *) calloc (1, sizeof (OPH_METADATA_operator_handle)))){
	pmesg(LOG_ERROR, __FILE__, __LINE__, "Error allocating memory\n");
	logging(LOG_ERROR,__FILE__,__LINE__, OPH_GENERIC_CONTAINER_ID,OPH_LOG_OPH_METADATA_MEMORY_ERROR_HANDLE);
    return OPH_ANALYTICS_OPERATOR_MEMORY_ERR;
  }

  //1 - Set up struct to empty values
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->id_datacube_input = 0;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->id_container_input = 0;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_id = 0;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_id_str = NULL;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_keys = NULL;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_keys_num = 0;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->variable = NULL;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_type = NULL;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_type_filter = NULL;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_value = NULL;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_value_filter = NULL;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->mode = -1;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->force = 0;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->user = NULL;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->objkeys = NULL;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->objkeys_num = -1;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->sessionid = NULL;
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->userrole = OPH_ROLE_NONE;

  ophidiadb *oDB = &((OPH_METADATA_operator_handle*)handle->operator_handle)->oDB;

  //Only master process has to continue
  if (handle->proc_rank != 0)
	return OPH_ANALYTICS_OPERATOR_SUCCESS;

  oph_odb_init_ophidiadb(oDB);

  if(oph_odb_read_ophidiadb_config_file(oDB)){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Unable to read OphidiaDB configuration\n");
    logging(LOG_ERROR,__FILE__,__LINE__, OPH_GENERIC_CONTAINER_ID,OPH_LOG_OPH_METADATA_OPHIDIADB_CONFIGURATION_FILE_NO_CONTAINER);
    return OPH_ANALYTICS_OPERATOR_UTILITY_ERROR;
  }

  if(oph_odb_connect_to_ophidiadb(oDB)){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Unable to connect to OphidiaDB. Check access parameters.\n");
    logging(LOG_ERROR,__FILE__,__LINE__, OPH_GENERIC_CONTAINER_ID,OPH_LOG_OPH_METADATA_OPHIDIADB_CONNECTION_ERROR_NO_CONTAINER);
    return OPH_ANALYTICS_OPERATOR_MYSQL_ERROR;
  }

  //3 - Fill struct with the correct data

  char *value;

  // retrieve objkeys
  value = hashtbl_get(task_tbl, OPH_IN_PARAM_OBJKEY_FILTER);
  if(!value){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_IN_PARAM_OBJKEY_FILTER);
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_FRAMEWORK_MISSING_INPUT_PARAMETER, OPH_IN_PARAM_OBJKEY_FILTER );
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  if(oph_tp_parse_multiple_value_param(value, &((OPH_METADATA_operator_handle*)handle->operator_handle)->objkeys, &((OPH_METADATA_operator_handle*)handle->operator_handle)->objkeys_num)){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Operator string not valid\n");
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, "Operator string not valid\n");
    oph_tp_free_multiple_value_param_list(((OPH_METADATA_operator_handle*)handle->operator_handle)->objkeys, ((OPH_METADATA_operator_handle*)handle->operator_handle)->objkeys_num);
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }

  // retrieve sessionid
  value = hashtbl_get(task_tbl, OPH_ARG_SESSIONID);
  if(!value){
	pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_ARG_SESSIONID);
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_FRAMEWORK_MISSING_INPUT_PARAMETER, OPH_ARG_SESSIONID);
	return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  if(!(((OPH_METADATA_operator_handle*)handle->operator_handle)->sessionid = (char *) strndup (value, OPH_TP_TASKLEN))){
	pmesg(LOG_ERROR, __FILE__, __LINE__, "Error allocating memory\n");
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_GENERIC_MEMORY_ERROR_INPUT, "sessionid" );
	return OPH_ANALYTICS_OPERATOR_MEMORY_ERR;
  }

  value = hashtbl_get(task_tbl, OPH_IN_PARAM_MODE);
  if(!value){
	pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_IN_PARAM_MODE);
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MISSING_INPUT_PARAMETER, OPH_IN_PARAM_MODE );
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  if (!strcasecmp(value,OPH_METADATA_MODE_INSERT)) {
      ((OPH_METADATA_operator_handle*)handle->operator_handle)->mode = OPH_METADATA_MODE_INSERT_VALUE;
  } else if (!strcasecmp(value,OPH_METADATA_MODE_READ)) {
      ((OPH_METADATA_operator_handle*)handle->operator_handle)->mode = OPH_METADATA_MODE_READ_VALUE;
  } else if (!strcasecmp(value,OPH_METADATA_MODE_UPDATE)) {
      ((OPH_METADATA_operator_handle*)handle->operator_handle)->mode = OPH_METADATA_MODE_UPDATE_VALUE;
  } else if (!strcasecmp(value,OPH_METADATA_MODE_DELETE)) {
      ((OPH_METADATA_operator_handle*)handle->operator_handle)->mode = OPH_METADATA_MODE_DELETE_VALUE;
  } else {
      pmesg(LOG_ERROR, __FILE__, __LINE__, "Invalid input parameter %s\n", value);
      logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_INVALID_INPUT_PARAMETER, value );
      return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }

  //Check if user can access container and retrieve container id
  value = hashtbl_get(task_tbl, OPH_ARG_USERNAME);
  if(!value){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_ARG_USERNAME);
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MISSING_INPUT_PARAMETER, OPH_ARG_USERNAME );
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  if(!(((OPH_METADATA_operator_handle*)handle->operator_handle)->user = (char *) strdup(value))){
      pmesg(LOG_ERROR, __FILE__, __LINE__, "Error allocating memory\n");
      logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MEMORY_ERROR_INPUT, OPH_ARG_USERNAME );
      return OPH_ANALYTICS_OPERATOR_MEMORY_ERR;
  }

  value = hashtbl_get(task_tbl, OPH_IN_PARAM_DATACUBE_INPUT);
  if(!value){
	pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_IN_PARAM_DATACUBE_INPUT);
	logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MISSING_INPUT_PARAMETER, OPH_IN_PARAM_DATACUBE_INPUT );
	return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
	  //Check if datacube exists (by ID container and datacube)
	  int exists = 0;
	  int status = 0;
	  int folder_id = 0;
	  int permission = 0;
	  char *uri = NULL;
	  if(oph_pid_parse_pid(value, &(((OPH_METADATA_operator_handle*)handle->operator_handle)->id_container_input), &(((OPH_METADATA_operator_handle*)handle->operator_handle)->id_datacube_input), &uri)){
		pmesg(LOG_ERROR, __FILE__, __LINE__, "Unable to parse the PID string\n");
		logging(LOG_ERROR, __FILE__, __LINE__, ((OPH_METADATA_operator_handle*)handle->operator_handle)->id_container_input, OPH_LOG_OPH_METADATA_PID_ERROR, value );
		if(uri) free(uri);
		return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
	  }
	  else if((oph_odb_cube_check_if_datacube_not_present_by_pid(oDB, uri, ((OPH_METADATA_operator_handle*)handle->operator_handle)->id_container_input, ((OPH_METADATA_operator_handle*)handle->operator_handle)->id_datacube_input, &exists)) || !exists){
		pmesg(LOG_ERROR, __FILE__, __LINE__, "Unknown input container - datacube combination\n");
		logging(LOG_ERROR, __FILE__, __LINE__, ((OPH_METADATA_operator_handle*)handle->operator_handle)->id_container_input, OPH_LOG_OPH_METADATA_NO_INPUT_DATACUBE, value );
		if(uri) free(uri);
		return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
	  }
	  else if((oph_odb_cube_check_datacube_availability(oDB, ((OPH_METADATA_operator_handle*)handle->operator_handle)->id_datacube_input, 0, &status)) || !status){
		pmesg(LOG_ERROR, __FILE__, __LINE__, "I/O nodes storing datacube aren't available\n");
		logging(LOG_ERROR, __FILE__, __LINE__, ((OPH_METADATA_operator_handle*)handle->operator_handle)->id_container_input, OPH_LOG_OPH_METADATA_DATACUBE_AVAILABILITY_ERROR, value );
		if(uri) free(uri);
		return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
	  }
	  else if((oph_odb_fs_retrive_container_folder_id(oDB, ((OPH_METADATA_operator_handle*)handle->operator_handle)->id_container_input, 1, &folder_id))){
		pmesg(LOG_ERROR, __FILE__, __LINE__, "Unable to retrieve folder of specified datacube or container is hidden\n");
		logging(LOG_ERROR, __FILE__, __LINE__, ((OPH_METADATA_operator_handle*)handle->operator_handle)->id_container_input, OPH_LOG_OPH_METADATA_DATACUBE_FOLDER_ERROR, value );
		if(uri) free(uri);
		return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
	  }
	  else if((oph_odb_fs_check_folder_session(folder_id, ((OPH_METADATA_operator_handle*)handle->operator_handle)->sessionid, oDB, &permission)) || !permission){
		//Check if user can work on datacube
		pmesg(LOG_ERROR, __FILE__, __LINE__, "User %s is not allowed to work on this datacube\n", ((OPH_METADATA_operator_handle*)handle->operator_handle)->user);
		logging(LOG_ERROR, __FILE__, __LINE__, ((OPH_METADATA_operator_handle*)handle->operator_handle)->id_container_input, OPH_LOG_OPH_METADATA_DATACUBE_PERMISSION_ERROR, ((OPH_METADATA_operator_handle*)handle->operator_handle)->user );
		if(uri) free(uri);
		return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
	  }
	if(uri) free(uri);
	uri = NULL;

  value = hashtbl_get(task_tbl, OPH_IN_PARAM_METADATA_KEY);
  if(!value){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_IN_PARAM_METADATA_KEY);
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MISSING_INPUT_PARAMETER, OPH_IN_PARAM_METADATA_KEY );
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  if(oph_tp_parse_multiple_value_param(value, &((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_keys, &((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_keys_num)){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Operator string not valid\n");
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_INVALID_INPUT_STRING);
    oph_tp_free_multiple_value_param_list(((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_keys, ((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_keys_num);
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  //If first value supplied as key is ALL, then free the structure and set values to NULL and 0
  if(strncmp(((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_keys[0], OPH_COMMON_ALL_FILTER, strlen(OPH_COMMON_ALL_FILTER)) == 0){
	oph_tp_free_multiple_value_param_list(((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_keys, ((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_keys_num);
	((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_keys = NULL;
	((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_keys_num = 0;
  }

  value = hashtbl_get(task_tbl, OPH_IN_PARAM_METADATA_ID);
  if(!value){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_IN_PARAM_METADATA_ID);
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MISSING_INPUT_PARAMETER, OPH_IN_PARAM_METADATA_ID );
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  if(!(((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_id_str = (char *) strdup(value))){
      pmesg(LOG_ERROR, __FILE__, __LINE__, "Error allocating memory\n");
      logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MEMORY_ERROR_INPUT, OPH_IN_PARAM_METADATA_ID );
      return OPH_ANALYTICS_OPERATOR_MEMORY_ERR;
  }
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_id = (int)strtol(value,NULL,10);

  value = hashtbl_get(task_tbl, OPH_IN_PARAM_METADATA_VARIABLE);
  if(!value){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_IN_PARAM_METADATA_VARIABLE);
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MISSING_INPUT_PARAMETER, OPH_IN_PARAM_METADATA_VARIABLE );
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  if (strcasecmp(value,OPH_COMMON_GLOBAL_VALUE)) {
	  if(!(((OPH_METADATA_operator_handle*)handle->operator_handle)->variable = (char *) strdup(value))){
	      pmesg(LOG_ERROR, __FILE__, __LINE__, "Error allocating memory\n");
	      logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MEMORY_ERROR_INPUT, OPH_IN_PARAM_METADATA_VARIABLE );
	      return OPH_ANALYTICS_OPERATOR_MEMORY_ERR;
	  }
  }

  value = hashtbl_get(task_tbl, OPH_IN_PARAM_METADATA_TYPE);
  if(!value){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_IN_PARAM_METADATA_TYPE);
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MISSING_INPUT_PARAMETER, OPH_IN_PARAM_METADATA_TYPE );
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  if(!(((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_type = (char *) strdup(value))){
      pmesg(LOG_ERROR, __FILE__, __LINE__, "Error allocating memory\n");
      logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MEMORY_ERROR_INPUT, OPH_IN_PARAM_METADATA_TYPE );
      return OPH_ANALYTICS_OPERATOR_MEMORY_ERR;
  }

  value = hashtbl_get(task_tbl, OPH_IN_PARAM_METADATA_VALUE);
  if(!value){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_IN_PARAM_METADATA_VALUE);
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MISSING_INPUT_PARAMETER, OPH_IN_PARAM_METADATA_VALUE );
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  if(strncmp(value, OPH_COMMON_DEFAULT_EMPTY_VALUE, OPH_TP_TASKLEN) != 0){
	  if(!(((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_value = (char *) strdup(value))){
		  pmesg(LOG_ERROR, __FILE__, __LINE__, "Error allocating memory\n");
		  logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MEMORY_ERROR_INPUT, OPH_IN_PARAM_METADATA_VALUE );
		  return OPH_ANALYTICS_OPERATOR_MEMORY_ERR;
	  }
  }

  value = hashtbl_get(task_tbl, OPH_IN_PARAM_METADATA_TYPE_FILTER);
  if(!value){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_IN_PARAM_METADATA_TYPE_FILTER);
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MISSING_INPUT_PARAMETER, OPH_IN_PARAM_METADATA_TYPE_FILTER );
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  if(strcasecmp(value,OPH_COMMON_ALL_FILTER) != 0){
	  if(!(((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_type_filter = (char *) strdup(value))){
		pmesg(LOG_ERROR, __FILE__, __LINE__, "Error allocating memory\n");
		logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MEMORY_ERROR_INPUT, OPH_IN_PARAM_METADATA_TYPE_FILTER );
		return OPH_ANALYTICS_OPERATOR_MEMORY_ERR;
	  }
  } else {
      if(!(((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_type_filter = (char *) strdup("%"))){
        pmesg(LOG_ERROR, __FILE__, __LINE__, "Error allocating memory\n");
        logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MEMORY_ERROR_INPUT, OPH_IN_PARAM_METADATA_TYPE_FILTER );
        return OPH_ANALYTICS_OPERATOR_MEMORY_ERR;
      }
  }

  value = hashtbl_get(task_tbl, OPH_IN_PARAM_METADATA_VALUE_FILTER);
  if(!value){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_IN_PARAM_METADATA_VALUE_FILTER);
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MISSING_INPUT_PARAMETER, OPH_IN_PARAM_METADATA_VALUE_FILTER );
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  if(strcasecmp(value,OPH_COMMON_ALL_FILTER) != 0){
      if(!(((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_value_filter = (char *) strdup(value))){
        pmesg(LOG_ERROR, __FILE__, __LINE__, "Error allocating memory\n");
        logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MEMORY_ERROR_INPUT, OPH_IN_PARAM_METADATA_VALUE_FILTER );
        return OPH_ANALYTICS_OPERATOR_MEMORY_ERR;
      }
  } else {
      if(!(((OPH_METADATA_operator_handle*)handle->operator_handle)->metadata_value_filter = (char *) strdup("%"))){
        pmesg(LOG_ERROR, __FILE__, __LINE__, "Error allocating memory\n");
        logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MEMORY_ERROR_INPUT, OPH_IN_PARAM_METADATA_VALUE_FILTER );
        return OPH_ANALYTICS_OPERATOR_MEMORY_ERR;
      }
  }

  value = hashtbl_get(task_tbl, OPH_IN_PARAM_FORCE);
  if(!value){
	pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_IN_PARAM_FORCE);
	logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MISSING_INPUT_PARAMETER, OPH_IN_PARAM_FORCE );
	return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  if(strcmp(value,OPH_COMMON_YES_VALUE) == 0){
	  ((OPH_METADATA_operator_handle*)handle->operator_handle)->force = 1;
  }

  value = hashtbl_get(task_tbl, OPH_ARG_USERROLE);
  if(!value){
    pmesg(LOG_ERROR, __FILE__, __LINE__, "Missing input parameter %s\n", OPH_ARG_USERROLE);
    logging(LOG_ERROR, __FILE__, __LINE__, OPH_GENERIC_CONTAINER_ID, OPH_LOG_OPH_METADATA_MISSING_INPUT_PARAMETER, OPH_ARG_USERROLE );
    return OPH_ANALYTICS_OPERATOR_INVALID_PARAM;
  }
  ((OPH_METADATA_operator_handle*)handle->operator_handle)->userrole = (int)strtol(value, NULL, 10);

  return OPH_ANALYTICS_OPERATOR_SUCCESS;
}
コード例 #9
0
ファイル: server.c プロジェクト: komali2/C-Programs2
int main(int argc, char* argv[])
{
    // a global variable defined in errno.h that's "set by system 
    // calls and some library functions [to a nonzero value]
    // in the event of an error to indicate what went wrong"
    errno = 0;

    // default to a random port
    int port = 0;

    // usage
    const char* usage = "Usage: server [-p port] /path/to/root";

    // parse command-line arguments
    int opt;
    while ((opt = getopt(argc, argv, "hp:")) != -1)
    {
        switch (opt)
        {
            // -h
            case 'h':
                printf("%s\n", usage);
                return 0;

            // -p port
            case 'p':
                port = atoi(optarg);
                break;
        }
    }

    // ensure port is a non-negative short and path to server's root is specified
    if (port < 0 || port > SHRT_MAX || argv[optind] == NULL || strlen(argv[optind]) == 0)
    {
        // announce usage
        printf("%s\n", usage);

        // return 2 just like bash's builtins
        return 2;
    }

    // start server
    start(port, argv[optind]);

    // listen for SIGINT (aka control-c)
    signal(SIGINT, handler);

    // accept connections one at a time
    while (true)
    {
        // reset server's state
        reset();

        // wait until client is connected
        if (connected())
        {
            // parse client's HTTP request
            ssize_t octets = parse();
            if (octets == -1)
            {
                continue;
            }

            // extract request's request-line
            // http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
            const char* haystack = request;
            char* needle = strstr(haystack, "\r\n");
            if (needle == NULL)
            {
                error(400);
                continue;
            }
            else if (needle - haystack + 2 > LimitRequestLine)
            {
                error(414);
                continue;
            }   
            char line[needle - haystack + 2 + 1];
            strncpy(line, haystack, needle - haystack + 2);
            line[needle - haystack + 2] = '\0';

            // log request-line
            printf("%s", line);
			
			//validate request line
			//break apart the request line
			char *method, *target, *version;
			const char *firstbuffer = line;
			const char *secondbuffer;
			
			while (*firstbuffer != ' ')
			{
				firstbuffer++;
			}
			method = strndup(line, firstbuffer - line);
			secondbuffer = ++firstbuffer;
			
			while(*firstbuffer != ' ')
			{
				firstbuffer++;
			}
			target = strndup(secondbuffer, firstbuffer-secondbuffer);
			secondbuffer = ++firstbuffer;
			while(*firstbuffer != '\r')
			{
				firstbuffer++;
			}
			version = strndup(secondbuffer, firstbuffer - secondbuffer);

			//request line is now broken apart
			
			//ensure method is GET
			if (strstr("GET", method) == NULL)
			{
				error(405);
			}
			
			//ensure request-target begins with /
			if (target[0] != '/')
			{
				error(501);
			}
			
			//search for " in target
			if(strchr(target, '\"') != NULL)
			{
				error(400);
			}
			
			//make sure the version is HTTP/1.1
			if(strcmp(version, "HTTP/1.1") != 0)
			{
				error(505);
			}
			
			//ensure there's a . in absolute-path 
			if(strchr(target, '.') == NULL)
			{
				error(501);
			}
			

            // extract query from request-target
			char* query = "\0";
            char* thirdbuffer = target;
			if (strstr(target, "p?") != NULL)
			{
				query = strstr(target, "p?");
				query++;
				thirdbuffer = strndup(target, query-target);
				target = thirdbuffer;
				query++;
			}
			
			
            // concatenate root and absolute-path
            char path[strlen(root) + strlen(target) + 2];
			snprintf(path, sizeof(path), "%s%s", root, target);
			

            // ensure path exists
			
			if(access(path, F_OK) != 0)
			{
				error(404);
			}
			
            
            // ensure path is readable
			
			if(access(path, R_OK) != 0)
			{
				error(403);
			}
 
            // extract path's extension
            char* extension = "\0";
			extension = strrchr(target, '.');
			extension++;		

            // dynamic content
            if (strcasecmp("php", extension) == 0)
            {
                // open pipe to PHP interpreter
                char* format = "QUERY_STRING=\"%s\" REDIRECT_STATUS=200 SCRIPT_FILENAME=\"%s\" php-cgi";
                char command[strlen(format) + (strlen(path) - 2) + (strlen(query) - 2) + 1];
                sprintf(command, format, query, path);
                file = popen(command, "r");
                if (file == NULL)
                {
                    error(500);
                    continue;
                }

                // load file
                ssize_t size = load();
                if (size == -1)
                {
                    error(500);
                    continue;
                }

                // subtract php-cgi's headers from body's size to get content's length
                haystack = body;
                needle = memmem(haystack, size, "\r\n\r\n", 4);
                if (needle == NULL)
                {
                    error(500);
                    continue;
                }
                size_t length = size - (needle - haystack + 4);

                // respond to client
                if (dprintf(cfd, "HTTP/1.1 200 OK\r\n") < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Connection: close\r\n") < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Content-Length: %i\r\n", length) < 0)
                {
                    continue;
                }
                if (write(cfd, body, size) == -1)
                {
                    continue;
                }
            }

            // static content
            else
            {
                // look up file's MIME type
                const char* type = lookup(extension);
                if (type == NULL)
                {
                    error(501);
                    continue;
                }

                // open file
                file = fopen(path, "r");
                if (file == NULL)
                {
                    error(500);
                    continue;
                }

                // load file
                ssize_t length = load();
                if (length == -1)
                {
                    error(500);
                    continue;
                }
								
                // respond to client
				if (dprintf(cfd, "HTTP/1.1 200 OK\r\n") < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Connection: close\r\n") < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "Content-Length: %i\r\n", length) < 0)
                {
                    continue;
                }
				if (dprintf(cfd, "Content-Type: %s\r\n", type) < 0)
                {
                    continue;
                }
                if (dprintf(cfd, "\r\n") < 0)
				{
					continue;
				}
				if (write(cfd, body, length) == -1)
                {
                    continue;
                }
            }
            
            // announce OK
            printf("\033[32m");
            printf("HTTP/1.1 200 OK");
            printf("\033[39m\n");
        }
    }
}
コード例 #10
0
ファイル: string.c プロジェクト: eworm-de/ipxe
/**
 * Duplicate string
 *
 * @v src		Source string
 * @ret dup		Duplicated string, or NULL if allocation failed
 */
char * strdup ( const char *src ) {

	return strndup ( src, ~( ( size_t ) 0 ) );
}
コード例 #11
0
main (int argc, char **argv) {
    bfd *ibfd, *obfd;
    asection *p;
    static asymbol **osympp, **delsympp;
    long symsize, symcount, delsymcount;
    int i;
    int c;
    int idx;
    struct add_reloc_struct *new_reloc;
    struct change_reloc_struct *new_change;
    struct delete_reloc_struct *new_delete;
    struct modify_byte_struct *new_modify;
    struct globalize_sym_struct *new_globalize;

    while ((c = getopt (argc, argv, "a:d:c:m:G:")) != -1) {
	switch (c) {
	    case 'a':
		/* check to see if we have two args: name and loc */
		if ((index(optarg, ',') == NULL) ||
		    (index(optarg, ',') != rindex(optarg, ','))) {
		    fprintf(stderr, "usage: -a argument should be <symbolname>,<location>, not \"%s\"\n", optarg);
		    exit(1);
		}
		/* record the add reloc command in the global array */
		new_reloc = (add_reloc_struct *)malloc(sizeof(add_reloc_struct));
		new_reloc->symbol_name = strndup(optarg, (index(optarg, ',') - optarg));
		new_reloc->loc = strtol(index(optarg, ',') + 1, NULL, 0);
		if (errno == EINVAL) {
		    fprintf(stderr, "the value %s is not a valid location for the add command\n", index(optarg, ',') + 1);
		    exit(1);
		}
		new_reloc->next = additional_relocs;
		additional_relocs = new_reloc;
		break;

	    case 'c':
		/* check to see if we have two args */
		if ((index(optarg, ',') == NULL) ||
		    (index(optarg, ',') != rindex(optarg, ','))) {
		    fprintf(stderr, "usage: -c argument should be <symbolname>,<symbolname>, not \"%s\"\n", optarg);
		    exit(1);
		}
		new_change = (change_reloc_struct *)malloc(sizeof(change_reloc_struct));
		new_change->old_symbol_name = strndup(optarg, strlen(optarg) - strlen(index(optarg, ',')));
		new_change->new_symbol_name = strdup(index(optarg, ',') + 1);
		new_change->next = change_relocs;
		change_relocs = new_change;
		break;

	    case 'd':
		new_delete = (delete_reloc_struct *)malloc(sizeof(delete_reloc_struct));
		new_delete->symbol_name = strdup(optarg);
		new_delete->next = delete_relocs;
		delete_relocs = new_delete;
		break;

	    case 'm':
		if ((index(optarg, '=') == NULL) ||
		    (index(optarg, '=') != rindex(optarg, '='))) {
		    fprintf(stderr, "usage: -m argument should be <location>=<value>, not \"%s\"\n", optarg);
		    exit(1);
		}
		new_modify = (modify_byte_struct *)malloc(sizeof(modify_byte_struct));
		new_modify->location = strtol(optarg, NULL, 0);
		new_modify->value = strtol(index(optarg, '=') + 1, NULL, 0);
		if (new_modify->value > 0xff) {
		    fprintf(stderr, "requested modify value %lx for location %lx exceeds 0xff\n",
			    new_modify->value, new_modify->location);
		    exit(1);
		}
		new_modify->next = modify_bytes;
		modify_bytes = new_modify;
		break;

	    case 'G':
		new_globalize = (globalize_sym_struct *)malloc(sizeof(globalize_sym_struct));
		new_globalize->symbol_name = strdup(optarg);
		new_globalize->next = globalize_syms;
		globalize_syms = new_globalize;
		break;

	    default:
		fprintf(stderr, "unrecognized argument character |%c|\n", c);
	}
    }

    if ((argc - optind) != 2) {
	fprintf(stderr, "usage: fixup_relocs [-a newsymbol,location] [-c oldsymbol,newsymbol] [-d symbol] infile.o outfile.o\n");
	exit(1);
    }

    ibfd = bfd_openr(argv[optind], NULL);
    if (ibfd == NULL) {
	bfd_perror("while opening input object file");
	exit(1);
    }

    /* if I don't do "check_format", there's no data in the bfd object.  wtf? */
    if (!bfd_check_format(ibfd, bfd_object)) {
	fprintf(stderr, "input file %s seems to NOT be an object file! exiting.\n", argv[optind]);
	exit(1);
    }

    obfd = bfd_openw(argv[optind+1], bfd_get_target(ibfd));
    if (obfd == NULL) {
	bfd_perror("while opening output object file");
	exit(1);
    }

    if (!bfd_set_format(obfd, bfd_get_format(ibfd))) {
	bfd_perror("while setting output object file format");
    }

    /* copy a bunch of necessary global stuff */
    bfd_set_start_address(obfd, bfd_get_start_address(ibfd));
    bfd_set_file_flags(obfd, bfd_get_file_flags(ibfd));
    bfd_set_arch_mach(obfd, bfd_get_arch(ibfd), bfd_get_mach(ibfd));
    /* BOZO objcopy sets format again at this point.  why? */

    bfd_map_over_sections (ibfd, setup_section, obfd);

    setup_bfd_headers (ibfd, obfd);

    /* Symbol filtering must happen after the output sections
       have been created, but before their contents are set.  */
    symsize = bfd_get_symtab_upper_bound (ibfd);
    if (symsize < 0) {
	fprintf(stderr, "problem processing %s\n", bfd_get_filename (ibfd));
	return FALSE;
    }

    /* count the added relocations so we can put extra space in the output symbol table for them */
    int reloc_add_cnt, reloc_delete_cnt;
    reloc_add_cnt = 0;
    reloc_delete_cnt = 0;
    for (new_reloc = additional_relocs; new_reloc != NULL; new_reloc = new_reloc->next) {
	reloc_add_cnt++;
    }
    /* the "change" symbols might also not be in the symbol table yet */
    for (new_change = change_relocs; new_change != NULL; new_change = new_change->next) {
	reloc_add_cnt++;
	/* the old symbol may be deleted, also */
	reloc_delete_cnt++;
    }
    for (new_delete = delete_relocs; new_delete != NULL; new_delete = new_delete->next) {
	reloc_delete_cnt++;
    }

    /* filter symbol table in two steps: */
    /* 1) move symbols bound for deletion to the end of the output symbol table array */
    /* 2) truncate the table at the first of those */
    /* this makes it possible to do the reloc processing with the symbol table intact, */
    /* and remove the deleted symbols afterwards, without corrupting the reloc data structures */
    isympp = malloc (symsize);
    osympp = malloc (symsize + reloc_add_cnt * sizeof(asymbol *));
    delsympp = malloc (reloc_delete_cnt * sizeof(asymbol *));
    symcount = bfd_canonicalize_symtab (ibfd, isympp);

    if (symcount < 0) {
	fprintf(stderr, "problem processing %s\n", bfd_get_filename (ibfd));
	return FALSE;
    }

    /* remove any undefined symbols whose relocation entries were deleted or changed */
    int osym_idx, delsym_idx;
    osym_idx = delsym_idx = 0;
    delsymcount = 0;
    for (i = 0; i < symcount; i++) {
	if ((is_delete_reloc(bfd_asymbol_name(isympp[i]), delete_relocs) ||
	     (find_change_reloc(bfd_asymbol_name(isympp[i]), change_relocs) != NULL)) &&
	    (isympp[i]->section != NULL) &&
	    (strcmp(isympp[i]->section->name, BFD_UND_SECTION_NAME) == 0)) {
	    delsympp[delsym_idx++] = isympp[i];
	}
	else {
	    if (is_globalize_sym(bfd_asymbol_name(isympp[i]), globalize_syms)) {
		isympp[i]->flags = BSF_GLOBAL;
	    }
	    osympp[osym_idx++] = isympp[i];
	}
    }
    symcount = osym_idx;
    delsymcount = delsym_idx;
    osympp[symcount] = NULL;

    /* add the symbols for additional relocs to the table */
    int added_symbol_cnt = 0;
    for (new_reloc = additional_relocs; new_reloc != NULL; new_reloc = new_reloc->next) {
	if (find_symbol(osympp, new_reloc->symbol_name) < 0) {
	    /* not yet present, so add it */
	    asymbol *new_sym;
	    new_sym = bfd_make_empty_symbol(obfd);
	    new_sym->name = strdup(new_reloc->symbol_name);
	    new_sym->section = bfd_get_section_by_name (obfd, ".text");
	    new_sym->value = new_reloc->loc;
	    new_sym->flags = BSF_GLOBAL;
	    osympp[symcount + added_symbol_cnt++] = new_sym;
	    osympp[symcount + added_symbol_cnt] = NULL;
	}
    }

    /* do the same for changed relocs */
    for (new_change = change_relocs; new_change != NULL; new_change = new_change->next) {
	if (find_symbol(osympp, new_change->new_symbol_name) < 0) {
	    /* not yet present, so add it */
	    /* since this is a name change, we will reuse the existing address (value field of reloc) */
	    int old_symbol_idx;
	    if ((old_symbol_idx = find_symbol(isympp, new_change->old_symbol_name)) < 0) {
		fprintf(stderr, "change command old symbol name %s not found in symbol table! Exiting.\n", new_change->old_symbol_name);
		exit(1);
	    }
	    asymbol *new_sym;
	    new_sym = bfd_make_empty_symbol(obfd);
	    new_sym->name = strdup(new_change->new_symbol_name);
	    new_sym->section = bfd_und_section_ptr;
	    new_sym->value = isympp[old_symbol_idx]->value;
	    new_sym->flags = BSF_GLOBAL;
	    fprintf(stderr, "adding new symbol %s for change reloc command\n", new_sym->name);
	    osympp[symcount + added_symbol_cnt++] = new_sym;
	    osympp[symcount + added_symbol_cnt] = NULL;
	}
    }

    /* append the soon-to-be deleted symbols to the end of the output symbol table */
    for (i = 0; i < delsymcount; i++) {
	osympp[symcount + added_symbol_cnt + i] = delsympp[i];
    }
    osympp[symcount + added_symbol_cnt + delsymcount] = NULL;

    bfd_set_symtab (obfd, osympp, symcount + added_symbol_cnt + delsymcount);

    /* This has to happen after the symbol table has been set.  */
    bfd_map_over_sections (ibfd, copy_section_relocs_edit, obfd);

    /* now truncate the symbol table to eliminate the deleted symbols */
    osympp[symcount + added_symbol_cnt] = NULL;

    bfd_set_symtab (obfd, osympp, symcount + added_symbol_cnt);
    
    /* now that we've set the relocs and cleaned the symtab, can call this */
    bfd_map_over_sections (ibfd, copy_section_data, obfd);

    bfd_close(obfd);
    bfd_close(ibfd);

    return 0;

}
コード例 #12
0
ファイル: linux-core.c プロジェクト: 4T-Shirt/node
/* Also reads the CPU frequency on x86. The other architectures only have
 * a BogoMIPS field, which may not be very accurate.
 *
 * Note: Simply returns on error, uv_cpu_info() takes care of the cleanup.
 */
static int read_models(unsigned int numcpus, uv_cpu_info_t* ci) {
  static const char model_marker[] = "model name\t: ";
  static const char speed_marker[] = "cpu MHz\t\t: ";
  const char* inferred_model;
  unsigned int model_idx;
  unsigned int speed_idx;
  char buf[1024];
  char* model;
  FILE* fp;

  /* Most are unused on non-ARM, non-MIPS and non-x86 architectures. */
  (void) &model_marker;
  (void) &speed_marker;
  (void) &speed_idx;
  (void) &model;
  (void) &buf;
  (void) &fp;

  model_idx = 0;
  speed_idx = 0;

#if defined(__arm__) || \
    defined(__i386__) || \
    defined(__mips__) || \
    defined(__x86_64__)
  fp = fopen("/proc/cpuinfo", "r");
  if (fp == NULL)
    return -errno;

  while (fgets(buf, sizeof(buf), fp)) {
    if (model_idx < numcpus) {
      if (strncmp(buf, model_marker, sizeof(model_marker) - 1) == 0) {
        model = buf + sizeof(model_marker) - 1;
        model = strndup(model, strlen(model) - 1);  /* Strip newline. */
        if (model == NULL) {
          fclose(fp);
          return -ENOMEM;
        }
        ci[model_idx++].model = model;
        continue;
      }
    }
#if defined(__arm__) || defined(__mips__)
    if (model_idx < numcpus) {
#if defined(__arm__)
      /* Fallback for pre-3.8 kernels. */
      static const char model_marker[] = "Processor\t: ";
#else	/* defined(__mips__) */
      static const char model_marker[] = "cpu model\t\t: ";
#endif
      if (strncmp(buf, model_marker, sizeof(model_marker) - 1) == 0) {
        model = buf + sizeof(model_marker) - 1;
        model = strndup(model, strlen(model) - 1);  /* Strip newline. */
        if (model == NULL) {
          fclose(fp);
          return -ENOMEM;
        }
        ci[model_idx++].model = model;
        continue;
      }
    }
#else  /* !__arm__ && !__mips__ */
    if (speed_idx < numcpus) {
      if (strncmp(buf, speed_marker, sizeof(speed_marker) - 1) == 0) {
        ci[speed_idx++].speed = atoi(buf + sizeof(speed_marker) - 1);
        continue;
      }
    }
#endif  /* __arm__ || __mips__ */
  }

  fclose(fp);
#endif  /* __arm__ || __i386__ || __mips__ || __x86_64__ */

  /* Now we want to make sure that all the models contain *something* because
   * it's not safe to leave them as null. Copy the last entry unless there
   * isn't one, in that case we simply put "unknown" into everything.
   */
  inferred_model = "unknown";
  if (model_idx > 0)
    inferred_model = ci[model_idx - 1].model;

  while (model_idx < numcpus) {
    model = strndup(inferred_model, strlen(inferred_model));
    if (model == NULL)
      return -ENOMEM;
    ci[model_idx++].model = model;
  }

  return 0;
}
コード例 #13
0
/**
 * arguments_parse(argc, argv)
 *
 * Utility function to parse the passed in arguments using getopt; also responsible for sanity-checking
 * any passed-in values and ensuring that the program's configuration is sane before returning (i.e.
 * using default values).
 **/
int arguments_parse(int argc, char **argv)
{
	char *char_ptr;
	struct hostent *hostent_ptr;
	char *hostname_tmp;
	int i, j;

	struct sockaddr_in sin;
	uintmax_t uint_tmp;

	/* Initialize our configuration to the default settings. */
	udploggerclientlib_conf.beacon_interval = DEFAULT_BEACON_INTERVAL;
	memset(&udploggerclientlib_conf.log_host, 0, sizeof(udploggerclientlib_conf.log_host));

	if (! add_option("help", no_argument, 'h'))
	{
		return -1;
	}
	if (! add_option("host", required_argument, 'o'))
	{
		return -1;
	}
	if (! add_option("interval", required_argument, 'i'))
	{
		return -1;
	}
	if (! add_option("version", no_argument, 'v'))
	{
		return -1;
	}
	if (! add_option_hook())
	{
		return -1;
	}
	if (! add_option(NULL, 0, 0))
	{
		return -1;
	}

	while (1)
	{
		i = getopt_long(argc, argv, short_options, long_options, NULL);
		if (i == -1)
		{
			break;
		}
		switch (i)
		{
			case 'h':
				printf("Usage: %s [OPTIONS]\n", argv[0]);
				printf("\n");
				printf("General Library Options\n");
				printf("  -h, --help                        display this help and exit\n");
				printf("  -o, --host <host>[:<port>]        host and port to target with beacon transmissions (default broadcast)\n");
				printf("                                    (default udplogger port is %u)\n", UDPLOGGER_DEFAULT_PORT);
				printf("  -i, --interval <interval>         interval in seconds between beacon transmissions (default %lu)\n", DEFAULT_BEACON_INTERVAL);
				printf("  -v, --version                     display version and exit\n");
				printf("\n");
				printf("%s Specific Options\n", argv[0]);
				usage_hook();
				return 0;
			case 'i':
				uint_tmp = strtoumax(optarg, 0, 10);
				if (! uint_tmp || uint_tmp == UINT_MAX)
				{
					fprintf(stderr, "udploggerclientlib.c invalid beacon interval '%s'\n", optarg);
					return -1;
				}
				udploggerclientlib_conf.beacon_interval = uint_tmp;
				break;
			case 'o':
				char_ptr = strstr(optarg, ":");
				if (char_ptr == optarg)
				{
					fprintf(stderr, "udploggerclientlib.c invalid host specification '%s'\n", optarg);
					return -1;
				}
#ifdef __DEBUG__
				printf("udploggerclientlib.c debug: parsing host target '%s'\n", optarg);
#endif

				if (char_ptr)
				{
					hostname_tmp = strndup(optarg, (char_ptr - optarg));
				}
				else
				{
					hostname_tmp = strdup(optarg);
				}
				if (! hostname_tmp)
				{
					fprintf(stderr, "udploggerclientlib.c could not allocate memory to record host '%s'\n", optarg);
					return -1;
				}
#ifdef __DEBUG__
				printf("udploggerclientlib.c debug:   determined hostname '%s'\n", hostname_tmp);
#endif

				if (char_ptr && *char_ptr == ':')
				{
					char_ptr++;
					uint_tmp = 0;
					if (char_ptr)
					{
						uint_tmp = strtoumax(char_ptr, 0, 10);
					}
					if (! uint_tmp || uint_tmp == UINT_MAX)
					{
						fprintf(stderr, "udploggerclientlib.c invalid port in host specification '%s'\n", optarg);
						free(hostname_tmp);
						return -1;
					}
				}
				else
				{
					uint_tmp = UDPLOGGER_DEFAULT_PORT;
				}
#ifdef __DEBUG__
				printf("udploggerclientlib.c debug:   determined port '%lu'\n", uint_tmp);
#endif

				hostent_ptr = gethostbyname(hostname_tmp);
				if (! hostent_ptr)
				{
					fprintf(stderr, "udploggerclientlib.c could not find the IP address of the host '%s'\n", hostname_tmp);
					free(hostname_tmp);
					return -1;
				}
				free(hostname_tmp);

				for (j = 0; hostent_ptr->h_addr_list[j] != NULL; j++)
				{
#ifdef __DEBUG__
					printf("udploggerclientlib.c debug:     considering address '%s', family '%hu'\n", inet_ntoa(*(struct in_addr *)(hostent_ptr->h_addr_list[j])), hostent_ptr->h_addrtype);
#endif
					if (hostent_ptr->h_addrtype == AF_INET)
					{
						sin.sin_family = hostent_ptr->h_addrtype;
						sin.sin_addr.s_addr = ((struct in_addr *)(hostent_ptr->h_addr_list[j]))->s_addr;
						sin.sin_port = htons(uint_tmp);

						add_log_host(&sin);
					}
				}
				break;
			case 'v':
				printf("udploggerclientlib.c revision r%d\n", REVISION);
				return 0;
			case '?':
				break;
			default:
				j = getopt_hook(i);
				if (! j)
				{
					fprintf(stderr, "udploggerclientlib.c unhandled option '%c'\n", i);
					return -1;
				}
				else if (j < 0)
				{
					return j;
				}
				break;
		}
	}

	if (udploggerclientlib_conf.log_host.address.sin_family == 0)
	{
		/* No target hosts have been passed in.  Default is to add all broadcast addresses. */
		broadcast_scan();
	}

	if (udploggerclientlib_conf.log_host.address.sin_family == 0)
	{
		/* Final sanity check.  If we don't have any log hosts to target, then don't continue. */
		printf("udploggerclientlib.c no log targets\n");
		return -1;
	}

	return 1;
}
コード例 #14
0
ファイル: sexpr.c プロジェクト: foomango/libvirt
/**
 * _string2sexpr:
 * @buffer: a zero terminated buffer containing an S-Expression in UTF-8
 * @end: pointer to an index in the buffer for the already parsed bytes
 *
 * Internal routine implementing the parse of S-Expression
 * Note that failure in this function is catastrophic.  If it returns
 * NULL, you've leaked memory and you're currently OOM.  It will always
 * parse an SEXPR given a buffer
 *
 * Returns a pointer to the resulting parsed S-Expression, or NULL in case of
 *         hard error.
 */
static struct sexpr *
_string2sexpr(const char *buffer, size_t * end)
{
    const char *ptr = buffer + *end;
    struct sexpr *ret = sexpr_new();

    if (ret == NULL)
        return NULL;

    ptr = trim(ptr);

    if (ptr[0] == '(') {
        ret->kind = SEXPR_NIL;

        ptr = trim(ptr + 1);
        while (*ptr && *ptr != ')') {
            struct sexpr *tmp;
            size_t tmp_len = 0;

            tmp = _string2sexpr(ptr, &tmp_len);
            if (tmp == NULL)
                goto error;
            if (append(ret, tmp) < 0) {
                sexpr_free(tmp);
                goto error;
            }
            ptr = trim(ptr + tmp_len);
        }

        if (*ptr == ')') {
            ptr++;
        }
    } else {
        const char *start;

        if (*ptr == '\'') {
            ptr++;
            start = ptr;

            while (*ptr && *ptr != '\'') {
                if (*ptr == '\\' && ptr[1])
                    ptr++;
                ptr++;
            }

            ret->u.value = strndup(start, ptr - start);
            if (ret->u.value == NULL) {
                virReportOOMError();
                goto error;
            }

            if (*ptr == '\'')
                ptr++;
        } else {
            start = ptr;

            while (*ptr && !c_isspace(*ptr)
                   && *ptr != ')' && *ptr != '(') {
                ptr++;
            }

            ret->u.value = strndup(start, ptr - start);
            if (ret->u.value == NULL) {
                virReportOOMError();
                goto error;
            }
        }

        ret->kind = SEXPR_VALUE;
        if (ret->u.value == NULL)
            goto error;
    }

    *end = ptr - buffer;

    return ret;

  error:
    sexpr_free(ret);
    return NULL;
}
コード例 #15
0
ファイル: access.c プロジェクト: mkeiser/vlc
/*****************************************************************************
 * access_New:
 *****************************************************************************/
static stream_t *access_New(vlc_object_t *parent, input_thread_t *input,
                            bool preparsing, const char *mrl)
{
    char *redirv[MAX_REDIR];
    unsigned redirc = 0;

    stream_t *access = vlc_stream_CommonNew(parent, vlc_access_Destroy);
    if (unlikely(access == NULL))
        return NULL;

    access->p_input = input;
    access->psz_name = NULL;
    access->psz_url = strdup(mrl);
    access->psz_filepath = NULL;
    access->b_preparsing = preparsing;

    if (unlikely(access->psz_url == NULL))
        goto error;

    while (redirc < MAX_REDIR)
    {
        char *url = access->psz_url;
        msg_Dbg(access, "creating access: %s", url);

        const char *p = strstr(url, "://");
        if (p == NULL)
            goto error;

        access->psz_name = strndup(url, p - url);
        if (unlikely(access->psz_name == NULL))
            goto error;

        access->psz_location = p + 3;
        access->psz_filepath = get_path(access->psz_location);
        if (access->psz_filepath != NULL)
            msg_Dbg(access, " (path: %s)", access->psz_filepath);

        access->p_module = module_need(access, "access", access->psz_name,
                                       true);
        if (access->p_module != NULL) /* success */
        {
            while (redirc > 0)
                free(redirv[--redirc]);

            assert(access->pf_control != NULL);
            return access;
        }

        if (access->psz_url == url) /* failure (no redirection) */
            goto error;

        /* redirection */
        msg_Dbg(access, "redirecting to: %s", access->psz_url);
        redirv[redirc++] = url;

        for (unsigned j = 0; j < redirc; j++)
            if (!strcmp(redirv[j], access->psz_url))
            {
                msg_Err(access, "redirection loop");
                goto error;
            }

        free(access->psz_filepath);
        free(access->psz_name);
        access->psz_filepath = access->psz_name = NULL;
    }

    msg_Err(access, "too many redirections");
error:
    while (redirc > 0)
        free(redirv[--redirc]);
    free(access->psz_filepath);
    free(access->psz_name);
    stream_CommonDelete(access);
    return NULL;
}
コード例 #16
0
ファイル: longBow_String.c プロジェクト: PARC/LongBow
char *
longBowString_ToString(const LongBowString *string)
{
    char *result = strndup(string->buffer, string->end);
    return result;
}
コード例 #17
0
ファイル: fileio.c プロジェクト: banada/systemd
int parse_env_file(
                const char *fname,
                const char *separator, ...) {

        int r = 0;
        char *contents = NULL, *p;

        assert(fname);
        assert(separator);

        r = read_full_file(fname, &contents, NULL);
        if (r < 0)
                return r;

        p = contents;
        for (;;) {
                const char *key = NULL;

                p += strspn(p, separator);
                p += strspn(p, WHITESPACE);

                if (!*p)
                        break;

                if (!strchr(COMMENTS, *p)) {
                        va_list ap;
                        char **value;

                        va_start(ap, separator);
                        while ((key = va_arg(ap, char *))) {
                                size_t n;
                                char *v;

                                value = va_arg(ap, char **);

                                n = strlen(key);
                                if (!strneq(p, key, n) ||
                                    p[n] != '=')
                                        continue;

                                p += n + 1;
                                n = strcspn(p, separator);

                                if (n >= 2 &&
                                    strchr(QUOTES, p[0]) &&
                                    p[n-1] == p[0])
                                        v = strndup(p+1, n-2);
                                else
                                        v = strndup(p, n);

                                if (!v) {
                                        r = -ENOMEM;
                                        va_end(ap);
                                        goto fail;
                                }

                                if (v[0] == '\0') {
                                        /* return empty value strings as NULL */
                                        free(v);
                                        v = NULL;
                                }

                                free(*value);
                                *value = v;

                                p += n;

                                r ++;
                                break;
                        }
                        va_end(ap);
                }

                if (!key)
                        p += strcspn(p, separator);
        }
コード例 #18
0
ファイル: xml.c プロジェクト: MOBO-OSS/systemd-relative
int xml_tokenize(const char **p, char **name, void **state) {
        const char *c, *e, *b;
        char *ret;
        int t;

        assert(p);
        assert(*p);
        assert(name);
        assert(state);

        t = PTR_TO_INT(*state);
        c = *p;

        for (;;) {
                if (*c == 0)
                        return XML_END;

                switch (t) {

                case STATE_TEXT: {
                        int x;

                        e = strchrnul(c, '<');
                        if (e > c) {
                                /* More text... */
                                ret = strndup(c, e - c);
                                if (!ret)
                                        return -ENOMEM;

                                *name = ret;
                                *p = e;
                                *state = INT_TO_PTR(STATE_TEXT);

                                return XML_TEXT;
                        }

                        assert(*e == '<');
                        b = c + 1;

                        if (startswith(b, "!--")) {
                                /* A comment */
                                e = strstr(b + 3, "-->");
                                if (!e)
                                        return -EINVAL;

                                c = e + 3;
                                continue;
                        }

                        if (*b == '?') {
                                /* Processing instruction */

                                e = strstr(b + 1, "?>");
                                if (!e)
                                        return -EINVAL;

                                c = e + 2;
                                continue;
                        }

                        if (*b == '!') {
                                /* DTD */

                                e = strchr(b + 1, '>');
                                if (!e)
                                        return -EINVAL;

                                c = e + 1;
                                continue;
                        }

                        if (*b == '/') {
                                /* A closing tag */
                                x = XML_TAG_CLOSE;
                                b++;
                        } else
                                x = XML_TAG_OPEN;

                        e = strpbrk(b, WHITESPACE "/>");
                        if (!e)
                                return -EINVAL;

                        ret = strndup(b, e - b);
                        if (!ret)
                                return -ENOMEM;

                        *name = ret;
                        *p = e;
                        *state = INT_TO_PTR(STATE_TAG);

                        return x;
                }

                case STATE_TAG:

                        b = c + strspn(c, WHITESPACE);
                        if (*b == 0)
                                return -EINVAL;

                        e = b + strcspn(b, WHITESPACE "=/>");
                        if (e > b) {
                                /* An attribute */

                                ret = strndup(b, e - b);
                                if (!ret)
                                        return -ENOMEM;

                                *name = ret;
                                *p = e;
                                *state = INT_TO_PTR(STATE_ATTRIBUTE);

                                return XML_ATTRIBUTE_NAME;
                        }

                        if (startswith(b, "/>")) {
                                /* An empty tag */

                                *name = NULL; /* For empty tags we return a NULL name, the caller must be prepared for that */
                                *p = b + 2;
                                *state = INT_TO_PTR(STATE_TEXT);

                                return XML_TAG_CLOSE_EMPTY;
                        }

                        if (*b != '>')
                                return -EINVAL;

                        c = b + 1;
                        t = STATE_TEXT;
                        continue;

                case STATE_ATTRIBUTE:

                        if (*c == '=') {
                                c++;

                                if (*c == '\'' || *c == '\"') {
                                        /* Tag with a quoted value */

                                        e = strchr(c+1, *c);
                                        if (!e)
                                                return -EINVAL;

                                        ret = strndup(c+1, e - c - 1);
                                        if (!ret)
                                                return -ENOMEM;

                                        *name = ret;
                                        *p = e + 1;
                                        *state = INT_TO_PTR(STATE_TAG);

                                        return XML_ATTRIBUTE_VALUE;

                                }

                                /* Tag with a value without quotes */

                                b = strpbrk(c, WHITESPACE ">");
                                if (!b)
                                        b = c;

                                ret = strndup(c, b - c);
                                if (!ret)
                                        return -ENOMEM;

                                *name = ret;
                                *p = b;
                                *state = INT_TO_PTR(STATE_TAG);
                                return XML_ATTRIBUTE_VALUE;
                        }

                        t = STATE_TAG;
                        continue;
                }

        }

        assert_not_reached("Bad state");
}
コード例 #19
0
ファイル: pbang.c プロジェクト: daveti/prov-tools
/*
 * All the heavy lifting happens here.  Checks to see if this inode is a hard
 * link to one we've already encountered, and if not, issues inode_alloc and
 * setattr messages.  Then, regardless of the check, sends an inode_link message
 * to "register" the filename.
 */
static int callback(const char *fpath, const struct stat *sb, int typeflag,
		struct FTW *ftwbuf)
{
	struct provmsg_inode_alloc allocmsg;
	struct provmsg_setattr attrmsg;
	struct provmsg_link linkmsg;
	char *parent_path;
	const char *fname;
	struct stat parent;
	int fname_len;

	/* Set up early so we can copy larger chunks to other messages */
	linkmsg.inode.sb_uuid = uuid;
	linkmsg.inode.ino = sb->st_ino;

	if (!bitvec_test(&inodes, sb->st_ino)) {
		bitvec_set(&inodes, sb->st_ino);

		/* Write allocation info */
		msg_initlen(&allocmsg.msg, sizeof(allocmsg));
		allocmsg.msg.type = PROVMSG_INODE_ALLOC;
		allocmsg.msg.cred_id = 0;
		allocmsg.inode = linkmsg.inode;
		if (gzwrite(loggz, &allocmsg, sizeof allocmsg) < sizeof allocmsg) {
			perror("gzwrite");
			return 1;
		}

		/* Write attribute info */
		msg_initlen(&attrmsg.msg, sizeof(attrmsg));
		attrmsg.msg.type = PROVMSG_SETATTR;
		attrmsg.msg.cred_id = 0;
		attrmsg.inode = linkmsg.inode;
		attrmsg.mode = sb->st_mode;
		attrmsg.uid = sb->st_uid;
		attrmsg.gid = sb->st_gid;
		if (gzwrite(loggz, &attrmsg, sizeof(attrmsg)) < sizeof(attrmsg)) {
			perror("gzwrite");
			return 1;
		}
	}

	/* Send link (i.e. filename) message */
	linkmsg.msg.type = PROVMSG_LINK;
	linkmsg.msg.cred_id = 0;
	/* .inode field was set up earlier */
	if (ftwbuf->level > 0) {
		fname = strndup(fpath, PATH_MAX);
		parent_path = strndup(fpath, PATH_MAX);
		if (stat(dirname(parent_path), &parent)) {
			perror("stat");
			return 1;
		}
		linkmsg.dir = parent.st_ino;
		fname = basename(fname);
		fname_len = strlen(fname);
	} else {
		/* Stick with convention that root dir is "its own parent" */
		linkmsg.dir = linkmsg.inode.ino;
		fname_len = 0;
	}
	msg_initlen(&linkmsg.msg, sizeof(linkmsg) + fname_len);
	if (gzwrite(loggz, &linkmsg, sizeof(linkmsg)) < sizeof(linkmsg)) {
		perror("gzwrite");
		return 1;
	}
	if (fname_len > 0 && gzwrite(loggz, fname, fname_len) < fname_len) {
		perror("gzwrite");
		return 1;
	}

	return 0;
}
コード例 #20
0
ファイル: pull-dkr.c プロジェクト: shaded-enmity/systemd
static int parse_ancestry(const void *payload, size_t size, char ***ret) {
        _cleanup_free_ char *buf = NULL;
        void *json_state = NULL;
        const char *p;
        enum {
                STATE_BEGIN,
                STATE_ITEM,
                STATE_COMMA,
                STATE_END,
        } state = STATE_BEGIN;
        _cleanup_strv_free_ char **l = NULL;
        size_t n = 0, allocated = 0;

        if (size <= 0)
                return -EBADMSG;

        if (memchr(payload, 0, size))
                return -EBADMSG;

        buf = strndup(payload, size);
        if (!buf)
                return -ENOMEM;

        p = buf;
        for (;;) {
                _cleanup_free_ char *str;
                union json_value v = {};
                int t;

                t = json_tokenize(&p, &str, &v, &json_state, NULL);
                if (t < 0)
                        return t;

                switch (state) {

                case STATE_BEGIN:
                        if (t == JSON_ARRAY_OPEN)
                                state = STATE_ITEM;
                        else
                                return -EBADMSG;

                        break;

                case STATE_ITEM:
                        if (t == JSON_STRING) {
                                if (!dkr_id_is_valid(str))
                                        return -EBADMSG;

                                if (n+1 > LAYERS_MAX)
                                        return -EFBIG;

                                if (!GREEDY_REALLOC(l, allocated, n + 2))
                                        return -ENOMEM;

                                l[n++] = str;
                                str = NULL;
                                l[n] = NULL;

                                state = STATE_COMMA;

                        } else if (t == JSON_ARRAY_CLOSE)
                                state = STATE_END;
                        else
                                return -EBADMSG;

                        break;

                case STATE_COMMA:
                        if (t == JSON_COMMA)
                                state = STATE_ITEM;
                        else if (t == JSON_ARRAY_CLOSE)
                                state = STATE_END;
                        else
                                return -EBADMSG;
                        break;

                case STATE_END:
                        if (t == JSON_END) {

                                if (strv_isempty(l))
                                        return -EBADMSG;

                                if (!strv_is_uniq(l))
                                        return -EBADMSG;

                                l = strv_reverse(l);

                                *ret = l;
                                l = NULL;
                                return 0;
                        } else
                                return -EBADMSG;
                }

        }
}
コード例 #21
0
ファイル: networkd-address.c プロジェクト: dds/systemd
int config_parse_address(const char *unit,
                const char *filename,
                unsigned line,
                const char *section,
                unsigned section_line,
                const char *lvalue,
                int ltype,
                const char *rvalue,
                void *data,
                void *userdata) {
        Network *network = userdata;
        _cleanup_address_free_ Address *n = NULL;
        _cleanup_free_ char *address = NULL;
        const char *e;
        int r;

        assert(filename);
        assert(section);
        assert(lvalue);
        assert(rvalue);
        assert(data);

        if (streq(section, "Network")) {
                /* we are not in an Address section, so treat
                 * this as the special '0' section */
                section_line = 0;
        }

        r = address_new_static(network, section_line, &n);
        if (r < 0)
                return r;

        /* Address=address/prefixlen */

        /* prefixlen */
        e = strchr(rvalue, '/');
        if (e) {
                unsigned i;
                r = safe_atou(e + 1, &i);
                if (r < 0) {
                        log_syntax(unit, LOG_ERR, filename, line, EINVAL,
                                   "Interface prefix length is invalid, "
                                   "ignoring assignment: %s", e + 1);
                        return 0;
                }

                n->prefixlen = (unsigned char) i;

                address = strndup(rvalue, e - rvalue);
                if (!address)
                        return log_oom();
        } else {
                address = strdup(rvalue);
                if (!address)
                        return log_oom();
        }

        r = net_parse_inaddr(address, &n->family, &n->in_addr);
        if (r < 0) {
                log_syntax(unit, LOG_ERR, filename, line, EINVAL,
                           "Address is invalid, ignoring assignment: %s", address);
                return 0;
        }

        if (n->family == AF_INET && !n->broadcast.s_addr)
                n->broadcast.s_addr = n->in_addr.in.s_addr |
                                      htonl(0xfffffffflu >> n->prefixlen);

        n = NULL;

        return 0;
}
コード例 #22
0
ファイル: otr.c プロジェクト: KwadroNaut/irssi-otr
/*
 * For the given message we received through irssi, check if we need to queue
 * it for the case where that message is part of a bigger OTR full message.
 * This can happen with bitlbee for instance where OTR message are split in
 * different PRIVMSG.
 *
 * This uses a "queue" in the peer context so it's it very important to have
 * the peer context associated with the message (nickname + irssi object).
 *
 * Return an otr_msg_status code indicating the caller what to do with the msg.
 * OTR_MSG_ERROR indicates an error probably memory related. OTR_MSG_WAIT_MORE
 * tells the caller to NOT send out the message since we are waiting for more
 * to complete the OTR original message. OTR_MSG_ORIGINAL tell the caller to
 * simply use the original message. OTR_MSG_USE_QUEUE indicates that full_msg
 * can be used containing the reconstructed message. The caller SHOULD free(3)
 * this pointer after use.
 */
static enum otr_msg_status enqueue_otr_fragment(const char *msg,
		struct otr_peer_context *opc, char **full_msg)
{
	enum otr_msg_status ret;
	size_t msg_len;

	assert(msg);
	assert(opc);

	/* We are going to use it quite a bit so ease our life a bit. */
	msg_len = strlen(msg);

	if (opc->full_msg) {
		if (msg_len > (opc->msg_size - opc->msg_len)) {
			char *tmp_ptr;

			/* Realloc memory if there is not enough space. */
			tmp_ptr = realloc(opc->full_msg, opc->msg_size + msg_len + 1);
			if (!tmp_ptr) {
				free(opc->full_msg);
				opc->full_msg = NULL;
				ret = OTR_MSG_ERROR;
				goto end;
			}
			opc->full_msg = tmp_ptr;
			opc->msg_size += msg_len + 1;
		}

		/* Copy msg to full message since we already have a part pending. */
		strncpy(opc->full_msg + opc->msg_len, msg, msg_len);
		opc->msg_len += msg_len;
		opc->full_msg[opc->msg_len] = '\0';

		IRSSI_DEBUG("Partial OTR message added to queue: %s", msg);

		/*
		 * Are we waiting for more? If the message ends with a ".", the
		 * transmission has ended else we have to wait for more.
		 */
		if (msg[msg_len - 1] != OTR_MSG_END_TAG) {
			ret = OTR_MSG_WAIT_MORE;
			goto end;
		}

		/*
		 * Dup the string with enough space for the NULL byte since we are
		 * about to free it before passing it to the caller.
		 */
		*full_msg = strndup(opc->full_msg, opc->msg_len + 1);
		/* Reset everything. */
		free(opc->full_msg);
		opc->full_msg = NULL;
		opc->msg_size = opc->msg_len = 0;
		ret = OTR_MSG_USE_QUEUE;
		goto end;
	} else {
		char *pos;

		/*
		 * Try to find the OTR message tag at the _beginning_of the packet and
		 * check if this packet is not the end with the end tag of OTR "."
		 */
		pos = strstr(msg, OTR_MSG_BEGIN_TAG);
		if (pos && (pos == msg) && msg[msg_len - 1] != OTR_MSG_END_TAG) {
			/* Allocate full message buffer with an extra for NULL byte. */
			opc->full_msg = zmalloc((msg_len * 2) + 1);
			if (!opc->full_msg) {
				ret = OTR_MSG_ERROR;
				goto end;
			}
			/* Copy full message with NULL terminated byte. */
			strncpy(opc->full_msg, msg, msg_len);
			opc->msg_len += msg_len;
			opc->msg_size += ((msg_len * 2) + 1);
			opc->full_msg[opc->msg_len] = '\0';
			ret = OTR_MSG_WAIT_MORE;
			IRSSI_DEBUG("Partial OTR message begins the queue: %s", msg);
			goto end;
		}

		/* Use original message. */
		ret = OTR_MSG_ORIGINAL;
		goto end;
	}

end:
	return ret;
}
コード例 #23
0
ファイル: xa_cache.c プロジェクト: gohar94/xenaccess
int xa_update_cache (xa_instance_t *instance,
                     char *symbol_name,
                     uint32_t virt_address,
                     int pid,
                     uint32_t mach_address)
{
    xa_cache_entry_t new_entry = NULL;
    uint32_t vlookup = virt_address & ~(instance->page_size - 1);
    uint32_t mlookup = mach_address & ~(instance->page_size - 1);

    /* is cache enabled? */
    if (XA_CACHE_SIZE == 0){
        return 1;
    }

    /* does anything match the passed symbol_name? */
    /* if so, update other entries */
    if (symbol_name){
        xa_cache_entry_t current = instance->cache_head;
        while (current != NULL){
            if (strncmp(current->symbol_name, symbol_name, MAX_SYM_LEN) == 0){
                current->last_used = time(NULL);
                current->virt_address = 0;
                current->pid = pid;
                if (mach_address){
                    current->mach_address = mach_address;
                }
                else{
                    current->mach_address =
                        xa_translate_kv2p(instance, virt_address);
                }
                xa_dbprint("++Cache update (%s --> 0x%.8x)\n",
                    symbol_name, current->mach_address);
                goto exit;
            }
            current = current->next;
        }
    }

    /* does anything match the passed virt_address? */
    /* if so, update other entries */
    if (virt_address){
        xa_cache_entry_t current = instance->cache_head;
        while (current != NULL){
            if (current->virt_address == vlookup){
                current->last_used = time(NULL);
                current->pid = pid;
                current->mach_address = mlookup;
                xa_dbprint("++Cache update (0x%.8x --> 0x%.8x)\n",
                    vlookup, mlookup);
                goto exit;
            }
            current = current->next;
        }
    }

    /* was this a spurious call with bad info? */
    if (!symbol_name && !virt_address){
        goto exit;
    }

    /* do we need to remove anything from the cache? */
    if (instance->current_cache_size >= XA_CACHE_SIZE){
        xa_cache_entry_t oldest = instance->cache_head;
        xa_cache_entry_t current = instance->cache_head;

        /* find the least recently used entry */
        while (current != NULL){
            if (current->last_used < oldest->last_used){
                oldest = current;
            }
            current = current->next;
        }

        /* remove that entry */
        if (NULL == oldest->next && NULL == oldest->prev){  /* only entry */
            instance->cache_head = NULL;
            instance->cache_tail = NULL;
        }
        else if (NULL == oldest->next){  /* last entry */
            instance->cache_tail = oldest->prev;
            oldest->prev->next = NULL;
        }
        else if (NULL == oldest->prev){  /* first entry */
            instance->cache_head = oldest->next;
            oldest->next->prev = NULL;
        }
        else{  /* somewhere in the middle */
            oldest->prev->next = oldest->next;
            oldest->next->prev = oldest->prev;
        }

        /* free up memory */
        if (oldest->symbol_name){
            free(oldest->symbol_name);
        }
        oldest->next = NULL;
        oldest->prev = NULL;
        free(oldest);

        instance->current_cache_size--;
    }

    /* allocate memory for the new cache entry */
    new_entry = (xa_cache_entry_t) malloc(sizeof(struct xa_cache_entry));
    new_entry->last_used = time(NULL);
    if (symbol_name){
        new_entry->symbol_name = strndup(symbol_name, MAX_SYM_LEN);
        new_entry->virt_address = 0;
        if (mach_address){
            new_entry->mach_address = mach_address;
        }
        else{
            new_entry->mach_address =
                xa_translate_kv2p(instance, virt_address);
        }
        xa_dbprint("++Cache set (%s --> 0x%.8x)\n",
            symbol_name, new_entry->mach_address);
    }
    else{
        new_entry->symbol_name = strndup("", MAX_SYM_LEN);
        new_entry->virt_address = vlookup;
        new_entry->mach_address = mlookup;
        xa_dbprint("++Cache set (0x%.8x --> 0x%.8x)\n", vlookup, mlookup);
    }
    new_entry->pid = pid;

    /* add it to the end of the list */
    if (NULL != instance->cache_tail){
        instance->cache_tail->next = new_entry;
    }
    new_entry->prev = instance->cache_tail;
    instance->cache_tail = new_entry;
    if (NULL == instance->cache_head){
        instance->cache_head = new_entry;
    }
    new_entry->next = NULL;
    instance->current_cache_size++;

exit:
    return 1;
}
コード例 #24
0
int mnt_context_setup_loopdev(struct libmnt_context *cxt)
{
	const char *backing_file, *optstr, *loopdev = NULL;
	char *val = NULL;
	size_t len;
	struct loopdev_cxt lc;
	int rc = 0, lo_flags = 0;
	uint64_t offset = 0, sizelimit = 0;

	assert(cxt);
	assert(cxt->fs);
	assert((cxt->flags & MNT_FL_MOUNTFLAGS_MERGED));

	backing_file = mnt_fs_get_srcpath(cxt->fs);
	if (!backing_file)
		return -EINVAL;

	DBG(CXT, mnt_debug_h(cxt, "trying to setup loopdev for %s", backing_file));

	if (cxt->mountflags & MS_RDONLY) {
		DBG(CXT, mnt_debug_h(cxt, "enabling READ-ONLY flag"));
		lo_flags |= LO_FLAGS_READ_ONLY;
	}

	rc = loopcxt_init(&lc, 0);
	if (rc)
		return rc;

	ON_DBG(CXT, loopcxt_enable_debug(&lc, 1));

	optstr = mnt_fs_get_user_options(cxt->fs);

	/*
	 * loop=
	 */
	if (rc == 0 && (cxt->user_mountflags & MNT_MS_LOOP) &&
	    mnt_optstr_get_option(optstr, "loop", &val, &len) == 0 && val) {

		val = strndup(val, len);
		rc = val ? loopcxt_set_device(&lc, val) : -ENOMEM;
		free(val);

		if (rc == 0)
			loopdev = loopcxt_get_device(&lc);
	}

	/*
	 * offset=
	 */
	if (rc == 0 && (cxt->user_mountflags & MNT_MS_OFFSET) &&
	    mnt_optstr_get_option(optstr, "offset", &val, &len) == 0) {
		rc = mnt_parse_offset(val, len, &offset);
		if (rc) {
			DBG(CXT, mnt_debug_h(cxt, "failed to parse offset="));
			rc = -MNT_ERR_MOUNTOPT;
		}
	}

	/*
	 * sizelimit=
	 */
	if (rc == 0 && (cxt->user_mountflags & MNT_MS_SIZELIMIT) &&
	    mnt_optstr_get_option(optstr, "sizelimit", &val, &len) == 0) {
		rc = mnt_parse_offset(val, len, &sizelimit);
		if (rc) {
			DBG(CXT, mnt_debug_h(cxt, "failed to parse sizelimit="));
			rc = -MNT_ERR_MOUNTOPT;
		}
	}

	/*
	 * encryption=
	 */
	if (rc == 0 && (cxt->user_mountflags & MNT_MS_ENCRYPTION) &&
	    mnt_optstr_get_option(optstr, "encryption", &val, &len) == 0) {
		DBG(CXT, mnt_debug_h(cxt, "encryption no longer supported"));
		rc = -MNT_ERR_MOUNTOPT;
	}

	if (rc == 0 && is_mounted_same_loopfile(cxt,
				mnt_context_get_target(cxt),
				backing_file, offset))
		rc = -EBUSY;

	if (rc)
		goto done;

	/* since 2.6.37 we don't have to store backing filename to mtab
	 * because kernel provides the name in /sys.
	 */
	if (get_linux_version() >= KERNEL_VERSION(2, 6, 37) ||
	    !cxt->mtab_writable) {
		DBG(CXT, mnt_debug_h(cxt, "enabling AUTOCLEAR flag"));
		lo_flags |= LO_FLAGS_AUTOCLEAR;
	}

	do {
		/* found free device */
		if (!loopdev) {
			rc = loopcxt_find_unused(&lc);
			if (rc)
				goto done;
			DBG(CXT, mnt_debug_h(cxt, "trying to use %s",
						loopcxt_get_device(&lc)));
		}

		/* set device attributes
		 * -- note that loopcxt_find_unused() resets "lc"
		 */
		rc = loopcxt_set_backing_file(&lc, backing_file);

		if (!rc && offset)
			rc = loopcxt_set_offset(&lc, offset);
		if (!rc && sizelimit)
			rc = loopcxt_set_sizelimit(&lc, sizelimit);
		if (!rc)
			loopcxt_set_flags(&lc, lo_flags);
		if (rc) {
			DBG(CXT, mnt_debug_h(cxt, "failed to set loopdev attributes"));
			goto done;
		}

		/* setup the device */
		rc = loopcxt_setup_device(&lc);
		if (!rc)
			break;		/* success */

		if (loopdev || rc != -EBUSY) {
			DBG(CXT, mnt_debug_h(cxt, "failed to setup device"));
			rc = -MNT_ERR_LOOPDEV;
			goto done;
		}
		DBG(CXT, mnt_debug_h(cxt, "loopdev stolen...trying again"));
	} while (1);

	if (!rc)
		rc = mnt_fs_set_source(cxt->fs, loopcxt_get_device(&lc));

	if (!rc) {
		/* success */
		cxt->flags |= MNT_FL_LOOPDEV_READY;

		if ((cxt->user_mountflags & MNT_MS_LOOP) &&
		    loopcxt_is_autoclear(&lc)) {
			/*
			 * autoclear flag accepted by kernel, don't store
			 * the "loop=" option to mtab.
			 */
			cxt->user_mountflags &= ~MNT_MS_LOOP;
			mnt_optstr_remove_option(&cxt->fs->user_optstr, "loop");
		}

		if (!(cxt->mountflags & MS_RDONLY) &&
		    loopcxt_is_readonly(&lc))
			/*
			 * mount planned read-write, but loopdev is read-only,
			 * let's fix mount options...
			 */
			mnt_context_set_mflags(cxt, cxt->mountflags | MS_RDONLY);

		/* we have to keep the device open until mount(1),
		 * otherwise it will auto-cleared by kernel
		 */
		cxt->loopdev_fd = loopcxt_get_fd(&lc);
		loopcxt_set_fd(&lc, -1, 0);
	}
done:
	loopcxt_deinit(&lc);
	return rc;
}
コード例 #25
0
ファイル: ext_curl.cpp プロジェクト: 360buyliulei/hiphop-php
  bool setOption(long option, CVarRef value) {
    if (m_cp == NULL) {
      return false;
    }
    m_error_no = CURLE_OK;

    switch (option) {
    case CURLOPT_INFILESIZE:
    case CURLOPT_VERBOSE:
    case CURLOPT_HEADER:
    case CURLOPT_NOPROGRESS:
    case CURLOPT_NOBODY:
    case CURLOPT_FAILONERROR:
    case CURLOPT_UPLOAD:
    case CURLOPT_POST:
    case CURLOPT_FTPLISTONLY:
    case CURLOPT_FTPAPPEND:
    case CURLOPT_NETRC:
    case CURLOPT_PUT:
    case CURLOPT_TIMEOUT:
#if LIBCURL_VERSION_NUM >= 0x071002
    case CURLOPT_TIMEOUT_MS:
#endif
    case CURLOPT_FTP_USE_EPSV:
    case CURLOPT_LOW_SPEED_LIMIT:
    case CURLOPT_SSLVERSION:
    case CURLOPT_LOW_SPEED_TIME:
    case CURLOPT_RESUME_FROM:
    case CURLOPT_TIMEVALUE:
    case CURLOPT_TIMECONDITION:
    case CURLOPT_TRANSFERTEXT:
    case CURLOPT_HTTPPROXYTUNNEL:
    case CURLOPT_FILETIME:
    case CURLOPT_MAXREDIRS:
    case CURLOPT_MAXCONNECTS:
    case CURLOPT_CLOSEPOLICY:
    case CURLOPT_FRESH_CONNECT:
    case CURLOPT_FORBID_REUSE:
    case CURLOPT_CONNECTTIMEOUT:
#if LIBCURL_VERSION_NUM >= 0x071002
    case CURLOPT_CONNECTTIMEOUT_MS:
#endif
    case CURLOPT_SSL_VERIFYHOST:
    case CURLOPT_SSL_VERIFYPEER:
      //case CURLOPT_DNS_USE_GLOBAL_CACHE: not thread-safe when set to true
    case CURLOPT_NOSIGNAL:
    case CURLOPT_PROXYTYPE:
    case CURLOPT_BUFFERSIZE:
    case CURLOPT_HTTPGET:
    case CURLOPT_HTTP_VERSION:
    case CURLOPT_CRLF:
    case CURLOPT_DNS_CACHE_TIMEOUT:
    case CURLOPT_PROXYPORT:
    case CURLOPT_FTP_USE_EPRT:
    case CURLOPT_HTTPAUTH:
    case CURLOPT_PROXYAUTH:
    case CURLOPT_FTP_CREATE_MISSING_DIRS:
    case CURLOPT_FTPSSLAUTH:
    case CURLOPT_FTP_SSL:
    case CURLOPT_UNRESTRICTED_AUTH:
    case CURLOPT_PORT:
    case CURLOPT_AUTOREFERER:
    case CURLOPT_COOKIESESSION:
    case CURLOPT_TCP_NODELAY:
    case CURLOPT_IPRESOLVE:
    case CURLOPT_FOLLOWLOCATION:
      m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, value.toInt64());
      break;
    case CURLOPT_RETURNTRANSFER:
      m_write.method = value.toBoolean() ? PHP_CURL_RETURN : PHP_CURL_STDOUT;
      break;
    case CURLOPT_BINARYTRANSFER:
      m_write.type = value.toBoolean() ? PHP_CURL_BINARY : PHP_CURL_ASCII;
      break;
    case CURLOPT_PRIVATE:
    case CURLOPT_URL:
    case CURLOPT_PROXY:
    case CURLOPT_USERPWD:
    case CURLOPT_PROXYUSERPWD:
    case CURLOPT_RANGE:
    case CURLOPT_CUSTOMREQUEST:
    case CURLOPT_USERAGENT:
    case CURLOPT_FTPPORT:
    case CURLOPT_COOKIE:
    case CURLOPT_REFERER:
    case CURLOPT_INTERFACE:
    case CURLOPT_KRB4LEVEL:
    case CURLOPT_EGDSOCKET:
    case CURLOPT_CAINFO:
    case CURLOPT_CAPATH:
    case CURLOPT_SSL_CIPHER_LIST:
    case CURLOPT_SSLKEY:
    case CURLOPT_SSLKEYTYPE:
    case CURLOPT_SSLKEYPASSWD:
    case CURLOPT_SSLENGINE:
    case CURLOPT_SSLENGINE_DEFAULT:
    case CURLOPT_SSLCERTTYPE:
    case CURLOPT_ENCODING:
    case CURLOPT_COOKIEJAR:
    case CURLOPT_SSLCERT:
    case CURLOPT_RANDOM_FILE:
    case CURLOPT_COOKIEFILE:
      {
        String svalue = value.toString();
#if LIBCURL_VERSION_NUM >= 0x071100
        /* Strings passed to libcurl as 'char *' arguments, are copied
           by the library... NOTE: before 7.17.0 strings were not copied. */
        m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, svalue.c_str());
#else
        char *copystr = strndup(svalue.data(), svalue.size());
        m_to_free->str.push_back(copystr);
        m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, copystr);
#endif
        if (option == CURLOPT_URL) m_url = value;
      }
      break;
    case CURLOPT_FILE:
    case CURLOPT_INFILE:
    case CURLOPT_WRITEHEADER:
    case CURLOPT_STDERR:
      {
        if (!value.isResource()) {
          return false;
        }

        Resource obj = value.toResource();
        if (obj.isNull() || obj.getTyped<File>(true) == NULL) {
          return false;
        }

        switch (option) {
          case CURLOPT_FILE:
            m_write.fp = obj;
            m_write.method = PHP_CURL_FILE;
            break;
          case CURLOPT_WRITEHEADER:
            m_write_header.fp = obj;
            m_write_header.method = PHP_CURL_FILE;
            break;
          case CURLOPT_INFILE:
            m_read.fp = obj;
            m_emptyPost = false;
            break;
          default: {
            if (obj.getTyped<PlainFile>(true) == NULL) {
              return false;
            }
            FILE *fp = obj.getTyped<PlainFile>()->getStream();
            if (!fp) {
              return false;
            }
            m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, fp);
            break;
          }
        }
      }
      break;
    case CURLOPT_WRITEFUNCTION:
      m_write.callback = value;
      m_write.method = PHP_CURL_USER;
      break;
    case CURLOPT_READFUNCTION:
      m_read.callback = value;
      m_read.method = PHP_CURL_USER;
      m_emptyPost = false;
      break;
    case CURLOPT_HEADERFUNCTION:
      m_write_header.callback = value;
      m_write_header.method = PHP_CURL_USER;
      break;
    case CURLOPT_POSTFIELDS:
      m_emptyPost = false;
      if (value.is(KindOfArray) || value.is(KindOfObject)) {
        Array arr = value.toArray();
        curl_httppost *first = NULL;
        curl_httppost *last  = NULL;
        for (ArrayIter iter(arr); iter; ++iter) {
          String key = iter.first().toString();
          String val = iter.second().toString();
          const char *postval = val.data();

          /* The arguments after _NAMELENGTH and _CONTENTSLENGTH
           * must be explicitly cast to long in curl_formadd
           * use since curl needs a long not an int. */
          if (*postval == '@') {
            ++postval;
            m_error_no = (CURLcode)curl_formadd
              (&first, &last,
               CURLFORM_COPYNAME, key.data(),
               CURLFORM_NAMELENGTH, (long)key.size(),
               CURLFORM_FILE, postval,
               CURLFORM_END);
          } else {
            m_error_no = (CURLcode)curl_formadd
              (&first, &last,
               CURLFORM_COPYNAME, key.data(),
               CURLFORM_NAMELENGTH, (long)key.size(),
               CURLFORM_COPYCONTENTS, postval,
               CURLFORM_CONTENTSLENGTH,(long)val.size(),
               CURLFORM_END);
          }
        }

        if (m_error_no != CURLE_OK) {
          return false;
        }

        m_to_free->post.push_back(first);
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_HTTPPOST, first);

      } else {
        String svalue = value.toString();
#if LIBCURL_VERSION_NUM >= 0x071100
        /* with curl 7.17.0 and later, we can use COPYPOSTFIELDS,
           but we have to provide size before */
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_POSTFIELDSIZE,
                                      svalue.size());
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_COPYPOSTFIELDS,
                                      svalue.c_str());
#else
        char *post = strndup(svalue.data(), svalue.size());
        m_to_free->str.push_back(post);

        m_error_no = curl_easy_setopt(m_cp, CURLOPT_POSTFIELDS, post);
        m_error_no = curl_easy_setopt(m_cp, CURLOPT_POSTFIELDSIZE,
                                      svalue.size());
#endif
      }
      break;
    case CURLOPT_HTTPHEADER:
    case CURLOPT_QUOTE:
    case CURLOPT_HTTP200ALIASES:
    case CURLOPT_POSTQUOTE:
      if (value.is(KindOfArray) || value.is(KindOfObject)) {
        Array arr = value.toArray();
        curl_slist *slist = NULL;
        for (ArrayIter iter(arr); iter; ++iter) {
          String key = iter.first().toString();
          String val = iter.second().toString();

          slist = curl_slist_append(slist, val.c_str());
          if (!slist) {
            raise_warning("Could not build curl_slist");
            return false;
          }
        }

        m_to_free->slist.push_back(slist);
        m_error_no = curl_easy_setopt(m_cp, (CURLoption)option, slist);

      } else {
        raise_warning("You must pass either an object or an array with "
                      "the CURLOPT_HTTPHEADER, CURLOPT_QUOTE, "
                      "CURLOPT_HTTP200ALIASES and CURLOPT_POSTQUOTE "
                      "arguments");
        return false;
      }
      break;

    case CURLINFO_HEADER_OUT:
      if (value.toInt64() == 1) {
        curl_easy_setopt(m_cp, CURLOPT_DEBUGFUNCTION, curl_debug);
        curl_easy_setopt(m_cp, CURLOPT_DEBUGDATA, (void *)this);
        curl_easy_setopt(m_cp, CURLOPT_VERBOSE, 1);
      } else {
        curl_easy_setopt(m_cp, CURLOPT_DEBUGFUNCTION, NULL);
        curl_easy_setopt(m_cp, CURLOPT_DEBUGDATA, NULL);
        curl_easy_setopt(m_cp, CURLOPT_VERBOSE, 0);
      }
      break;

    case CURLOPT_FB_TLS_VER_MAX:
      {
        int64_t val = value.toInt64();
        if (value.isInteger() &&
            (val == CURLOPT_FB_TLS_VER_MAX_1_0 ||
             val == CURLOPT_FB_TLS_VER_MAX_1_1 ||
             val == CURLOPT_FB_TLS_VER_MAX_NONE)) {
            m_opts.set(int64_t(option), value);
        } else {
          raise_warning("You must pass CURLOPT_FB_TLS_VER_MAX_1_0, "
                        "CURLOPT_FB_TLS_VER_MAX_1_1 or "
                        "CURLOPT_FB_TLS_VER_MAX_NONE with "
                        "CURLOPT_FB_TLS_VER_MAX");
        }
      }
      break;
    case CURLOPT_FB_TLS_CIPHER_SPEC:
      if (value.isString() && !value.toString().empty()) {
        m_opts.set(int64_t(option), value);
      } else {
        raise_warning("CURLOPT_FB_TLS_CIPHER_SPEC requires a non-empty string");
      }
      break;

    default:
      m_error_no = CURLE_FAILED_INIT;
      throw_invalid_argument("option: %ld", option);
      break;
    }

    m_opts.set(int64_t(option), value);

    return m_error_no == CURLE_OK;
  }
コード例 #26
0
ファイル: data.c プロジェクト: janrinze/netsurf
static bool fetch_data_process(struct fetch_data_context *c)
{
	fetch_msg msg;
	char *params;
	char *comma;
	char *unescaped;
        int unescaped_len;
	
	/* format of a data: URL is:
	 *   data:[<mimetype>][;base64],<data>
	 * The mimetype is optional.  If it is missing, the , before the
	 * data must still be there.
	 */
	
	LOG("url: %.140s", c->url);
	
	if (strlen(c->url) < 6) {
		/* 6 is the minimum possible length (data:,) */
		msg.type = FETCH_ERROR;
		msg.data.error = "Malformed data: URL";
		fetch_data_send_callback(&msg, c);
		return false;
	}
	
	/* skip the data: part */
	params = c->url + SLEN("data:");
	
	/* find the comma */
	if ( (comma = strchr(params, ',')) == NULL) {
		msg.type = FETCH_ERROR;
		msg.data.error = "Malformed data: URL";
		fetch_data_send_callback(&msg, c);
		return false;
	}
	
	if (params[0] == ',') {
		/* there is no mimetype here, assume text/plain */
		c->mimetype = strdup("text/plain;charset=US-ASCII");
	} else {	
		/* make a copy of everything between data: and the comma */
		c->mimetype = strndup(params, comma - params);
	}
	
	if (c->mimetype == NULL) {
		msg.type = FETCH_ERROR;
		msg.data.error = 
			"Unable to allocate memory for mimetype in data: URL";
		fetch_data_send_callback(&msg, c);
		return false;
	}
	
	if (strcmp(c->mimetype + strlen(c->mimetype) - 7, ";base64") == 0) {
		c->base64 = true;
		c->mimetype[strlen(c->mimetype) - 7] = '\0';
	} else {
		c->base64 = false;
	}
	
	/* URL unescape the data first, just incase some insane page
	 * decides to nest URL and base64 encoding.  Like, say, Acid2.
	 */
        unescaped = curl_easy_unescape(curl, comma + 1, 0, &unescaped_len);
        if (unescaped == NULL) {
		msg.type = FETCH_ERROR;
		msg.data.error = "Unable to URL decode data: URL";
		fetch_data_send_callback(&msg, c);
		return false;
	}
	
	if (c->base64) {
		base64_decode_alloc(unescaped, unescaped_len, &c->data,	&c->datalen);
		if (c->data == NULL) {
			msg.type = FETCH_ERROR;
			msg.data.error = "Unable to Base64 decode data: URL";
			fetch_data_send_callback(&msg, c);
			curl_free(unescaped);
			return false;
		}
	} else {
		c->data = malloc(unescaped_len);
		if (c->data == NULL) {
			msg.type = FETCH_ERROR;
			msg.data.error =
				"Unable to allocate memory for data: URL";
			fetch_data_send_callback(&msg, c);
			curl_free(unescaped);
			return false;
		}
		c->datalen = unescaped_len;
		memcpy(c->data, unescaped, unescaped_len);
	}
	
	curl_free(unescaped);
	
	return true;
}
コード例 #27
0
// first we split strings on '.'
// then we call each split string a 'label'
// Do not allow '*' for the top level domain label; eg never allow *.*.com
// Do not allow '*' for subsequent subdomains; eg never allow *.foo.example.com
// Do allow *.example.com
uint32_t
check_wildcard_match_rfc2595 (const char *orig_hostname,
                      const char *orig_cert_wild_card)
{
  char *hostname;
  char *hostname_to_free;
  char *cert_wild_card;
  char *cert_wild_card_to_free;
  char *expected_label;
  char *wildcard_label;
  char *delim;
  char *wildchar;
  uint32_t ok;
  uint32_t wildcard_encountered;
  uint32_t label_count;

  // First we copy the original strings
  hostname = strndup(orig_hostname, strlen(orig_hostname));
  cert_wild_card = strndup(orig_cert_wild_card, strlen(orig_cert_wild_card));
  hostname_to_free = hostname;
  cert_wild_card_to_free = cert_wild_card;
  delim = strdup(".");
  wildchar = strdup("*");

  verb ("V: Inspecting '%s' for possible wildcard match against '%s'\n",
         hostname, cert_wild_card);

  // By default we have not processed any labels
  label_count = dns_label_count(cert_wild_card, delim);

  // By default we have no match
  ok = 0;
  wildcard_encountered = 0;
  // First - do we have labels? If not, we refuse to even try to match
  if ((NULL != strpbrk(cert_wild_card, delim)) &&
      (NULL != strpbrk(hostname, delim)) &&
      (label_count <= ((uint32_t)RFC2595_MIN_LABEL_COUNT)))
  {
    if (wildchar[0] == cert_wild_card[0])
    {
      verb ("V: Found wildcard in at start of provided certificate name\n");
      do
      {
        // Skip over the bytes between the first char and until the next label
        wildcard_label = strsep(&cert_wild_card, delim);
        expected_label = strsep(&hostname, delim);
        if (NULL != wildcard_label &&
            NULL != expected_label &&
            NULL != hostname &&
            NULL != cert_wild_card)
        {
          // Now we only consider this wildcard valid if the rest of the
          // hostnames match verbatim
          verb ("V: Attempting match of '%s' against '%s'\n",
                 expected_label, wildcard_label);
          // This is the case where we have a label that begins with wildcard
          // Furthermore, we only allow this for the first label
          if (wildcard_label[0] == wildchar[0] &&
              0 == wildcard_encountered && 0 == ok)
          {
            verb ("V: Forced match of '%s' against '%s'\n", expected_label, wildcard_label);
            wildcard_encountered = 1;
          } else {
            verb ("V: Attempting match of '%s' against '%s'\n",
                   hostname, cert_wild_card);
            if (0 == strcasecmp (expected_label, wildcard_label) &&
                label_count >= ((uint32_t)RFC2595_MIN_LABEL_COUNT))
            {
              ok = 1;
              verb ("V: remaining labels match!\n");
              break;
            } else {
              ok = 0;
              verb ("V: remaining labels do not match!\n");
              break;
            }
          }
        } else {
          // We hit this case when we have a mismatched number of labels
          verb("V: NULL label; no wildcard here\n");
          break;
        }
      } while (0 != wildcard_encountered && label_count <= RFC2595_MIN_LABEL_COUNT);
    } else {
      verb ("V: Not a RFC 2595 wildcard\n");
    }
  } else {
    verb ("V: Not a valid wildcard certificate\n");
    ok = 0;
  }
  // Free our copies
  free(wildchar);
  free(delim);
  free(hostname_to_free);
  free(cert_wild_card_to_free);
  if (wildcard_encountered & ok && label_count >= RFC2595_MIN_LABEL_COUNT)
  {
    verb ("V: wildcard match of %s against %s\n",
          orig_hostname, orig_cert_wild_card);
    return (wildcard_encountered & ok);
  } else {
    verb ("V: wildcard match failure of %s against %s\n",
          orig_hostname, orig_cert_wild_card);
    return 0;
  }
}
コード例 #28
0
static struct passwd *
parse_user(char *line, size_t len)
{
	static struct passwd pw;
	int i,j;
	char *tokens[_PASSWD_FIELDS];
	char *token = NULL;
	bool comment = true;

	free(pw.pw_name);
	free(pw.pw_passwd);
	free(pw.pw_class);
	free(pw.pw_gecos);
	free(pw.pw_dir);
	free(pw.pw_shell);
	memset(&pw, 0, sizeof(pw));

	if (line == NULL) return NULL;

	memset(&tokens, 0, sizeof(char *) * _PASSWD_FIELDS);

	for (i = 0, j = 0; i < len && j < _PASSWD_FIELDS; ++i) {
		int c = line[i];
		if (!isspace(c) && c != '#') {
			comment = false;
		}
		if (!comment && token == NULL) {
			// start a new token
			token = &line[i];
		} else if (token && (c == ':' || c == '\n')) {
			// end the current token
			// special case for empty token
			while (token[0] == ':' && token < &line[i]) {
				tokens[j++] = strdup("");
				++token;
			}
			tokens[j++] = strndup(token, &line[i] - token);
			token = NULL;
		}
	}

	if (comment || j != _PASSWD_FIELDS) return NULL;

	j = 0;
	pw.pw_name = tokens[j++];
	pw.pw_passwd = tokens[j++];
	pw.pw_uid = atoi(tokens[j]);
	free(tokens[j++]);
	pw.pw_gid = atoi(tokens[j]);
	free(tokens[j++]);
	pw.pw_class = tokens[j++];
	pw.pw_change = atoi(tokens[j]);
	free(tokens[j++]);
	pw.pw_expire = atoi(tokens[j]);
	free(tokens[j++]);
	pw.pw_gecos = tokens[j++];
	pw.pw_dir = tokens[j++];
	pw.pw_shell = tokens[j++];

	return &pw;
}
コード例 #29
0
ファイル: mutt_notmuch.c プロジェクト: kostaz/mutt-kz
static int url_parse_query(char *url, char **filename, struct uri_tag **tags)
{
	char *p = strstr(url, "://");	/* remote unsupported */
	char *e;
	struct uri_tag *tag, *last = NULL;

	*filename = NULL;
	*tags = NULL;

	if (!p || !*(p + 3))
		return -1;

	p += 3;
	*filename = p;

	e = strchr(p, '?');

	*filename = e ? e == p ? NULL : strndup(p, e - p) : safe_strdup(p);
	if (!e)
		return 0;

	if (*filename && url_pct_decode(*filename) < 0)
		goto err;
	if (!e)
		return 0;	/* only filename */

	++e;	/* skip '?' */
	p = e;

	while (p && *p) {
		tag = safe_calloc(1, sizeof(struct uri_tag));
		if (!tag)
			goto err;

		if (!*tags)
			last = *tags = tag;
		else {
			last->next = tag;
			last = tag;
		}

		e = strchr(p, '=');
		if (!e)
			e = strchr(p, '&');
		tag->name = e ? strndup(p, e - p) : safe_strdup(p);
		if (!tag->name || url_pct_decode(tag->name) < 0)
			goto err;
		if (!e)
			break;

		p = e + 1;

		if (*e == '&')
			continue;

		e = strchr(p, '&');
		tag->value = e ? strndup(p, e - p) : safe_strdup(p);
		if (!tag->value || url_pct_decode(tag->value) < 0)
			goto err;
		if (!e)
			break;
		p = e + 1;
	}

	return 0;
err:
	FREE(&(*filename));
	url_free_tags(*tags);
	return -1;
}
コード例 #30
0
ファイル: jam.c プロジェクト: cpascal/af-cpp
char *executable_path(const char *argv0) {
    char buf[1024];
    ssize_t ret = readlink("/proc/self/exe", buf, sizeof(buf));
    if (ret == 0 || ret == sizeof(buf)) return NULL;
    return strndup(buf, ret);
}