Ejemplo n.º 1
0
void MailingList::SetBounceMsg(std::string path)
{
	//attempt to read the custom bounce message file
	BFile bouncemsgbfile;
	status_t bouncemsgfilestatus=bouncemsgbfile.SetTo(path.c_str(),B_READ_ONLY);
	if (bouncemsgfilestatus==B_NO_ERROR)
	{
		off_t bytes; //size of file
		if (bouncemsgbfile.GetSize(&bytes) == B_NO_ERROR)
		{
			
			char* buff = new char[bytes];
			off_t bytesread=bouncemsgbfile.Read(buff,bytes);
			if ( (bytesread > 0) && (bytesread < 50001)  )
			{
				//file read ok
				std::string oldbouncemsg=fUnauthorisedBounceMsgContents; //save generic bounce msg so it can be appended later
				fUnauthorisedBounceMsgContents=""; //clear existing contents
				for (int x=0; x < bytesread; x++)
				{
					fUnauthorisedBounceMsgContents=fUnauthorisedBounceMsgContents+buff[x];
				}	
				fUnauthorisedBounceMsgContents=fUnauthorisedBounceMsgContents+"\n\n"+oldbouncemsg; //append generic msg
			}
			delete buff;
			
		}
		bouncemsgbfile.Unset(); //close file
	}
}
Ejemplo n.º 2
0
Emoconfig::Emoconfig(const char* xmlfile): BMessage()
{
	fEmoticonSize = 16.0; //default
	numfaces = 0;

	fParser = XML_ParserCreate(NULL);

	XML_SetUserData(fParser, this);
	XML_SetElementHandler(fParser, StartElement, EndElement);
	XML_SetCharacterDataHandler(fParser, Characters);

	//path!
	BPath p(xmlfile);
	p.GetParent(&path);

	// loading the config file..
	BFile* settings = new BFile(xmlfile, B_READ_ONLY);
	off_t size;
	settings->GetSize(&size);
	if (size) {
		void* buffer = malloc((size_t)size);
		size = settings->Read(buffer, (size_t)size);
		XML_Parse(fParser, (const char*)buffer, (int)size, true);
		free(buffer);
	}
	delete settings;

	if (fParser)
		XML_ParserFree(fParser);

	printf("Emoconfig: loaded %d faces\n", numfaces);

}
Ejemplo n.º 3
0
void Filters::Load()
{
	status_t err;

	// figure out where the file should be
	BPath path;
	err = find_directory(B_USER_SETTINGS_DIRECTORY, &path, true);
	if (err != B_NO_ERROR)
		return;
	path.Append(FileNames::filtersFileName);

	// open the file
	BFile* file = new BFile(path.Path(), B_READ_ONLY);
	if (file->InitCheck() != B_NO_ERROR) {
		delete file;
		return;
		}

	// load the text
	off_t fileSize;
	file->GetSize(&fileSize);
	char* text = new char[fileSize];
	file->ReadAt(0, text, fileSize);
	delete file;

	// parse it
	TextReader reader(string_slice(text, text + fileSize));
	FilterGroup* curGroup = NULL;
	while (!reader.AtEOF()) {
		// get the groupName
		string_slice groupName = reader.NextTabField();
		if (groupName.length() > 0) {
			curGroup = GetFilterGroup(groupName);
			if (curGroup == NULL) {
				curGroup = new FilterGroup(groupName);
				AddFilterGroup(curGroup);
				}
			reader.NextLine();
			}

		// if none, this is a filter line (if it's not blank)
		else {
			string_slice filterLine = reader.NextLine();
			if (filterLine.length() > 0 && curGroup != NULL) {
				Filter* filter = new Filter();
				TextReader lineReader(filterLine);
				filter->ReadFrom(&lineReader);
				curGroup->AddFilter(filter);
				}
			}
		}

	// clean up
	delete text;
}
Ejemplo n.º 4
0
status_t
DefaultCatalog::ReadFromFile(const char *path)
{
	if (!path)
		path = fPath.String();

	BFile catalogFile;
	status_t res = catalogFile.SetTo(path, B_READ_ONLY);
	if (res != B_OK) {
		log_team(LOG_DEBUG, "LocaleKit DefaultCatalog: no catalog at %s", path);
		return B_ENTRY_NOT_FOUND;
	}

	fPath = path;
	log_team(LOG_DEBUG, "LocaleKit DefaultCatalog: found catalog at %s", path);

	off_t sz = 0;
	res = catalogFile.GetSize(&sz);
	if (res != B_OK) {
		log_team(LOG_ERR, "LocaleKit DefaultCatalog: couldn't get size for "
			"catalog-file %s", path);
		return res;
	}

	auto_ptr<char> buf(new(std::nothrow) char [sz]);
	if (buf.get() == NULL) {
		log_team(LOG_ERR, "LocaleKit DefaultCatalog: couldn't allocate array "
			"of %d chars", sz);
		return B_NO_MEMORY;
	}
	res = catalogFile.Read(buf.get(), sz);
	if (res < B_OK) {
		log_team(LOG_ERR, "LocaleKit DefaultCatalog: couldn't read from "
			"catalog-file %s", path);
		return res;
	}
	if (res < sz) {
		log_team(LOG_ERR,
			"LocaleKit DefaultCatalog: only got %lu instead of %Lu bytes from "
			"catalog-file %s", res, sz, path);
		return res;
	}
	BMemoryIO memIO(buf.get(), sz);
	res = Unflatten(&memIO);

	if (res == B_OK) {
		// some information living in member variables needs to be copied
		// to attributes. Although these attributes should have been written
		// when creating the catalog, we make sure that they exist there:
		UpdateAttributes(catalogFile);
	}

	return res;
}
Ejemplo n.º 5
0
status_t
get_named_icon(const char* name, uint8** _data, size_t* _size, type_code* _type)
{
	if (name == NULL || _data == NULL || _size == NULL || _type == NULL)
		return B_BAD_VALUE;

	directory_which kWhich[] = {
		B_USER_DATA_DIRECTORY,
		B_COMMON_DATA_DIRECTORY,
		B_BEOS_DATA_DIRECTORY,
	};

	status_t status = B_ENTRY_NOT_FOUND;
	BFile file;
	off_t size;

	for (uint32 i = 0; i < sizeof(kWhich) / sizeof(kWhich[0]); i++) {
		BPath path;
		if (find_directory(kWhich[i], &path) != B_OK)
			continue;

		path.Append("icons");
		path.Append(name);

		status = file.SetTo(path.Path(), B_READ_ONLY);
		if (status == B_OK) {
			status = file.GetSize(&size);
			if (size > 1024 * 1024)
				status = B_ERROR;
		}
		if (status == B_OK)
			break;
	}

	if (status != B_OK)
		return status;

	*_data = new(std::nothrow) uint8[size];
	if (*_data == NULL)
		return B_NO_MEMORY;

	if (file.Read(*_data, size) != size) {
		delete[] *_data;
		return B_ERROR;
	}

	*_size = size;
	*_type = B_VECTOR_ICON_TYPE;
		// TODO: for now

	return B_OK;
}
Ejemplo n.º 6
0
status_t
PictureView::_LoadPicture(const entry_ref* ref)
{
	BFile file;
	status_t status = file.SetTo(ref, B_READ_ONLY);
	if (status != B_OK)
		return status;

	off_t fileSize;
	status = file.GetSize(&fileSize);
	if (status != B_OK)
		return status;

	// Check that we've at least some data to translate...
	if (fileSize < 1)
		return B_OK;

	translator_info info;
	memset(&info, 0, sizeof(translator_info));
	BMessage ioExtension;

	BTranslatorRoster* roster = BTranslatorRoster::Default();
	if (roster == NULL)
		return B_ERROR;

	status = roster->Identify(&file, &ioExtension, &info, 0, NULL,
		B_TRANSLATOR_BITMAP);

	BBitmapStream stream;

	if (status == B_OK) {
		status = roster->Translate(&file, &info, &ioExtension, &stream,
			B_TRANSLATOR_BITMAP);
	}
	if (status != B_OK)
		return status;

	BBitmap* picture = NULL;
	if (stream.DetachBitmap(&picture) != B_OK
		|| picture == NULL)
		return B_ERROR;

	// Remember image format so we could store using the same
	fPictureMIMEType = info.MIME;
	fPictureType = info.type;

	_SetPicture(picture);
	return B_OK;
}
Ejemplo n.º 7
0
filter_result
DCCFileFilter::HandleAlert (BMessage *msg)
{
	BTextControl *text (dynamic_cast<BTextControl *>(
		panel->Window()->FindView ("text view")));
	int32 which;

	msg->FindInt32 ("which", &which);

	if (which == 0 || text == 0)
	{
		return B_SKIP_MESSAGE;
	}

	entry_ref ref;
	panel->GetPanelDirectory (&ref);

	if (which == 2)
	{
		BDirectory dir (&ref);
		BFile file (&dir, text->Text(), B_READ_ONLY);
		BEntry entry (&dir, text->Text());
		BPath path;
		off_t position;

		file.GetSize (&position);
		entry.GetPath (&path);
		send_msg.AddString ("path", path.Path());
		send_msg.AddInt64  ("pos", position);

		send_msg.what = M_ADD_RESUME_DATA;
	}
	else
	{
		send_msg.AddRef ("directory", &ref);
		send_msg.AddString ("name", text->Text());
	}

	panel->Messenger().SendMessage (&send_msg);

	BMessage cmsg (B_CANCEL);
	cmsg.AddPointer ("source", panel);
	panel->Messenger().SendMessage (&cmsg);

	return B_SKIP_MESSAGE;
}
Ejemplo n.º 8
0
void
TSigTextView::MessageReceived(BMessage *msg)
{
	char		type[B_FILE_NAME_LENGTH];
	char		*text;
	int32		end;
	int32		start;
	BFile		file;
	BNodeInfo	*node;
	entry_ref	ref;
	off_t		size;

	switch (msg->what) {
		case B_SIMPLE_DATA:
			if (msg->HasRef("refs")) {
				msg->FindRef("refs", &ref);
				file.SetTo(&ref, O_RDONLY);
				if (file.InitCheck() == B_NO_ERROR) {
					node = new BNodeInfo(&file);
					node->GetType(type);
					delete node;
					file.GetSize(&size);
					if ((!strncasecmp(type, "text/", 5)) && (size)) {
						text = (char *)malloc(size);
						file.Read(text, size);
						Delete();
						GetSelection(&start, &end);
						Insert(text, size);
						Select(start, start + size);
						free(text);
					}
				}
			}
			else
				BTextView::MessageReceived(msg);
			break;

		case M_SELECT:
			if (IsSelectable())
				Select(0, TextLength());
			break;

		default:
			BTextView::MessageReceived(msg);
	}
}
Ejemplo n.º 9
0
/***********************************************************
 * ProcessCommand
 ***********************************************************/
