Exemple #1
0
/**
 * Copies file from source <code>srcPath</code> to destination <code>destPath</code>.
 *
 * @param srcPath source full file path.
 * @param destPath destination full file path.
 * @param overwrite whether to overwrite existing file.
 * @throws IOException exception is thrown if overwrite flag is set to false and destination file already exists.
 *         Or the file copy operation failed.
 */
void digidoc::util::File::copyFile(const std::string& srcPath, const std::string& destPath, bool overwrite) throw(IOException)
{
    if(!fileExists(srcPath))
    {
        THROW_IOEXCEPTION("Source file '%s' does not exist.", srcPath.c_str());
    }

    if(!overwrite && fileExists(destPath))
    {
        THROW_IOEXCEPTION("Destination file exists '%s' can not copy to there. Overwrite flag is set to false.", destPath.c_str());
    }

    // Copy file.
    std::ifstream ifs(encodeName(srcPath).c_str(), std::ios::binary);
    std::ofstream ofs(encodeName(destPath).c_str(), std::ios::binary | std::ios::trunc);

    ofs << ifs.rdbuf();

    ifs.close();
    ofs.close();

    if(ifs.fail() || ofs.fail())
    {
        THROW_IOEXCEPTION("Failed to copy file '%s' to '%s'.", srcPath.c_str(), destPath.c_str());
    }
}
Exemple #2
0
/**
 * Moves file from source <code>srcPath</code> to destination <code>destPath</code>.
 *
 * @param srcPath source full file path.
 * @param destPath destination full file path.
 * @param overwrite whether to overwrite existing file.
 * @throws IOException exception is thrown if overwrite flag is set to false and destination file already exists.
 *         Or the file move operation failed.
 */
void digidoc::util::File::moveFile(const std::string& srcPath, const std::string& destPath, bool overwrite) throw(IOException)
{
    if(!fileExists(srcPath))
    {
        THROW_IOEXCEPTION("Source file '%s' does not exist.", srcPath.c_str());
    }

    if(!overwrite && fileExists(destPath))
    {
        THROW_IOEXCEPTION("Destination file exists '%s' can not move to there. Overwrite flag is set to false.", destPath.c_str());
    }

    f_string _srcPath = encodeName(srcPath);
    f_string _destPath = encodeName(destPath);
    int result = f_rename(_srcPath.c_str(), _destPath.c_str());
    if ( result != 0 )
    {
		// -=K=-: copy and remove source should work as move between different partitions
		copyFile( srcPath, destPath, overwrite );
        result = f_remove( _srcPath.c_str() );
    }
	if ( result != 0 )
	{
		// -=K=-: suceeded to copy, failed to remove. Should we throw or warn?
		WARN( "Failed to remove source file '%s' when moving it to '%s'.", _srcPath.c_str(), _destPath.c_str() );
	}

}
Exemple #3
0
/**
 * Returns last modified time
 *
 * @param path path which modified time will be checked.
 * @return returns given path modified time.
 */
tm* digidoc::util::File::modifiedTime(const std::string &path)
{
    f_string _path = encodeName(path);
    f_statbuf fileInfo;
    f_stat(_path.c_str(), &fileInfo);
    return gmtime(&fileInfo.st_mtime);
}
void QtServiceBase::logMessage(const QString &message, QtServiceBase::MessageType type,
			    int, uint, const QByteArray &)
{
    if (!d_ptr->sysd)
        return;
    int st;
    switch(type) {
        case QtServiceBase::Error:
	    st = LOG_ERR;
	    break;
        case QtServiceBase::Warning:
            st = LOG_WARNING;
	    break;
        default:
	    st = LOG_INFO;
    }
    if (!d_ptr->sysd->ident) {
	QString tmp = encodeName(serviceName(), TRUE);
	int len = tmp.toLocal8Bit().size();
	d_ptr->sysd->ident = new char[len+1];
	d_ptr->sysd->ident[len] = '\0';
	::memcpy(d_ptr->sysd->ident, tmp.toLocal8Bit().constData(), len);
    }
    openlog(d_ptr->sysd->ident, LOG_PID, LOG_DAEMON);
    foreach(QString line, message.split('\n'))
        syslog(st, "%s", line.toLocal8Bit().constData());
    closelog();
}
Exemple #5
0
/**
 * Deletes the directory named <code>dname</code>. The directory must be empty.
 *
 * @param fname full file or directory fname.
 */
void digidoc::util::File::removeDirectory(const std::string& dname)
{
    f_string _dname = encodeName(dname);
#ifdef _WIN32
    if (!RemoveDirectoryW(_dname.c_str()))
#else
    if (remove( _dname.c_str() ) != 0)
#endif
		WARN( "Tried to remove the temporary directory '%s', but failed.", _dname.c_str() );
}
Exemple #6
0
std::string digidoc::util::File::env(const std::string &varname)
{
    f_string _varname = encodeName( varname );
#ifdef _WIN32
    if( wchar_t *var = _wgetenv( _varname.c_str() ) )
#else
    if( char *var = getenv( _varname.c_str() ) )
#endif
        return decodeName( var );
    return std::string();
}
Exemple #7
0
/**
 * Checks whether file exists and is type of file.
 *
 * @param path path to the file, which existence is checked.
 * @return returns true if the file is a file and it exists.
 */
bool digidoc::util::File::fileExists(const std::string& path)
{
    f_statbuf fileInfo;
    f_string _path = encodeName(path);
    if(f_stat(_path.c_str(), &fileInfo) != 0)
        return false;

    // XXX: != S_IFREG
    if((fileInfo.st_mode & S_IFMT) == S_IFDIR)
        return false;

    return true;
}
Exemple #8
0
/**
 * Returns true if the path is relative
 *
 * @return returns true if the path is relative
 */
