Ejemplo n.º 1
0
static int ooxml_parse_document(int fd, cli_ctx *ctx)
{
    int ret = CL_SUCCESS;
    xmlTextReaderPtr reader = NULL;

    cli_dbgmsg("in ooxml_parse_document\n");

    /* perform engine limit checks in temporary tracking session */
    ret = ooxml_updatelimits(fd, ctx);
    if (ret != CL_CLEAN)
        return ret;

    reader = xmlReaderForFd(fd, "properties.xml", NULL, CLAMAV_MIN_XMLREADER_FLAGS);
    if (reader == NULL) {
        cli_dbgmsg("ooxml_parse_document: xmlReaderForFd error\n");
        return CL_SUCCESS; // internal error from libxml2
    }

    ret = cli_msxml_parse_document(ctx, reader, ooxml_keys, num_ooxml_keys, 1);

    if (ret != CL_SUCCESS && ret != CL_ETIMEOUT && ret != CL_BREAK)
        cli_warnmsg("ooxml_parse_document: encountered issue in parsing properties document\n");

    xmlTextReaderClose(reader);
    xmlFreeTextReader(reader);
    return ret;
}
Ejemplo n.º 2
0
/**
 * Read the xml document in from a file descriptor.
 * @param   xml The xml document
 * @param   fd The source xml input descriptor
 * @return  @c TRUE if successful, @c FALSE if an error occurs.
 * @ingroup EXML_Read_Group
 */
int exml_fd_read(EXML *xml, int fd)
{
	xmlTextReaderPtr reader;

	CHECK_PARAM_POINTER_RETURN("xml", xml, FALSE);

	reader = xmlReaderForFd( fd, "", NULL, XML_PARSE_RECOVER );

	return _exml_read(xml, reader);
}
Ejemplo n.º 3
0
/*
 * mgmt_convert_param() converts legacy params file of each LUN
 * to scf data. It will convert LUNs under one target each time.
 * Args:
 *   dir - string of directory where param file is stored
 *   tnode - node tree which contains to a target
 */
Boolean_t
mgmt_convert_param(char *dir, tgt_node_t *tnode)
{
	Boolean_t	ret = False;
	char		path[MAXPATHLEN];
	int		xml_fd = -1;
	int		n;
	int		lun_num;
	tgt_node_t	*lun = NULL;
	tgt_node_t	*params = NULL;
	xmlTextReaderPtr	r;

	while ((lun = tgt_node_next(tnode, XML_ELEMENT_LUN, lun)) != NULL) {
		if ((tgt_find_value_int(lun, XML_ELEMENT_LUN, &lun_num)) ==
		    False)
			continue;
		(void) snprintf(path, sizeof (path), "%s/%s%d",
		    dir, PARAMBASE, lun_num);
		if ((xml_fd = open(path, O_RDONLY)) < 0)
			continue;
		if ((r = (xmlTextReaderPtr)xmlReaderForFd(xml_fd,
		    NULL, NULL, 0)) == NULL)
			continue;

		n = xmlTextReaderRead(r);
		while (n == 1) {
			if (tgt_node_process(r, &params) == False) {
				break;
			}
			n = xmlTextReaderRead(r);
		}
		if (n < 0) {
			ret = False;
			break;
		}

		if (mgmt_param_save2scf(params, tnode->x_value, lun_num)
		    != True) {
			ret = False;
			break;
		} else {
			backup(path, tnode->x_value);
			ret = True;
		}
		params = NULL;
		(void) close(xml_fd);
		xmlTextReaderClose(r);
		xmlFreeTextReader(r);
	}

	if (ret == False)
		syslog(LOG_ERR, "Converting target %s params failed", dir);
	return (ret);
}
Ejemplo n.º 4
0
int main (void)
{
  xmlTextReaderPtr xml = xmlReaderForFd (STDIN_FILENO, "", NULL, 0);
  while (xmlTextReaderRead (xml)) {
    char *name = (char *) BAD_CAST xmlTextReaderName (xml);
    if (xmlTextReaderNodeType (xml) == XML_READER_TYPE_ELEMENT &&
         strcasecmp (name, "text") == 0) {
      while (xmlTextReaderRead (xml) && // memory leak :
              xmlStrcmp (xmlTextReaderName (xml), BAD_CAST "#text") != 0) {}
      printf ("%s\n", xmlTextReaderValue (xml));
    }
  }
}
Ejemplo n.º 5
0
/**
 * Given a file descriptor (that can be @p stdin) for an XML file, validate
 * schema, process nodes, convert and save it in the @p ks KeySet.
 *
 * @param ks keyset
 * @param fd POSIX file descriptior
 * @ingroup stream
 */