status_t
PGP::ProcessCommand(const char* cmd ,const char* in,BString *out)
{
	BFile file;
	status_t err = B_OK;	
	// Delete tmp files
	DeleteFiles();
	
	// Create an input tmp file
	if(strlen(in) > 0)
	{
		PRINT(("PGPIN:%s\n",in));
		if(CreateInputFilePointer(&file) != B_OK)
			return B_ERROR;
		file.Write(in, ::strlen(in));
		file.Unset();
	}	
	// Excute pgp command
	PRINT(("PGPCMD:%s\n",cmd));
	::system(cmd);
	
	if(out)
	{
		// Create output file pointer
		err = CreateOutputFilePointer(&file);
		// Read output file
		if(err == B_OK)
		{
			off_t size;
			file.GetSize(&size);
			if(size != 0)
			{
				out->SetTo("");
				char *buf = out->LockBuffer(size+1);
				size = file.Read(buf,size);
				buf[size] = '\0';
				out->UnlockBuffer();
			}
		}
		PRINT(("PGPOUT:%s\n",out->String()));
	}
	// Delete tmp files
	DeleteFiles();
	return err;	
}
Ejemplo n.º 10
0
// _InitPEFFile
void
ResourceFile::_InitPEFFile(BFile& file, const PEFContainerHeader& pefHeader)
{
	status_t error = B_OK;
	// get the file size
	off_t fileSize = 0;
	error = file.GetSize(&fileSize);
	if (error != B_OK)
		throw Exception(error, "Failed to get the file size.");
	// check architecture -- we support PPC only
	if (memcmp(pefHeader.architecture, kPEFArchitecturePPC, 4))
		throw Exception("PEF file architecture is not PPC.");
	fHostEndianess = B_HOST_IS_BENDIAN;
	// get the section count
	uint16 sectionCount = _GetUInt16(pefHeader.sectionCount);
	// iterate through the PEF sections headers
	uint32 sectionHeaderTableOffset = kPEFContainerHeaderSize;
	uint32 sectionHeaderTableEnd
		= sectionHeaderTableOffset + sectionCount * kPEFSectionHeaderSize;
	uint32 resourceOffset = sectionHeaderTableEnd;
	for (int32 i = 0; i < (int32)sectionCount; i++) {
		uint32 shOffset = sectionHeaderTableOffset + i * kPEFSectionHeaderSize;
		PEFSectionHeader sectionHeader;
		read_exactly(file, shOffset, &sectionHeader, kPEFSectionHeaderSize,
					 "Failed to read PEF section header.");
		// get the header values
		uint32 offset	= _GetUInt32(sectionHeader.containerOffset);
		uint32 size		= _GetUInt32(sectionHeader.packedSize);
		// check the values
		if (offset < sectionHeaderTableEnd || offset > fileSize) {
			throw Exception("Invalid PEF section header: invalid "
							"section offset: %lu.", offset);
		}
		uint32 sectionEnd = offset + size;
		if (sectionEnd > fileSize) {
			throw Exception("Invalid PEF section header: section "
							"exceeds file: %lu.", sectionEnd);
		}
		resourceOffset = max(resourceOffset, sectionEnd);
	}
	// init the offset file
	fFile.SetTo(file, resourceOffset);
}
Ejemplo n.º 11
0
status_t
KeyboardLayout::Load(entry_ref& ref)
{
	BFile file;
	status_t status = file.SetTo(&ref, B_READ_ONLY);
	if (status != B_OK)
		return status;

	off_t size;
	status = file.GetSize(&size);
	if (status != B_OK)
		return status;

	if (size > 65536) {
		// We don't accept files larger than this
		return B_BAD_VALUE;
	}

	char* data = (char*)malloc(size + 1);
	if (data == NULL)
		return B_NO_MEMORY;

	ssize_t bytesRead = file.Read(data, size);
	if (bytesRead != size) {
		free(data);

		if (bytesRead < 0)
			return bytesRead;

		return B_IO_ERROR;
	}

	data[size] = '\0';

	status = _InitFrom(data);
	if (status == B_OK)
		fIsDefault = false;

	free(data);

	return status;
}
status_t
DefaultCatalog::ReadFromFile(const char *path)
{
	if (!path)
		path = fPath.String();

	BFile catalogFile;
	status_t res = catalogFile.SetTo(path, B_READ_ONLY);
	if (res != B_OK)
		return B_ENTRY_NOT_FOUND;

	fPath = path;

	off_t sz = 0;
	res = catalogFile.GetSize(&sz);
	if (res != B_OK) {
		return res;
	}

	auto_ptr<char> buf(new(std::nothrow) char [sz]);
	if (buf.get() == NULL)
		return B_NO_MEMORY;
	res = catalogFile.Read(buf.get(), sz);
	if (res < B_OK)
		return res;
	if (res < sz)
		return res;
	BMemoryIO memIO(buf.get(), sz);
	res = Unflatten(&memIO);

	if (res == B_OK) {
		// some information living in member variables needs to be copied
		// to attributes. Although these attributes should have been written
		// when creating the catalog, we make sure that they exist there:
		UpdateAttributes(catalogFile);
	}

	return res;
}
Ejemplo n.º 13
0
void MarkupWindow::MessageReceived(BMessage* msg)
{
	switch(msg->what)
	{
		case LOAD_CONTENT:
			selected = topicListView->CurrentSelection();
			if(selected >= 0) // you selected something
			{
				HelpStringItem* item;
				BString contentPath = GetAppDirPath();
				BFile file;
				item = dynamic_cast<HelpStringItem*>(topicListView->ItemAt(selected));
				contentPath += "/";
				contentPath += item->ReturnContent();
				printf("contentpath: %s\n", contentPath.String());
				if(file.SetTo(contentPath, B_READ_ONLY) == B_OK)
				{
					off_t length;
					char* text;
					file.GetSize(&length);
					text = (char*) malloc(length);
					if(text && (file.Read(text, length)) >= B_OK)
					{
						contentTextView->SetText(text, length);
					}
					free(text);
				}
			}
			break;
		
		default:
		{
			BWindow::MessageReceived(msg);
			break;
		}
	}
}
Ejemplo n.º 14
0
void
process_refs(entry_ref ref, BMessage* msg, void* reserved)
{
	int32 	buttonIndex= 0; 
	int32	prefsset=0;

	BFile 		file;
	char		confirm = 'y';
	char		showStatus = 'y';
	char		*iterations;

	int32 entryCount = 0;
	entry_ref fref;


	// Get the config
	if (file.SetTo("/boot/home/config/settings/Shredder.conf", B_READ_ONLY) == B_OK) {
		off_t length;
		file.GetSize(&length);		// Get the file length;
		iterations = (char *) malloc(length);
		file.Read(iterations, length);
		confirm = iterations[2];
		showStatus = iterations[3];	
	
		free(iterations);		
	}		
	// Got the config

	
	if ((confirm != 'n') && (msg->FindRef("refs", 0, &fref) == B_OK)) {
		BAlert *shredAlert = new BAlert(B_TRANSLATE_SYSTEM_NAME("Shredder"),
			B_TRANSLATE("Are you sure you want to continue shredding?"),
			B_TRANSLATE("Yes"), B_TRANSLATE("Preferences" B_UTF8_ELLIPSIS), B_TRANSLATE("Cancel"));
		shredAlert->SetShortcut(2, B_ESCAPE);

		buttonIndex = shredAlert->Go();
	}	

	if (buttonIndex==2) {
		return;
	}
	
	if (buttonIndex==1) {
		PAppWindow * prefsWindow = new PAppWindow(/*ref, msg*/);
	
		thread_id thread = prefsWindow->Thread();
		//wait for the window thread to return
		status_t win_status = B_OK;
		wait_for_thread(thread, &win_status);
		prefsset=1;
	}

	if ((prefsset==0) && (msg->FindRef("refs", 0, &fref) == B_OK)) {

		for(int32 count = 0 ; msg->FindRef("refs", count, &fref) == B_OK ; count++) {
			PStatWindow * statWindow = new PStatWindow(fref, msg, showStatus);
			thread_id thread = statWindow->Thread();
			status_t win_status = B_OK;	
			wait_for_thread(thread, &win_status);

			entryCount++;
		}
	}

	if ((entryCount == 0) && (prefsset==0)) {
		PAppWindow * prefsWindow = new PAppWindow(/*ref, msg*/);
		thread_id thread = prefsWindow->Thread();
		//wait for the window thread to return
		status_t win_status = B_OK;
		wait_for_thread(thread, &win_status);
	}

}
Ejemplo n.º 15
0
status_t
TRoster::_LoadRosterSettings(const char* path)
{
	BPath _path;
	const char* settingsPath
		= path ? path : get_default_roster_settings_path(_path, false);

	RosterSettingsCharStream stream;
	status_t error;
	BFile file;

	error = file.SetTo(settingsPath, B_READ_ONLY);
	off_t size;
	if (!error)
		error = file.GetSize(&size);

	char* data = NULL;

	if (!error) {
		data = new(nothrow) char[size + 1];
		error = data ? B_OK : B_NO_MEMORY;
	}
	if (!error) {
		ssize_t bytes = file.Read(data, size);
		error = bytes < 0 ? bytes : (bytes == size ? B_OK : B_FILE_ERROR);
	}
	if (!error) {
		data[size] = 0;
		error = stream.SetTo(std::string(data));
	}

	delete[] data;

	if (!error) {
		// Clear the current lists as
		// we'll be manually building them up
		fRecentDocuments.Clear();
		fRecentFolders.Clear();
		fRecentApps.Clear();

		// Now we just walk through the file and read in the info
		while (true) {
			status_t streamError;
			char str[B_PATH_NAME_LENGTH];

			// (RecentDoc | RecentFolder | RecentApp)
			streamError = stream.GetString(str);
			if (!streamError) {
				enum EntryType {
					etDoc,
					etFolder,
					etApp,
					etSomethingIsAmiss,
				} type;

				if (strcmp(str, "RecentDoc") == 0)
					type = etDoc;
				else if (strcmp(str, "RecentFolder") == 0)
					type = etFolder;
				else if (strcmp(str, "RecentApp") == 0)
					type = etApp;
				else
					type = etSomethingIsAmiss;

				switch (type) {
					case etDoc:
					case etFolder:
					{
						// For curing laziness
						std::list<recent_entry*>* list = type == etDoc
							? &fRecentDocuments.fEntryList
							: &fRecentFolders.fEntryList;

						char path[B_PATH_NAME_LENGTH];
						char app[B_PATH_NAME_LENGTH];
						char rank[B_PATH_NAME_LENGTH];
						entry_ref ref;
						ulong index = 0;

						// Convert the given path to an entry ref
						streamError = stream.GetString(path);
						if (!streamError)
							streamError = get_ref_for_path(path, &ref);

						// Add a new entry to the list for each application
						// signature and rank we find
						while (!streamError) {
							if (!streamError)
								streamError = stream.GetString(app);
							if (!streamError) {
								BPrivate::Storage::to_lower(app);
								streamError = stream.GetString(rank);
							}
							if (!streamError) {
								index = strtoul(rank, NULL, 10);
								if (index == ULONG_MAX)
									streamError = errno;
							}
							recent_entry* entry = NULL;
							if (!streamError) {
								entry = new(nothrow) recent_entry(&ref, app,
									index);
								streamError = entry ? B_OK : B_NO_MEMORY;
							}
							if (!streamError) {
								D(printf("pushing entry, leaf == '%s', app == "
									"'%s', index == %" B_PRId32 "\n",
									entry->ref.name, entry->sig.c_str(),
									entry->index));

								list->push_back(entry);
							}
						}

						if (streamError) {
							D(printf("entry error 0x%" B_PRIx32 "\n",
								streamError));
							if (streamError
									!= RosterSettingsCharStream::kEndOfLine
							    && streamError
							    	!= RosterSettingsCharStream::kEndOfStream)
							stream.SkipLine();
						}

						break;
					}


					case etApp:
					{
						char app[B_PATH_NAME_LENGTH];
						streamError = stream.GetString(app);
						if (!streamError) {
							BPrivate::Storage::to_lower(app);
							fRecentApps.fAppList.push_back(app);
						} else
							stream.SkipLine();
						break;
					}

					default:
						// Something was amiss; skip to the next line
						stream.SkipLine();
						break;
				}

			}

			if (streamError == RosterSettingsCharStream::kEndOfStream)
				break;
		}

		// Now we must sort our lists of documents and folders by the
		// indicies we read for each entry (largest index first)
		fRecentDocuments.fEntryList.sort(larger_index);
		fRecentFolders.fEntryList.sort(larger_index);

		D(
			printf("----------------------------------------------------------------------\n");
			fRecentDocuments.Print();
			printf("----------------------------------------------------------------------\n");
			fRecentFolders.Print();
			printf("----------------------------------------------------------------------\n");
			fRecentApps.Print();
			printf("----------------------------------------------------------------------\n");
		);
Ejemplo n.º 16
0
void
print_tga_info(BFile &file)
{
	uint8 buf[TGA_HEADERS_SIZE];
	
	// read in TGA headers
	ssize_t size = TGA_HEADERS_SIZE;
	if (size > 0 && file.Read(buf, size) != size) {
		printf(B_TRANSLATE("Error: unable to read all TGA headers\n"));
		return;
	}
	
	// TGA file header
	TGAFileHeader fh;
	fh.idlength = buf[0];
	fh.colormaptype = buf[1];
	fh.imagetype = buf[2];
	
	printf(B_TRANSLATE("\nFile Header:\n"));
	printf(B_TRANSLATE("    id length: %d\n"), static_cast<int>(fh.idlength));
	
	printf(B_TRANSLATE("colormap type: %d (%s)\n"),
		static_cast<int>(fh.colormaptype),
		static_cast<const char *>(colormaptype(fh.colormaptype)));
	printf(B_TRANSLATE("   image type: %d (%s)\n"),
		static_cast<int>(fh.imagetype),
		static_cast<const char *>(imagetype(fh.imagetype)));
	
	
	// TGA color map spec
	TGAColorMapSpec mapspec;
	mapspec.firstentry = tga_uint16(reinterpret_cast<char *>(buf), 3);
	mapspec.length = tga_uint16(reinterpret_cast<char *>(buf), 5);
	mapspec.entrysize = buf[7];
	
	printf(B_TRANSLATE("\nColormap Spec:\n"));
	printf(B_TRANSLATE("first entry: %d\n"),
		static_cast<int>(mapspec.firstentry));
	printf(B_TRANSLATE("     length: %d\n"),
		static_cast<int>(mapspec.length));
	printf(B_TRANSLATE(" entry size: %d\n"),
		static_cast<int>(mapspec.entrysize));
	
	
	// TGA image spec
	TGAImageSpec imagespec;
	imagespec.xorigin = tga_uint16(reinterpret_cast<char *>(buf), 8);
	imagespec.yorigin = tga_uint16(reinterpret_cast<char *>(buf), 10);
	imagespec.width = tga_uint16(reinterpret_cast<char *>(buf), 12);
	imagespec.height = tga_uint16(reinterpret_cast<char *>(buf), 14);
	imagespec.depth = buf[16];
	imagespec.descriptor = buf[17];
	
	printf(B_TRANSLATE("\nImage Spec:\n"));
	printf(B_TRANSLATE("  x origin: %d\n"),
		static_cast<int>(imagespec.xorigin));
	printf(B_TRANSLATE("  y origin: %d\n"),
		static_cast<int>(imagespec.yorigin));
	printf(B_TRANSLATE("     width: %d\n"),
		static_cast<int>(imagespec.width));
	printf(B_TRANSLATE("    height: %d\n"),
		static_cast<int>(imagespec.height));
	printf(B_TRANSLATE("     depth: %d\n"),
		static_cast<int>(imagespec.depth));
	printf(B_TRANSLATE("descriptor: 0x%.2x\n"),
		static_cast<int>(imagespec.descriptor));
	printf(B_TRANSLATE("\talpha (attr): %d\n"),
		static_cast<int>(imagespec.descriptor & TGA_DESC_ALPHABITS));
	if (imagespec.descriptor & TGA_ORIGIN_VERT_BIT)
		if (imagespec.descriptor & TGA_ORIGIN_HORZ_BIT)
			printf(B_TRANSLATE("\t      origin: %d (%s %s)\n"),
				static_cast<int>(imagespec.descriptor & (TGA_ORIGIN_VERT_BIT 
				| TGA_ORIGIN_HORZ_BIT)), static_cast<const char *>("top"),
				static_cast<const char *>("right"));
		else
			printf(B_TRANSLATE("\t      origin: %d (%s %s)\n"),
			static_cast<int>(imagespec.descriptor & (TGA_ORIGIN_VERT_BIT 
				| TGA_ORIGIN_HORZ_BIT)), static_cast<const char *>("top"),
				static_cast<const char *>("left"));
	else
		if (imagespec.descriptor & TGA_ORIGIN_HORZ_BIT)
			printf(B_TRANSLATE("\t      origin: %d (%s %s)\n"),
				static_cast<int>(imagespec.descriptor & (TGA_ORIGIN_VERT_BIT 
				| TGA_ORIGIN_HORZ_BIT)), static_cast<const char *>("bottom"),
				static_cast<const char *>("right"));
		else
			printf(B_TRANSLATE("\t      origin: %d (%s %s)\n"),
			static_cast<int>(imagespec.descriptor & (TGA_ORIGIN_VERT_BIT 
				| TGA_ORIGIN_HORZ_BIT)), static_cast<const char *>("bottom"),
				static_cast<const char *>("left"));
			
			
	printf(B_TRANSLATE("\t  bits 7 & 6: %d\n"),
		static_cast<int>(imagespec.descriptor & TGA_DESC_BITS76));
		
		
	// Optional TGA Footer
	off_t filesize = 0;
	if (file.GetSize(&filesize) == B_OK) {
	
		char tgafooter[TGA_FTR_LEN + 1] = { 0 };
		if (file.ReadAt(filesize - TGA_FTR_LEN, tgafooter, TGA_FTR_LEN) == TGA_FTR_LEN) {
		
			if (strcmp(tgafooter + 8, "TRUEVISION-XFILE.") == 0) {
			
				uint32 extoffset = 0, devoffset = 0;
				extoffset = tga_uint32(tgafooter, 0);
				devoffset = tga_uint32(tgafooter, 4);
			
				printf(B_TRANSLATE("\nTGA Footer:\n"));
				printf(B_TRANSLATE("extension offset: 0x%.8lx (%ld)\n"),
					static_cast<long int>(extoffset),
					static_cast<long int>(extoffset));
				printf(B_TRANSLATE("developer offset: 0x%.8lx (%ld)\n"),
					static_cast<long int>(devoffset),
					static_cast<long int>(devoffset));
				printf(B_TRANSLATE("signature: %s\n"), tgafooter + 8);
				
				if (extoffset) {
					char extbuf[TGA_EXT_LEN];
					if (file.ReadAt(extoffset, extbuf, TGA_EXT_LEN) == TGA_EXT_LEN) {
					
						printf(B_TRANSLATE("\nExtension Area:\n"));
						
						char strbuffer[LINE_LEN];
						
						uint16 extsize = tga_uint16(extbuf, 0);
						if (extsize < TGA_EXT_LEN) {
							printf(B_TRANSLATE("\nError: extension "
								"area is too small (%d)\n"), extsize);
							return;
						}
						printf(B_TRANSLATE("size: %d\n"), extsize);
						
						memset(strbuffer, 0, LINE_LEN);
						strncpy(strbuffer, extbuf + 2, 41);
						printf("author: \"%s\"\n", strbuffer);
						
						printf(B_TRANSLATE("comments:\n"));
						for (int32 i = 0; i < 4; i++) {
							memset(strbuffer, 0, LINE_LEN);
							strcpy(strbuffer, extbuf + 43 + (i * 81));
							printf(B_TRANSLATE("\tline %ld: \"%s\"\n"),
								static_cast<long int>(i + 1),
								static_cast<const char *>(strbuffer));
						}

						printf(B_TRANSLATE("date/time (yyyy-mm-dd hh:mm:ss): "
							"%.4d-%.2d-%.2d %.2d:%.2d:%.2d\n"),
							tga_uint16(extbuf, 367), tga_uint16(extbuf, 369),
							tga_uint16(extbuf, 371), tga_uint16(extbuf, 373),
							tga_uint16(extbuf, 375), tga_uint16(extbuf, 377));
							
						memset(strbuffer, 0, LINE_LEN);
						strncpy(strbuffer, extbuf + 379, 41);
						printf(B_TRANSLATE("job name: \"%s\"\n"), strbuffer);

						printf(B_TRANSLATE("job time (hh:mm:ss): "
							"%.2d:%.2d:%.2d\n"), tga_uint16(extbuf, 420),
							tga_uint16(extbuf, 422), tga_uint16(extbuf, 424));
							
						memset(strbuffer, 0, LINE_LEN);
						strncpy(strbuffer, extbuf + 426, 41);
						printf(B_TRANSLATE("software id: \"%s\"\n"),
							strbuffer);
						
						char strver[] = "[null]";
						if (extbuf[469] != '\0') {
							strver[0] = extbuf[469];
							strver[1] = '\0';
						}
						printf(B_TRANSLATE("software version, letter: %d, "
							"%s\n"), tga_uint16(extbuf, 467), strver);
						
						printf(B_TRANSLATE("key color (A,R,G,B): %d, %d, %d, "
							"%d\n"), extbuf[470], extbuf[471], extbuf[472],
							extbuf[473]);
						
						printf(B_TRANSLATE("pixel aspect ratio: %d / %d\n"),
							tga_uint16(extbuf, 474), tga_uint16(extbuf, 476));

						printf(B_TRANSLATE("gamma value: %d / %d\n"),
							tga_uint16(extbuf, 478), tga_uint16(extbuf, 480));
						
						printf(B_TRANSLATE("color correction offset: 0x%.8lx "
							"(%ld)\n"),	tga_uint32(extbuf, 482),
							tga_uint32(extbuf, 482));
						printf(B_TRANSLATE("postage stamp offset: 0x%.8lx "
							"(%ld)\n"),	tga_uint32(extbuf, 486),
							tga_uint32(extbuf, 486));
						printf(B_TRANSLATE("scan line offset: 0x%.8lx "
							"(%ld)\n"), tga_uint32(extbuf, 490),
							tga_uint32(extbuf, 490));
						
						const char *strattrtype = NULL;
						uint8 attrtype = extbuf[494];
						switch (attrtype) {
							case 0: strattrtype 
								= B_TRANSLATE("no alpha"); break;
							case 1: strattrtype 
								= B_TRANSLATE("undefined, ignore"); break;
							case 2: strattrtype 
								= B_TRANSLATE("undefined, retain"); break;
							case 3: strattrtype 
								= B_TRANSLATE("alpha"); break;
							case 4: strattrtype 
								= B_TRANSLATE("pre-multiplied alpha"); break;
							default:
								if (attrtype > 4 && attrtype < 128)
									strattrtype = B_TRANSLATE("reserved");
								else
									strattrtype = B_TRANSLATE("unassigned");
								break;
						}
						printf(B_TRANSLATE("attributes type: %d (%s)\n"),
							attrtype, strattrtype);
						
					} else
						printf(B_TRANSLATE("\nError: Unable to read entire "
							"extension area\n"));
				}
				
			} else
				printf(B_TRANSLATE("\nTGA footer not found\n"));

		} else
			printf(B_TRANSLATE("\nError: Unable to read TGA footer "
				"section\n"));
			
	} else
		printf(B_TRANSLATE("\nError: Unable to get file size\n"));
}
Ejemplo n.º 17
0
BMailFilterAction
HaikuMailFormatFilter::HeaderFetched(entry_ref& ref, BFile& file,
	BMessage& attributes)
{
	file.Seek(0, SEEK_SET);

	// TODO: attributes.AddInt32(B_MAIL_ATTR_CONTENT, length);
	attributes.AddInt32(B_MAIL_ATTR_ACCOUNT_ID, fAccountID);
	attributes.AddString(B_MAIL_ATTR_ACCOUNT, fAccountName);

	BString header;
	off_t size;
	if (file.GetSize(&size) == B_OK) {
		char* buffer = header.LockBuffer(size);
		if (buffer == NULL)
			return B_NO_MEMORY;

		ssize_t bytesRead = file.Read(buffer, size);
		if (bytesRead < 0)
			return bytesRead;
		if (bytesRead != size)
			return B_IO_ERROR;

		header.UnlockBuffer(size);
	}

	for (int i = 0; gDefaultFields[i].rfc_name; ++i) {
		BString target;
		status_t status = extract_from_header(header,
			gDefaultFields[i].rfc_name, target);
		if (status != B_OK)
			continue;

		switch (gDefaultFields[i].attr_type){
			case B_STRING_TYPE:
				sanitize_white_space(target);
				attributes.AddString(gDefaultFields[i].attr_name, target);
				break;

			case B_TIME_TYPE:
			{
				time_t when;
				when = ParseDateWithTimeZone(target);
				if (when == -1)
					when = time(NULL); // Use current time if it's undecodable.
				attributes.AddData(B_MAIL_ATTR_WHEN, B_TIME_TYPE, &when,
					sizeof(when));
				break;
			}
		}
	}

	BString senderName = _ExtractName(attributes.FindString(B_MAIL_ATTR_FROM));
	attributes.AddString(B_MAIL_ATTR_NAME, senderName);

	// Generate a file name for the incoming message.  See also
	// Message::RenderTo which does a similar thing for outgoing messages.
	BString name = attributes.FindString(B_MAIL_ATTR_SUBJECT);
	SubjectToThread(name); // Extract the core subject words.
	if (name.Length() <= 0)
		name = "No Subject";
	attributes.AddString(B_MAIL_ATTR_THREAD, name);

	// Convert the date into a year-month-day fixed digit width format, so that
	// sorting by file name will give all the messages with the same subject in
	// order of date.
	time_t dateAsTime = 0;
	const time_t* datePntr;
	ssize_t dateSize;
	char numericDateString[40];
	struct tm timeFields;

	if (attributes.FindData(B_MAIL_ATTR_WHEN, B_TIME_TYPE,
			(const void**)&datePntr, &dateSize) == B_OK)
		dateAsTime = *datePntr;
	localtime_r(&dateAsTime, &timeFields);
	snprintf(numericDateString, sizeof(numericDateString),
		"%04d%02d%02d%02d%02d%02d",
		timeFields.tm_year + 1900, timeFields.tm_mon + 1, timeFields.tm_mday,
		timeFields.tm_hour, timeFields.tm_min, timeFields.tm_sec);
	name << " " << numericDateString;

	BString workerName = attributes.FindString(B_MAIL_ATTR_FROM);
	extract_address_name(workerName);
	name << " " << workerName;

	name.Truncate(222);	// reserve space for the unique number

	// Get rid of annoying characters which are hard to use in the shell.
	name.ReplaceAll('/', '_');
	name.ReplaceAll('\'', '_');
	name.ReplaceAll('"', '_');
	name.ReplaceAll('!', '_');
	name.ReplaceAll('<', '_');
	name.ReplaceAll('>', '_');
	_RemoveExtraWhitespace(name);
	_RemoveLeadingDots(name);
		// Avoid files starting with a dot.

	if (!attributes.HasString(B_MAIL_ATTR_STATUS))
		attributes.AddString(B_MAIL_ATTR_STATUS, "New");

	_SetType(attributes, B_PARTIAL_MAIL_TYPE);

	ref.set_name(name.String());

	return B_MOVE_MAIL_ACTION;
}
Ejemplo n.º 18
0
int
main(int argc, char **argv)
{
	while ((++argv)[0]) {
		if (argv[0][0] == '-' && argv[0][1] != '-') {
			char *arg = argv[0] + 1;
			char c;
			while ((c = *arg++) != '\0') {
				if (c == 'p')
					showKeys = true;
				else if (c == 'l')
					catalogLang = (++argv)[0];
				else if (c == 's')
					catalogSig = (++argv)[0];
				else if (c == 'v')
					showSummary = true;
				else if (c == 'w')
					showWarnings = true;
				else if (c == 'o') {
					outputFile = (++argv)[0];
					break;
				}
				else if (c == 'r') {
					rxString = (++argv)[0];
					break;
				}
			}
		} else if (!strcmp(argv[0], "--help")) {
			usage();
		} else {
			if (!inputFile)
				inputFile = argv[0];
			else
				usage();
		}
	}
	if (!outputFile.Length() && inputFile) {
		// generate default output-file from input-file by replacing 
		// the extension with '.catkeys':
		outputFile = inputFile;
		int32 dot = outputFile.FindLast('.');
		if (dot >= B_OK)
			outputFile.Truncate(dot);
		outputFile << ".catkeys";
	}
	if (!inputFile || !catalogSig || !outputFile.Length() || !catalogLang)
		usage();
	
	BFile inFile;
	status_t res = inFile.SetTo(inputFile, B_READ_ONLY);
	if (res != B_OK) {
		fprintf(stderr, "unable to open inputfile %s - error: %s\n", inputFile, 
			strerror(res));
		exit(-1);
	}
	off_t sz;
	inFile.GetSize(&sz);
	if (sz > 0) {
		BString inputStr;
		char *buf = inputStr.LockBuffer(sz);
		off_t rsz = inFile.Read(buf, sz);
		if (rsz < sz) {
			fprintf(stderr, "couldn't read %Ld bytes from %s (got only %Ld)\n", 
				sz, inputFile, rsz);
			exit(-1);
		}
		inputStr.UnlockBuffer(rsz);
		catalog = new EditableCatalog("Default", catalogSig, catalogLang);
		collectAllCatalogKeys(inputStr);
		res = catalog->WriteToFile(outputFile.String());
		if (res != B_OK) {
			fprintf(stderr, "couldn't write catalog to %s - error: %s\n", 
				outputFile.String(), strerror(res));
			exit(-1);
		}
		if (showSummary) {
			int32 count = catalog->CountItems();
			if (count)
				fprintf(stderr, "%ld key%s found and written to %s\n",
					count, (count==1 ? "": "s"), outputFile.String());
			else
				fprintf(stderr, "no keys found\n");
		}
		delete catalog;
	}

//	BEntry inEntry(inputFile);
//	inEntry.Remove();
	
	return res;
}
status_t
OptiPNGTranslator::DerivedTranslate(BPositionIO *source,
	const translator_info *info, BMessage *ioExtension,
	uint32 outType, BPositionIO *target, int32 baseType)
{
	if(baseType == 1 && outType == OPTIPNG_PNG_FORMAT) {
		// create temp file
		int tempFileFD;
		BPath tempDir;
		BString tempFilePath;
		if(find_directory(B_SYSTEM_TEMP_DIRECTORY, &tempDir) != B_OK )
			return B_ERROR;
		
		tempFilePath.Append(tempDir.Path())
			.Append("/OptiPNGTranslator.XXXXXX");
		
		tempFileFD = mkstemp(tempFilePath.LockBuffer(0));
		tempFilePath.UnlockBuffer();
		
		if(tempFileFD == -1)
			return B_ERROR;
		close(tempFileFD);
		
		BFile tempFile = BFile(tempFilePath, O_WRONLY);
		
		// write PNG to file
		off_t sourceSize;
		source->GetSize(&sourceSize);
		unsigned char sourceChars[sourceSize];
		
		BTranslatorRoster *roster = BTranslatorRoster::Default();
		roster->Translate(source, NULL, NULL, &tempFile, (uint32)B_PNG_FORMAT);
		
		// optimize file
		BString optipng;
		if(system("optipng &> /dev/null") == 0) {
			optipng = "optipng";
		} else if(system("optipng-x86 &> /dev/null") == 0) {
			optipng = "optipng-x86";
		} else {
			return B_ERROR;
		}
		
		// optipng -clobber -out (file) (file)
		BString command;
		command = optipng;
		if(!fSettings->SetGetBool(OPTIPNG_SETTING_BIT_DEPTH_REDUCTION))
			command += " -nb"; // no bit-depth reduction
		if(!fSettings->SetGetBool(OPTIPNG_SETTING_COLOR_TYPE_REDUCTION))
			command += " -nc";
		if(!fSettings->SetGetBool(OPTIPNG_SETTING_PALETTE_REDUCTION))
			command += " -np";
		
		command.Append(" -o")
			.Append((char)(fSettings->
				SetGetInt32(OPTIPNG_SETTING_OPTIMIZATION_LEVEL)+'0'),1);
		// rest of command
		command.Append(" -clobber -out ")
			.Append(tempFilePath)
			.Append(" ")
			.Append(tempFilePath)
		;
		
		if(system(command) != 0) {
			return B_ERROR;
		}
		
		// read the file
		tempFile = BFile(tempFilePath, O_RDONLY);
		
		off_t fileSize;
		tempFile.GetSize(&fileSize);
		unsigned char *buffer;
		
		buffer = new unsigned char[fileSize];
		if(buffer == NULL)
			return B_ERROR;
		tempFile.ReadAt(0, buffer, fileSize);
		target->Write(buffer, fileSize);
		delete [] buffer;
		
		// delete the file
		BEntry entry = BEntry(tempFilePath);
		entry.Remove();
		
		return B_OK;
	}
	return B_NO_TRANSLATOR;
}
Ejemplo n.º 20
0
int32 RipView::RipThread(void *data)
{
	acquire_sem(abort_thread);
	
	RipView *view = (RipView*)data;
	
	view->Window()->Lock();
	view->fProgressBar->SetText(_T("Creating songs from CD..."));
	view->Window()->Unlock();
	
	// Get all the preferences that we'll need in one shot to save on piddling
	// around with locking
	prefsLock.Lock();
	
	int16 foldermode;
	if (preferences.FindInt16("foldermode",&foldermode)!=B_OK)
		foldermode=1;
	
	int16 trackname;
	if (preferences.FindInt16("namestyle",&trackname)!=B_OK)
		trackname=0;
	
	int16 bitrate;
	if (preferences.FindInt16("bitrate",&bitrate)!=B_OK)
		bitrate=1;
	
	BString destfolder;
	if (preferences.FindString("path",&destfolder)!=B_OK)
		destfolder="/boot/home/music";
	
	bool use_mp3;
	if (preferences.FindBool("usemp3",&use_mp3)!=B_OK)
		use_mp3=false;
	
	if (use_mp3 && (!gMP3Format || !gMP3Codec))
		use_mp3=false;
	
	bool make_playlist;
	if (preferences.FindBool("makeplaylist",&make_playlist)!=B_OK)
		make_playlist=true;
	
	BString playlistfolder;
	if (preferences.FindString("playlistfolder",&playlistfolder)!=B_OK)
	{
		playlistfolder=destfolder;
		playlistfolder << "/playlists";
	}
	
	prefsLock.Unlock();
	

	bool write_attributes=true;
	
	dev_t destDevice = dev_for_path(destfolder.String());
	BVolume volume(destDevice);
	if (!volume.KnowsAttr())
	{
		write_attributes=false;
		//printf("Volume for %s doesn't support attributes\n",destfolder.String());
	}
	
	// If we are grouping by artist or artist/album, we need to make sure the
	// directory exists
	switch(foldermode)
	{
		case 1:	// Artist
		{
			destfolder << "/" << gCDData.Artist() << "/";
			break;
		}
		case 2: // Album
		{
			destfolder << "/" << gCDData.Album() << "/";
			break;
		}
		case 3: // Artist & Album
		{
			destfolder << "/" << gCDData.Artist() << "/" << gCDData.Album() << "/";
			break;
		}
		default: // no special grouping
		{
			break;
		}
	}
	if (create_directory(destfolder.String(),0777)!=B_OK)
	{
		BEntry dir(destfolder.String());
		if (!dir.Exists())
		{
			BString errormsg;
			#ifdef SYS_ZETA
				errormsg=_T("Uh-oh... SimplyVorbis couldn't create the folder '");
				errormsg << destfolder << _T("RipViewMultiline1");
				
				BAlert *alert = new BAlert("SimplyVorbis",errormsg.String(),_T("OK"));
			#else
				errormsg="Uh-oh... SimplyVorbis couldn't create the folder '";
				errormsg << destfolder << "'.\n\nThis may have happened for a number of different reasons, but "
					"most often happens when making music files on a non-BeOS drive, such as one shared "
					"with Windows. Certain characters, such as question marks and slashes cause problems "
					"on these disks. You may want to check the names of the artist, album, and songs for "
					"such characters and put a good substitute in its place or remove the character entirely.";
				
				BAlert *alert = new BAlert("SimplyVorbis",errormsg.String(),"OK");
			#endif
			alert->Go();
			
			view->fRipThread = -1;
			view->Window()->PostMessage(M_STOP_ENCODING);
			
			release_sem(abort_thread);
			return 0;
		}
	}
	
	// make the directory only if the user wants to create playlists
	if (make_playlist && create_directory(playlistfolder.String(),0777)!=B_OK)
	{
		BEntry playdir(playlistfolder.String());
		if (!playdir.Exists())
		{
			BString errormsg;
			#ifdef SYS_ZETA			
			errormsg=_T("Uh-oh... SimplyVorbis couldn't create the folder '");
			errormsg << playlistfolder << _T("RIpViewMultiline2");
			
			BAlert *alert = new BAlert("SimplyVorbis",errormsg.String(),_T("OK"));
			#else
			errormsg="Uh-oh... SimplyVorbis couldn't create the folder '";
			errormsg << playlistfolder << "' for the playlists.\n\nThis may have happened for a number of different reasons, but "
				"most often happens when making playlists on a non-BeOS drive, such as one shared "
				"with Windows. Certain characters, such as question marks and slashes cause problems "
				"on these disks. You may want to check the names of the artist, album, and songs for "
				"such characters and put a good substitute in its place or remove the character entirely."
				"For the moment, your music will be created, but the playlist will not. Sorry.";
			
			BAlert *alert = new BAlert("SimplyVorbis",errormsg.String(),"OK");
			#endif
			alert->Go();
			make_playlist=false;
		}
	}
	
	// *Sigh* FAT32 volumes don't support use of question marks. I wonder what else... :(
	if (!write_attributes)
	{
		destfolder.RemoveAll("?");
		playlistfolder.RemoveAll("?");
	}
	
	BString trackPrefix;
	switch(trackname)
	{
		case 0:	// Artist
		{
			trackPrefix = gCDData.Artist();
			trackPrefix+=" - ";
			break;
		}
		case 1: // Album
		{
			trackPrefix = gCDData.Album();
			trackPrefix+=" - ";
			break;
		}
		case 2: // Artist & Album
		{
			trackPrefix = gCDData.Artist();
			trackPrefix << " - " << gCDData.Album() << " - ";
			break;
		}
		default: // no special grouping
		{
			break;
		}
	}
	
	// Populate the list of tracks to be ripped
	view->Window()->Lock();
	
	for(int32 i=view->fRipList->CountItems(); i>0; i--)
	{
		BStringItem *item = (BStringItem *)view->fRipList->RemoveItem(i);
		delete item;
	}
	
	for(int32 i=0; i<gTrackList.CountItems(); i++)
	{
		if (*(gTrackList.ItemAt(i)))
		{
			if (gCDDrive.IsDataTrack(i))
			{
				*(gTrackList.ItemAt(i)) = false;
				continue;
			}
			
			view->fRipList->AddItem(new BStringItem(gCDData.TrackAt(i)));
		}
	}
	view->Window()->Unlock();
	
	// playlists are a nice thing for quite a few people, apparently. :)
	BFile playlistfile;
	BString playlistfilename=playlistfolder;
	
	if (make_playlist)
	{
		playlistfilename << "/" << gCDData.Artist() << " - " << gCDData.Album() << ".m3u";
		
		// Append to playlists instead of overwriting them
		BEntry playlistentry(playlistfilename.String());
		if (playlistentry.Exists())
		{
			if (playlistfile.SetTo(playlistfilename.String(),B_READ_WRITE)==B_OK)
			{
				// HACK: This works around a bug in R5's BFile::Seek implementation
//				playlistfile.Seek(SEEK_END,0);
				off_t filesize;
				playlistfile.GetSize(&filesize);
				if (filesize>0)
				{
					char data[filesize];
					playlistfile.Read(&data,filesize);
				}
			}
			else
				playlistfile.SetTo(playlistfilename.String(),B_READ_WRITE | B_CREATE_FILE | B_ERASE_FILE);
		}
		else
			playlistfile.SetTo(playlistfilename.String(),B_READ_WRITE | B_CREATE_FILE);
		
		if (playlistfile.InitCheck()!=B_OK)
		{
			BString errormsg;
			#ifdef SYS_ZETA
			errormsg=_T("Uh-oh... SimplyVorbis couldn't create the playlist '");
			errormsg << playlistfilename << _T("RIpViewMultiline3");
			BAlert *alert = new BAlert("SimplyVorbis",errormsg.String(),_T("OK"));
			#else
			errormsg="Uh-oh... SimplyVorbis couldn't create the playlist '";
			errormsg << playlistfilename << "'.\n\nThis may have happened for a number of different reasons, but "
				"most often happens when making playlists on a non-BeOS drive, such as one shared "
				"with Windows. Certain characters, such as question marks and slashes cause problems "
				"on these disks. You may want to check the names of the artist, album, and songs for "
				"such characters and put a good substitute in its place or remove the character entirely."
				"For the moment, your music will be created, but the playlist will not. Sorry.";
			BAlert *alert = new BAlert("SimplyVorbis",errormsg.String(),"OK");
			#endif	

			alert->Go();
			make_playlist = false;
		}
	}
	
	BString syscmd;
	BMessenger msgr(view);
	bool copyfailed = false;
	bool showfailalert = 0;
	for (int32 i = 0; i < gTrackList.CountItems(); i++)
	{
		if (*(gTrackList.ItemAt(i)))
		{
			view->Window()->Lock();
			BStringItem *oldtrack = (BStringItem*)view->fRipList->RemoveItem(0L);
			view->Window()->Unlock();
			delete oldtrack;
			
			BString filename(trackPrefix);
			filename += gCDData.TrackAt(i);
			
			// FAT32 is such a pain in the neck here. Certain characters which are *just* *fine* for
			// other OSes are illegal. Just for the user's sake, we will constrain ourselves to its limits.
			// This means that question marks, double quotes, and colons will be substituted or removed.
			// Although it has not popped up in testing, backslashes are also substituted just in case
			filename.RemoveSet("?");
			filename.ReplaceAll("/", "-");
			filename.ReplaceAll("\\", "-");
			filename.ReplaceAll("\"", "'");
			filename.ReplaceAll(":", "-");
			
			// Set things up for the progress bar for ripping this particular track
			view->Window()->Lock();
			
			view->fProgressLabel=_T("Converting '");
			view->fProgressLabel << gCDData.TrackAt(i) << "'";
			view->fProgressBar->SetText(view->fProgressLabel.String());
			
			rgb_color blue={50,150,255,255};
			view->fProgressBar->SetBarColor(blue);
			
			cdaudio_time tracklength;
			gCDDrive.GetTimeForTrack(i+1,tracklength);
			view->fProgressBar->SetMaxValue( (tracklength.minutes * 60) + tracklength.seconds);
			view->fProgressDelta = 100.0 / float( (tracklength.minutes * 60) + tracklength.seconds);
			view->fProgressBar->Reset();
			
			view->Window()->Unlock();
			
			BString ripname(filename);
			ripname += use_mp3 ? ".mp3" : ".ogg";
			cdaudio_time rippedtime;
			
			status_t ripstat=B_OK;
			
			if (use_mp3)
				ripstat=ConvertTrack(gCDDrive.GetDrivePath(),ripname.String(),i+1,*gMP3Format,
									*gMP3Codec,&msgr,abort_thread);
			else
				ripstat=VorbifyTrack(gCDDrive.GetDrivePath(),ripname.String(),i+1,&msgr,abort_thread);
			
			if (ripstat==B_INTERRUPTED)
			{
				//  This will unblock the window
				view->fRipThread = -1;
				view->Window()->PostMessage(M_STOP_ENCODING);
				release_sem(abort_thread);
				BEntry entry(ripname.String());
				if (entry.Exists())
					entry.Remove();
				return -1;
			}
			else
			if (ripstat!=B_OK)
			{
				// Because things aren't really accurate on some CDs on the last audio track, 
				// we bear with it.
				if (!gCDDrive.IsDataTrack(i+1))
				{
					view->Window()->Lock();
					view->fProgressBar->SetText(_T("Couldn't read song from the CD. Sorry!"));
					view->Window()->Unlock();
					BEntry entry(ripname.String());
					if (entry.Exists())
						entry.Remove();
					continue;
				}
				else
				{
					view->Window()->Lock();
					rgb_color darkblue={0,0,127,255};
					view->fProgressBar->Update(view->fProgressBar->MaxValue() - 
												view->fProgressBar->CurrentValue(),
												_T("Finishing early. This is not a bad thing."));
					view->fProgressBar->SetBarColor(darkblue);
					view->Window()->Unlock();
					rippedtime = GetTimeRipped();
				}
			}
			else
			{
				view->Window()->Lock();
				rgb_color darkblue={0,0,127,255};
				view->fProgressBar->SetBarColor(darkblue);
				view->Window()->Unlock();
			}
			
			// This will ensure that the drive isn't running for an unnecesary amount of time
			gCDDrive.Stop();
			
			// Set the mime type
			filename=destfolder;
			filename << trackPrefix << gCDData.TrackAt(i) << (use_mp3 ? ".mp3" : ".ogg");
			
			BNode node(ripname.String());
#ifndef FAKE_RIPPING
			if (node.InitCheck()==B_OK)
#endif
			{
				BNodeInfo nodeinfo(&node);
				if (nodeinfo.InitCheck()==B_OK)
					nodeinfo.SetType( use_mp3 ? "audio/x-mpeg" : "audio/x-vorbis");
				
				if (write_attributes)
				{
					if (strlen(gCDData.Genre())>0)
						node.WriteAttr("Audio:Genre",B_STRING_TYPE,0,gCDData.Genre(),strlen(gCDData.Genre())+1);
					node.WriteAttr("Audio:Comment",B_STRING_TYPE,0,"Created by SimplyVorbis",
									strlen("Created by SimplyVorbis")+1);
					node.WriteAttr("Audio:Title",B_STRING_TYPE,0,gCDData.TrackAt(i),
									strlen(gCDData.TrackAt(i))+1);
					node.WriteAttr("Audio:Album",B_STRING_TYPE,0,gCDData.Album(),
									strlen(gCDData.Album())+1);
					node.WriteAttr("Audio:Artist",B_STRING_TYPE,0,gCDData.Artist(),
									strlen(gCDData.Artist())+1);
					
					int32 tracknum = i+1;
					node.WriteAttr("Audio:Track",B_INT32_TYPE,0,(const void *)&tracknum, sizeof(int32));
					
					node.WriteAttr("Audio:Bitrate",B_STRING_TYPE,0,(const void *)"128", strlen("128")+1);
					
					cdaudio_time tracktime;
					if (gCDDrive.GetTimeForTrack(i+1,tracktime))
					{
						char timestring[20];
						
						// The only time when we will ever get this far when ripstat != B_OK is if
						// we have issues related to misreported track times on an enhanced CD. In this
						// case, we make use of the riptime variable declared above to find out
						// just how much was actually ripped in order to write the proper playing time
						if (ripstat!=B_OK)
							sprintf(timestring,"%.2ld:%.2ld",rippedtime.minutes,rippedtime.seconds);
						else
							sprintf(timestring,"%.2ld:%.2ld",tracktime.minutes,tracktime.seconds);
						node.WriteAttr("Audio:Length",B_STRING_TYPE,0,timestring, strlen(timestring)+1);
					}
				}
				
				// write the file's tags
				BString inString;
				
				syscmd = "tagwriter ";
				inString = gCDData.TrackAt(i);
				inString.CharacterEscape(FILE_ESCAPE_CHARACTERS,'\\');
				syscmd << "-t " << inString;
				
				inString = gCDData.Artist();
				inString.CharacterEscape("<> '\"\\|?[]{}():;`,",'\\');
				syscmd << " -a " << inString;
				
				if (strlen(gCDData.Genre())>0)
				{
					inString = gCDData.Genre();
					inString.CharacterEscape(FILE_ESCAPE_CHARACTERS,'\\');
					syscmd << " -g " << inString;
				}
				
				if (strlen(gCDData.Album())>0)
				{
					inString = gCDData.Album();
					inString.CharacterEscape(FILE_ESCAPE_CHARACTERS,'\\');
					syscmd << " -A " << inString;
				}
				
				syscmd << " -T " << (i+1) << " ";
				syscmd << " -c 'Created by SimplyVorbis' ";
				
				inString = ripname;
				inString.ReplaceAll("/", " - ");
				inString.CharacterEscape(FILE_ESCAPE_CHARACTERS,'\\');
				syscmd+=inString;
				
				//printf("Tag command: %s\n",syscmd.String());
				system(syscmd.String());
				
				// Move the file to the real destination
				BEntry entry(ripname.String());
#ifdef FAKE_RIPPING
				{
					{
#else
				if (entry.Exists())
				{
					BDirectory destination(destfolder.String());
				
					// overwrite an existing file - allow re-ripping a file :)
					if (entry.MoveTo(&destination,NULL,true)!=B_OK)
					{
#endif
						// chances are that if this failed, it's because the destination
						// path is not on the same volume
						view->Window()->Lock();
						BString out(_T("Copying to "));
						out << destfolder;
						view->fProgressBar->SetText(out.String());
						view->Window()->Unlock();
						
						BString cmddest(destfolder);
						cmddest.CharacterEscape("<> '\"\\|[]{}():;`,",'\\');
						
						// *sigh* Certain characters are not allowed for FAT32 names.
						if (!write_attributes)
						{
							cmddest.RemoveAll("?");
							syscmd="cp -fp ";
							syscmd << inString << " " << cmddest;
						}
						else
						{
							syscmd = "copyattr -d ";
							syscmd << inString << " " << cmddest;
						}
						
						//printf("Copy command: %s\n",syscmd.String());
						if (system(syscmd.String())!=0)
							copyfailed=true;
						
						if (!copyfailed)
						{
							entry.Remove();
							syscmd = "settype -t \"audio/x-vorbis\" ";
							syscmd << cmddest << inString;
							system(syscmd.String());
							printf("type command: %s\n", syscmd.String());
						}
						else
						{
							copyfailed=false;
							showfailalert++;
						}
					}
					BString playlistentry(destfolder.String());
					playlistentry << ripname << "\n";
					playlistfile.Write(playlistentry.String(),playlistentry.Length());
				}
			}
		}
		
		gCDDrive.Stop();

#ifndef FAKE_RIPPING		
		// This will show the alert once in the ripping process, as opposed to after every track.
		if (showfailalert == 1)
		{
			copyfailed=false;
			#ifdef SYS_ZETA
			BAlert *alert = new BAlert("SimplyVorbis",_T("RIpViewMultiline4"),_T("OK"));
			#else
			BAlert *alert = new BAlert("SimplyVorbis","SimplyVorbis ran into unexpected issues copying your "
				"music files to the music folder. They have not been lost, however. After clicking "
				"OK, a window will pop up and you can move them to wherever you want.","OK");
			#endif
			alert->Go();
			
			system("/boot/beos/system/Tracker . &");
		}
#endif

	}
	
	if (make_playlist)
	{
		BNodeInfo nodeinfo(&playlistfile);
		if (nodeinfo.InitCheck()==B_OK)
			nodeinfo.SetType("text/x-playlist");
		playlistfile.Unset();
	}
	
	view->Window()->Lock();
	view->fProgressBar->SetText(_T("Finished."));
	view->Window()->Unlock();
	snooze(1000000);
	
	view->fRipThread = -1;
	view->Window()->PostMessage(M_STOP_ENCODING);
	
	release_sem(abort_thread);
	return 0;
}
Ejemplo n.º 21
0
// constructor
Hall::Hall(void):
	List(NULL),
	List1(NULL),
	List2(NULL),
	List3(NULL),
	List4(NULL),
	List5(NULL),
	path(NULL),
	_changed(false),
	_count(0)
{
BFile F;
off_t size;
struct score s;
int i;

	List = new BList(1);
	List1 = new BList(6);	// for 14x6
	List2 = new BList(6);	// for 18x8
	List3 = new BList(6);	// for 24 x 12
	List4 = new BList(6);	// for 28 x 16
	List5 = new BList(6);	// for 32 x 20

	path = new BPath();
	
	/*
	 * Find the scores file, if it exists
	 *
	 */
	/*B_COMMON_SETTINGS_DIRECTORY*/
	if (
		find_directory(B_USER_SETTINGS_DIRECTORY, path) == B_NO_ERROR
		&& path->Append(FILE_NAME, true) == B_NO_ERROR
		&& F.SetTo(path->Path(), B_READ_ONLY) == B_NO_ERROR)
	{
		if ((F.GetSize(&size) == B_NO_ERROR) 
			&& ((size % sizeof (struct score))==0))
		{
			_count = size / sizeof (struct score);
			if (_count && _count <= NUMBER)
				for ( i = 0; i < _count; i++)
				{
					BList *L;
					F.Read(&s, sizeof(struct score));
					HSList *h = new HSList();

					h->SetName((char *)s.Name);
					h->SetGameID(s.gameID);
					h->SetGameTime(s.gameTime);
					h->SetNumberTiles(s.gameTiles);
					h->SetTimeOfGame(s.absTime);

					//List->AddItem(h);
					switch(s.gameTiles)
					{
					case 14 * 6: L = List1; break;
					case 18 * 8: L = List2; break;
					case 24 * 12: L = List3; break;
					case 28 * 16: L = List4; break;
					case 32 * 20: L = List5; break;
					default: L = NULL;
					}
					if (L) L->AddItem(h);
				}
		}
	}
	//else fprintf(stderr, "Couldn't open high scores file\n");

}
Ejemplo n.º 22
0
bool MailingList::DistributeEmail(IncomingMail* ICMail, std::string ogaddrfilepath)
{
	
	//send ICMail to every address in ogaddrfilepath
	std::vector<std::string> recipients;
	BFile recipientlistbfile;
	status_t filestatus=recipientlistbfile.SetTo(ogaddrfilepath.c_str(),B_READ_ONLY);
	if (filestatus!=B_NO_ERROR)
	{
		LogError("ERROR: Could not read temp file from authentication program - the file could not be opened. Does it exist?");
		return false;	
	}
		off_t bytes; //size of file
		if (recipientlistbfile.GetSize(&bytes) == B_NO_ERROR)
		{
		
			char* buff = new char[bytes];
			off_t bytesread=recipientlistbfile.Read(buff,bytes);
			if (bytesread > 0)
			{
				//file read ok
	
				std::string addr="";
	
				for (int x=0; x < bytesread; x++)
				{
					if (buff[x]!='\n')
					{
						addr=addr+buff[x];
					}
					else
					{
						recipients.push_back(addr);
						addr="";	
					}
				}	
				delete buff;
			}
			else
			{
				LogError("ERROR: Could not read temp file from authentication program - the file was empty");
				delete buff;
				return false;	
			}
		}
		else
		{
			LogError("ERROR: Could not read temp file from authentication program -- could not determine file size");
			return false;	
		}
		
		ICMail->AddSubjectPrefix(fListSubjectPrefix); //fListSubjectPrefix will be null str if not defined in conf file
		ICMail->CleanHeaders(); //clean & setup headers ready for sending message out to recipients
		ICMail->AdjustReplyTo(fForceReplyToList); //set reply to to either sender or list IC address
		
		//if List-Xyz header values were set in conf file we need to set them in msg
		if (fListOwner!="")
		{
			ICMail->SetListOwnerHeader(fListOwner);
		}
		if (fListHelp!="")
		{
			ICMail->SetListHelpHeader(fListHelp);
		}
		if (fListArchive!="")
		{
			ICMail->SetListArchiveHeader(fListArchive);
		}
		if (fListSubscribe!="")
		{
			ICMail->SetListSubscribeHeader(fListSubscribe);
		}
		if (fListUnSubscribe!="")
		{
			ICMail->SetListUnSubscribeHeader(fListUnSubscribe);
		}
	//call GetFromField to get email address in case we need to bounce msg 

	std::string ICsendersAddrField=ICMail->GetSendersAddr(); //returns null string if unable to find
	//at present ICsendersAddrField now has address in form user@domain NOT <user@domain> is this in line with RFC spec?
	


	if (ICMail->CheckIfPlainTextCriteriaPassed(fPlainTextOnly)==false)
	{
		//bounce
		if (fPlainTextOnly=='Y')
		{
				//bounce to sender
				LogError("INFO: Incoming email not text/plain and non plain text messages are not allowed. Bounced to "+ICsendersAddrField);
				BMailMessage* ogmail;
				ogmail= new BMailMessage();
				ogmail->AddHeaderField(B_MAIL_TO,ICsendersAddrField.c_str());
				ogmail->AddHeaderField(B_MAIL_FROM,fListOGEnvelopeAddressFromAddress.c_str());
				std::string bouncesubject=std::string("Undelivered mail: Your message to ");
				bouncesubject=bouncesubject+fListName+" was rejected";
				ogmail->AddHeaderField(B_MAIL_SUBJECT,bouncesubject.c_str());
				std::string xmailer=(fApp->GetAppName())+" mailing list server for Haiku";
				ogmail->AddHeaderField("X-Mailer: ",xmailer.c_str());
				ogmail->AddHeaderField("precedence: ","list");
				std::string bouncecontent="Your message to "+fListName+" was rejected because this list only accepts plain text messages. Make sure your email program is not creating HTML or Rich Text emails and that there are no attached files.";
				bouncecontent=bouncecontent+"\n\nThis is an automated reply sent from the "+fApp->GetAppName()+" for Haiku server at "+fListICAddress;
    			ogmail->AddContent(bouncecontent.c_str(),strlen(bouncecontent.c_str()));
				ogmail->Send();
				delete ogmail;
		}
		else
		{
				//fPlainTextOnly must be 'H'
				//bounce to sender
				LogError("INFO: Incoming email not HTML or plain text and non text messages are not allowed. Bounced to "+ICsendersAddrField);
				BMailMessage* ogmail;
				ogmail= new BMailMessage();
				ogmail->AddHeaderField(B_MAIL_TO,ICsendersAddrField.c_str());
				ogmail->AddHeaderField(B_MAIL_FROM,fListOGEnvelopeAddressFromAddress.c_str());
				std::string bouncesubject=std::string("Undelivered mail: Your message to ");
				bouncesubject=bouncesubject+fListName+" was rejected";
				ogmail->AddHeaderField(B_MAIL_SUBJECT,bouncesubject.c_str());
				std::string xmailer=(fApp->GetAppName())+" mailing list server for Haiku";
				ogmail->AddHeaderField("X-Mailer: ",xmailer.c_str());
				ogmail->AddHeaderField("precedence: ","list");
				std::string bouncecontent="Your message to "+fListName+" was rejected because this list only accepts HTML or plain text messages. Make sure that there are no attached files.";
				bouncecontent=bouncecontent+"\n\nThis is an automated reply sent from the "+fApp->GetAppName()+" for Haiku server at "+fListICAddress;
    			ogmail->AddContent(bouncecontent.c_str(),strlen(bouncecontent.c_str()));
				ogmail->Send();
				delete ogmail;
		}
		return true;
	}

	
	if (ICMail->GetICFileSize() > fMaxContentBytes)
	{
		//msg too big bounce to sender
		LogError("INFO: Incoming email too big. Bounced to "+ICsendersAddrField);
		BMailMessage* ogmail;
		ogmail= new BMailMessage();
		ogmail->AddHeaderField(B_MAIL_TO,ICsendersAddrField.c_str());
		ogmail->AddHeaderField(B_MAIL_FROM,fListOGEnvelopeAddressFromAddress.c_str());
		std::string bouncesubject=std::string("Undelivered mail: Your message to ");
		bouncesubject=bouncesubject+fListName+" was rejected";
		ogmail->AddHeaderField(B_MAIL_SUBJECT,bouncesubject.c_str());
		std::string xmailer=(fApp->GetAppName())+" mailing list server for Haiku";
		ogmail->AddHeaderField("X-Mailer: ",xmailer.c_str());
		ogmail->AddHeaderField("precedence: ","list");
		stringstream converter;
		converter << fMaxContentBytes << " bytes, your message was " << ICMail->GetICFileSize() << " bytes";
		std::string toobigcontent="Your message to "+fListName+" is too big and was rejected. Maximum allowable size for this list is "+converter.str();
		toobigcontent=toobigcontent+"\n\nThis is an automated reply sent from the "+fApp->GetAppName()+" for Haiku server at "+fListICAddress;
    	ogmail->AddContent(toobigcontent.c_str(),strlen(toobigcontent.c_str()));
		ogmail->Send();
		delete ogmail;
		return true;
	}



	//setup a temp file to store the modified og msg
	std::stringstream epochsecs;
	epochsecs << real_time_clock(); //secs now since unix epoch
	int filenamecounterInt=0; //will be incremented until we get a unique filename string
	bool nonuniquefilename=true;
	BEntry tempFileBEntry;
	std::string tempFilePath;
	BFile* tempFileBFile = new BFile();
	do
	{
		filenamecounterInt++;
		std::stringstream filenamecounter;
		filenamecounter << filenamecounterInt;
		tempFilePath=fApp->GetTempDirPath()+fListICAddress+"--"+epochsecs.str()+filenamecounter.str();
		//test if tempFilePath already exists
		tempFileBEntry.SetTo(tempFilePath.c_str());
		status_t tempFileResult=tempFileBFile->SetTo(&tempFileBEntry,B_READ_WRITE|B_FAIL_IF_EXISTS|B_CREATE_FILE); //fails if already exists
		if (tempFileResult==B_FILE_EXISTS)
		{
			nonuniquefilename=true;	
		}
		else if (tempFileResult==B_NO_ERROR)
		{
			nonuniquefilename=false;
			
		}
		else
		{
			//error
			LogError("ERROR: Could not create temp file to store outgoing email");
			return false;
		}
		
	}while(nonuniquefilename);

	//Write modified msg into temp file

	ICMail->WriteToFile(tempFileBFile);



	//store senders addr so we can log it later
	std::string sender="";
	//Send out modified msg in temp file to all recipients
	for (int x=0; x< recipients.size(); x++)
	{
		std::string recipient=recipients[x];
		
		BEmailMessage* ogmail;
		ogmail= new BEmailMessage(tempFileBFile);
    	ogmail->SetTo(recipient.c_str());
    	sender=std::string(ogmail->From());
    	//1st version of send indicates whether to change the From: field to the specified account (requires modified mailkit)
		ogmail->SendViaAccountWithFromPreset(fListOGEnvelopeAddressFromAddress.c_str());
		//ogmail->SendViaAccount(fListOGEnvelopeAddressFromAddress.c_str());
		ogmail->Send(true);
		delete ogmail;
		
	}
	tempFileBFile->Unset(); //close file
	delete tempFileBFile; //delete obj
	//archive msg if needed
	bool archived=false;
	if (fArchivePath!="")
	{
			
			BDirectory dir;
			if ( dir.SetTo(fArchivePath.c_str()) !=B_OK )
			{
				LogError("ERROR: Could not archive message. Check archive folder exists and is writable");
			}
			else
			{
				if ( tempFileBEntry.MoveTo(&dir) !=B_NO_ERROR)
				{
					LogError("ERROR: Could not archive message. Check archive folder exists and is writable");
				}
				else
				{
					archived=true;	
				}
			}
			
	}
	if (archived==false)
	{
		//if archived  then the file was moved so we dont need to delete the original
		tempFileBEntry.Remove();//remove file from filesystem	
	}
	
	stringstream numRecipients;
	numRecipients << recipients.size();
	
	if ( (fLogSuccesses) && (recipients.size()>0)  )
	{
		//if we recipients.size() was 0 sender var is null str as its set in the distribution loop
		LogError("INFO: Successfully distributed an email to "+numRecipients.str()+" recipients from "+sender);
	}
	return true;
}
Ejemplo n.º 23
0
int main(int argc, char** argv) try {
	// Arguments
	char*	flag;
	char*	keyt;
	char*	path1;  // input file
	char*	path2;  // output file
	
	// Check Arguments For "--help" or "--version"
	if (argc > 1) {
		flag = *(argv + 1);
		
		if (strcmp("--help", flag) == 0) { cout << rawaes_menu; exit(0); }
		if (strcmp("--version", flag) == 0) { cout << rawaes_version; exit(0); }
	}
	else { cout << rawaes_menu; exit(0); }
	
	// Check Argument Count
	if (argc != 5) throw "Must have 4 arguments!";
	
	// AES Class Variable
	bool	dir_enc = true;
	int		key_size = 128;
	aes		crypto;
	
	// Check Direction and Key Size
	if (
		strcmp("-d", flag) == 0 ||
		strcmp("--decrypt", flag) == 0 ||
		strcmp("-d16", flag) == 0 ||
		strcmp("-d128", flag) == 0
	) {	dir_enc = false; }
	else if (
		strcmp("-d24", flag) == 0 ||
		strcmp("-d192", flag) == 0
	) { dir_enc = false; key_size = 192; }
	else if (
		strcmp("-d32", flag) == 0 ||
		strcmp("-d256", flag) == 0
	) { dir_enc = false; key_size = 256; }
	else if (
		strcmp("-e32", flag) == 0 ||
		strcmp("-e256", flag) == 0
	) { key_size = 256; }
	else if (
		strcmp("-e24", flag) == 0 ||
		strcmp("-e192", flag) == 0
	) { key_size = 192; }
	else if (
		strcmp("-e", flag) != 0 &&
		strcmp("--encrypt", flag) != 0 &&
		strcmp("-e16", flag) != 0 &&
		strcmp("-e128", flag) != 0
	) { throw "Must Specify Direction: --encrypt --decrypt"; }
	
	// Initalize Key Set-up
	keyt = *(argv + 2);
	int		keyln = strlen(keyt);
	byte*	keydt = new byte[keyln];
	for (int i = 0; i < keyln; ++i) *(keydt + i) = static_cast<byte>(*(keyt + i)); 
		
	if (dir_enc) crypto.key(keydt, key_size, aes::enc);
	else crypto.key(keydt, key_size, aes::dec);
	
	delete keydt;
	

	// Open Input and Output Files
	path1 = *(argv + 3);
	path2 = *(argv + 4);
	
	BFile*	fin;
	BFile*	fout;
	
	fin = new BFile(path1, B_READ_ONLY);
	if (fin->InitCheck() != B_OK) {
		delete fin;
		throw "Cannot Initialize Input File!";
	}
	
	fout = new BFile(path2, B_WRITE_ONLY|B_CREATE_FILE);
	if (fout->InitCheck() != B_OK) {
		fin->Unset();
		delete fin;
		delete fout;
		throw "Cannot Initialize Output File!";
	}
	
	// Get Input File Dimensions
	off_t* fin_size_temp = new off_t;
	fin->GetSize(fin_size_temp);
	
	uint64 fin_size = static_cast<unsigned>(*fin_size_temp);
	delete fin_size_temp;
	
	// Encrypt or Decrypt Loop
	uint64	fin_offset = 0;
	byte*	fin_buffer;
	byte*	fout_buffer;
	
	fin_buffer = new byte[17];
	fout_buffer = new byte[17];
	
	typedef void (aes::* aes_encrypt_decrypt)(const byte[], byte[]);
	
	aes_encrypt_decrypt aesfunc;
	if (dir_enc) aesfunc = &aes::encrypt;
	else aesfunc = &aes::decrypt;
	
	if (dir_enc) cout << "Encrypting...";
	else cout << "Decrypting...";
	
	while ((fin_size - fin_offset) >= 16) {
		fin->Read(fin_buffer, 16);
		(crypto.*aesfunc)(fin_buffer, fout_buffer);
		fout->Write(fout_buffer, 16);
		
		fin_offset += 16;
	}
	
	int fin_rsize = fin_size - fin_offset;
	if (fin_rsize != 0) {
		for (int i = fin_rsize; i < 16; ++i) *(fin_buffer + i) = 0; 
		
		fin->Read(fin_buffer, fin_rsize);
		(crypto.*aesfunc)(fin_buffer, fout_buffer);
		fout->Write(fout_buffer, 16);
	}
	
	fin->Unset();
	fout->Unset();
	
	delete fout;
	delete fin;
	delete fout_buffer;
	delete fin_buffer;

	// Output Good News
	cout << "Complete!\n";
	
	return 0;
	
} catch (const char* str) {
	cout << rawaes_menu << endl << "ERROR: " << str << endl;
	exit(1);
}
Ejemplo n.º 24
0
int
main(int argc, char *argv[])
{
	type_code attrType = B_STRING_TYPE;
	char *attrValue = NULL;
	size_t valueFileLength = 0;
	bool resolveLinks = true;

	int c;
	while ((c = getopt_long(argc, argv, "hf:t:P", kLongOptions, NULL)) != -1) {
		switch (c) {
			case 0:
				break;
			case 'f':
			{
				// retrieve attribute value from file
				BFile file;
				off_t size;
				status_t status = file.SetTo(optarg, B_READ_ONLY);
				if (status < B_OK) {
					ERR("can't read attribute value from file %s: %s\n",
						optarg, strerror(status));
					return 1;
				}
		
				status = file.GetSize(&size);
				if (status == B_OK) {
					if (size == 0) {
						ERR_0("attribute value is empty: 0 bytes\n");
						return 1;
					}
					if (size > 4 * 1024 * 1024) {
						ERR("attribute value is too large: %" B_PRIdOFF
							" bytes\n", size);
						return 1;
					}
					attrValue = (char *)malloc(size);
					if (attrValue != NULL)
						status = file.Read(attrValue, size);
					else
						status = B_NO_MEMORY;
				}
		
				if (status < B_OK) {
					ERR("can't read attribute value: %s\n", strerror(status));
					return 1;
				}
		
				valueFileLength = (size_t)size;
				break;
			}
			case 't':
				// Get the attribute type
				if (typeForString(optarg, &attrType) != B_OK)
					invalidAttrType(optarg);
				break;
			case 'P':
				resolveLinks = false;
				break;
			case 'h':
				usage(0);
				break;
			default:
				usage(1);
				break;
		}
	}
	
	if (argc - optind < 1)
		usage(1);
	const char *attrName = argv[optind++];

	if (argc - optind < 1)
		usage(1);
	if (!valueFileLength)
		attrValue = argv[optind++];

	if (argc - optind < 1)
		usage(1);

	// Now that we gathered all the information proceed
	// to add the attribute to the file(s)

	int result = 0;

	for (; optind < argc; optind++) {
		status_t status = addAttr(argv[optind], attrType, attrName, attrValue,
			valueFileLength, resolveLinks);

		// special case for bool types
		if (status == B_BAD_VALUE && attrType == B_BOOL_TYPE)
			invalidBoolValue(attrValue);

		if (status != B_OK) {
			ERR("can't add attribute to file %s: %s\n", argv[optind],
				strerror(status));

			// proceed files, but return an error at the end
			result = 1;
		}
	}

	if (valueFileLength)
		free(attrValue);

	return result;
}
Ejemplo n.º 25
0
// _InitELFFile
void
ResourceFile::_InitELFFile(BFile& file)
{
	status_t error = B_OK;
	// get the file size
	off_t fileSize = 0;
	error = file.GetSize(&fileSize);
	if (error != B_OK)
		throw Exception(error, "Failed to get the file size.");
	// read ELF header
	Elf32_Ehdr fileHeader;
	read_exactly(file, 0, &fileHeader, sizeof(Elf32_Ehdr),
				 "Failed to read ELF header.");
	// check data encoding (endianess)
	switch (fileHeader.e_ident[EI_DATA]) {
		case ELFDATA2LSB:
			fHostEndianess = B_HOST_IS_LENDIAN;
			break;
		case ELFDATA2MSB:
			fHostEndianess = B_HOST_IS_BENDIAN;
			break;
		default:
		case ELFDATANONE:
			throw Exception("Unsupported ELF data encoding.");
			break;
	}
	// get the header values
	uint32 headerSize				= _GetUInt16(fileHeader.e_ehsize);
	uint32 programHeaderTableOffset	= _GetUInt32(fileHeader.e_phoff);
	uint32 programHeaderSize		= _GetUInt16(fileHeader.e_phentsize);
	uint32 programHeaderCount		= _GetUInt16(fileHeader.e_phnum);
	uint32 sectionHeaderTableOffset	= _GetUInt32(fileHeader.e_shoff);
	uint32 sectionHeaderSize		= _GetUInt16(fileHeader.e_shentsize);
	uint32 sectionHeaderCount		= _GetUInt16(fileHeader.e_shnum);
	bool hasProgramHeaderTable = (programHeaderTableOffset != 0);
	bool hasSectionHeaderTable = (sectionHeaderTableOffset != 0);
//printf("headerSize              : %lu\n", headerSize);
//printf("programHeaderTableOffset: %lu\n", programHeaderTableOffset);
//printf("programHeaderSize       : %lu\n", programHeaderSize);
//printf("programHeaderCount      : %lu\n", programHeaderCount);
//printf("sectionHeaderTableOffset: %lu\n", sectionHeaderTableOffset);
//printf("sectionHeaderSize       : %lu\n", sectionHeaderSize);
//printf("sectionHeaderCount      : %lu\n", sectionHeaderCount);
	// check the sanity of the header values
	// ELF header size
	if (headerSize < sizeof(Elf32_Ehdr) || headerSize > kMaxELFHeaderSize) {
		throw Exception("Invalid ELF header: invalid ELF header size: %lu.",
						headerSize);
	}
	uint32 resourceOffset = headerSize;
	uint32 resourceAlignment = 0;
	// program header table offset and entry count/size
	uint32 programHeaderTableSize = 0;
	if (hasProgramHeaderTable) {
		if (programHeaderTableOffset < headerSize
			|| programHeaderTableOffset > fileSize) {
			throw Exception("Invalid ELF header: invalid program header table "
							"offset: %lu.", programHeaderTableOffset);
		}
		programHeaderTableSize = programHeaderSize * programHeaderCount;
		if (programHeaderSize < sizeof(Elf32_Phdr)
			|| programHeaderTableOffset + programHeaderTableSize > fileSize) {
			throw Exception("Invalid ELF header: program header table exceeds "
							"file: %lu.",
							programHeaderTableOffset + programHeaderTableSize);
		}
		resourceOffset = max(resourceOffset, programHeaderTableOffset
											 + programHeaderTableSize);
		// iterate through the program headers
		for (int32 i = 0; i < (int32)programHeaderCount; i++) {
			uint32 shOffset = programHeaderTableOffset + i * programHeaderSize;
			Elf32_Phdr programHeader;
			read_exactly(file, shOffset, &programHeader, sizeof(Elf32_Shdr),
						 "Failed to read ELF program header.");
			// get the header values
			uint32 type			= _GetUInt32(programHeader.p_type);
			uint32 offset		= _GetUInt32(programHeader.p_offset);
			uint32 size			= _GetUInt32(programHeader.p_filesz);
			uint32 alignment	= _GetUInt32(programHeader.p_align);
//printf("segment: type: %ld, offset: %lu, size: %lu, alignment: %lu\n",
//type, offset, size, alignment);
			// check the values
			// PT_NULL marks the header unused,
			if (type != PT_NULL) {
				if (/*offset < headerSize ||*/ offset > fileSize) {
					throw Exception("Invalid ELF program header: invalid "
									"program offset: %lu.", offset);
				}
				uint32 segmentEnd = offset + size;
				if (segmentEnd > fileSize) {
					throw Exception("Invalid ELF section header: segment "
									"exceeds file: %lu.", segmentEnd);
				}
				resourceOffset = max(resourceOffset, segmentEnd);
				resourceAlignment = max(resourceAlignment, alignment);
			}
		}
	}
	// section header table offset and entry count/size
	uint32 sectionHeaderTableSize = 0;
	if (hasSectionHeaderTable) {
		if (sectionHeaderTableOffset < headerSize
			|| sectionHeaderTableOffset > fileSize) {
			throw Exception("Invalid ELF header: invalid section header table "
							"offset: %lu.", sectionHeaderTableOffset);
		}
		sectionHeaderTableSize = sectionHeaderSize * sectionHeaderCount;
		if (sectionHeaderSize < sizeof(Elf32_Shdr)
			|| sectionHeaderTableOffset + sectionHeaderTableSize > fileSize) {
			throw Exception("Invalid ELF header: section header table exceeds "
							"file: %lu.",
							sectionHeaderTableOffset + sectionHeaderTableSize);
		}
		resourceOffset = max(resourceOffset, sectionHeaderTableOffset
											 + sectionHeaderTableSize);
		// iterate through the section headers
		for (int32 i = 0; i < (int32)sectionHeaderCount; i++) {
			uint32 shOffset = sectionHeaderTableOffset + i * sectionHeaderSize;
			Elf32_Shdr sectionHeader;
			read_exactly(file, shOffset, &sectionHeader, sizeof(Elf32_Shdr),
						 "Failed to read ELF section header.");
			// get the header values
			uint32 type		= _GetUInt32(sectionHeader.sh_type);
			uint32 offset	= _GetUInt32(sectionHeader.sh_offset);
			uint32 size		= _GetUInt32(sectionHeader.sh_size);
//printf("section: type: %ld, offset: %lu, size: %lu\n", type, offset, size);
			// check the values
			// SHT_NULL marks the header unused,
			// SHT_NOBITS sections take no space in the file
			if (type != SHT_NULL && type != SHT_NOBITS) {
				if (offset < headerSize || offset > fileSize) {
					throw Exception("Invalid ELF section header: invalid "
									"section offset: %lu.", offset);
				}
				uint32 sectionEnd = offset + size;
				if (sectionEnd > fileSize) {
					throw Exception("Invalid ELF section header: section "
									"exceeds file: %lu.", sectionEnd);
				}
				resourceOffset = max(resourceOffset, sectionEnd);
			}
		}
	}
//printf("resourceOffset: %lu\n", resourceOffset);
	// align the offset
	if (resourceAlignment < kELFMinResourceAlignment)
		resourceAlignment = kELFMinResourceAlignment;
	if (resourceAlignment > kELFMaxResourceAlignment) {
		throw Exception("The ELF object file requires an invalid alignment: "
						"%lu.", resourceAlignment);
	}
	resourceOffset = align_value(resourceOffset, resourceAlignment);
//printf("resourceOffset: %lu\n", resourceOffset);
	if (resourceOffset >= fileSize)
		throw Exception("The ELF object file does not contain resources.");
	// fine, init the offset file
	fFile.SetTo(file, resourceOffset);
}
Ejemplo n.º 26
0
void PrefWindow::save_stroke(const char* stroke, const char* filename)
{
  cout << "save stroke '" << traineroutput.String() << "' as '" << stroke << "'" << endl;

  BFile strokes;
  BEntry entry;
  BPath settingspath; 

  if (stroke[0]==0) return;

  if ((find_directory(B_USER_SETTINGS_DIRECTORY, &settingspath))==B_OK)
  {
    //found path to settings...
    cout << "The path to the settings is... " << settingspath.Path() << endl;

    settingspath.Append("strokeit/strokes/");
    settingspath.Append( filename ); //selected_file.String() );

    cout << "Using for strokefile : "<< settingspath.Path() << endl; 
    
    entry.SetTo( settingspath.Path() );

    if (B_OK != strokes.SetTo(&entry, B_READ_WRITE))
    {
      cout << "no strokes" << endl; 
      return;
    }
    else 
    {
      cout << "strokes loaded" << endl;
      
      off_t _size;
      strokes.GetSize(&_size);
      cout << "size is " << _size << endl;

      strokes.Seek(_size, 0); 
      uint32 pos = strokes.Position();
      cout << "pos is " << pos << endl;
       
      char ch;
      strokes.Seek(-1, SEEK_END); 
      strokes.Read(&ch, sizeof(char)); //go back one

      int32 _offset = 0; 
      if (ch==0x0a)
        _offset = -4; // "0=0\n" 
      else 
        _offset = -3; // "0=0"

      strokes.Seek(_offset, SEEK_END); //go back a few chars..

      char tmp[4]= {0, 0, 0, 0};
      strokes.Read( &tmp, sizeof(tmp) );
      tmp[3] = 0; //make sure we kill off the last char...

      BString tmp_in;
      tmp_in << tmp;

      cout << "found... " << tmp_in.String() << endl;
      if (tmp_in.Compare("0=0")==0)
        strokes.Seek(_offset, SEEK_END); //remove the eof char sequence...

      tmp_in.SetTo(""); 
      tmp_in << trainer_output->Text() << "=" << stroke << (char)0x0a;
      cout << "we have ... "<< tmp_in.String(); 
      strokes.Write( tmp_in.String(), tmp_in.CountChars() );

      tmp_in.SetTo(""); 
      tmp_in << "0=0" << (char)0x0a;
      cout << "we have ... "<< tmp_in.String(); 
      strokes.Write( tmp_in.String(), tmp_in.CountChars() );  
    }          
  }
  update_trainer_output("");
}
Ejemplo n.º 27
0
int32 DCCReceive::Transfer(void* arg)
{
	BMessenger msgr(reinterpret_cast<DCCReceive*>(arg));
	struct sockaddr_in address;
	BLooper* looper(NULL);

	int32 dccSock(-1);

	if ((dccSock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		UpdateStatus(msgr, S_DCC_ESTABLISH_ERROR);
		return B_ERROR;
	}

	BMessage reply;

	if (msgr.SendMessage(M_DCC_GET_CONNECT_DATA, &reply) == B_ERROR) return B_ERROR;

	memset(&address, 0, sizeof(sockaddr_in));
	address.sin_family = AF_INET;
	address.sin_port = htons(atoi(reply.FindString("port")));
	address.sin_addr.s_addr = htonl(strtoul(reply.FindString("ip"), 0, 10));

	UpdateStatus(msgr, S_DCC_CONNECT_TO_SENDER);
	if (connect(dccSock, (sockaddr*)&address, sizeof(address)) < 0) {
		UpdateStatus(msgr, S_DCC_ESTABLISH_ERROR);
		close(dccSock);
		return B_ERROR;
	}

	BPath path(reply.FindString("name"));
	BString buffer;
	off_t file_size(0);

	buffer << S_DCC_RECV1 << path.Leaf() << S_DCC_RECV2 << reply.FindString("nick") << ".";

	UpdateStatus(msgr, buffer.String());

	BFile file;

	if (msgr.IsValid()) {
		if (reply.FindBool("resume")) {
			if (file.SetTo(reply.FindString("name"), B_WRITE_ONLY | B_OPEN_AT_END) == B_NO_ERROR &&
				file.GetSize(&file_size) == B_NO_ERROR && file_size > 0LL)
				UpdateBar(msgr, file_size, 0, 0, true);
			else
				file_size = 0LL;
		} else {
			file.SetTo(reply.FindString("name"), B_WRITE_ONLY | B_CREATE_FILE | B_ERASE_FILE);
		}
	}

	uint32 bytes_received(file_size);
	uint32 size(atol(reply.FindString("size")));
	uint32 cps(0);

	if (file.InitCheck() == B_NO_ERROR) {
		bigtime_t last(system_time()), now;
		char inBuffer[8196];
		bigtime_t start = system_time();

		while ((msgr.Target(&looper) != NULL) && bytes_received < size) {
			int readSize;
			if ((readSize = recv(dccSock, inBuffer, 8196, 0)) < 0) break;

			file.Write(inBuffer, readSize);
			bytes_received += readSize;
			BMessage msg(M_DCC_UPDATE_TRANSFERRED);
			msg.AddInt32("transferred", bytes_received);
			msgr.SendMessage(&msg);

			uint32 feed_back(htonl(bytes_received));
			send(dccSock, &feed_back, sizeof(uint32), 0);

			now = system_time();
			bool hit(false);

			if (now - last > 500000) {
				cps = (int)ceil((bytes_received - file_size) / ((now - start) / 1000000.0));
				BMessage updmsg(M_DCC_UPDATE_AVERAGE);
				updmsg.AddInt32("average", cps);
				msgr.SendMessage(&updmsg);
				last = now;
				hit = true;
			}

			DCCConnect::UpdateBar(msgr, readSize, cps, bytes_received, hit);
		}
	}

	if (msgr.IsValid()) {
		BMessage msg(M_DCC_STOP_BUTTON);
		msgr.SendMessage(&msg);
	}

	if (dccSock > 0) {
		close(dccSock);
	}

	if (file.InitCheck() == B_OK) {
		file.Unset();
		update_mime_info(reply.FindString("name"), 0, 0, 1);
	}
	return 0;
}