bool digidoc::util::File::isRelative(const std::string &path)
{
    f_string _path = encodeName(path);
    if( _path.length() == 0 ) return true;
    if( _path[0] == '/' ) return false;
#ifdef _WIN32
    // drive, e.g. "a:", or UNC root, e.q. "//"
    if( _path.length() >= 2 &&
        ((iswalpha(_path[0]) && _path[1] == ':') ||
         (_path[0] == '/' && _path[1] == '/')) )
        return false;
#endif
    return true;
}
Exemple #9
0
/**
 * Checks that file is a file and it exists, if the file exists returns its size in bytes.
 *
 * @param path full path of the file.
 * @return size of the file in bytes.
 * @throws IOException throws exception if the file does not exists.
 */
unsigned long digidoc::util::File::fileSize(const std::string& path) throw(IOException)
{
    f_statbuf fileInfo;
    f_string _path = encodeName(path);
    if(f_stat(_path.c_str(), &fileInfo) != 0)
        THROW_IOEXCEPTION("File '%s' does not exist.", _path.c_str());

    if((fileInfo.st_mode & S_IFMT) == S_IFDIR)
        THROW_IOEXCEPTION("'%s' is not a file.", _path.c_str());

    if (fileInfo.st_size < 0)
        THROW_IOEXCEPTION("Failed to get size for file '%s'.", _path.c_str());

    return static_cast<unsigned long>(fileInfo.st_size);
}
Exemple #10
0
/**
 * Creates directory recursively. Also access rights can be omitted. Defaults are 700 in unix.
 *
 * @param path full path of the directory created.
 * @param mode directory access rights, optional parameter, default value 0700 (owner: rwx, group: ---, others: ---)
 * @throws IOException exception is thrown if the directory creation failed.
 */
void digidoc::util::File::createDirectory(const std::string& path) throw(IOException)
{
    if(path.empty())
    {
        THROW_IOEXCEPTION("Can not create directory with no name.");
    }

    if(directoryExists(path))
    {
        return;
    }

    std::string parentDir(path);
    if(parentDir[parentDir.size() - 1] == '/' || parentDir[parentDir.size() - 1] == '\\')
    {
        parentDir = parentDir.substr(0, parentDir.size() - 1);
    }
    parentDir = parentDir.substr(0, parentDir.find_last_of("/\\"));

    if(!directoryExists(parentDir))
    {
        createDirectory(parentDir);
    }

    f_string _path = encodeName(path);
#ifdef _WIN32
    int result = _wmkdir(_path.c_str());
    if ( result )
        DEBUG("Creating directory '%s' failed with errno = %d", _path.c_str(), errno);
    else
        DEBUG("Created directory '%s'", _path.c_str());
#else
    umask(0);
    int result = mkdir(_path.c_str(), 0700);
    DEBUG("Created directory '%s' with result = %d", _path.c_str(), result);
#endif

    if(result || !directoryExists(path))
    {
        THROW_IOEXCEPTION("Failed to create directory '%s'", path.c_str());
    }
}
Exemple #11
0
/**
 * Checks whether directory exists and is type of directory.
 *
 * @param path path to the directory, which existence is checked.
 * @return returns true if the directory is a directory and it exists.
 */