int ksFromXML(KeySet *ks, int fd)
{
	// a complete XML document is expected
	xmlTextReaderPtr reader=0;
	int ret;
	reader=xmlReaderForFd(fd,"file:/tmp/imp.xml",0,0);
	if (reader) {
		ret=ksFromXMLReader(ks,reader);
	} else {
		printf("kdb: Unable to open file descriptor %d for XML reading\n", fd);
		return 1;
	}
	return ret;
}
Ejemplo n.º 6
0
xmlDocPtr _waitForAnswerBACKUP(int sockfd) {
    xmlTextReaderPtr reader = NULL;
    int ret;
    int processNodeRet = 0;
    xmlDocPtr soapDoc = NULL;
	
    reader = xmlReaderForFd(sockfd, NULL, NULL, 0);
    if (reader != NULL) {
        ret = xmlTextReaderRead(reader);
        while(ret == 1) {
            ret = xmlTextReaderRead(reader);
        }
        soapDoc = xmlTextReaderCurrentDoc(reader);
        xmlFreeTextReader(reader);
 	}
	return soapDoc;
}
Ejemplo n.º 7
0
static int ooxml_parse_document(int fd, cli_ctx *ctx)
{
    int ret = CL_SUCCESS;
    xmlTextReaderPtr reader = NULL;

    cli_dbgmsg("in ooxml_parse_document\n");

    reader = xmlReaderForFd(fd, "properties.xml", NULL, 0);
    if (reader == NULL) {
        cli_dbgmsg("ooxml_parse_document: xmlReaderForFd error\n");
        return CL_SUCCESS; // internal error from libxml2
    }

    /* move reader to first element */
    if (xmlTextReaderRead(reader) != 1) {
        return CL_SUCCESS; /* libxml2 failed */
    }

    ret = ooxml_parse_element(reader, ctx->wrkproperty, 0, 0);

    xmlTextReaderClose(reader);
    xmlFreeTextReader(reader);
    return ret;
}
Ejemplo n.º 8
0
int
main(int argc, char **argv) {

    struct cmdlineInfo cmdline;
    FILE * ifP;
    xmlTextReaderPtr xmlReaderP;

    pnm_init(&argc, argv);

    xmlInitParser();

    LIBXML_TEST_VERSION;

    parseCommandLine(argc, argv, &cmdline);
    
    traceDraw = cmdline.trace;

    ifP = pm_openr(cmdline.inputFileName);

    xmlReaderP = xmlReaderForFd(fileno(ifP), "SVG_IMAGE", NULL, 0);

    if (xmlReaderP) {
        processDocument(xmlReaderP, stdout);

        /* xmlTextReaderIsValid() does not appear to work.  It always says
           the document is invalid
        */

        xmlFreeTextReader(xmlReaderP);
    } else
        pm_error("Failed to create xmlReader");

    xmlCleanupParser();

    return 0;
}
Ejemplo n.º 9
0
int main (void)
{
  xmlTextReaderPtr xml = xmlReaderForFd (STDIN_FILENO, "", NULL, 0);
  FILE *file = fopen ("gosmore.pak", "r");
  if (!xml || !file || fseek (file, 0, SEEK_END) != 0 ||
        !GosmInit (mmap (NULL, ftell (file), PROT_READ, MAP_SHARED,
                              fileno (file), 0), ftell (file))) {
    fprintf (stderr, "Unable to open gosmore.pak\n");
    return 1;
  }
                              
  
  int ptCnt = 0;
  printf ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  "<gpx\n"
  " version=\"1.0\"\n"
  " creator=\"osmunda\"\n"
  " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
  " xmlns=\"http://www.topografix.com/GPX/1/0\"\n"
  " xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/\">\n");
  while (xmlTextReaderRead (xml)) {
    char *name = (char *) BAD_CAST xmlTextReaderName (xml);
    if (xmlTextReaderNodeType (xml) == XML_READER_TYPE_ELEMENT) {
      while (stricmp (name, "trkpt") == 0 &&
             xmlTextReaderMoveToNextAttribute (xml)) {
        char *aname = (char *) BAD_CAST xmlTextReaderName (xml);
        char *avalue = (char *) BAD_CAST xmlTextReaderValue (xml);
        if (stricmp (aname, "lat") == 0) tlat = Latitude (atof (avalue));
        if (stricmp (aname, "lon") == 0) tlon = Longitude (atof (avalue));
        xmlFree (aname);
        xmlFree (avalue);
      }
    }
    if (xmlTextReaderNodeType (xml) == XML_READER_TYPE_END_ELEMENT) {
      if (stricmp (name, "trkpt") == 0) {
        if (ptCnt++ > 0) {
          int vehicle[] = { bicycleR, motorcarR, footR }, i;
          for (i = 0; i < sizeof (vehicle) / sizeof (vehicle[0]); i++) {
            Route (TRUE, 0, 0, /*tlon - flon, tlat - flat,*/ bicycleR, 0);
            //routeNode *itr;
            //for (itr = shortest; itr->shortest; itr = itr->shortest) {}
            if (routeHeapSize > 0 && (!shortest || !shortest->shortest ||
                !shortest->shortest->shortest)) break;
          }
          if (i == sizeof (vehicle) / sizeof (vehicle[0])) {
//                fprintf (stderr, "%d\n", shortest->best);
            printf ("<trk>\n<trkseg>\n<trkpt lat=\"%.5lf\" "
              "lon=\"%.5lf\"/>\n<trkpt lat=\"%.5lf\" lon=\"%.5lf\"/>\n"
              "</trkseg>\n</trk>\n", LatInverse (flat), LonInverse (flon),
              LatInverse (tlat), LonInverse (tlon));
          }
        }
        flat = tlat;
        flon = tlon;
      }
      if (stricmp (name, "trk") == 0) ptCnt = 0; // Gap in track
    }
    xmlFree (name);
  }
  printf ("</gpx>\n");
  return 0;
}
static gboolean
file_parse (gchar                     *filename,
	    GtkSourceLanguage         *language,
	    GtkSourceContextData      *ctx_data,
	    GHashTable                *defined_regexes,
	    GHashTable                *styles,
	    GHashTable                *loaded_lang_ids,
	    GQueue                    *replacements,
	    GError                   **error)
{
	ParserState *parser_state;
	xmlTextReader *reader = NULL;
	int fd = -1;
	GError *tmp_error = NULL;
	GtkSourceLanguageManager *lm;
	const gchar *rng_lang_schema;

	g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

	DEBUG (g_message ("loading file '%s'", filename));

	/*
	 * Use fd instead of filename so that it's utf8 safe on w32.
	 */
	fd = g_open (filename, O_RDONLY, 0);

	if (fd != -1)
		reader = xmlReaderForFd (fd, filename, NULL, 0);

	if (reader == NULL)
	{
		g_set_error (&tmp_error,
			     PARSER_ERROR,
			     PARSER_ERROR_CANNOT_OPEN,
			     "unable to open the file");
		goto error;
	}

	lm = _gtk_source_language_get_language_manager (language);
	rng_lang_schema = _gtk_source_language_manager_get_rng_file (lm);

	if (rng_lang_schema == NULL)
	{
		g_set_error (&tmp_error,
			     PARSER_ERROR,
			     PARSER_ERROR_CANNOT_VALIDATE,
			     "could not find the RelaxNG schema file");
		goto error;
	}

	if (xmlTextReaderRelaxNGValidate (reader, rng_lang_schema))
	{
		g_set_error (&tmp_error,
			     PARSER_ERROR,
			     PARSER_ERROR_CANNOT_VALIDATE,
			     "unable to load the RelaxNG schema '%s'",
			     rng_lang_schema);
		goto error;
	}

	parser_state = parser_state_new (language, ctx_data,
					 defined_regexes, styles,
					 replacements, reader,
					 filename, loaded_lang_ids);
	xmlTextReaderSetStructuredErrorHandler (reader,
						(xmlStructuredErrorFunc) text_reader_structured_error_func,
						parser_state);

	while ((parser_state->error == NULL) &&
	        (1 == xmlTextReaderRead (parser_state->reader)))
	{
		int type;

		/* FIXME: does xmlTextReaderRead already do it? */
		xmlTextReaderIsValid (parser_state->reader);

		if (parser_state->error != NULL)
			break;

		type = xmlTextReaderNodeType (parser_state->reader);

		switch (type)
		{
			case XML_READER_TYPE_ELEMENT:
				element_start (parser_state);
				break;
			case XML_READER_TYPE_END_ELEMENT:
				element_end (parser_state);
				break;
		}
	}

	if (parser_state->error != NULL)
	{
		g_propagate_error (&tmp_error, parser_state->error);
		parser_state->error = NULL;
	}

	parser_state_destroy (parser_state);

	if (tmp_error != NULL)
		goto error;

	close (fd);

	return TRUE;

error:
	if (fd != -1)
		close (fd);
	g_propagate_error (error, tmp_error);
	return FALSE;
}
Ejemplo n.º 11
0
GtkSourceLanguage *
_gtk_source_language_new_from_file (const gchar              *filename,
				    GtkSourceLanguageManager *lm)
{
	GtkSourceLanguage *lang = NULL;
	xmlTextReaderPtr reader = NULL;
	gint ret;
	gint fd;

	g_return_val_if_fail (filename != NULL, NULL);
	g_return_val_if_fail (lm != NULL, NULL);

	/*
	 * Use fd instead of filename so that it's utf8 safe on w32.
	 */
	fd = g_open (filename, O_RDONLY, 0);
	if (fd != -1)
		reader = xmlReaderForFd (fd, filename, NULL, 0);

	if (reader != NULL)
	{
        	ret = xmlTextReaderRead (reader);

        	while (ret == 1)
		{
			if (xmlTextReaderNodeType (reader) == 1)
			{
				xmlChar *name;

				name = xmlTextReaderName (reader);

				if (xmlStrcmp (name, BAD_CAST "language") == 0)
				{
					lang = process_language_node (reader, filename);
					ret = 0;
				}

				xmlFree (name);
			}

			if (ret == 1)
				ret = xmlTextReaderRead (reader);
		}

		xmlFreeTextReader (reader);
		close (fd);

		if (ret != 0)
		{
	            g_warning("Failed to parse '%s'", filename);
		    return NULL;
		}
        }
	else
	{
		g_warning("Unable to open '%s'", filename);

    	}

	if (lang != NULL)
	{
		lang->priv->language_manager = lm;
		g_object_add_weak_pointer (G_OBJECT (lm),
					   (gpointer) &lang->priv->language_manager);
	}

	return lang;
}
Ejemplo n.º 12
0
/*
 * this function tries to convert configuration in files into scf
 * it loads xml conf into node tree then dump them to scf with
 * mgmt_config_save2scf()
 * this function has 3 return values:
 * CONVERT_OK: successfully converted
 * CONVERT_INIT_NEW: configuration files dont exist, created a new scf entry
 * CONVERT_FAIL: some error occurred in conversion and no scf entry created.
 *               In this case, user have to check files manually and try
 *               conversion again.
 */