bool digidoc::util::File::directoryExists(const std::string& path)
{
    f_string _path = encodeName(path);
#ifdef _WIN32
    // stat will fail on win32 if path ends with backslash
    if(!_path.empty() && (_path[_path.size() - 1] == L'/' || _path[_path.size() - 1] == L'\\'))
        _path = _path.substr(0, _path.size() - 1);
    // TODO:XXX: "C:" is not a directory, so create recursively will
    // do stack overflow in case first-dir in root doesn't exist.
#endif

    f_statbuf fileInfo;
    if(f_stat(_path.c_str(), &fileInfo) != 0)
        return false;

    if((fileInfo.st_mode & S_IFMT) != S_IFDIR)
        return false;

    return true;
}
Exemple #12
0
bool IDnsResource::setName(const std::string& newName)
{
	char encodedName[256];
	size_t encodedNameLen = 0;
	encodeName(newName, encodedName, encodedNameLen);
	if (m_DnsLayer != NULL)
	{
		if (encodedNameLen > m_NameLength)
		{
			if (!m_DnsLayer->extendLayer(m_OffsetInLayer, encodedNameLen-m_NameLength, this))
			{
				LOG_ERROR("Couldn't set name for DNS query, unable to extend layer");
				return false;
			}
		}
		else if (encodedNameLen < m_NameLength)
		{
			if (!m_DnsLayer->shortenLayer(m_OffsetInLayer, m_NameLength-encodedNameLen, this))
			{
				LOG_ERROR("Couldn't set name for DNS query, unable to shorten layer");
				return false;
			}
		}
	}
	else
	{
		char tempData[getSize()];
		memcpy(tempData, m_ExternalRawData, getSize());
		memcpy(m_ExternalRawData + encodedNameLen, tempData, getSize());
	}

	memcpy(getRawData(), encodedName, encodedNameLen);
	m_NameLength = encodedNameLen;
	m_DecodedName = newName;

	return true;
}
Exemple #13
0
string NameIO::decodeName(const string &name) const {
  return getReverseEncryption() ? encodeName(name, nullptr)
                                : decodeName(name, nullptr);
}
static QString socketPath(const QString &serviceName)
{
    QString sn = encodeName(serviceName);
    return QString(QLatin1String("/var/tmp/") + sn + QLatin1String(".") + login());
}
Exemple #15
0
static boolean_t
updateConfiguration(int *newState)
{
	boolean_t		changed			= FALSE;
	CFStringRef		computerName;
	CFStringEncoding	computerNameEncoding;
	CFArrayRef		configuredServices	= NULL;
	CFDictionaryRef		dict;
	CFIndex			i;
	CFIndex			ifCount			= 0;
	CFMutableArrayRef	info			= NULL;
	CFArrayRef		interfaces		= NULL;
	CFStringRef		key;
	CFArrayRef		keys;
	CFIndex			n;
	CFMutableArrayRef	newConfigFile;
	CFMutableDictionaryRef	newDefaults;
	CFMutableDictionaryRef	newDict;
	CFMutableDictionaryRef	newGlobals;
	CFMutableDictionaryRef	newGlobalsX;			/* newGlobals without ServiceID */
	CFMutableDictionaryRef	newStartup;
	CFMutableDictionaryRef	newZones;
	CFNumberRef		num;
	CFMutableDictionaryRef	curGlobalsX;			/* curGlobals without ServiceID */
	CFStringRef		pattern;
	boolean_t		postGlobals		= FALSE;
	CFStringRef		primaryPort		= NULL;	/* primary interface */
	CFStringRef		primaryZone		= NULL;
	CFArrayRef		serviceOrder		= NULL;
	CFDictionaryRef		setGlobals		= NULL;

	cache_open();

	/*
	 * establish the "new" AppleTalk configuration
	 */
	*newState     = curState;
	newConfigFile = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
	newGlobals    = CFDictionaryCreateMutable(NULL,
						  0,
						  &kCFTypeDictionaryKeyCallBacks,
						  &kCFTypeDictionaryValueCallBacks);
	newDefaults   = CFDictionaryCreateMutable(NULL,
						  0,
						  &kCFTypeDictionaryKeyCallBacks,
						  &kCFTypeDictionaryValueCallBacks);
	newStartup    = CFDictionaryCreateMutable(NULL,
						  0,
						  &kCFTypeDictionaryKeyCallBacks,
						  &kCFTypeDictionaryValueCallBacks);
	newZones      = CFDictionaryCreateMutable(NULL,
						  0,
						  &kCFTypeDictionaryKeyCallBacks,
						  &kCFTypeDictionaryValueCallBacks);

	/* initialize overall state */
	CFDictionarySetValue(newStartup, CFSTR("APPLETALK"), CFSTR("-NO-"));

	/*
	 * get the global settings (ServiceOrder, ComputerName, ...)
	 */
	key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
							 kSCDynamicStoreDomainSetup,
							 kSCEntNetAppleTalk);
	setGlobals = cache_SCDynamicStoreCopyValue(store, key);
	CFRelease(key);
	if (setGlobals) {
		if (isA_CFDictionary(setGlobals)) {
			/* get service order */
			serviceOrder = CFDictionaryGetValue(setGlobals,
							    kSCPropNetServiceOrder);
			serviceOrder = isA_CFArray(serviceOrder);
			if (serviceOrder) {
				CFRetain(serviceOrder);
			}
		} else {
			CFRelease(setGlobals);
			setGlobals = NULL;
		}
	}

	/*
	 * if we don't have an AppleTalk ServiceOrder, use IPv4's (if defined)
	 */
	if (!serviceOrder) {
		key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
								 kSCDynamicStoreDomainSetup,
								 kSCEntNetIPv4);
		dict = cache_SCDynamicStoreCopyValue(store, key);
		CFRelease(key);
		if (dict) {
			if (isA_CFDictionary(dict)) {
				serviceOrder = CFDictionaryGetValue(dict,
								    kSCPropNetServiceOrder);
				serviceOrder = isA_CFArray(serviceOrder);
				if (serviceOrder) {
					CFRetain(serviceOrder);
				}
			}
			CFRelease(dict);
		}
	}

	/*
	 * get the list of ALL configured services
	 */
	configuredServices = entity_all(store, kSCEntNetAppleTalk, serviceOrder);
	if (configuredServices) {
		ifCount = CFArrayGetCount(configuredServices);
	}

	if (serviceOrder)	CFRelease(serviceOrder);

	/*
	 * get the list of ALL active interfaces
	 */
	key  = SCDynamicStoreKeyCreateNetworkInterface(NULL, kSCDynamicStoreDomainState);
	dict = cache_SCDynamicStoreCopyValue(store, key);
	CFRelease(key);
	if (dict) {
		if (isA_CFDictionary(dict)) {
			interfaces = CFDictionaryGetValue(dict,
							  kSCDynamicStorePropNetInterfaces);
			interfaces = isA_CFArray(interfaces);
			if (interfaces) {
				CFRetain(interfaces);
			}
		}
		CFRelease(dict);
	}

	/*
	 * get the list of previously configured services
	 */
	pattern = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
							      kSCDynamicStoreDomainState,
							      kSCCompAnyRegex,
							      kSCEntNetAppleTalk);
	keys = SCDynamicStoreCopyKeyList(store, pattern);
	CFRelease(pattern);
	if (keys) {
		info = CFArrayCreateMutableCopy(NULL, 0, keys);
		CFRelease(keys);
	}

	/*
	 * iterate over each configured service to establish the new
	 * configuration.
	 */
	for (i = 0; i < ifCount; i++) {
		CFDictionaryRef		service;
		CFStringRef		ifName;
		CFStringRef		configMethod;
		CFMutableStringRef	portConfig	= NULL;
		CFArrayRef		networkRange;	/* for seed ports, CFArray[2] of CFNumber (lo, hi) */
		int			sNetwork;
		int			eNetwork;
		CFArrayRef		zoneList;	/* for seed ports, CFArray[] of CFString (zones names) */
		CFIndex			zCount;
		CFIndex			j;
		CFMutableDictionaryRef	ifDefaults	= NULL;
		CFNumberRef		defaultNetwork;
		CFNumberRef		defaultNode;
		CFStringRef		defaultZone;

		/* get AppleTalk service dictionary */
		service = CFArrayGetValueAtIndex(configuredServices, i);

		/* get interface name */
		ifName  = CFDictionaryGetValue(service, kSCPropNetInterfaceDeviceName);

		/* check inteface availability */
		if (!interfaces ||
		    !CFArrayContainsValue(interfaces, CFRangeMake(0, CFArrayGetCount(interfaces)), ifName)) {
			/* if interface not available */
			goto nextIF;
		}

		/* check interface link status */
		key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL,
								    kSCDynamicStoreDomainState,
								    ifName,
								    kSCEntNetLink);
		dict = cache_SCDynamicStoreCopyValue(store, key);
		CFRelease(key);
		if (dict) {
			Boolean	linkStatus	= TRUE;  /* assume the link is "up" */
			Boolean	ifDetaching	= FALSE; /* assume link is not detaching */

			/* the link key for this interface is available */
			if (isA_CFDictionary(dict)) {
				CFBooleanRef	bVal;

				bVal = CFDictionaryGetValue(dict, kSCPropNetLinkActive);
				if (isA_CFBoolean(bVal)) {
					linkStatus = CFBooleanGetValue(bVal);
				}

				/* check if interface is detaching - value
				   doesn't really matter, only that it exists */
				ifDetaching = CFDictionaryContainsKey(dict, kSCPropNetLinkDetaching);
			}
			CFRelease(dict);

			if (!linkStatus || ifDetaching) {
				/* if link status down or the interface is detaching */
				goto nextIF;
			}
		}

		/*
		 * Determine configuration method for this service
		 */
		configMethod = CFDictionaryGetValue(service, kSCPropNetAppleTalkConfigMethod);
		if (!isA_CFString(configMethod)) {
			/* if no ConfigMethod */
			goto nextIF;
		}

		if (!CFEqual(configMethod, kSCValNetAppleTalkConfigMethodNode      ) &&
		    !CFEqual(configMethod, kSCValNetAppleTalkConfigMethodRouter    ) &&
		    !CFEqual(configMethod, kSCValNetAppleTalkConfigMethodSeedRouter)) {
			/* if not one of the expected values, disable */
			SCLog(TRUE, LOG_NOTICE,
			      CFSTR("Unexpected AppleTalk ConfigMethod: %@"),
			      configMethod);
			goto nextIF;
		}

		/*
		 * the first service to be defined will always be "primary"
		 */
		if (CFArrayGetCount(newConfigFile) == 0) {
			CFDictionaryRef	active;

			CFDictionarySetValue(newGlobals,
					     kSCDynamicStorePropNetPrimaryService,
					     CFDictionaryGetValue(service, CFSTR("ServiceID")));
			CFDictionarySetValue(newGlobals,
					     kSCDynamicStorePropNetPrimaryInterface,
					     ifName);

			/* and check if AT newtorking is active on the primary interface */
			key = SCDynamicStoreKeyCreateNetworkInterfaceEntity(NULL,
									    kSCDynamicStoreDomainState,
									    ifName,
									    kSCEntNetAppleTalk);
			active = cache_SCDynamicStoreCopyValue(store, key);
			CFRelease(key);
			if (active) {
				if (isA_CFDictionary(active)) {
					postGlobals = TRUE;
				}
				CFRelease(active);
			}
		}

		/*
		 * define the port
		 */
		portConfig = CFStringCreateMutable(NULL, 0);
		CFStringAppendFormat(portConfig, NULL, CFSTR("%@:"), ifName);

		if (CFEqual(configMethod, kSCValNetAppleTalkConfigMethodSeedRouter)) {
			CFNumberRef	num;

			/*
			 * we have been asked to configure this interface as a
			 * seed port. Ensure that we have been provided at least
			 * one network number, have been provided with at least
			 * one zonename, ...
			 */

			networkRange = CFDictionaryGetValue(service,
							    kSCPropNetAppleTalkSeedNetworkRange);
			if (!isA_CFArray(networkRange) || (CFArrayGetCount(networkRange) == 0)) {
				SCLog(TRUE, LOG_NOTICE,
				      CFSTR("AppleTalk configuration error (%@)"),
				      kSCPropNetAppleTalkSeedNetworkRange);
				goto nextIF;
			}

			/*
			 * establish the starting and ending network numbers
			 */
			num = CFArrayGetValueAtIndex(networkRange, 0);
			if (!isA_CFNumber(num)) {
				SCLog(TRUE, LOG_NOTICE,
				      CFSTR("AppleTalk configuration error (%@)"),
				      kSCPropNetAppleTalkSeedNetworkRange);
				goto nextIF;
			}
			CFNumberGetValue(num, kCFNumberIntType, &sNetwork);
			eNetwork = sNetwork;

			if (CFArrayGetCount(networkRange) > 1) {
				num = CFArrayGetValueAtIndex(networkRange, 1);
				if (!isA_CFNumber(num)) {
					SCLog(TRUE, LOG_NOTICE,
					      CFSTR("AppleTalk configuration error (%@)"),
					      kSCPropNetAppleTalkSeedNetworkRange);
					goto nextIF;
				}
				CFNumberGetValue(num, kCFNumberIntType, &eNetwork);
			}
			CFStringAppendFormat(portConfig, NULL, CFSTR("%d:%d:"), sNetwork, eNetwork);

			/*
			 * establish the zones associated with this port
			 */
			zoneList = CFDictionaryGetValue(service,
							kSCPropNetAppleTalkSeedZones);
			if (!isA_CFArray(zoneList)) {
				SCLog(TRUE, LOG_NOTICE,
				      CFSTR("AppleTalk configuration error (%@)"),
				      kSCPropNetAppleTalkSeedZones);
				goto nextIF;
			}

			zCount = CFArrayGetCount(zoneList);
			for (j = 0; j < zCount; j++) {
				CFStringRef		zone;
				CFArrayRef		ifList;
				CFMutableArrayRef	newIFList;

				zone = CFArrayGetValueAtIndex(zoneList, j);
				if (!isA_CFString(zone)) {
					continue;
				}

				if (CFDictionaryGetValueIfPresent(newZones, zone, (const void **)&ifList)) {
					/* known zone */
					newIFList = CFArrayCreateMutableCopy(NULL, 0, ifList);
				} else {
					/* new zone */
					newIFList = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
				}
				CFArrayAppendValue(newIFList, ifName);
				CFArraySortValues(newIFList,
						  CFRangeMake(0, CFArrayGetCount(newIFList)),
						  (CFComparatorFunction)CFStringCompare,
						  NULL);
				CFDictionarySetValue(newZones, zone, newIFList);
				CFRelease(newIFList);

				/*
				 * flag the default zone
				 */
				if (!primaryZone) {
					primaryZone = CFRetain(zone);
				}
			}
			if (!primaryZone) {
				SCLog(TRUE, LOG_NOTICE,
				      CFSTR("AppleTalk configuration error (%@)"),
				      kSCPropNetAppleTalkSeedZones);
				goto nextIF;
			}
		}

		/* get the (per-interface) "Computer Name" */
		computerName = CFDictionaryGetValue(service,
						    kSCPropNetAppleTalkComputerName);
		if (CFDictionaryGetValueIfPresent(service,
						  kSCPropNetAppleTalkComputerNameEncoding,
						  (const void **)&num) &&
		    isA_CFNumber(num)) {
			CFNumberGetValue(num, kCFNumberIntType, &computerNameEncoding);
		} else {
			computerNameEncoding = CFStringGetSystemEncoding();
		}
		encodeName(computerName, computerNameEncoding, newStartup, newGlobals);

		/*
		 * declare the first configured AppleTalk service / interface
		 * as the "home port".
		 */
		if (CFArrayGetCount(newConfigFile) == 0) {
			CFStringAppend(portConfig, CFSTR("*"));
			primaryPort = CFRetain(ifName);
		}
		CFArrayAppendValue(newConfigFile, portConfig);

		/*
		 * get the per-interface defaults
		 */
		ifDefaults = CFDictionaryCreateMutable(NULL,
						       0,
						       &kCFTypeDictionaryKeyCallBacks,
						       &kCFTypeDictionaryValueCallBacks);

		defaultNetwork = CFDictionaryGetValue(service, kSCPropNetAppleTalkNetworkID);
		defaultNode    = CFDictionaryGetValue(service, kSCPropNetAppleTalkNodeID);
		if (isA_CFNumber(defaultNetwork) && isA_CFNumber(defaultNode)) {
			/*
			 * set the default node and network
			 */
			CFDictionarySetValue(ifDefaults,
					     kSCPropNetAppleTalkNetworkID,
					     defaultNetwork);
			CFDictionarySetValue(ifDefaults,
					     kSCPropNetAppleTalkNodeID,
					     defaultNode);
		}

		if ((CFDictionaryGetValueIfPresent(service,
						   kSCPropNetAppleTalkDefaultZone,
						   (const void **)&defaultZone) == TRUE)) {
			/*
			 * set the default zone for this interface
			 */
			CFDictionarySetValue(ifDefaults,
					     kSCPropNetAppleTalkDefaultZone,
					     defaultZone);
		}

		CFDictionarySetValue(newDefaults, ifName, ifDefaults);
		CFRelease(ifDefaults);

		switch (CFArrayGetCount(newConfigFile)) {
			case 1:
				/*
				 * first AppleTalk interface
				 */
				CFDictionarySetValue(newStartup, CFSTR("APPLETALK"), ifName);
				break;
			case 2:
				/* second AppleTalk interface */
				if (!CFEqual(CFDictionaryGetValue(newStartup, CFSTR("APPLETALK")),
					     CFSTR("-ROUTER-"))) {
					/*
					 * if not routing (yet), configure as multi-home
					 */
					CFDictionarySetValue(newStartup, CFSTR("APPLETALK"), CFSTR("-MULTIHOME-"));
				}
				break;
		}

		if (CFEqual(configMethod, kSCValNetAppleTalkConfigMethodRouter) ||
		    CFEqual(configMethod, kSCValNetAppleTalkConfigMethodSeedRouter)) {
			/* if not a simple node, enable routing */
			CFDictionarySetValue(newStartup, CFSTR("APPLETALK"), CFSTR("-ROUTER-"));
		}

		/*
		 * establish the State:/Network/Service/nnn/AppleTalk key info
		 */
		key = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL,
								  kSCDynamicStoreDomainState,
								  CFDictionaryGetValue(service, CFSTR("ServiceID")),
								  kSCEntNetAppleTalk);
		newDict = CFDictionaryCreateMutable(NULL,
						    0,
						    &kCFTypeDictionaryKeyCallBacks,
						    &kCFTypeDictionaryValueCallBacks);
		CFDictionaryAddValue(newDict, kSCPropInterfaceName, ifName);
		cache_SCDynamicStoreSetValue(store, key, newDict);
		CFRelease(newDict);
		if (info) {
			j = CFArrayGetFirstIndexOfValue(info,
							CFRangeMake(0, CFArrayGetCount(info)),
							key);
			if (j != kCFNotFound) {
				CFArrayRemoveValueAtIndex(info, j);
			}
		}
		CFRelease(key);

	    nextIF :

		if (portConfig)	CFRelease(portConfig);
	}

	if (primaryZone) {
		CFArrayRef		ifList;
		CFMutableArrayRef	newIFList;

		ifList = CFDictionaryGetValue(newZones, primaryZone);
		if (CFArrayContainsValue(ifList,
					 CFRangeMake(0, CFArrayGetCount(ifList)),
					 primaryPort)) {
			newIFList = CFArrayCreateMutableCopy(NULL, 0, ifList);
			CFArrayAppendValue(newIFList, CFSTR("*"));
			CFDictionarySetValue(newZones, primaryZone, newIFList);
			CFRelease(newIFList);
		}
		CFRelease(primaryZone);
	}
	if (primaryPort) {
		CFRelease(primaryPort);
	}

	/* sort the ports */
	i = CFArrayGetCount(newConfigFile);
	CFArraySortValues(newConfigFile,
			  CFRangeMake(0, i),
			  (CFComparatorFunction)CFStringCompare,
			  NULL);

	/* add the zones to the configuration */
	CFDictionaryApplyFunction(newZones, addZoneToPorts, newConfigFile);
	CFRelease(newZones);

	/* sort the zones */
	CFArraySortValues(newConfigFile,
			  CFRangeMake(i, CFArrayGetCount(newConfigFile)-i),
			  (CFComparatorFunction)CFStringCompare,
			  NULL);

	/* ensure that the last line of the configuration file is terminated */
	CFArrayAppendValue(newConfigFile, CFSTR(""));

	/*
	 * Check if we have a "ComputerName" and look elsewhere if we don't have
	 * one yet.
	 */
	if (!CFDictionaryContainsKey(newStartup, CFSTR("APPLETALK_HOSTNAME")) &&
	    (setGlobals != NULL)) {
		computerName = CFDictionaryGetValue(setGlobals,
						    kSCPropNetAppleTalkComputerName);
		if (CFDictionaryGetValueIfPresent(setGlobals,
						  kSCPropNetAppleTalkComputerNameEncoding,
						  (const void **)&num) &&
		    isA_CFNumber(num)) {
			CFNumberGetValue(num, kCFNumberIntType, &computerNameEncoding);
		} else {
			computerNameEncoding = CFStringGetSystemEncoding();
		}
		encodeName(computerName, computerNameEncoding, newStartup, newGlobals);
	}
	if (!CFDictionaryContainsKey(newStartup, CFSTR("APPLETALK_HOSTNAME"))) {
		computerName = SCDynamicStoreCopyComputerName(store, &computerNameEncoding);
		if (computerName) {
			encodeName(computerName, computerNameEncoding, newStartup, newGlobals);
			CFRelease(computerName);
		}
	}
	if (!CFDictionaryContainsKey(newStartup, CFSTR("APPLETALK_HOSTNAME"))) {
		struct utsname	name;

		if (uname(&name) == 0) {
			computerName = CFStringCreateWithCString(NULL, name.nodename, kCFStringEncodingASCII);
			if (computerName) {
				encodeName(computerName, kCFStringEncodingASCII, NULL, newGlobals);
				CFRelease(computerName);
			}
		}
	}

	/* compare the previous and current configurations */

	curGlobalsX = CFDictionaryCreateMutableCopy(NULL, 0, curGlobals);
	CFDictionaryRemoveValue(curGlobalsX, kSCDynamicStorePropNetPrimaryService);

	newGlobalsX = CFDictionaryCreateMutableCopy(NULL, 0, newGlobals);
	CFDictionaryRemoveValue(newGlobalsX, kSCDynamicStorePropNetPrimaryService);

	key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL,
							 kSCDynamicStoreDomainState,
							 kSCEntNetAppleTalk);

	if (CFEqual(curGlobalsX   , newGlobalsX   ) &&
	    CFEqual(curConfigFile , newConfigFile) &&
	    CFEqual(curDefaults   , newDefaults  ) &&
	    CFEqual(curStartup    , newStartup   )
	    ) {
		/*
		 * the configuration has not changed.
		 */

		if (postGlobals) {
			/*
			 * the requested configuration hasn't changed but we
			 * now need to tell everyone that AppleTalk is active.
			 */
			if (!SCDynamicStoreSetValue(store, key, newGlobals)) {
				SCLog(TRUE,
				      LOG_ERR,
				      CFSTR("SCDynamicStoreSetValue() failed: %s"),
				      SCErrorString(SCError()));
			}
		}

		CFRelease(newGlobals);
		CFRelease(newConfigFile);
		CFRelease(newDefaults);
		CFRelease(newStartup);
	} else if (CFArrayGetCount(newConfigFile) <= 1) {
		/*
		 * the configuration has changed but there are no
		 * longer any interfaces configured for AppleTalk
		 * networking.
		 */

		/*
		 * remove the global (State:/Network/Global/AppleTalk) key.
		 *
		 * Note: it will be restored later after AT networking has
		 *       been activated.
		 */

		/* remove the (/etc/appletalk.cfg) configuration file */
		(void)unlink(AT_CFG_FILE);

		/*
		 * update the per-service (and global) state
		 */
		cache_SCDynamicStoreRemoveValue(store, key);	// remove State:/Network/Global/AppleTalk
		n = CFArrayGetCount(info);
		for (i = 0; i < n; i++) {
			CFStringRef	xKey	= CFArrayGetValueAtIndex(info, i);

			cache_SCDynamicStoreRemoveValue(store, xKey);
		}
		cache_write(store);

		/* flag this as a new configuration */
		*newState = -(abs(curState) + 1);
		changed = TRUE;
	} else {
		/*
		 * the configuration has changed.
		 */

		/* update the (/etc/appletalk.cfg) configuration file */
		configWrite(AT_CFG_FILE, newConfigFile);

		/*
		 * update the per-service (and global) state
		 *
		 * Note: if present, we remove any existing global state key and allow it
		 *       to be restored after the stack has been re-started.
		 */
		CFDictionaryApplyFunction(newDefaults, updateDefaults, NULL);
		cache_SCDynamicStoreRemoveValue(store, key);	// remove State:/Network/Global/AppleTalk
		n = CFArrayGetCount(info);
		for (i = 0; i < n; i++) {
			CFStringRef	xKey	= CFArrayGetValueAtIndex(info, i);

			cache_SCDynamicStoreRemoveValue(store, xKey);
		}
		cache_write(store);

		/* flag this as a new configuration */
		*newState = abs(curState) + 1;
		changed = TRUE;
	}

	CFRelease(curGlobalsX);
	CFRelease(newGlobalsX);
	CFRelease(key);

	if (changed) {
		CFRelease(curGlobals);
		curGlobals    = newGlobals;
		CFRelease(curConfigFile);
		curConfigFile = newConfigFile;
		CFRelease(curDefaults);
		curDefaults   = newDefaults;
		CFRelease(curStartup);
		curStartup    = newStartup;
	}

	if (info)		CFRelease(info);
	if (interfaces)		CFRelease(interfaces);
	if (configuredServices)	CFRelease(configuredServices);
	if (setGlobals)		CFRelease(setGlobals);

	cache_close();

	return changed;
}
Exemple #16
0
/**
 * Deletes the filesystem object named <code>fname</code>. Mysteriously fails to delete empty directories
 * on Windows, so use removeDirectory instead.
 *
 * @param fname full file or directory fname.
 */
void digidoc::util::File::removeFile(const std::string& fname)
{
    f_string _fname = encodeName(fname);
    if ( f_remove( _fname.c_str() ) )
        WARN( "Tried to remove the temporary file or directory '%s', but failed.", _fname.c_str() );
}
Exemple #17
0
/**
 * Lists files or sub directories in directory. If flag <code>filesOnly</code> is set
 * to <code>true</code> returns ONLY files, otherwise returns ONLY directories.
 *
 * @param directory full path of the directory.
 * @param relative should the returned file list be relative to the <code>directory</code>.
 * @param filesOnly if set to <code>true</code>, returns only files, otherwise returns only directories.
 * @param unixStyle should the returned file path entries in the file list use the unix style
 *        path separators.
 * @throws IOException throws exception if the directory listing failed.
 */
std::vector<std::string> digidoc::util::File::getDirSubElements(const std::string& directory,
		bool relative, bool filesOnly, bool unixStyle) throw(IOException)
{
    std::vector<std::string> files;

#ifdef _POSIX_VERSION

    std::string _directory = encodeName(directory);
    DIR* pDir = opendir(_directory.c_str());
    if(!pDir)
    {
        THROW_IOEXCEPTION("Failed to open directory '%s'", _directory.c_str());
    }

    char fullPath[MAXPATHLEN];
    struct stat info;
    dirent* entry;
    while((entry = readdir(pDir)) != NULL)
    {
        if(std::string(".").compare(entry->d_name) == 0
        || std::string("..").compare(entry->d_name) == 0)
        {
            continue;
        }

        sprintf(fullPath, "%s/%s", _directory.c_str(), entry->d_name);
        lstat(fullPath, &info);

        if((!filesOnly && (entry->d_type == 0x04||S_ISDIR(info.st_mode))) // Directory
        || (filesOnly && (entry->d_type == 0x08||S_ISREG(info.st_mode)))) // File
        {
            if(relative)
                files.push_back(decodeName(entry->d_name));
            else
                files.push_back(path(directory, decodeName(entry->d_name), unixStyle));
        }
    }

    closedir(pDir);

#else

    WIN32_FIND_DATAW findFileData;
    HANDLE hFind = NULL;

    try
    {
        if ( directory.size() > MAX_PATH )
        {
            // MSDN: "Relative paths are limited to MAX_PATH characters." - can this be true?
            THROW_IOEXCEPTION("Directory path '%s' exceeds the limit %d", directory.c_str(), MAX_PATH);
        }

        std::wstring findPattern = encodeName(directory + "\\*");
        hFind = ::FindFirstFileW(findPattern.c_str(), &findFileData);
        if (hFind == INVALID_HANDLE_VALUE)
        {
            THROW_IOEXCEPTION("Listing contents of directory '%s' failed with error %d", directory.c_str(), ::GetLastError());
        }

        do
        {
            std::wstring fileName(findFileData.cFileName);
            if ( fileName == L"." || fileName == L".." )
            {
                continue; // skip those too
            }

            if(!filesOnly && (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) // Directory
            || filesOnly && !(findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) // File
            {
                if(relative)
                    files.push_back(decodeName(fileName));
                else
                    files.push_back(path(directory, decodeName(fileName), unixStyle));
            }
        } while ( ::FindNextFileW(hFind, &findFileData) != FALSE );

        // double-check for errors
        if ( ::GetLastError() != ERROR_NO_MORE_FILES )
        {
            THROW_IOEXCEPTION("Listing contents of directory '%s' failed with error %d", directory.c_str(), ::GetLastError());
        }

        ::FindClose(hFind);
    }
    catch (...)
    {
        ::FindClose(hFind);
        throw;
    }


#endif

    return files;
}
Exemple #18
0
/*!
 * Export QT Contact into Versit Document.
 */
void QVersitContactExporterPrivate::exportContact(
    const QContact& contact,
    QVersitDocument& document)
{
    QList<QContactDetail> allDetails = contact.details();
    foreach (const QContactDetail& detail, allDetails) {
        // If the custom detail handler handles it, we don't have to.
        if (mDetailHandler
            && mDetailHandler->preProcessDetail(contact, detail, &document))
            continue;

        QList<QVersitProperty> removedProperties;
        QList<QVersitProperty> generatedProperties;
        QSet<QString> processedFields;

        if (detail.definitionName() == QContactName::DefinitionName) {
            encodeName(detail, document, &removedProperties, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactPhoneNumber::DefinitionName) {
            encodePhoneNumber(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactEmailAddress::DefinitionName) {
            encodeEmail(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactAddress::DefinitionName) {
            encodeAddress(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactGuid::DefinitionName) {
            encodeUid(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactUrl::DefinitionName) {
            encodeUrl(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactTimestamp::DefinitionName) {
            encodeRev(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactBirthday::DefinitionName) {
            encodeBirthDay(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactGeoLocation::DefinitionName) {
            encodeGeoLocation(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactNote::DefinitionName) {
            encodeNote(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactOrganization::DefinitionName) {
            encodeOrganization(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactRingtone::DefinitionName) {
            encodeRingtone(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactThumbnail::DefinitionName) {
            encodeThumbnail(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactAvatar::DefinitionName){
            encodeAvatar(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactAnniversary::DefinitionName) {
            encodeAnniversary(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactNickname::DefinitionName) {
            encodeNickname(detail, document, &removedProperties, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactTag::DefinitionName) {
            encodeTag(detail, document, &removedProperties, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactGender::DefinitionName) {
            encodeGender(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactOnlineAccount::DefinitionName) {
            encodeOnlineAccount(detail, &generatedProperties, &processedFields);
        } else if (detail.definitionName() == QContactFamily::DefinitionName) {
            encodeFamily(detail, &generatedProperties, &processedFields);
        }

        // run plugin handlers
        foreach (QVersitContactExporterDetailHandlerV2* handler, mPluginDetailHandlers) {
            handler->detailProcessed(contact, detail, document,
                                     &processedFields, &removedProperties, &generatedProperties);
        }
        // run the v2 handler, if set
        if (mDetailHandler2 && mDetailHandlerVersion > 1) {
            mDetailHandler2->detailProcessed(contact, detail, document,
                                             &processedFields, &removedProperties, &generatedProperties);
        }

        foreach(const QVersitProperty& property, removedProperties) {
            document.removeProperty(property);
        }
Exemple #19
0
bool DnsResource::setData(const std::string& dataAsString)
{
	// convert data to byte array according to the DNS type
	size_t dataLength = 0;
	uint8_t dataAsByteArr[256];

	switch (getDnsType())
	{
	case DNS_TYPE_A:
	{
		IPv4Address ip4Addr((std::string)dataAsString);
		if (!ip4Addr.isValid())
		{
			LOG_ERROR("Requested DNS type is A but data '%s' is an illegal IPv4 address. Couldn't set data for resource", dataAsString.c_str());
			return false;
		}
		dataLength = 4;
		uint32_t addrAsInt = ip4Addr.toInt();
		memcpy(dataAsByteArr, &addrAsInt, dataLength);
		break;
	}

	case DNS_TYPE_AAAA:
	{
		IPv6Address ip6Addr((std::string)dataAsString);
		if (!ip6Addr.isValid())
		{
			LOG_ERROR("Requested DNS type is AAAA but data '%s' is an illegal IPv6 address. Couldn't set data for resource", dataAsString.c_str());
			return false;
		}
		dataLength = 16;
		ip6Addr.copyTo(dataAsByteArr);
		break;
	}

	case DNS_TYPE_NS:
	case DNS_TYPE_CNAME:
	case DNS_TYPE_DNAM:
	case DNS_TYPE_PTR:
	case DNS_TYPE_MX:
	{
		encodeName(dataAsString, (char*)dataAsByteArr, dataLength);
		break;
	}

	default:
	{
		if (dataAsString.substr(0, 2) != "0x")
		{
			LOG_ERROR("DNS data for DNS type %d should be an hex stream and begin with '0x'", getDnsType());
			return false;
		}
		if (dataAsString.length() % 2 != 0)
		{
			LOG_ERROR("DNS data for DNS type %d should be an hex stream with an even number of character. "
					"Current character count is an odd number: %d", getDnsType(), dataAsString.length());
			return false;
		}
		char* dataAsCharPtr = (char*)dataAsString.c_str();
		dataAsCharPtr += 2; //skip the '0x' prefix
		char strtolBuf[5] = { '0', 'x', 0, 0, 0 };
		char* strtolEndPtr;
		while (*dataAsCharPtr != 0)
		{
			strtolBuf[2] = dataAsCharPtr[0];
			strtolBuf[3] = dataAsCharPtr[1];
			dataAsByteArr[dataLength] = strtol(strtolBuf, &strtolEndPtr, 0);

	        if (strtolEndPtr[0] != '\0') {
	        	//non-hexadecimal character encountered
	        	LOG_ERROR("DNS data for DNS type %d should be a valid hex stream", getDnsType());
	            return false;
	        }

	        dataAsCharPtr += 2 * sizeof(char);
	        dataLength++;
		}
		break;
	}
	}

	size_t dataLengthOffset = m_NameLength + (2*sizeof(uint16_t)) + sizeof(uint32_t);
	size_t dataOffset = dataLengthOffset + sizeof(uint16_t);

	if (m_DnsLayer != NULL)
	{
		size_t curLength = getDataLength();
		if (dataLength > curLength)
		{
			if (!m_DnsLayer->extendLayer(m_OffsetInLayer + dataOffset, dataLength-curLength, this))
			{
				LOG_ERROR("Couldn't set data for DNS query, unable to extend layer");
				return false;
			}
		}
		else if (dataLength < curLength)
		{
			if (!m_DnsLayer->shortenLayer(m_OffsetInLayer + dataOffset, curLength-dataLength, this))
			{
				LOG_ERROR("Couldn't set data for DNS query, unable to shorten layer");
				return false;
			}
		}
	}

	// write data to resource
	memcpy(getRawData() + dataOffset, dataAsByteArr, dataLength);
	//update data length in resource
	dataLength = htons(dataLength);
	memcpy(getRawData() + dataLengthOffset, &dataLength, sizeof(uint16_t));

	return true;
}