convert_ret_t
mgmt_convert_conf()
{
	targ_scf_t		*h = NULL;
	xmlTextReaderPtr	r;
	convert_ret_t		ret = CONVERT_FAIL;
	int			xml_fd = -1;
	int			n;
	tgt_node_t		*node = NULL;
	tgt_node_t		*next = NULL;
	char			path[MAXPATHLEN];
	char			*target = NULL;

	h = mgmt_handle_init();
	if (h == NULL)
		return (CONVERT_FAIL);

	/* check main config in pgroup iscsitgt */
	if (scf_service_get_pg(h->t_service, "iscsitgt", h->t_pg) == 0) {
		ret = CONVERT_OK;
		goto done;
	}

	/* check the conf files */
	if (access(config_file, R_OK) != 0) {
		/*
		 * if there is no configuration file, initialize
		 * an empty scf entry
		 */
		if (mgmt_transaction_start(h, "iscsitgt", "basic") == True) {
			ret = CONVERT_INIT_NEW;

			node = tgt_node_alloc(XML_ELEMENT_VERS, String, "1.0");
			new_property(h, node);
			tgt_node_free(node);
			/* "daemonize" is set to true by default */
			node = tgt_node_alloc(XML_ELEMENT_DBGDAEMON, String,
			    "true");
			new_property(h, node);
			tgt_node_free(node);
			node = NULL;
			node = tgt_node_alloc(ISCSI_MODIFY_AUTHNAME, String,
			    ISCSI_AUTH_MODIFY);
			new_property(h, node);
			tgt_node_free(node);
			node = tgt_node_alloc(ISCSI_VALUE_AUTHNAME, String,
			    ISCSI_AUTH_VALUE);
			new_property(h, node);
			tgt_node_free(node);
			mgmt_transaction_end(h);
		} else {
			syslog(LOG_ERR, "Creating empty entry failed");
			ret = CONVERT_FAIL;
			goto done;
		}
		if (mgmt_transaction_start(h, "passwords", "application") ==
		    True) {
			node = tgt_node_alloc(ISCSI_READ_AUTHNAME, String,
			    ISCSI_AUTH_READ);
			new_property(h, node);
			tgt_node_free(node);
			node = tgt_node_alloc(ISCSI_MODIFY_AUTHNAME, String,
			    ISCSI_AUTH_MODIFY);
			new_property(h, node);
			tgt_node_free(node);
			node = tgt_node_alloc(ISCSI_VALUE_AUTHNAME, String,
			    ISCSI_AUTH_VALUE);
			new_property(h, node);
			tgt_node_free(node);
			mgmt_transaction_end(h);
		} else {
			syslog(LOG_ERR, "Creating empty entry failed");
			ret = CONVERT_FAIL;
		}
		goto done;
	}

	if ((xml_fd = open(config_file, O_RDONLY)) >= 0)
		r = (xmlTextReaderPtr)xmlReaderForFd(xml_fd, NULL, NULL, 0);

	if (r != NULL) {
		n = xmlTextReaderRead(r);
		while (n == 1) {
			if (tgt_node_process(r, &node) == False) {
				break;
			}
			n = xmlTextReaderRead(r);
		}
		if (n < 0) {
			syslog(LOG_ERR, "Parsing main config failed");
			ret = CONVERT_FAIL;
			goto done;
		}

		main_config = node;

		(void) tgt_find_value_str(node, XML_ELEMENT_BASEDIR,
		    &target_basedir);

		if (target_basedir == NULL)
			target_basedir = strdup(DEFAULT_TARGET_BASEDIR);

		/* Now convert targets' config if possible */
		if (xml_fd != -1)
			(void) close(xml_fd);
		xmlTextReaderClose(r);
		xmlFreeTextReader(r);
		xmlCleanupParser();
		r = NULL;
		xml_fd = -1;
		node = NULL;

		(void) snprintf(path, MAXPATHLEN, "%s/%s",
		    target_basedir, "config.xml");

		if ((xml_fd = open(path, O_RDONLY)) >= 0)
			r = (xmlTextReaderPtr)xmlReaderForFd(xml_fd,
			    NULL, NULL, 0);

		if (r != NULL) {
			n = xmlTextReaderRead(r);
			while (n == 1) {
				if (tgt_node_process(r, &node) == False) {
					break;
				}
				n = xmlTextReaderRead(r);
			}
			if (n < 0) {
				syslog(LOG_ERR, "Parsing target conf failed");
				ret = CONVERT_FAIL;
				goto done;
			}

			/* now combine main_config and node */
			if (node) {
				next = NULL;
				while ((next = tgt_node_next(node,
				    XML_ELEMENT_TARG, next)) != NULL) {
					tgt_node_add(main_config,
					    tgt_node_dup(next));
				}
				tgt_node_free(node);
			}

			if (mgmt_config_save2scf() != True) {
				syslog(LOG_ERR, "Converting config failed");
				if (xml_fd != -1)
					(void) close(xml_fd);
				xmlTextReaderClose(r);
				xmlFreeTextReader(r);
				xmlCleanupParser();
				ret = CONVERT_FAIL;
				goto done;
			}

			/* Copy files into backup dir */
			(void) snprintf(path, sizeof (path), "%s/backup",
			    target_basedir);
			if ((mkdir(path, 0755) == -1) && (errno != EEXIST)) {
				syslog(LOG_ERR, "Creating backup dir failed");
				ret = CONVERT_FAIL;
				goto done;
			}
			backup(config_file, NULL);
			(void) snprintf(path, MAXPATHLEN, "%s/%s",
			    target_basedir, "config.xml");
			backup(path, NULL);


			while ((next = tgt_node_next(main_config,
			    XML_ELEMENT_TARG, next)) != NULL) {
				if (tgt_find_value_str(next, XML_ELEMENT_INAME,
				    &target) == False) {
					continue;
				}
				(void) snprintf(path, MAXPATHLEN, "%s/%s",
				    target_basedir, target);
				if (mgmt_convert_param(path, next)
				    != True) {
					ret = CONVERT_FAIL;
					goto done;
				}
				free(target);
			}

			ret = CONVERT_OK;
			syslog(LOG_NOTICE, "Conversion succeeded");

			xmlTextReaderClose(r);
			xmlFreeTextReader(r);
			xmlCleanupParser();
		} else {
			syslog(LOG_ERR, "Reading targets config failed");
			ret = CONVERT_FAIL;
			goto done;
		}
	} else {
		syslog(LOG_ERR, "Reading main config failed");
		ret = CONVERT_FAIL;
		goto done;
	}

done:
	if (xml_fd != -1)
		(void) close(xml_fd);
	mgmt_handle_fini(h);
	return (ret);
}
Ejemplo n.º 13
0
static int ooxml_content_cb(int fd, cli_ctx *ctx)
{
    int ret = CL_SUCCESS, tmp, toval = 0, state;
    int core=0, extn=0, cust=0, dsig=0;
    int mcore=0, mextn=0, mcust=0;
    const xmlChar *name, *value, *CT, *PN;
    xmlTextReaderPtr reader = NULL;
    uint32_t loff;

    unsigned long sav_scansize = ctx->scansize;
    unsigned int sav_scannedfiles = ctx->scannedfiles;

    cli_dbgmsg("in ooxml_content_cb\n");

    /* perform engine limit checks in temporary tracking session */
    ret = ooxml_updatelimits(fd, ctx);
    if (ret != CL_CLEAN)
        return ret;

    /* apply a reader to the document */
    reader = xmlReaderForFd(fd, "[Content_Types].xml", NULL, CLAMAV_MIN_XMLREADER_FLAGS);
    if (reader == NULL) {
        cli_dbgmsg("ooxml_content_cb: xmlReaderForFd error for ""[Content_Types].xml""\n");
        cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_XML_READER_FD");

        ctx->scansize = sav_scansize;
        ctx->scannedfiles = sav_scannedfiles;
        return CL_SUCCESS; // libxml2 failed!
    }

    /* locate core-properties, extended-properties, and custom-properties (optional) */
    while ((state = xmlTextReaderRead(reader)) == 1) {
        if (cli_json_timeout_cycle_check(ctx, &toval) != CL_SUCCESS) {
            ret = CL_ETIMEOUT;
            goto ooxml_content_exit;
        }

        name = xmlTextReaderConstLocalName(reader);
        if (name == NULL) continue;

        if (strcmp((const char *)name, "Override")) continue;

        if (xmlTextReaderHasAttributes(reader) != 1) continue;

        CT = PN = NULL;
        while (xmlTextReaderMoveToNextAttribute(reader) == 1) {
            name = xmlTextReaderConstLocalName(reader);
            value = xmlTextReaderConstValue(reader);
            if (name == NULL || value == NULL) continue;

            if (!xmlStrcmp(name, (const xmlChar *)"ContentType")) {
                CT = value;
            }
            else if (!xmlStrcmp(name, (const xmlChar *)"PartName")) {
                PN = value;
            }

            cli_dbgmsg("%s: %s\n", name, value);
        }

        if (!CT && !PN) continue;

        if (!xmlStrcmp(CT, (const xmlChar *)"application/vnd.openxmlformats-package.core-properties+xml")) {
            /* default: /docProps/core.xml*/
            tmp = unzip_search_single(ctx, (const char *)(PN+1), xmlStrlen(PN)-1, &loff);
            if (tmp == CL_ETIMEOUT) {
                ret = tmp;
            }
            else if (tmp != CL_VIRUS) {
                cli_dbgmsg("cli_process_ooxml: failed to find core properties file \"%s\"!\n", PN);
                mcore++;
            }
            else {
                cli_dbgmsg("ooxml_content_cb: found core properties file \"%s\" @ %x\n", PN, loff);
                if (!core) {
                    tmp = unzip_single_internal(ctx, loff, ooxml_core_cb);
                    if (tmp == CL_ETIMEOUT || tmp == CL_EMEM) {
                        ret = tmp;
                    }
                }
                core++;
            }
        }
        else if (!xmlStrcmp(CT, (const xmlChar *)"application/vnd.openxmlformats-officedocument.extended-properties+xml")) {
            /* default: /docProps/app.xml */
            tmp = unzip_search_single(ctx, (const char *)(PN+1), xmlStrlen(PN)-1, &loff);
            if (tmp == CL_ETIMEOUT) {
                ret = tmp;
            }
            else if (tmp != CL_VIRUS) {
                cli_dbgmsg("cli_process_ooxml: failed to find extended properties file \"%s\"!\n", PN);
                mextn++;
            }
            else {
                cli_dbgmsg("ooxml_content_cb: found extended properties file \"%s\" @ %x\n", PN, loff);
                if (!extn) {
                    tmp = unzip_single_internal(ctx, loff, ooxml_extn_cb);
                    if (tmp == CL_ETIMEOUT || tmp == CL_EMEM) {
                        ret = tmp;
                    }
                }
                extn++;
            }
        }
        else if (!xmlStrcmp(CT, (const xmlChar *)"application/vnd.openxmlformats-officedocument.custom-properties+xml")) {
            /* default: /docProps/custom.xml */
            tmp = unzip_search_single(ctx, (const char *)(PN+1), xmlStrlen(PN)-1, &loff);
            if (tmp == CL_ETIMEOUT) {
                ret = tmp;
            }
            else if (tmp != CL_VIRUS) {
                cli_dbgmsg("cli_process_ooxml: failed to find custom properties file \"%s\"!\n", PN);
                mcust++;
            }
            else {
                cli_dbgmsg("ooxml_content_cb: found custom properties file \"%s\" @ %x\n", PN, loff);
                /* custom properties are not parsed */
                cust++;
            }
        }
        else if (!xmlStrcmp(CT, (const xmlChar *)"application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml")) {
            dsig++;
        }

        if (ret != CL_SUCCESS)
            goto ooxml_content_exit;
    }

 ooxml_content_exit:
    if (core) {
        cli_jsonint(ctx->wrkproperty, "CorePropertiesFileCount", core);
        if (core > 1)
            cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_MULTIPLE_CORE_PROPFILES");
    }
    else if (!mcore)
        cli_dbgmsg("cli_process_ooxml: file does not contain core properties file\n");
    if (mcore) {
        cli_jsonint(ctx->wrkproperty, "CorePropertiesMissingFileCount", mcore);
        cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_MISSING_CORE_PROPFILES");
    }

    if (extn) {
        cli_jsonint(ctx->wrkproperty, "ExtendedPropertiesFileCount", extn);
        if (extn > 1)
            cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_MULTIPLE_EXTN_PROPFILES");
    }
    else if (!mextn)
        cli_dbgmsg("cli_process_ooxml: file does not contain extended properties file\n");
    if (mextn) {
        cli_jsonint(ctx->wrkproperty, "ExtendedPropertiesMissingFileCount", mextn);
        cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_MISSING_EXTN_PROPFILES");
    }

    if (cust) {
        cli_jsonint(ctx->wrkproperty, "CustomPropertiesFileCount", cust);
        if (cust > 1)
            cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_MULTIPLE_CUSTOM_PROPFILES");
    }
    else if (!mcust)
        cli_dbgmsg("cli_process_ooxml: file does not contain custom properties file\n");
    if (mcust) {
        cli_jsonint(ctx->wrkproperty, "CustomPropertiesMissingFileCount", mcust);
        cli_json_parse_error(ctx->wrkproperty, "OOXML_ERROR_MISSING_CUST_PROPFILES");
    }

    if (dsig) {
        cli_jsonint(ctx->wrkproperty, "DigitalSignaturesCount", dsig);
    }

    /* restore the engine tracking limits; resets session limit tracking */
    ctx->scansize = sav_scansize;
    ctx->scannedfiles = sav_scannedfiles;

    xmlTextReaderClose(reader);
    xmlFreeTextReader(reader);
    return ret;
}
Ejemplo n.º 14
0
int openioc_parse(const char * fname, int fd, struct cl_engine *engine, unsigned int options)
{
    int rc;
    xmlTextReaderPtr reader = NULL;
    const xmlChar * name;
    struct openioc_hash * elems = NULL, * elem = NULL;
    const char * iocp = NULL;
    uint16_t ioclen;
    char * virusname;
    int hash_count = 0;
    
    if (fname == NULL)
        return CL_ENULLARG;

    if (fd < 0)
        return CL_EARG;

    cli_dbgmsg("openioc_parse: XML parsing file %s\n", fname);

    reader = xmlReaderForFd(fd, NULL, NULL, CLAMAV_MIN_XMLREADER_FLAGS);
    if (reader == NULL) {
        cli_dbgmsg("openioc_parse: xmlReaderForFd error\n");
        return CL_EOPEN;
    }
    rc = xmlTextReaderRead(reader);
    while (rc == 1) {
        name = xmlTextReaderConstLocalName(reader);
        cli_dbgmsg("openioc_parse: xmlTextReaderRead read %s\n", name);
        if (xmlStrEqual(name, (const xmlChar *)"Indicator") && 
            xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {
            rc = openioc_parse_indicator(reader, &elems);
            if (rc != CL_SUCCESS) {
                xmlTextReaderClose(reader);
                xmlFreeTextReader(reader);
                return rc;
            }
        }
        if (xmlStrEqual(name, (const xmlChar *)"ioc") &&
            xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {
            break;
        }
        rc = xmlTextReaderRead(reader);
    }

    iocp = strrchr(fname, *PATHSEP);

    if (NULL == iocp)
        iocp = fname;
    else
        iocp++;

    ioclen = strlen(fname);

    if (elems != NULL) {
        if (NULL == engine->hm_hdb) {
            engine->hm_hdb = mpool_calloc(engine->mempool, 1, sizeof(struct cli_matcher));
            if (NULL == engine->hm_hdb) {            
                xmlTextReaderClose(reader);
                xmlFreeTextReader(reader);
                return CL_EMEM;
            }
#ifdef USE_MPOOL
            engine->hm_hdb->mempool = engine->mempool;
#endif
        }
    }

    while (elems != NULL) {
        const char * sp;
        char * hash, * vp;
        int i, hashlen;

        elem = elems;
        elems = elems->next;
        hash = (char *)(elem->hash);
        while (isspace(*hash))
            hash++;
        hashlen = strlen(hash);
        if (hashlen == 0) {
            xmlFree(elem->hash);
            free(elem);
            continue;
        }
        vp = hash+hashlen-1;
        while (isspace(*vp) && vp > hash) {
            *vp-- = '\0';
            hashlen--;
        }
        virusname = calloc(1, ioclen+hashlen+2);
        if (NULL == virusname) {
            cli_dbgmsg("openioc_parse: mpool_malloc for virname memory failed.\n");
            xmlTextReaderClose(reader);
            xmlFreeTextReader(reader);
            return CL_EMEM;
        }
        sp = fname;
        vp = virusname;
        for (i=0; i<ioclen; i++, sp++, vp++) {
            switch (*sp) {
            case '\\':
            case '/':
            case '?':
            case '%':
            case '*':
            case ':':
            case '|':
            case '"':
            case '<':
            case '>':
                *vp = '_';
                break;
            default:
                if (isspace(*sp))
                    *vp = '_';
                else
                    *vp = *sp;
            }
        }
        *vp++ = '.';
        sp = hash;
        for (i=0; i<hashlen; i++, sp++) {
            if (isxdigit(*sp)) {
                *vp++ = *sp;
            }
        }

        vp = virusname;
        virusname = cli_mpool_virname(engine->mempool, virusname, options & CL_DB_OFFICIAL);
        if (!(virusname)) {
            cli_dbgmsg("openioc_parse: mpool_malloc for virname memory failed.\n");
            xmlTextReaderClose(reader);
            xmlFreeTextReader(reader);
            free(vp);
            return CL_EMEM;
        }

        free(vp);

        rc = hm_addhash_str(engine->hm_hdb, hash, 0, virusname);
        if (rc != CL_SUCCESS)
            cli_dbgmsg("openioc_parse: hm_addhash_str failed with %i hash len %i for %s.\n",
                       rc, hashlen, virusname);
        else
            hash_count++;

        xmlFree(elem->hash);
        free(elem);
    }

    if (hash_count == 0)
        cli_warnmsg("openioc_parse: No hash signatures extracted from %s.\n", fname);
    else
        cli_dbgmsg("openioc_parse: %i hash signature%s extracted from %s.\n",
                   hash_count, hash_count==1?"":"s", fname);

    xmlTextReaderClose(reader);
    xmlFreeTextReader(reader);

    return CL_SUCCESS;
}
Ejemplo n.º 15
0
int main( int argc, const char* argv[] )
{
#ifdef WIN32
     _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
    int ret=-1;
    time_t start_time=time(NULL);
    FILE *file=NULL;
    int writer_indent=0;
    pbool_t reader_mce=PTRUE;
    const char *fileName=NULL;
    for(int i=1;i<argc;i++) {
        if ((0==xmlStrcmp(_X("--understands"), _X(argv[i])) || 0==xmlStrcmp(_X("-u"), _X(argv[i]))) && i+1<argc) {
            i++; // skip namespace, registered later when parser was created.
        } else if ((0==xmlStrcmp(_X("--out"), _X(argv[i])) || 0==xmlStrcmp(_X("--out"), _X(argv[i]))) && i+1<argc && NULL==file) {
            const char *filename=argv[++i];
            file=fopen(filename, "w");
        } else if (0==xmlStrcmp(_X("--indent"), _X(argv[i]))) {
            writer_indent=1;
        } else if (0==xmlStrcmp(_X("--raw"), _X(argv[i]))) {
            reader_mce=PFALSE;
        } else if (NULL==fileName) {
            fileName=argv[i];
        } else {
            fprintf(stderr, "IGNORED: %s\n", argv[i]);
        }
    }
    xmlTextWriter *writer=xmlNewTextWriterFile(file);
    if (NULL==fileName || NULL==writer) {
        printf("mcepp [--understands NAMESPACE] [--out FILENAME] [--indent] [--raw] [FILENAME | - ]\n\n");
        printf("Sample: mcepp sample.xml\n");
    } else {
        xmlInitParser();
        xmlTextWriterSetIndent(writer, writer_indent);
        mceTextReader_t mceTextReader;
        mceTextReaderInit(&mceTextReader, ('-'==fileName[0] && 0==fileName[1]?xmlReaderForFd(0, NULL, NULL, 0):xmlReaderForFile(fileName, NULL, 0)));
        mceTextReaderDisableMCE(&mceTextReader, !reader_mce);
        for(int i=1;i<argc;i++) {
            if ((0==xmlStrcmp(_X("--understands"), _X(argv[i])) || 0==xmlStrcmp(_X("-u"), _X(argv[i]))) && i+1<argc) {
                const xmlChar *ns=_X(argv[++i]);
                mceTextReaderUnderstandsNamespace(&mceTextReader, ns);
            }
        }

        if (-1==mceTextReaderDump(&mceTextReader, writer, PFALSE)) {
            ret=mceTextReaderGetError(&mceTextReader);
        } else {
            ret=0;
        }
        mceTextReaderCleanup(&mceTextReader);
        xmlCleanupParser();
    }
    if (NULL!=writer) xmlFreeTextWriter(writer);
    if (NULL!=file) fclose(file);
    time_t end_time=time(NULL);
    fprintf(stderr, "time %.2lfsec\n", difftime(end_time, start_time));
#ifdef WIN32
    OPC_ASSERT(!_CrtDumpMemoryLeaks());
#endif
    return ret;
}
Ejemplo n.º 16
0
static int ooxml_content_cb(int fd, cli_ctx *ctx)
{
    int ret = CL_SUCCESS;
    int core=0, extn=0, cust=0, dsig=0;
    const xmlChar *name, *value, *CT, *PN;
    xmlTextReaderPtr reader = NULL;
    uint32_t loff;

    cli_dbgmsg("in ooxml_content_cb\n");

    reader = xmlReaderForFd(fd, "[Content_Types].xml", NULL, 0);
    if (reader == NULL) {
        cli_dbgmsg("ooxml_content_cb: xmlReaderForFd error for ""[Content_Types].xml""\n");
        return CL_SUCCESS; // libxml2 failed!
    }

    /* locate core-properties, extended-properties, and custom-properties (optional)  */
    while (xmlTextReaderRead(reader) == 1) {
        name = xmlTextReaderConstLocalName(reader);
        if (name == NULL) continue;

        if (strcmp(name, "Override")) continue;

        if (!xmlTextReaderHasAttributes(reader)) continue;

        CT = NULL; PN = NULL;
        while (xmlTextReaderMoveToNextAttribute(reader) == 1) {
            name = xmlTextReaderConstLocalName(reader);
            value = xmlTextReaderConstValue(reader);
            if (name == NULL || value == NULL) continue;

            if (!xmlStrcmp(name, "ContentType")) {
                CT = value;
            }
            else if (!xmlStrcmp(name, "PartName")) {
                PN = value;
            }

            cli_dbgmsg("%s: %s\n", name, value);
        }

        if (!CT && !PN) continue;

        if (!core && !xmlStrcmp(CT, "application/vnd.openxmlformats-package.core-properties+xml")) {
            /* default: /docProps/core.xml*/
            if (unzip_search(ctx, PN+1, xmlStrlen(PN)-1, &loff) != CL_VIRUS) {
                cli_dbgmsg("cli_process_ooxml: failed to find core properties file \"%s\"!\n", PN);
            }
            else {
                cli_dbgmsg("ooxml_content_cb: found core properties file \"%s\" @ %x\n", PN, loff);
                ret = unzip_single_internal(ctx, loff, ooxml_core_cb);
            }
            core = 1;
        }
        else if (!extn && !xmlStrcmp(CT, "application/vnd.openxmlformats-officedocument.extended-properties+xml")) {
            /* default: /docProps/app.xml */
            if (unzip_search(ctx, PN+1, xmlStrlen(PN)-1, &loff) != CL_VIRUS) {
                cli_dbgmsg("cli_process_ooxml: failed to find extended properties file \"%s\"!\n", PN);
            }
            else {
                cli_dbgmsg("ooxml_content_cb: found extended properties file \"%s\" @ %x\n", PN, loff);
                ret = unzip_single_internal(ctx, loff, ooxml_extn_cb);
            }
            extn = 1;
        }
        else if (!cust && !xmlStrcmp(CT, "application/vnd.openxmlformats-officedocument.custom-properties+xml")) {
            /* default: /docProps/custom.xml */
            if (unzip_search(ctx, PN+1, xmlStrlen(PN)-1, &loff) != CL_VIRUS) {
                cli_dbgmsg("cli_process_ooxml: failed to find custom properties file \"%s\"!\n", PN);
            }
            else {
                cli_dbgmsg("ooxml_content_cb: found custom properties file \"%s\" @ %x\n", PN, loff);
                /* custom properties ignored for now */
                cli_jsonbool(ctx->wrkproperty, "CustomProperties", 1);
                //ret = unzip_single_internal(ctx, loff, ooxml_cust_cb);
            }
            cust = 1;
        }
        else if (!dsig && !xmlStrcmp(CT, "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml")) {
            if (unzip_search(ctx, PN+1, xmlStrlen(PN)-1, &loff) != CL_VIRUS) {
                cli_dbgmsg("cli_process_ooxml: failed to find digital signature file \"%s\"!\n", PN);
            }
            else {
                cli_dbgmsg("ooxml_content_cb: found digital signature file \"%s\" @ %x\n", PN, loff);
                /* digital signatures ignored for now */
                cli_jsonbool(ctx->wrkproperty, "DigitalSignatures", 1);
                //ret = unzip_single_internal(ctx, loff, ooxml_dsig_cb);
            }
            dsig = 1;
        }

        if (ret != CL_SUCCESS)
            goto ooxml_content_exit;
    }

    if (!core) {
        cli_dbgmsg("cli_process_ooxml: file does not contain core properties file\n");
    }
    if (!extn) {
        cli_dbgmsg("cli_process_ooxml: file does not contain extended properties file\n");
    }
    if (!cust) {
        cli_dbgmsg("cli_process_ooxml: file does not contain custom properties file\n");
    }

 ooxml_content_exit:
    xmlTextReaderClose(reader);
    xmlFreeTextReader(reader);
    return ret;
}
Ejemplo n.º 17
0
static int ooxml_basic_json(int fd, cli_ctx *ctx, const char *key)
{
    int ret = CL_SUCCESS;
    const xmlChar *stack[OOXML_JSON_RECLEVEL];
    json_object *summary, *wrkptr;
    int type, rlvl = 0;
    int32_t val2;
    const xmlChar *name, *value;
    xmlTextReaderPtr reader = NULL;

    cli_dbgmsg("in ooxml_basic_json\n");

    reader = xmlReaderForFd(fd, "properties.xml", NULL, 0);
    if (reader == NULL) {
        cli_dbgmsg("ooxml_basic_json: xmlReaderForFd error for %s\n", key);
        return CL_SUCCESS; // libxml2 failed!
    }

    summary = json_object_new_object();
    if (NULL == summary) {
        cli_errmsg("ooxml_basic_json: no memory for json object.\n");
        ret = CL_EFORMAT;
        goto ooxml_basic_exit;
    }

    while (xmlTextReaderRead(reader) == 1) {
        name = xmlTextReaderConstLocalName(reader);
        value = xmlTextReaderConstValue(reader);
        type = xmlTextReaderNodeType(reader);

        cli_dbgmsg("%s [%i]: %s\n", name, type, value);

        switch (type) {
        case XML_READER_TYPE_ELEMENT:
            stack[rlvl] = name;
            rlvl++;
            break;
        case XML_READER_TYPE_TEXT:
            {
                wrkptr = summary;
                if (rlvl > 2) { /* 0 is root xml object */
                    int i;
                    for (i = 1; i < rlvl-1; ++i) {
                        json_object *newptr = json_object_object_get(wrkptr, stack[i]);
                        if (!newptr) {
                            newptr = json_object_new_object();
                            if (NULL == newptr) {
                                cli_errmsg("ooxml_basic_json: no memory for json object.\n");
                                ret = CL_EMEM;
                                goto ooxml_basic_exit;
                            }
                            json_object_object_add(wrkptr, stack[i], newptr);
                        }
                        else {
                            /* object already exists */
                            if (!json_object_is_type(newptr, json_type_object)) {
                                cli_warnmsg("ooxml_content_cb: json object already exists as not an object\n");
                                ret = CL_EFORMAT;
                                goto ooxml_basic_exit;
                            } 
                        }
                        wrkptr = newptr;
                        cli_dbgmsg("stack %d: %s\n", i, stack[i]);
                    }
                }
                
                if (ooxml_is_int(value, xmlStrlen(value), &val2)) {
                    ret = cli_jsonint(wrkptr, stack[rlvl-1], val2);
                }
                else if (!xmlStrcmp(value, "true")) {
                    ret = cli_jsonbool(wrkptr, stack[rlvl-1], 1);
                }
                else if (!xmlStrcmp(value, "false")) {
                    ret = cli_jsonbool(wrkptr, stack[rlvl-1], 0);
                }
                else {
                    ret = cli_jsonstr(wrkptr, stack[rlvl-1], value);
                }

                if (ret != CL_SUCCESS)
                    goto ooxml_basic_exit;
            }
            break;
        case XML_READER_TYPE_END_ELEMENT:
            rlvl--;
            break;
        default:
            cli_dbgmsg("ooxml_content_cb: unhandled xml node %s [%i]: %s\n", name, type, value);
            ret = CL_EFORMAT;
            goto ooxml_basic_exit;
        }
    }

    json_object_object_add(ctx->wrkproperty, key, summary);

    if (rlvl != 0) {
        cli_warnmsg("ooxml_basic_json: office property file has unbalanced tags\n");
        /* FAIL */
    }

 ooxml_basic_exit:
    xmlTextReaderClose(reader);
    xmlFreeTextReader(reader);
    return ret;
}
Ejemplo n.º 18
0
static void
target_info(char **msg, char *targ_name, xml_node_t *tnode)
{
	char			path[MAXPATHLEN],
				lun_buf[16],
				*prop;
	xmlTextReaderPtr	r;
	xml_node_t		*lnode,	/* list node */
				*lnp, /* list node pointer */
				*lun,
				*params;
	int			xml_fd,
				lun_num;

	if ((lnode = xml_node_next(tnode, XML_ELEMENT_ACLLIST, NULL)) !=
	    NULL) {
		lnp = NULL;
		buf_add_tag(msg, XML_ELEMENT_ACLLIST, Tag_Start);
		while ((lnp = xml_node_next(lnode, XML_ELEMENT_INIT, lnp)) !=
		    NULL)
			xml_add_tag(msg, XML_ELEMENT_INIT, lnp->x_value);
		buf_add_tag(msg, XML_ELEMENT_ACLLIST, Tag_End);
	}

	if ((lnode = xml_node_next(tnode, XML_ELEMENT_TPGTLIST, NULL)) !=
	    NULL) {
		lnp = NULL;
		buf_add_tag(msg, XML_ELEMENT_TPGTLIST, Tag_Start);
		while ((lnp = xml_node_next(lnode, XML_ELEMENT_TPGT, lnp)) !=
		    NULL)
			xml_add_tag(msg, XML_ELEMENT_TPGT, lnp->x_value);
		buf_add_tag(msg, XML_ELEMENT_TPGTLIST, Tag_End);
	}

	if ((lnode = xml_node_next(tnode, XML_ELEMENT_ALIAS, NULL)) != NULL)
		xml_add_tag(msg, XML_ELEMENT_ALIAS, lnode->x_value);

	if ((lnode = xml_node_next(tnode, XML_ELEMENT_MAXRECV, NULL)) != NULL)
		xml_add_tag(msg, XML_ELEMENT_MAXRECV, lnode->x_value);

	if ((lnode = xml_node_next(tnode, XML_ELEMENT_LUNLIST, NULL)) == NULL)
		return;

	buf_add_tag(msg, XML_ELEMENT_LUNINFO, Tag_Start);
	lun = NULL;
	while ((lun = xml_node_next(lnode, XML_ELEMENT_LUN, lun)) != NULL) {
		if ((xml_find_value_int(lun, XML_ELEMENT_LUN, &lun_num)) ==
		    False)
			continue;
		(void) snprintf(path, sizeof (path), "%s/%s/%s%d",
		    target_basedir, targ_name, PARAMBASE, lun_num);
		if ((xml_fd = open(path, O_RDONLY)) < 0)
			continue;
		if ((r = (xmlTextReaderPtr)xmlReaderForFd(xml_fd,
		    NULL, NULL, 0)) == NULL)
			continue;

		params = NULL;
		while (xmlTextReaderRead(r) == 1) {
			if (xml_process_node(r, &params) == False)
				break;
		}
		(void) close(xml_fd);
		xmlTextReaderClose(r);
		xmlFreeTextReader(r);

		buf_add_tag(msg, XML_ELEMENT_LUN, Tag_Start);
		snprintf(lun_buf, sizeof (lun_buf), "%d", lun_num);
		buf_add_tag(msg, lun_buf, Tag_String);

		if (xml_find_value_str(params, XML_ELEMENT_GUID, &prop) ==
		    True) {
			xml_add_tag(msg, XML_ELEMENT_GUID, prop);
			free(prop);
		}
		if (xml_find_value_str(params, XML_ELEMENT_VID, &prop) ==
		    True) {
			xml_add_tag(msg, XML_ELEMENT_VID, prop);
			free(prop);
		}
		if (xml_find_value_str(params, XML_ELEMENT_PID, &prop) ==
		    True) {
			xml_add_tag(msg, XML_ELEMENT_PID, prop);
			free(prop);
		}
		if (xml_find_value_str(params, XML_ELEMENT_DTYPE, &prop) ==
		    True) {
			xml_add_tag(msg, XML_ELEMENT_DTYPE, prop);
			free(prop);
		}
		if (xml_find_value_str(params, XML_ELEMENT_SIZE, &prop) ==
		    True) {
			xml_add_tag(msg, XML_ELEMENT_SIZE, prop);
			free(prop);
		}
		if (xml_find_value_str(params, XML_ELEMENT_STATUS, &prop) ==
		    True) {
			xml_add_tag(msg, XML_ELEMENT_STATUS, prop);
			free(prop);
		}
		if (xml_find_value_str(params, XML_ELEMENT_BACK, &prop) ==
		    True) {
			xml_add_tag(msg, XML_ELEMENT_BACK, prop);
			free(prop);
		}
		buf_add_tag(msg, XML_ELEMENT_LUN, Tag_End);

		xml_tree_free(params);
	}
	buf_add_tag(msg, XML_ELEMENT_LUNINFO, Tag_End);
}
Ejemplo n.º 19
0
Archivo: mgmt_scf.c Proyecto: imp/slist
/*
 * Convert legacy (XML) configuration files into an equivalent SCF
 * representation.
 *
 * Read the XML from disk, translate the XML into a tree of nodes of
 * type tgt_node_t, and write the in-memory tree to SCF's persistent
 * data-store using mgmt_config_save2scf().
 *
 * Return Values:
 * CONVERT_OK:	     successfully converted
 * CONVERT_INIT_NEW: configuration files don't exist; created an SCF entry
 * CONVERT_FAIL: some conversion error occurred; no SCF entry created.
 *		 In this case, user has to manually check files and try
 *		 conversion again.
 */
convert_ret_t
mgmt_convert_conf()
{
	targ_scf_t		*h = NULL;
	xmlTextReaderPtr	r;
	convert_ret_t		ret = CONVERT_FAIL;
	int			xml_fd = -1;
	int			n;
	tgt_node_t		*node = NULL;
	tgt_node_t		*next = NULL;
	char			path[MAXPATHLEN];
	char			*target = NULL;

	h = mgmt_handle_init();
	if (h == NULL)
		return (CONVERT_FAIL);

	/*
	 * Check if the "iscsitgt" PropertyGroup has already been added
	 * to the "iscsitgt" SMF Service.  If so, then we have already
	 * converted the legacy configuration files (and there is no work
	 * to do).
	 */
	if (scf_service_get_pg(h->t_service, "iscsitgt", h->t_pg) == 0) {
		ret = CONVERT_OK;
		goto done;
	}

	if (access(config_file, R_OK) != 0) {
		/*
		 * then the Main Config file is not present; initialize
		 * SCF Properties to default values.
		 */
		if (mgmt_transaction_start(h, "iscsitgt", "basic") == True) {
			ret = CONVERT_INIT_NEW;

			node = tgt_node_alloc(XML_ELEMENT_VERS, String, "1.0");
			new_property(h, node);
			tgt_node_free(node);
			/* "daemonize" is set to true by default */
			node = tgt_node_alloc(XML_ELEMENT_DBGDAEMON, String,
			    "true");
			new_property(h, node);
			tgt_node_free(node);
			node = NULL;
			node = tgt_node_alloc(ISCSI_MODIFY_AUTHNAME, String,
			    ISCSI_AUTH_MODIFY);
			new_property(h, node);
			tgt_node_free(node);
			node = tgt_node_alloc(ISCSI_VALUE_AUTHNAME, String,
			    ISCSI_AUTH_VALUE);
			new_property(h, node);
			tgt_node_free(node);
			(void) mgmt_transaction_end(h);
		} else {
			syslog(LOG_ERR, "Creating empty entry failed");
			ret = CONVERT_FAIL;
			goto done;
		}
		if (mgmt_transaction_start(h, "passwords", "application") ==
		    True) {
			node = tgt_node_alloc(ISCSI_READ_AUTHNAME, String,
			    ISCSI_AUTH_READ);
			new_property(h, node);
			tgt_node_free(node);
			node = tgt_node_alloc(ISCSI_MODIFY_AUTHNAME, String,
			    ISCSI_AUTH_MODIFY);
			new_property(h, node);
			tgt_node_free(node);
			node = tgt_node_alloc(ISCSI_VALUE_AUTHNAME, String,
			    ISCSI_AUTH_VALUE);
			new_property(h, node);
			tgt_node_free(node);
			(void) mgmt_transaction_end(h);
		} else {
			syslog(LOG_ERR, "Creating empty entry failed");
			ret = CONVERT_FAIL;
		}
		goto done;
	}

	if ((xml_fd = open(config_file, O_RDONLY)) >= 0)
		r = (xmlTextReaderPtr)xmlReaderForFd(xml_fd, NULL, NULL, 0);

	if (r != NULL) {
		int is_target_config;

		n = xmlTextReaderRead(r);
		while (n == 1) {
			if (tgt_node_process(r, &node) == False) {
				break;
			}
			n = xmlTextReaderRead(r);
		}
		if (n < 0) {
			syslog(LOG_ERR, "Parsing main config failed");
			ret = CONVERT_FAIL;
			goto done;
		}

		main_config = node;

		/*
		 * Initialize the Base Directory (global) variable by
		 * using the value specified in the XML_ELEMENT_BASEDIR
		 * XML tag.  If a tag is not specified, use a default.
		 */
		(void) tgt_find_value_str(node, XML_ELEMENT_BASEDIR,
		    &target_basedir);

		if (target_basedir == NULL)
			target_basedir = strdup(DEFAULT_TARGET_BASEDIR);

		if (xml_fd != -1) {
			(void) close(xml_fd);
			xml_fd = -1;
		}
		(void) xmlTextReaderClose(r);
		xmlFreeTextReader(r);
		xmlCleanupParser();

		/*
		 * If a Target Config file is present, read and translate
		 * its XML representation into a tree of tgt_node_t.
		 * Merge that tree with the tree of tgt_node_t rooted at
		 * 'main_config'.  The merged tree will then be archived
		 * using an SCF representation.
		 */
		(void) snprintf(path, MAXPATHLEN, "%s/%s",
		    target_basedir, "config.xml");

		if ((xml_fd = open(path, O_RDONLY)) >= 0) {
			is_target_config = 1;
			r = (xmlTextReaderPtr)xmlReaderForFd(xml_fd,
			    NULL, NULL, 0);
		} else {
			is_target_config = 0;
			r = NULL;
		}

		if (r != NULL) {
			/* then the Target Config file is available. */

			node = NULL;

			/*
			 * Create a tree of tgt_node_t rooted at 'node' by
			 * processing each XML Tag in the file.
			 */
			n = xmlTextReaderRead(r);
			while (n == 1) {
				if (tgt_node_process(r, &node) == False) {
					break;
				}
				n = xmlTextReaderRead(r);
			}
			if (n < 0) {
				syslog(LOG_ERR, "Parsing target conf failed");
				ret = CONVERT_FAIL;
				goto done;
			}

			/*
			 * Merge the tree at 'node' into the tree rooted at
			 * 'main_config'.
			 */
			if (node != NULL) {
				next = NULL;
				while ((next = tgt_node_next(node,
				    XML_ELEMENT_TARG, next)) != NULL) {
					tgt_node_add(main_config,
					    tgt_node_dup(next));
				}
				tgt_node_free(node);
			}
		}

		/*
		 * Iterate over the in-memory tree rooted at 'main_config'
		 * and write a representation of the appropriate nodes to
		 * SCF's persistent data-store.
		 */
		if (mgmt_config_save2scf() != True) {
			syslog(LOG_ERR, "Converting config failed");
			if (xml_fd != -1) {
				(void) close(xml_fd);
				xml_fd = -1;
			}
			(void) xmlTextReaderClose(r);
			xmlFreeTextReader(r);
			xmlCleanupParser();
			ret = CONVERT_FAIL;
			goto done;
		}

		/*
		 * Move the configuration files into a well-known backup
		 * directory.  This allows a user to restore their
		 * configuration, if they choose.
		 */
		(void) snprintf(path, sizeof (path), "%s/backup",
		    target_basedir);
		if ((mkdir(path, 0755) == -1) && (errno != EEXIST)) {
			syslog(LOG_ERR, "Creating backup dir failed");
			ret = CONVERT_FAIL;
			goto done;
		}
		/* Save the Main Config file. */
		backup(config_file, NULL);

		/* Save the Target Config file, if it was present. */
		if (is_target_config != 0) {
			(void) snprintf(path, MAXPATHLEN, "%s/%s",
			    target_basedir, "config.xml");
			backup(path, NULL);
		}

		/*
		 * For each tgt_node_t node in 'main_config' whose value is
		 * an iSCSI Name as defined in the RFC (3720) standard (eg,
		 * "iqn.1986..."), read its XML-encoded attributes from a
		 * flat-file and write an equivalent representation to SCF's
		 * data-store.
		 */
		while ((next = tgt_node_next(main_config,
		    XML_ELEMENT_TARG, next)) != NULL) {
			if (tgt_find_value_str(next, XML_ELEMENT_INAME,
			    &target) == False) {
				continue;
			}
			(void) snprintf(path, MAXPATHLEN, "%s/%s",
			    target_basedir, target);
			if (mgmt_convert_param(path, next)
			    != True) {
				ret = CONVERT_FAIL;
				goto done;
			}
			free(target);
		}

		ret = CONVERT_OK;
		syslog(LOG_NOTICE, "Conversion succeeded");

		(void) xmlTextReaderClose(r);
		xmlFreeTextReader(r);
		xmlCleanupParser();
	} else {
		syslog(LOG_ERR, "Reading main config failed");
		ret = CONVERT_FAIL;
		goto done;
	}

done:
	if (xml_fd != -1)
		(void) close(xml_fd);
	mgmt_handle_fini(h);
	return (ret);
}